context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//
//((s.a+s.b)+s.c)
//permutations for ((s.a+s.b)+s.c)
//((s.a+s.b)+s.c)
//(s.c+(s.a+s.b))
//(s.a+s.b)
//(s.b+s.a)
//s.a
//s.b
//(s.b+s.a)
//(s.a+s.b)
//s.c
//(s.a+(s.b+s.c))
//(s.b+(s.a+s.c))
//(s.b+s.c)
//(s.c+s.b)
//s.b
//s.c
//(s.c+s.b)
//(s.b+s.c)
//(s.a+s.c)
//(s.c+s.a)
//s.a
//s.c
//(s.c+s.a)
//(s.a+s.c)
//(s.c+(s.a+s.b))
//((s.a+s.b)+s.c)
namespace CseTest
{
using System;
public class Test_Main
{
static int Main()
{
int ret = 100;
class_s s = new class_s();
s.a = return_int(false, -62);
s.b = return_int(false, -4);
s.c = return_int(false, 6);
int v;
#if LOOP
do {
#endif
v = ((s.a + s.b) + s.c);
if (v != -60)
{
Console.WriteLine("test0: for ((s.a+s.b)+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + (s.a + s.b));
if (v != -60)
{
Console.WriteLine("test1: for (s.c+(s.a+s.b)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + s.b);
if (v != -66)
{
Console.WriteLine("test2: for (s.a+s.b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + s.a);
if (v != -66)
{
Console.WriteLine("test3: for (s.b+s.a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + s.a);
if (v != -66)
{
Console.WriteLine("test4: for (s.b+s.a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + s.b);
if (v != -66)
{
Console.WriteLine("test5: for (s.a+s.b) failed actual value {0} ", v);
ret = ret + 1;
}
#if LOOP
do {
#endif
v = (s.a + (s.b + s.c));
if (v != -60)
{
Console.WriteLine("test6: for (s.a+(s.b+s.c)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + (s.a + s.c));
#if TRY
try {
#endif
if (v != -60)
{
Console.WriteLine("test7: for (s.b+(s.a+s.c)) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + s.c);
if (v != 2)
{
Console.WriteLine("test8: for (s.b+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
#if TRY
}
finally {
#endif
v = (s.c + s.b);
#if TRY
}
#endif
if (v != 2)
{
Console.WriteLine("test9: for (s.c+s.b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + s.b);
if (v != 2)
{
Console.WriteLine("test10: for (s.c+s.b) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.b + s.c);
if (v != 2)
{
Console.WriteLine("test11: for (s.b+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + s.c);
if (v != -56)
{
Console.WriteLine("test12: for (s.a+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + s.a);
if (v != -56)
{
Console.WriteLine("test13: for (s.c+s.a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + s.a);
if (v != -56)
{
Console.WriteLine("test14: for (s.c+s.a) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.a + s.c);
if (v != -56)
{
Console.WriteLine("test15: for (s.a+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
v = (s.c + (s.a + s.b));
if (v != -60)
{
Console.WriteLine("test16: for (s.c+(s.a+s.b)) failed actual value {0} ", v);
ret = ret + 1;
}
#if LOOP
} while (v == 0);
#endif
v = ((s.a + s.b) + s.c);
if (v != -60)
{
Console.WriteLine("test17: for ((s.a+s.b)+s.c) failed actual value {0} ", v);
ret = ret + 1;
}
#if LOOP
} while (v == 0);
#endif
Console.WriteLine(ret);
return ret;
}
private static int return_int(bool verbose, int input)
{
int ans;
try
{
ans = input;
}
finally
{
if (verbose)
{
Console.WriteLine("returning : ans");
}
}
return ans;
}
}
public class class_s
{
public int a;
public int b;
public int c;
}
}
| |
// Copyright (c) 2015, Outercurve Foundation.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// - Neither the name of the Outercurve Foundation nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using WebsitePanel.EnterpriseServer.Base.HostedSolution;
using WebsitePanel.Providers;
using WebsitePanel.Providers.DNS;
using WebsitePanel.Providers.HostedSolution;
using WebsitePanel.Providers.SharePoint;
namespace WebsitePanel.EnterpriseServer.Code.SharePoint
{
/// <summary>
/// Exposes handful API on hosted SharePoint site collections management.
/// </summary>
public class HostedSharePointServerController : IImportController, IBackupController
{
private const int FILE_BUFFER_LENGTH = 5000000; // ~5MB
/// <summary>
/// Gets site collections in raw form.
/// </summary>
/// <param name="packageId">Package to which desired site collections belong.</param>
/// <param name="organizationId">Organization to which desired site collections belong.</param>
/// <param name="filterColumn">Filter column name.</param>
/// <param name="filterValue">Filter value.</param>
/// <param name="sortColumn">Sort column name.</param>
/// <param name="startRow">Row index to start from.</param>
/// <param name="maximumRows">Maximum number of rows to retrieve.</param>
/// <returns>Site collections that match.</returns>
public static SharePointSiteCollectionListPaged GetSiteCollectionsPaged(int packageId, int organizationId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows)
{
if (IsDemoMode)
{
SharePointSiteCollectionListPaged demoResult = new SharePointSiteCollectionListPaged();
demoResult.SiteCollections = GetSiteCollections(1, false);
demoResult.TotalRowCount = demoResult.SiteCollections.Count;
return demoResult;
}
SharePointSiteCollectionListPaged paged = new SharePointSiteCollectionListPaged();
DataSet result = PackageController.GetRawPackageItemsPaged(packageId, ResourceGroups.SharepointFoundationServer, typeof(SharePointSiteCollection),
true, filterColumn, filterValue, sortColumn, startRow, Int32.MaxValue);
List<SharePointSiteCollection> items = PackageController.CreateServiceItemsList(result, 1).ConvertAll<SharePointSiteCollection>(delegate(ServiceProviderItem item) { return (SharePointSiteCollection)item; });
if (organizationId > 0)
{
items = items.FindAll(delegate(SharePointSiteCollection siteCollection) { return siteCollection.OrganizationId == organizationId; });
}
paged.TotalRowCount = items.Count;
if (items.Count > maximumRows)
{
items.RemoveRange(maximumRows, items.Count - maximumRows);
}
paged.SiteCollections = items;
return paged;
}
public static List<SharePointSiteCollection> GetSiteCollections(int organizationId)
{
Organization org = OrganizationController.GetOrganization(organizationId);
List<ServiceProviderItem> items = PackageController.GetPackageItemsByType(org.PackageId, typeof(SharePointSiteCollection), false);
items.ConvertAll<SharePointSiteCollection>(delegate(ServiceProviderItem item) { return (SharePointSiteCollection)item; });
List<SharePointSiteCollection> ret = new List<SharePointSiteCollection>();
foreach (ServiceProviderItem item in items)
{
SharePointSiteCollection siteCollection = item as SharePointSiteCollection;
if (siteCollection != null && siteCollection.OrganizationId == organizationId)
{
ret.Add(siteCollection);
}
}
return ret;
}
/// <summary>
/// Gets list of supported languages by this installation of SharePoint.
/// </summary>
/// <returns>List of supported languages</returns>
public static int[] GetSupportedLanguages(int packageId)
{
if (IsDemoMode)
{
return new int[] { 1033 };
}
// Log operation.
TaskManager.StartTask("HOSTEDSHAREPOINT", "GET_LANGUAGES");
int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.SharepointFoundationServer);
if (serviceId == 0)
{
return new int[] { };
}
try
{
// Create site collection on server.
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(serviceId);
return hostedSharePointServer.GetSupportedLanguages();
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
/// <summary>
/// Gets list of SharePoint site collections that belong to the package.
/// </summary>
/// <param name="packageId">Package that owns site collections.</param>
/// <param name="recursive">A value which shows whether nested spaces must be searched as well.</param>
/// <returns>List of found site collections.</returns>
public static List<SharePointSiteCollection> GetSiteCollections(int packageId, bool recursive)
{
if (IsDemoMode)
{
List<SharePointSiteCollection> demoResult = new List<SharePointSiteCollection>();
SharePointSiteCollection siteCollection1 = new SharePointSiteCollection();
siteCollection1.Id = 1;
siteCollection1.OrganizationId = 1;
siteCollection1.LocaleId = 1033;
siteCollection1.Name = "http://john.fabrikam.com";
siteCollection1.OwnerEmail = "john@fabrikam.com";
siteCollection1.OwnerLogin = "john@fabrikam.com";
siteCollection1.OwnerName = "John Smith";
siteCollection1.PhysicalAddress = "http://john.fabrikam.com";
siteCollection1.Title = "John Smith's Team Site";
siteCollection1.Url = "http://john.fabrikam.com";
demoResult.Add(siteCollection1);
SharePointSiteCollection siteCollection2 = new SharePointSiteCollection();
siteCollection2.Id = 2;
siteCollection1.OrganizationId = 1;
siteCollection2.LocaleId = 1033;
siteCollection2.Name = "http://mark.contoso.com";
siteCollection2.OwnerEmail = "mark@contoso.com";
siteCollection2.OwnerLogin = "mark@contoso.com";
siteCollection2.OwnerName = "Mark Jonsons";
siteCollection2.PhysicalAddress = "http://mark.contoso.com";
siteCollection2.Title = "Mark Jonsons' Blog";
siteCollection2.Url = "http://mark.contoso.com";
demoResult.Add(siteCollection2);
return demoResult;
}
List<ServiceProviderItem> items = PackageController.GetPackageItemsByType(packageId, typeof(SharePointSiteCollection), recursive);
return items.ConvertAll<SharePointSiteCollection>(delegate(ServiceProviderItem item) { return (SharePointSiteCollection)item; });
}
/// <summary>
/// Gets SharePoint site collection with given id.
/// </summary>
/// <param name="itemId">Site collection id within metabase.</param>
/// <returns>Site collection or null in case no such item exist.</returns>
public static SharePointSiteCollection GetSiteCollection(int itemId)
{
if (IsDemoMode)
{
return GetSiteCollections(1, false)[itemId - 1];
}
SharePointSiteCollection item = PackageController.GetPackageItem(itemId) as SharePointSiteCollection;
return item;
}
/// <summary>
/// Adds SharePoint site collection.
/// </summary>
/// <param name="item">Site collection description.</param>
/// <returns>Created site collection id within metabase.</returns>
public static int AddSiteCollection(SharePointSiteCollection item)
{
// Check account.
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0)
{
return accountCheck;
}
// Check package.
int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive);
if (packageCheck < 0)
{
return packageCheck;
}
// Check quota.
OrganizationStatistics orgStats = OrganizationController.GetOrganizationStatisticsByOrganization(item.OrganizationId);
//QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, Quotas.HOSTED_SHAREPOINT_SITES);
if (orgStats.AllocatedSharePointSiteCollections > -1
&& orgStats.CreatedSharePointSiteCollections >= orgStats.AllocatedSharePointSiteCollections)
{
return BusinessErrorCodes.ERROR_SHAREPOINT_RESOURCE_QUOTA_LIMIT;
}
// Check if stats resource is available
int serviceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.SharepointFoundationServer);
if (serviceId == 0)
{
return BusinessErrorCodes.ERROR_SHAREPOINT_RESOURCE_UNAVAILABLE;
}
StringDictionary hostedSharePointSettings = ServerController.GetServiceSettings(serviceId);
QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, Quotas.HOSTED_SHAREPOINT_USESHAREDSSL);
Uri rootWebApplicationUri = new Uri(hostedSharePointSettings["RootWebApplicationUri"]);
Organization org = OrganizationController.GetOrganization(item.OrganizationId);
string siteName = item.Name;
if (quota.QuotaAllocatedValue == 1)
{
string sslRoot = hostedSharePointSettings["SharedSSLRoot"];
string defaultDomain = org.DefaultDomain;
string hostNameBase = string.Empty;
string[] tmp = defaultDomain.Split('.');
if (tmp.Length == 2)
{
hostNameBase = tmp[0];
}
else
{
if (tmp.Length > 2)
{
hostNameBase = tmp[0] + tmp[1];
}
}
int counter = 0;
item.Name = String.Format("{0}://{1}", rootWebApplicationUri.Scheme, hostNameBase + "-" + counter.ToString() + "." + sslRoot);
siteName = String.Format("{0}", hostNameBase + "-" + counter.ToString() + "." + sslRoot);
while ( DataProvider. CheckServiceItemExists( serviceId, item. Name, "WebsitePanel.Providers.SharePoint.SharePointSiteCollection, WebsitePanel.Providers.Base"))
{
counter++;
item.Name = String.Format("{0}://{1}", rootWebApplicationUri.Scheme, hostNameBase + "-" + counter.ToString() + "." + sslRoot);
siteName = String.Format("{0}", hostNameBase + "-" + counter.ToString() + "." + sslRoot);
}
}
else
item.Name = String.Format("{0}://{1}", rootWebApplicationUri.Scheme, item.Name);
if (rootWebApplicationUri.Port > 0 && rootWebApplicationUri.Port != 80 && rootWebApplicationUri.Port != 443)
{
item.PhysicalAddress = String.Format("{0}:{1}", item.Name, rootWebApplicationUri.Port);
}
else
{
item.PhysicalAddress = item.Name;
}
if (Utils.ParseBool(hostedSharePointSettings["LocalHostFile"], false))
{
item.RootWebApplicationInteralIpAddress = hostedSharePointSettings["RootWebApplicationInteralIpAddress"];
item.RootWebApplicationFQDN = item.Name.Replace(rootWebApplicationUri.Scheme + "://", "");
}
item.MaxSiteStorage = RecalculateMaxSize(org.MaxSharePointStorage, (int)item.MaxSiteStorage);
item.WarningStorage = item.MaxSiteStorage == -1 ? -1 : Math.Min((int)item.WarningStorage, item.MaxSiteStorage);
// Check package item with given name already exists.
if (PackageController.GetPackageItemByName(item.PackageId, item.Name, typeof(SharePointSiteCollection)) != null)
{
return BusinessErrorCodes.ERROR_SHAREPOINT_PACKAGE_ITEM_EXISTS;
}
// Log operation.
TaskManager.StartTask("HOSTEDSHAREPOINT", "ADD_SITE_COLLECTION", item.Name);
try
{
// Create site collection on server.
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(serviceId);
hostedSharePointServer.CreateSiteCollection(item);
// Make record in metabase.
item.ServiceId = serviceId;
int itemId = PackageController.AddPackageItem(item);
hostedSharePointServer.SetPeoplePickerOu(item.Name, org.DistinguishedName);
int dnsServiceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.Dns);
if (dnsServiceId > 0)
{
string[] tmpStr = siteName.Split('.');
string hostName = tmpStr[0];
string domainName = siteName.Substring(hostName.Length + 1, siteName.Length - (hostName.Length + 1));
List<GlobalDnsRecord> dnsRecords = ServerController.GetDnsRecordsByService(serviceId);
List<DnsRecord> resourceRecords = DnsServerController.BuildDnsResourceRecords(dnsRecords, hostName, domainName, "");
DNSServer dns = new DNSServer();
ServiceProviderProxy.Init(dns, dnsServiceId);
// add new resource records
dns.AddZoneRecords(domainName, resourceRecords.ToArray());
}
TaskManager.ItemId = itemId;
return itemId;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
/// <summary>
/// Deletes SharePoint site collection with given id.
/// </summary>
/// <param name="itemId">Site collection id within metabase.</param>
/// <returns>?</returns>
public static int DeleteSiteCollection(int itemId)
{
// Check account.
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0)
{
return accountCheck;
}
// Load original meta item
SharePointSiteCollection origItem = (SharePointSiteCollection)PackageController.GetPackageItem(itemId);
if (origItem == null)
{
return BusinessErrorCodes.ERROR_SHAREPOINT_PACKAGE_ITEM_NOT_FOUND;
}
// Get service settings.
StringDictionary hostedSharePointSettings = ServerController.GetServiceSettings(origItem.ServiceId);
Uri rootWebApplicationUri = new Uri(hostedSharePointSettings["RootWebApplicationUri"]);
string siteName = origItem.Name.Replace(String.Format("{0}://", rootWebApplicationUri.Scheme), String.Empty);
// Log operation.
TaskManager.StartTask("HOSTEDSHAREPOINT", "DELETE_SITE", origItem.Name, itemId);
try
{
// Delete site collection on server.
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(origItem.ServiceId);
hostedSharePointServer.DeleteSiteCollection(origItem);
// Delete record in metabase.
PackageController.DeletePackageItem(origItem.Id);
int dnsServiceId = PackageController.GetPackageServiceId(origItem.PackageId, ResourceGroups.Dns);
if (dnsServiceId > 0)
{
string[] tmpStr = siteName.Split('.');
string hostName = tmpStr[0];
string domainName = siteName.Substring(hostName.Length + 1, siteName.Length - (hostName.Length + 1));
List<GlobalDnsRecord> dnsRecords = ServerController.GetDnsRecordsByService(origItem.ServiceId);
List<DnsRecord> resourceRecords = DnsServerController.BuildDnsResourceRecords(dnsRecords, hostName, domainName, "");
DNSServer dns = new DNSServer();
ServiceProviderProxy.Init(dns, dnsServiceId);
// add new resource records
dns.DeleteZoneRecords(domainName, resourceRecords.ToArray());
}
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
/// <summary>
/// Deletes SharePoint site collections which belong to organization.
/// </summary>
/// <param name="organizationId">Site collection id within metabase.</param>
public static void DeleteSiteCollections(int organizationId)
{
Organization org = OrganizationController.GetOrganization(organizationId);
SharePointSiteCollectionListPaged existentSiteCollections = GetSiteCollectionsPaged(org.PackageId, org.Id, String.Empty, String.Empty, String.Empty, 0, Int32.MaxValue);
foreach (SharePointSiteCollection existentSiteCollection in existentSiteCollections.SiteCollections)
{
DeleteSiteCollection(existentSiteCollection.Id);
}
}
/// <summary>
/// Backups SharePoint site collection.
/// </summary>
/// <param name="itemId">Site collection id within metabase.</param>
/// <param name="fileName">Backed up site collection file name.</param>
/// <param name="zipBackup">A value which shows whether back up must be archived.</param>
/// <param name="download">A value which shows whether created back up must be downloaded.</param>
/// <param name="folderName">Local folder to store downloaded backup.</param>
/// <returns>Created backup file name. </returns>
public static string BackupSiteCollection(int itemId, string fileName, bool zipBackup, bool download, string folderName)
{
// Check account.
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0)
{
return null;
}
// Load original meta item
SharePointSiteCollection origItem = (SharePointSiteCollection)PackageController.GetPackageItem(itemId);
if (origItem == null)
{
return null;
}
// Log operation.
TaskManager.StartTask("HOSTEDSHAREPOINT", "BACKUP_SITE_COLLECTION", origItem.Name, itemId);
try
{
// Create site collection on server.
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(origItem.ServiceId);
string backFile = hostedSharePointServer.BackupSiteCollection(origItem.Name, fileName, zipBackup);
if (!download)
{
// Copy backup files to space folder.
string relFolderName = FilesController.CorrectRelativePath(folderName);
if (!relFolderName.EndsWith("\\"))
{
relFolderName = relFolderName + "\\";
}
// Create backup folder if not exists
if (!FilesController.DirectoryExists(origItem.PackageId, relFolderName))
{
FilesController.CreateFolder(origItem.PackageId, relFolderName);
}
string packageFile = relFolderName + Path.GetFileName(backFile);
// Delete destination file if exists
if (FilesController.FileExists(origItem.PackageId, packageFile))
{
FilesController.DeleteFiles(origItem.PackageId, new string[] { packageFile });
}
byte[] buffer = null;
int offset = 0;
do
{
// Read remote content.
buffer = hostedSharePointServer.GetTempFileBinaryChunk(backFile, offset, FILE_BUFFER_LENGTH);
// Write remote content.
FilesController.AppendFileBinaryChunk(origItem.PackageId, packageFile, buffer);
offset += FILE_BUFFER_LENGTH;
}
while (buffer.Length == FILE_BUFFER_LENGTH);
}
return backFile;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
/// <summary>
/// Restores SharePoint site collection.
/// </summary>
/// <param name="itemId">Site collection id within metabase.</param>
/// <param name="uploadedFile"></param>
/// <param name="packageFile"></param>
/// <returns></returns>
public static int RestoreSiteCollection(int itemId, string uploadedFile, string packageFile)
{
// Check account.
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0)
{
return accountCheck;
}
// Load original meta item.
SharePointSiteCollection origItem = (SharePointSiteCollection)PackageController.GetPackageItem(itemId);
if (origItem == null)
{
return BusinessErrorCodes.ERROR_SHAREPOINT_PACKAGE_ITEM_NOT_FOUND;
}
// Check package.
int packageCheck = SecurityContext.CheckPackage(origItem.PackageId, DemandPackage.IsActive);
if (packageCheck < 0)
{
return packageCheck;
}
// Log operation.
TaskManager.StartTask("HOSTEDSHAREPOINT", "BACKUP_SITE_COLLECTION", origItem.Name, itemId);
try
{
// Create site collection on server.
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(origItem.ServiceId);
string backupFile = null;
if (!String.IsNullOrEmpty(packageFile))
{
// Copy package files to the remote SharePoint Server.
string path = null;
byte[] buffer = null;
int offset = 0;
do
{
// Read package file.
buffer = FilesController.GetFileBinaryChunk(origItem.PackageId, packageFile, offset, FILE_BUFFER_LENGTH);
// Write remote backup file
string tempPath = hostedSharePointServer.AppendTempFileBinaryChunk(Path.GetFileName(packageFile), path, buffer);
if (path == null)
{
path = tempPath;
backupFile = path;
}
offset += FILE_BUFFER_LENGTH;
}
while (buffer.Length == FILE_BUFFER_LENGTH);
}
else if (!String.IsNullOrEmpty(uploadedFile))
{
// Upladed files.
backupFile = uploadedFile;
}
// Restore.
if (!String.IsNullOrEmpty(backupFile))
{
hostedSharePointServer.RestoreSiteCollection(origItem, backupFile);
}
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
/// <summary>
/// Gets binary data chunk of specified size from specified offset.
/// </summary>
/// <param name="itemId">Item id to obtain realted service id.</param>
/// <param name="path">Path to file to get bunary data chunk from.</param>
/// <param name="offset">Offset from which to start data reading.</param>
/// <param name="length">Binary data chunk length.</param>
/// <returns>Binary data chunk read from file.</returns>
public static byte[] GetBackupBinaryChunk(int itemId, string path, int offset, int length)
{
// Load original meta item.
SharePointSiteCollection item = (SharePointSiteCollection)PackageController.GetPackageItem(itemId);
if (item == null)
{
return null;
}
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(item.ServiceId);
return hostedSharePointServer.GetTempFileBinaryChunk(path, offset, length);
}
/// <summary>
/// Appends supplied binary data chunk to file.
/// </summary>
/// <param name="itemId">Item id to obtain realted service id.</param>
/// <param name="fileName">Non existent file name to append to.</param>
/// <param name="path">Full path to existent file to append to.</param>
/// <param name="chunk">Binary data chunk to append to.</param>
/// <returns>Path to file that was appended with chunk.</returns>
public static string AppendBackupBinaryChunk(int itemId, string fileName, string path, byte[] chunk)
{
// Load original meta item.
SharePointSiteCollection item = (SharePointSiteCollection)PackageController.GetPackageItem(itemId);
if (item == null)
{
return null;
}
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(item.ServiceId);
return hostedSharePointServer.AppendTempFileBinaryChunk(fileName, path, chunk);
}
/// <summary>
/// Initializes a new hosted SharePoint server proxy.
/// </summary>
/// <param name="serviceId">Hosted SharePoint service id.</param>
/// <returns>Hosted SharePoint server proxy.</returns>
private static HostedSharePointServer GetHostedSharePointServer(int serviceId)
{
HostedSharePointServer sps = new HostedSharePointServer();
ServiceProviderProxy.Init(sps, serviceId);
return sps;
}
/// <summary>
/// Gets list of importable items.
/// </summary>
/// <param name="packageId">Package that owns importable items.</param>
/// <param name="itemTypeId">Item type id.</param>
/// <param name="itemType">Item type.</param>
/// <param name="group">Item resource group.</param>
/// <returns>List of importable item names.</returns>
public List<string> GetImportableItems(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group)
{
List<string> items = new List<string>();
// Get service id
int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
if (serviceId == 0)
{
return items;
}
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(serviceId);
if (itemType == typeof(SharePointSiteCollection))
{
foreach (SharePointSiteCollection siteCollection in hostedSharePointServer.GetSiteCollections())
{
items.Add(siteCollection.Url);
}
}
return items;
}
/// <summary>
/// Imports selected item into metabase.
/// </summary>
/// <param name="packageId">Package to which items must be imported.</param>
/// <param name="itemTypeId">Item type id.</param>
/// <param name="itemType">Item type.</param>
/// <param name="group">Item resource group.</param>
/// <param name="itemName">Item name to import.</param>
public void ImportItem(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group, string itemName)
{
// Get service id
int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName);
if (serviceId == 0)
{
return;
}
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(serviceId);
if (itemType == typeof(SharePointSiteCollection))
{
SharePointSiteCollection siteCollection = hostedSharePointServer.GetSiteCollection(itemName);
PackageController.AddPackageItem(siteCollection);
}
}
/// <summary>
/// Backups service item by serializing it into supplied writer.
/// </summary>
/// <param name="tempFolder">Temporary directory path.</param>
/// <param name="writer">Xml wirter used to store backuped service provider items.</param>
/// <param name="item">Service provider item to be backed up..</param>
/// <param name="group">Service provider resource group.</param>
/// <returns>Resulting code.</returns>
public int BackupItem(string tempFolder, XmlWriter writer, ServiceProviderItem item, ResourceGroupInfo group)
{
SharePointSiteCollection siteCollection = item as SharePointSiteCollection;
if (siteCollection != null)
{
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(siteCollection.ServiceId);
SharePointSiteCollection loadedSiteCollection = hostedSharePointServer.GetSiteCollection(siteCollection.Url);
// Update item
siteCollection.Url = loadedSiteCollection.Url;
siteCollection.OwnerLogin = loadedSiteCollection.OwnerLogin;
siteCollection.OwnerName = loadedSiteCollection.OwnerName;
siteCollection.OwnerEmail = loadedSiteCollection.OwnerEmail;
siteCollection.LocaleId = loadedSiteCollection.LocaleId;
siteCollection.Title = loadedSiteCollection.Title;
siteCollection.Description = loadedSiteCollection.Description;
// Serialize it.
XmlSerializer serializer = new XmlSerializer(typeof(SharePointSiteCollection));
serializer.Serialize(writer, siteCollection);
}
return 0;
}
/// <summary>
/// Restore backed up previously service provider item.
/// </summary>
/// <param name="tempFolder">Temporary directory path.</param>
/// <param name="itemNode">Serialized service provider item.</param>
/// <param name="itemId">Service provider item id.</param>
/// <param name="itemType">Service provider item type.</param>
/// <param name="itemName">Service provider item name.</param>
/// <param name="packageId">Service provider item package.</param>
/// <param name="serviceId">Service provider item service id.</param>
/// <param name="group">Service provider item resource group.</param>
/// <returns>Resulting code.</returns>
public int RestoreItem(string tempFolder, XmlNode itemNode, int itemId, Type itemType, string itemName, int packageId, int serviceId, ResourceGroupInfo group)
{
if (itemType == typeof(SharePointSiteCollection))
{
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(serviceId);
// Deserialize item.
XmlSerializer serializer = new XmlSerializer(typeof(SharePointSiteCollection));
SharePointSiteCollection siteCollection = (SharePointSiteCollection)serializer.Deserialize(new XmlNodeReader(itemNode.SelectSingleNode("SharePointSiteCollection")));
siteCollection.PackageId = packageId;
siteCollection.ServiceId = serviceId;
// Create site collection if needed.
if (hostedSharePointServer.GetSiteCollection(siteCollection.Url) == null)
{
hostedSharePointServer.CreateSiteCollection(siteCollection);
}
// Add metabase record if needed.
SharePointSiteCollection metaSiteCollection = (SharePointSiteCollection)PackageController.GetPackageItemByName(packageId, itemName, typeof(SharePointSiteCollection));
if (metaSiteCollection == null)
{
PackageController.AddPackageItem(siteCollection);
}
}
return 0;
}
private static int GetHostedSharePointServiceId(int packageId)
{
return PackageController.GetPackageServiceId(packageId, ResourceGroups.SharepointFoundationServer);
}
private static List<SharePointSiteCollection> GetOrganizationSharePointSiteCollections(int orgId)
{
Organization org = OrganizationController.GetOrganization(orgId);
SharePointSiteCollectionListPaged siteCollections = GetSiteCollectionsPaged(org.PackageId, org.Id, String.Empty, String.Empty, String.Empty, 0, Int32.MaxValue);
return siteCollections.SiteCollections;
}
private static int RecalculateStorageMaxSize(int size, int packageId)
{
PackageContext cntx = PackageController.GetPackageContext(packageId);
QuotaValueInfo quota = cntx.Quotas[Quotas.HOSTED_SHAREPOINT_STORAGE_SIZE];
if (quota.QuotaAllocatedValue == -1)
{
if (size == -1)//Unlimited
return -1;
else
return size;
}
else
{
if (size == -1)
return quota.QuotaAllocatedValue;
return Math.Min(size, quota.QuotaAllocatedValue);
}
}
private static int RecalculateMaxSize(int parentSize, int realSize)
{
if (parentSize == -1)
{
if (realSize == -1 || realSize == 0)
return -1;
else
return realSize;
}
if (realSize == -1 || realSize == 0)
return parentSize;
return Math.Min(parentSize, realSize);
}
public static int SetStorageSettings(int itemId, int maxStorage, int warningStorage, bool applyToSiteCollections)
{
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0) return accountCheck;
// place log record
TaskManager.StartTask("HOSTED_SHAREPOINT", "SET_ORG_LIMITS", itemId);
try
{
Organization org = (Organization)PackageController.GetPackageItem(itemId);
if (org == null)
return 0;
// set limits
int realMaxSizeValue = RecalculateStorageMaxSize(maxStorage, org.PackageId);
org.MaxSharePointStorage = realMaxSizeValue;
org.WarningSharePointStorage = realMaxSizeValue == -1 ? -1 : Math.Min(warningStorage, realMaxSizeValue);
// save organization
UpdateOrganization(org);
if (applyToSiteCollections)
{
int serviceId = GetHostedSharePointServiceId(org.PackageId);
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(serviceId);
List<SharePointSiteCollection> currentOrgSiteCollection =
GetOrganizationSharePointSiteCollections(org.Id);
foreach (SharePointSiteCollection siteCollection in currentOrgSiteCollection)
{
try
{
SharePointSiteCollection sc = GetSiteCollection(siteCollection.Id);
sc.MaxSiteStorage = realMaxSizeValue;
sc.WarningStorage = realMaxSizeValue == -1 ? -1 : warningStorage;
PackageController.UpdatePackageItem(sc);
hostedSharePointServer.UpdateQuotas(siteCollection.PhysicalAddress, realMaxSizeValue,
warningStorage);
}
catch (Exception ex)
{
TaskManager.WriteError(ex);
}
}
}
return 0;
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
public static SharePointSiteDiskSpace[] CalculateSharePointSitesDiskSpace(int itemId, out int errorCode)
{
SharePointSiteDiskSpace[] retDiskSpace = null;
errorCode = 0;
// check account
int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive);
if (accountCheck < 0)
{
errorCode = accountCheck;
return null;
}
// place log record
TaskManager.StartTask("HOSTED_SHAREPOINT", "CALCULATE_DISK_SPACE", itemId);
try
{
Organization org = (Organization)PackageController.GetPackageItem(itemId);
if (org == null)
return null;
int serviceId = GetHostedSharePointServiceId(org.PackageId);
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(serviceId);
List<SharePointSiteCollection> currentOrgSiteCollection =
GetOrganizationSharePointSiteCollections(org.Id);
List<string> urls = new List<string>();
foreach (SharePointSiteCollection siteCollection in currentOrgSiteCollection)
{
urls.Add(siteCollection.PhysicalAddress);
}
if (urls.Count > 0)
retDiskSpace = hostedSharePointServer.CalculateSiteCollectionsDiskSpace(urls.ToArray());
else
{
retDiskSpace = new SharePointSiteDiskSpace[1];
retDiskSpace[0] = new SharePointSiteDiskSpace();
retDiskSpace[0].DiskSpace = 0;
retDiskSpace[0].Url = string.Empty;
}
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
return retDiskSpace;
}
private static void UpdateOrganization(Organization organization)
{
PackageController.UpdatePackageItem(organization);
}
public static void UpdateQuota(int itemId, int siteCollectionId, int maxStorage, int warningStorage)
{
TaskManager.StartTask("HOSTED_SHAREPOINT", "UPDATE_QUOTA");
try
{
Organization org = (Organization)PackageController.GetPackageItem(itemId);
if (org == null)
return;
int serviceId = GetHostedSharePointServiceId(org.PackageId);
HostedSharePointServer hostedSharePointServer = GetHostedSharePointServer(serviceId);
SharePointSiteCollection sc = GetSiteCollection(siteCollectionId);
int maxSize = RecalculateMaxSize(org.MaxSharePointStorage, maxStorage);
int warningSize = warningStorage;
sc.MaxSiteStorage = maxSize;
sc.WarningStorage = maxSize == -1 ? -1 : Math.Min(warningSize, maxSize);
PackageController.UpdatePackageItem(sc);
hostedSharePointServer.UpdateQuotas(sc.PhysicalAddress, maxSize,
warningStorage);
}
catch (Exception ex)
{
throw TaskManager.WriteError(ex);
}
finally
{
TaskManager.CompleteTask();
}
}
/// <summary>
/// Gets a value if caller is in demo mode.
/// </summary>
private static bool IsDemoMode
{
get
{
return (SecurityContext.CheckAccount(DemandAccount.NotDemo) < 0);
}
}
}
}
| |
// 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.Linq;
using Xunit;
namespace System.Collections.Specialized.Tests
{
public static class StringCollectionTests
{
private const string ElementNotPresent = "element-not-present";
/// <summary>
/// Data used for testing with Insert.
/// </summary>
/// Format is:
/// 1. initial Collection
/// 2. internal data
/// 3. data to insert (ElementNotPresent or null)
/// 4. location to insert (0, count / 2, count)
/// <returns>Row of data</returns>
public static IEnumerable<object[]> Insert_Data()
{
foreach (object[] data in StringCollection_Data().Concat(StringCollection_Duplicates_Data()))
{
string[] d = (string[])(data[1]);
foreach (string element in new[] { ElementNotPresent, null })
{
foreach (int location in new[] { 0, d.Length / 2, d.Length }.Distinct())
{
StringCollection initial = new StringCollection();
initial.AddRange(d);
yield return new object[] { initial, d, element, location };
}
}
}
}/// <summary>
/// Data used for testing with RemoveAt.
/// </summary>
/// Format is:
/// 1. initial Collection
/// 2. internal data
/// 3. location to remove (0, count / 2, count)
/// <returns>Row of data</returns>
public static IEnumerable<object[]> RemoveAt_Data()
{
foreach (object[] data in StringCollection_Data().Concat(StringCollection_Duplicates_Data()))
{
string[] d = (string[])(data[1]);
if (d.Length > 0)
{
foreach (int location in new[] { 0, d.Length / 2, d.Length - 1 }.Distinct())
{
StringCollection initial = new StringCollection();
initial.AddRange(d);
yield return new object[] { initial, d, location };
}
}
}
}
/// <summary>
/// Data used for testing with a set of collections.
/// </summary>
/// Format is:
/// 1. Collection
/// 2. internal data
/// <returns>Row of data</returns>
public static IEnumerable<object[]> StringCollection_Data()
{
yield return ConstructRow(new string[] { /* empty */ });
yield return ConstructRow(new string[] { null });
yield return ConstructRow(new string[] { "single" });
yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x.ToString()).ToArray());
for (int index = 0; index < 100; index += 25)
{
yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x == index ? null : x.ToString()).ToArray());
}
}
/// <summary>
/// Data used for testing with a set of collections, where the data has duplicates.
/// </summary>
/// Format is:
/// 1. Collection
/// 2. internal data
/// <returns>Row of data</returns>
public static IEnumerable<object[]> StringCollection_Duplicates_Data()
{
yield return ConstructRow(Enumerable.Range(0, 100).Select(x => (string)null).ToArray());
yield return ConstructRow(Enumerable.Range(0, 100).Select(x => x % 10 == 0 ? null : (x % 10).ToString()).ToArray());
yield return ConstructRow(Enumerable.Range(0, 100).Select(x => (x % 10).ToString()).ToArray());
}
private static object[] ConstructRow(string[] data)
{
if (data.Contains(ElementNotPresent)) throw new ArgumentException("Do not include \"" + ElementNotPresent + "\" in data.");
StringCollection col = new StringCollection();
col.AddRange(data);
return new object[] { col, data };
}
[Fact]
public static void Constructor_DefaultTest()
{
StringCollection sc = new StringCollection();
Assert.Equal(0, sc.Count);
Assert.False(sc.Contains(null));
Assert.False(sc.Contains(""));
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void AddTest(StringCollection collection, string[] data)
{
StringCollection added = new StringCollection();
for (int i = 0; i < data.Length; i++)
{
Assert.Equal(i, added.Count);
Assert.Throws<ArgumentOutOfRangeException>(() => added[i]);
added.Add(data[i]);
Assert.Equal(data[i], added[i]);
Assert.Equal(i + 1, added.Count);
}
Assert.Equal(collection, added);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void Add_ExplicitInterface_Test(StringCollection collection, string[] data)
{
IList added = new StringCollection();
for (int i = 0; i < data.Length; i++)
{
Assert.Equal(i, added.Count);
Assert.Throws<ArgumentOutOfRangeException>(() => added[i]);
added.Add(data[i]);
Assert.Equal(data[i], added[i]);
Assert.Equal(i + 1, added.Count);
}
Assert.Equal(collection, added);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void AddRangeTest(StringCollection collection, string[] data)
{
StringCollection added = new StringCollection();
added.AddRange(data);
Assert.Equal(collection, added);
added.AddRange(new string[] { /*empty*/});
Assert.Equal(collection, added);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void AddRange_NullTest(StringCollection collection, string[] data)
{
_ = data;
AssertExtensions.Throws<ArgumentNullException>("value", () => collection.AddRange(null));
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void ClearTest(StringCollection collection, string[] data)
{
Assert.Equal(data.Length, collection.Count);
collection.Clear();
Assert.Equal(0, collection.Count);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void CopyToTest(StringCollection collection, string[] data)
{
string[] full = new string[data.Length];
collection.CopyTo(full, 0);
Assert.Equal(data, full);
string[] large = new string[data.Length * 2];
collection.CopyTo(large, data.Length / 4);
for (int i = 0; i < large.Length; i++)
{
if (i < data.Length / 4 || i >= data.Length + data.Length / 4)
{
Assert.Null(large[i]);
}
else
{
Assert.Equal(data[i - data.Length / 4], large[i]);
}
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void CopyTo_ExplicitInterface_Test(ICollection collection, string[] data)
{
string[] full = new string[data.Length];
collection.CopyTo(full, 0);
Assert.Equal(data, full);
string[] large = new string[data.Length * 2];
collection.CopyTo(large, data.Length / 4);
for (int i = 0; i < large.Length; i++)
{
if (i < data.Length / 4 || i >= data.Length + data.Length / 4)
{
Assert.Null(large[i]);
}
else
{
Assert.Equal(data[i - data.Length / 4], large[i]);
}
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void CopyTo_ArgumentInvalidTest(StringCollection collection, string[] data)
{
Assert.Throws<ArgumentNullException>(() => collection.CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => collection.CopyTo(data, -1));
if (data.Length > 0)
{
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => collection.CopyTo(new string[0], data.Length - 1));
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => collection.CopyTo(new string[data.Length - 1], 0));
}
// As explicit interface implementation
Assert.Throws<ArgumentNullException>(() => ((ICollection)collection).CopyTo(null, 0));
Assert.Throws<ArgumentOutOfRangeException>(() => ((ICollection)collection).CopyTo(data, -1));
if (data.Length > 0)
{
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => ((ICollection)collection).CopyTo(new string[0], data.Length - 1));
AssertExtensions.Throws<ArgumentException>("destinationArray", "", () => ((ICollection)collection).CopyTo(new string[data.Length - 1], 0));
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void CountTest(StringCollection collection, string[] data)
{
Assert.Equal(data.Length, collection.Count);
collection.Clear();
Assert.Equal(0, collection.Count);
collection.Add("one");
Assert.Equal(1, collection.Count);
collection.AddRange(data);
Assert.Equal(1 + data.Length, collection.Count);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void ContainsTest(StringCollection collection, string[] data)
{
Assert.All(data, element => Assert.True(collection.Contains(element)));
Assert.All(data, element => Assert.True(((IList)collection).Contains(element)));
Assert.False(collection.Contains(ElementNotPresent));
Assert.False(((IList)collection).Contains(ElementNotPresent));
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void GetEnumeratorTest(StringCollection collection, string[] data)
{
bool repeat = true;
StringEnumerator enumerator = collection.GetEnumerator();
Assert.NotNull(enumerator);
while (repeat)
{
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
foreach (string element in data)
{
Assert.True(enumerator.MoveNext());
Assert.Equal(element, enumerator.Current);
Assert.Equal(element, enumerator.Current);
}
Assert.False(enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Current);
Assert.False(enumerator.MoveNext());
enumerator.Reset();
enumerator.Reset();
repeat = false;
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void GetEnumerator_ModifiedCollectionTest(StringCollection collection, string[] data)
{
StringEnumerator enumerator = collection.GetEnumerator();
Assert.NotNull(enumerator);
if (data.Length > 0)
{
Assert.True(enumerator.MoveNext());
string current = enumerator.Current;
Assert.Equal(data[0], current);
collection.RemoveAt(0);
if (data.Length > 1 && data[0] != data[1])
{
Assert.NotEqual(current, collection[0]);
}
Assert.Equal(current, enumerator.Current);
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
Assert.Throws<InvalidOperationException>(() => enumerator.Reset());
}
else
{
collection.Add("newValue");
Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext());
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void GetSetTest(StringCollection collection, string[] data)
{
for (int i = 0; i < data.Length; i++)
{
Assert.Equal(data[i], collection[i]);
}
for (int i = 0; i < data.Length / 2; i++)
{
string temp = collection[i];
collection[i] = collection[data.Length - i - 1];
collection[data.Length - i - 1] = temp;
}
for (int i = 0; i < data.Length; i++)
{
Assert.Equal(data[data.Length - i - 1], collection[i]);
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void GetSet_ExplicitInterface_Test(IList collection, string[] data)
{
for (int i = 0; i < data.Length; i++)
{
Assert.Equal(data[i], collection[i]);
}
for (int i = 0; i < data.Length / 2; i++)
{
object temp = collection[i];
if (temp != null)
{
Assert.IsType<string>(temp);
}
collection[i] = collection[data.Length - i - 1];
collection[data.Length - i - 1] = temp;
}
for (int i = 0; i < data.Length; i++)
{
Assert.Equal(data[data.Length - i - 1], collection[i]);
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void GetSet_ArgumentInvalidTest(StringCollection collection, string[] data)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = ElementNotPresent);
Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1] = null);
Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length] = ElementNotPresent);
Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length] = null);
Assert.Throws<ArgumentOutOfRangeException>(() => collection[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => collection[data.Length]);
// As explicitly implementing the interface
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1] = ElementNotPresent);
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1] = null);
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length] = ElementNotPresent);
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length] = null);
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[-1]);
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection)[data.Length]);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void IndexOfTest(StringCollection collection, string[] data)
{
Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), collection.IndexOf(element)));
Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), ((IList)collection).IndexOf(element)));
Assert.Equal(-1, collection.IndexOf(ElementNotPresent));
Assert.Equal(-1, ((IList)collection).IndexOf(ElementNotPresent));
}
[Theory]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void IndexOf_DuplicateTest(StringCollection collection, string[] data)
{
// Only the index of the first element will be returned.
data = data.Distinct().ToArray();
Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), collection.IndexOf(element)));
Assert.All(data, element => Assert.Equal(Array.IndexOf(data, element), ((IList)collection).IndexOf(element)));
Assert.Equal(-1, collection.IndexOf(ElementNotPresent));
Assert.Equal(-1, ((IList)collection).IndexOf(ElementNotPresent));
}
[Theory]
[MemberData(nameof(Insert_Data))]
public static void InsertTest(StringCollection collection, string[] data, string element, int location)
{
collection.Insert(location, element);
Assert.Equal(data.Length + 1, collection.Count);
if (element == ElementNotPresent)
{
Assert.Equal(location, collection.IndexOf(ElementNotPresent));
}
for (int i = 0; i < data.Length + 1; i++)
{
if (i < location)
{
Assert.Equal(data[i], collection[i]);
}
else if (i == location)
{
Assert.Equal(element, collection[i]);
}
else
{
Assert.Equal(data[i - 1], collection[i]);
}
}
}
[Theory]
[MemberData(nameof(Insert_Data))]
public static void Insert_ExplicitInterface_Test(IList collection, string[] data, string element, int location)
{
collection.Insert(location, element);
Assert.Equal(data.Length + 1, collection.Count);
if (element == ElementNotPresent)
{
Assert.Equal(location, collection.IndexOf(ElementNotPresent));
}
for (int i = 0; i < data.Length + 1; i++)
{
if (i < location)
{
Assert.Equal(data[i], collection[i]);
}
else if (i == location)
{
Assert.Equal(element, collection[i]);
}
else
{
Assert.Equal(data[i - 1], collection[i]);
}
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void Insert_ArgumentInvalidTest(StringCollection collection, string[] data)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(-1, ElementNotPresent));
Assert.Throws<ArgumentOutOfRangeException>(() => collection.Insert(data.Length + 1, ElementNotPresent));
// And as explicit interface implementation
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection).Insert(-1, ElementNotPresent));
Assert.Throws<ArgumentOutOfRangeException>(() => ((IList)collection).Insert(data.Length + 1, ElementNotPresent));
}
[Fact]
public static void IsFixedSizeTest()
{
Assert.False(((IList)new StringCollection()).IsFixedSize);
}
[Fact]
public static void IsReadOnlyTest()
{
Assert.False(new StringCollection().IsReadOnly);
Assert.False(((IList)new StringCollection()).IsReadOnly);
}
[Fact]
public static void IsSynchronizedTest()
{
Assert.False(new StringCollection().IsSynchronized);
Assert.False(((IList)new StringCollection()).IsSynchronized);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
public static void RemoveTest(StringCollection collection, string[] data)
{
Assert.All(data, element =>
{
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
collection.Remove(element);
Assert.False(collection.Contains(element));
Assert.False(((IList)collection).Contains(element));
});
Assert.Equal(0, collection.Count);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
public static void Remove_IListTest(StringCollection collection, string[] data)
{
Assert.All(data, element =>
{
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
((IList)collection).Remove(element);
Assert.False(collection.Contains(element));
Assert.False(((IList)collection).Contains(element));
});
Assert.Equal(0, collection.Count);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void Remove_NotPresentTest(StringCollection collection, string[] data)
{
collection.Remove(ElementNotPresent);
Assert.Equal(data.Length, collection.Count);
((IList)collection).Remove(ElementNotPresent);
Assert.Equal(data.Length, collection.Count);
}
[Theory]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void Remove_DuplicateTest(StringCollection collection, string[] data)
{
// Only the first element will be removed.
string[] first = data.Distinct().ToArray();
Assert.All(first, element =>
{
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
collection.Remove(element);
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
});
Assert.Equal(data.Length - first.Length, collection.Count);
for (int i = first.Length; i < data.Length; i++)
{
string element = data[i];
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
collection.Remove(element);
bool stillPresent = i < data.Length - first.Length;
Assert.Equal(stillPresent, collection.Contains(element));
Assert.Equal(stillPresent, ((IList)collection).Contains(element));
}
Assert.Equal(0, collection.Count);
}
[Theory]
[MemberData(nameof(RemoveAt_Data))]
public static void RemoveAtTest(StringCollection collection, string[] data, int location)
{
collection.RemoveAt(location);
Assert.Equal(data.Length - 1, collection.Count);
for (int i = 0; i < data.Length - 1; i++)
{
if (i < location)
{
Assert.Equal(data[i], collection[i]);
}
else if (i >= location)
{
Assert.Equal(data[i + 1], collection[i]);
}
}
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void RemoveAt_ArgumentInvalidTest(StringCollection collection, string[] data)
{
Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(-1));
Assert.Throws<ArgumentOutOfRangeException>(() => collection.RemoveAt(data.Length));
}
[Theory]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void Remove_Duplicate_IListTest(StringCollection collection, string[] data)
{
// Only the first element will be removed.
string[] first = data.Distinct().ToArray();
Assert.All(first, element =>
{
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
((IList)collection).Remove(element);
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
});
Assert.Equal(data.Length - first.Length, collection.Count);
for (int i = first.Length; i < data.Length; i++)
{
string element = data[i];
Assert.True(collection.Contains(element));
Assert.True(((IList)collection).Contains(element));
((IList)collection).Remove(element);
bool stillPresent = i < data.Length - first.Length;
Assert.Equal(stillPresent, collection.Contains(element));
Assert.Equal(stillPresent, ((IList)collection).Contains(element));
}
Assert.Equal(0, collection.Count);
}
[Theory]
[MemberData(nameof(StringCollection_Data))]
[MemberData(nameof(StringCollection_Duplicates_Data))]
public static void SyncRootTest(StringCollection collection, string[] data)
{
object syncRoot = collection.SyncRoot;
Assert.NotNull(syncRoot);
Assert.IsType<ArrayList>(syncRoot);
Assert.Same(syncRoot, collection.SyncRoot);
Assert.NotSame(syncRoot, new StringCollection().SyncRoot);
StringCollection other = new StringCollection();
other.AddRange(data);
Assert.NotSame(syncRoot, other.SyncRoot);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Facebook
{
sealed class AndroidFacebook : AbstractFacebook, IFacebook
{
public const int BrowserDialogMode = 0;
private const string AndroidJavaFacebookClass = "com.facebook.unity.FB";
private const string CallbackIdKey = "callback_id";
// key Hash used for Android SDK
private string keyHash;
public string KeyHash { get { return keyHash; } }
#region IFacebook
public override int DialogMode { get { return BrowserDialogMode; } set { } }
public override bool LimitEventUsage
{
get
{
return limitEventUsage;
}
set
{
limitEventUsage = value;
CallFB("SetLimitEventUsage", value.ToString());
}
}
#endregion
private FacebookDelegate deepLinkDelegate;
#region FBJava
#if UNITY_ANDROID
private AndroidJavaClass fbJava;
private AndroidJavaClass FB
{
get
{
if (fbJava == null)
{
fbJava = new AndroidJavaClass(AndroidJavaFacebookClass);
if (fbJava == null)
{
throw new MissingReferenceException(string.Format("AndroidFacebook failed to load {0} class", AndroidJavaFacebookClass));
}
}
return fbJava;
}
}
#endif
private void CallFB(string method, string args)
{
#if UNITY_ANDROID
FB.CallStatic(method, args);
#else
FbDebug.Error("Using Android when not on an Android build! Doesn't Work!");
#endif
}
#endregion
#region FBAndroid
protected override void OnAwake()
{
keyHash = "";
#if DEBUG
AndroidJNIHelper.debug = true;
#endif
}
private bool IsErrorResponse(string response)
{
//var res = MiniJSON.Json.Deserialize(response);
return false;
}
private InitDelegate onInitComplete = null;
public override void Init(
InitDelegate onInitComplete,
string appId,
bool cookie = false,
bool logging = true,
bool status = true,
bool xfbml = false,
string channelUrl = "",
string authResponse = null,
bool frictionlessRequests = false,
HideUnityDelegate hideUnityDelegate = null)
{
if (string.IsNullOrEmpty(appId))
{
throw new ArgumentException("appId cannot be null or empty!");
}
var parameters = new Dictionary<string, object>();
parameters.Add("appId", appId);
if (cookie != false)
{
parameters.Add("cookie", true);
}
if (logging != true)
{
parameters.Add("logging", false);
}
if (status != true)
{
parameters.Add("status", false);
}
if (xfbml != false)
{
parameters.Add("xfbml", true);
}
if (!string.IsNullOrEmpty(channelUrl))
{
parameters.Add("channelUrl", channelUrl);
}
if (!string.IsNullOrEmpty(authResponse))
{
parameters.Add("authResponse", authResponse);
}
if (frictionlessRequests != false)
{
parameters.Add("frictionlessRequests", true);
}
var paramJson = MiniJSON.Json.Serialize(parameters);
this.onInitComplete = onInitComplete;
this.CallFB("Init", paramJson.ToString());
}
public void OnInitComplete(string message)
{
OnLoginComplete(message);
if (this.onInitComplete != null)
{
this.onInitComplete();
}
}
public override void Login(string scope = "", FacebookDelegate callback = null)
{
var parameters = new Dictionary<string, object>();
parameters.Add("scope", scope);
var paramJson = MiniJSON.Json.Serialize(parameters);
AddAuthDelegate(callback);
this.CallFB("Login", paramJson);
}
public void OnLoginComplete(string message)
{
var parameters = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message);
if (parameters.ContainsKey("user_id"))
{
isLoggedIn = true;
userId = (string)parameters["user_id"];
accessToken = (string)parameters["access_token"];
accessTokenExpiresAt = FromTimestamp(int.Parse((string)parameters["expiration_timestamp"]));
}
if (parameters.ContainsKey("key_hash"))
{
keyHash = (string)parameters["key_hash"];
}
OnAuthResponse(new FBResult(message));
}
//TODO: move into AbstractFacebook
public void OnAccessTokenRefresh(string message)
{
var parameters = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message);
if (parameters.ContainsKey("access_token"))
{
accessToken = (string)parameters["access_token"];
accessTokenExpiresAt = FromTimestamp(int.Parse((string)parameters["expiration_timestamp"]));
}
}
public override void Logout()
{
this.CallFB("Logout", "");
}
public void OnLogoutComplete(string message)
{
isLoggedIn = false;
userId = "";
accessToken = "";
}
public override void AppRequest(
string message,
string[] to = null,
string filters = "",
string[] excludeIds = null,
int? maxRecipients = null,
string data = "",
string title = "",
FacebookDelegate callback = null)
{
Dictionary<string, object> paramsDict = new Dictionary<string, object>();
// Marshal all the above into the thing
paramsDict["message"] = message;
if (callback != null)
{
paramsDict["callback_id"] = AddFacebookDelegate(callback);
}
if (to != null)
{
paramsDict["to"] = string.Join(",", to);
}
if (!string.IsNullOrEmpty(filters))
{
paramsDict["filters"] = filters;
}
if (maxRecipients != null)
{
paramsDict["max_recipients"] = maxRecipients.Value;
}
if (!string.IsNullOrEmpty(data))
{
paramsDict["data"] = data;
}
if (!string.IsNullOrEmpty(title))
{
paramsDict["title"] = title;
}
CallFB("AppRequest", MiniJSON.Json.Serialize(paramsDict));
}
public void OnAppRequestsComplete(string message)
{
var rawResult = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message);
if (rawResult.ContainsKey(CallbackIdKey))
{
var result = new Dictionary<string, object>();
var callbackId = (string)rawResult[CallbackIdKey];
rawResult.Remove(CallbackIdKey);
if (rawResult.Count > 0)
{
List<string> to = new List<string>(rawResult.Count - 1);
foreach (string key in rawResult.Keys)
{
if (!key.StartsWith("to"))
{
result[key] = rawResult[key];
continue;
}
to.Add((string)rawResult[key]);
}
result.Add("to", to);
rawResult.Clear();
OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result)));
}
else
{
//if we make it here java returned a callback message with only an id
//this isnt supposed to happen
OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result), "Malformed request response. Please file a bug with facebook here: https://developers.facebook.com/bugs/create"));
}
}
}
public override void FeedRequest(
string toId = "",
string link = "",
string linkName = "",
string linkCaption = "",
string linkDescription = "",
string picture = "",
string mediaSource = "",
string actionName = "",
string actionLink = "",
string reference = "",
Dictionary<string, string[]> properties = null,
FacebookDelegate callback = null)
{
Dictionary<string, object> paramsDict = new Dictionary<string, object>();
// Marshal all the above into the thing
if (callback != null)
{
paramsDict["callback_id"] = AddFacebookDelegate(callback);
}
if (!string.IsNullOrEmpty(toId))
{
paramsDict.Add("to", toId);
}
if (!string.IsNullOrEmpty(link))
{
paramsDict.Add("link", link);
}
if (!string.IsNullOrEmpty(linkName))
{
paramsDict.Add("name", linkName);
}
if (!string.IsNullOrEmpty(linkCaption))
{
paramsDict.Add("caption", linkCaption);
}
if (!string.IsNullOrEmpty(linkDescription))
{
paramsDict.Add("description", linkDescription);
}
if (!string.IsNullOrEmpty(picture))
{
paramsDict.Add("picture", picture);
}
if (!string.IsNullOrEmpty(mediaSource))
{
paramsDict.Add("source", mediaSource);
}
if (!string.IsNullOrEmpty(actionName) && !string.IsNullOrEmpty(actionLink))
{
Dictionary<string, object> dict = new Dictionary<string, object>();
dict.Add("name", actionName);
dict.Add("link", actionLink);
paramsDict.Add("actions", new[] { dict });
}
if (!string.IsNullOrEmpty(reference))
{
paramsDict.Add("ref", reference);
}
if (properties != null)
{
Dictionary<string, object> newObj = new Dictionary<string, object>();
foreach (KeyValuePair<string, string[]> pair in properties)
{
if (pair.Value.Length < 1)
continue;
if (pair.Value.Length == 1)
{
// String-string
newObj.Add(pair.Key, pair.Value[0]);
}
else
{
// String-Object with two parameters
Dictionary<string, object> innerObj = new Dictionary<string, object>();
innerObj.Add("text", pair.Value[0]);
innerObj.Add("href", pair.Value[1]);
newObj.Add(pair.Key, innerObj);
}
}
paramsDict.Add("properties", newObj);
}
CallFB("FeedRequest", MiniJSON.Json.Serialize(paramsDict));
}
public void OnFeedRequestComplete(string message)
{
var rawResult = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message);
if (rawResult.ContainsKey(CallbackIdKey))
{
var result = new Dictionary<string, object>();
var callbackId = (string)rawResult[CallbackIdKey];
rawResult.Remove(CallbackIdKey);
if (rawResult.Count > 0)
{
foreach (string key in rawResult.Keys)
{
result[key] = rawResult[key];
}
rawResult.Clear();
OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result)));
}
else
{
//if we make it here java returned a callback message with only a callback id
//this isnt supposed to happen
OnFacebookResponse(callbackId, new FBResult(MiniJSON.Json.Serialize(result), "Malformed request response. Please file a bug with facebook here: https://developers.facebook.com/bugs/create"));
}
}
}
public override void Pay(
string product,
string action = "purchaseitem",
int quantity = 1,
int? quantityMin = null,
int? quantityMax = null,
string requestId = null,
string pricepointId = null,
string testCurrency = null,
FacebookDelegate callback = null)
{
throw new PlatformNotSupportedException("There is no Facebook Pay Dialog on Android");
}
public override void GetDeepLink(FacebookDelegate callback)
{
if (callback != null)
{
deepLinkDelegate = callback;
CallFB("GetDeepLink", "");
}
}
public void OnGetDeepLinkComplete(string message)
{
var rawResult = (Dictionary<string, object>) MiniJSON.Json.Deserialize(message);
if (deepLinkDelegate != null)
{
object deepLink = "";
rawResult.TryGetValue("deep_link", out deepLink);
deepLinkDelegate(new FBResult(deepLink.ToString()));
}
}
public override void AppEventsLogEvent(
string logEvent,
float? valueToSum = null,
Dictionary<string, object> parameters = null)
{
var paramsDict = new Dictionary<string, object>();
paramsDict["logEvent"] = logEvent;
if (valueToSum.HasValue)
{
paramsDict["valueToSum"] = valueToSum.Value;
}
if (parameters != null)
{
paramsDict["parameters"] = ToStringDict(parameters);
}
CallFB("AppEvents", MiniJSON.Json.Serialize(paramsDict));
}
public override void AppEventsLogPurchase(
float logPurchase,
string currency = "USD",
Dictionary<string, object> parameters = null)
{
var paramsDict = new Dictionary<string, object>();
paramsDict["logPurchase"] = logPurchase;
paramsDict["currency"] = (!string.IsNullOrEmpty(currency)) ? currency : "USD";
if (parameters != null)
{
paramsDict["parameters"] = ToStringDict(parameters);
}
CallFB("AppEvents", MiniJSON.Json.Serialize(paramsDict));
}
#endregion
#region Helper Functions
public override void PublishInstall(string appId, FacebookDelegate callback = null)
{
var parameters = new Dictionary<string, string>(2);
parameters["app_id"] = appId;
if (callback != null)
{
parameters["callback_id"] = AddFacebookDelegate(callback);
}
CallFB("PublishInstall", MiniJSON.Json.Serialize(parameters));
}
public void OnPublishInstallComplete(string message)
{
var response = (Dictionary<string, object>)MiniJSON.Json.Deserialize(message);
if (response.ContainsKey("callback_id"))
{
OnFacebookResponse((string)response["callback_id"], new FBResult(""));
}
}
private Dictionary<string, string> ToStringDict(Dictionary<string, object> dict)
{
if (dict == null)
{
return null;
}
var newDict = new Dictionary<string, string>();
foreach (KeyValuePair<string, object> kvp in dict)
{
newDict[kvp.Key] = kvp.Value.ToString();
}
return newDict;
}
//TODO: move into AbstractFacebook
private DateTime FromTimestamp(int timestamp)
{
return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(timestamp);
}
#endregion
}
}
| |
/*
* 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 System;
using System.Collections.Generic;
using System.Diagnostics;
using QuantConnect.Data;
using QuantConnect.Logging;
namespace QuantConnect.Indicators
{
/// <summary>
/// Provides a base type for all indicators
/// </summary>
/// <typeparam name="T">The type of data input into this indicator</typeparam>
[DebuggerDisplay("{ToDetailedString()}")]
public abstract partial class IndicatorBase<T> : IIndicator<T>
where T : IBaseData
{
/// <summary>the most recent input that was given to this indicator</summary>
private Dictionary<SecurityIdentifier, T> _previousInput = new Dictionary<SecurityIdentifier, T>();
/// <summary>
/// Event handler that fires after this indicator is updated
/// </summary>
public event IndicatorUpdatedHandler Updated;
/// <summary>
/// Initializes a new instance of the Indicator class using the specified name.
/// </summary>
/// <param name="name">The name of this indicator</param>
protected IndicatorBase(string name)
{
Name = name;
Current = new IndicatorDataPoint(DateTime.MinValue, 0m);
}
/// <summary>
/// Gets a name for this indicator
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Gets a flag indicating when this indicator is ready and fully initialized
/// </summary>
public abstract bool IsReady { get; }
/// <summary>
/// Gets the current state of this indicator. If the state has not been updated
/// then the time on the value will equal DateTime.MinValue.
/// </summary>
public IndicatorDataPoint Current { get; protected set; }
/// <summary>
/// Gets the number of samples processed by this indicator
/// </summary>
public long Samples { get; private set; }
/// <summary>
/// Updates the state of this indicator with the given value and returns true
/// if this indicator is ready, false otherwise
/// </summary>
/// <param name="input">The value to use to update this indicator</param>
/// <returns>True if this indicator is ready, false otherwise</returns>
public bool Update(IBaseData input)
{
T _previousSymbolInput = default(T);
if (_previousInput.TryGetValue(input.Symbol.ID, out _previousSymbolInput) && input.EndTime < _previousSymbolInput.EndTime)
{
// if we receive a time in the past, log and return
Log.Error($"This is a forward only indicator: {Name} Input: {input.EndTime:u} Previous: {_previousSymbolInput.EndTime:u}. It will not be updated with this input.");
return IsReady;
}
if (!ReferenceEquals(input, _previousSymbolInput))
{
// compute a new value and update our previous time
Samples++;
if (!(input is T))
{
throw new ArgumentException($"IndicatorBase.Update() 'input' expected to be of type {typeof(T)} but is of type {input.GetType()}");
}
_previousInput[input.Symbol.ID] = (T)input;
var nextResult = ValidateAndComputeNextValue((T)input);
if (nextResult.Status == IndicatorStatus.Success)
{
Current = new IndicatorDataPoint(input.EndTime, nextResult.Value);
// let others know we've produced a new data point
OnUpdated(Current);
}
}
return IsReady;
}
/// <summary>
/// Updates the state of this indicator with the given value and returns true
/// if this indicator is ready, false otherwise
/// </summary>
/// <param name="time">The time associated with the value</param>
/// <param name="value">The value to use to update this indicator</param>
/// <returns>True if this indicator is ready, false otherwise</returns>
public bool Update(DateTime time, decimal value)
{
if (typeof(T) == typeof(IndicatorDataPoint))
{
return Update((T)(object)new IndicatorDataPoint(time, value));
}
var suggestions = new List<string>
{
"Update(TradeBar)",
"Update(QuoteBar)"
};
if (typeof(T) == typeof(IBaseData))
{
suggestions.Add("Update(Tick)");
}
throw new NotSupportedException($"{GetType().Name} does not support the `Update(DateTime, decimal)` method. Use one of the following methods instead: {string.Join(", ", suggestions)}");
}
/// <summary>
/// Resets this indicator to its initial state
/// </summary>
public virtual void Reset()
{
Samples = 0;
_previousInput.Clear();
Current = new IndicatorDataPoint(DateTime.MinValue, default(decimal));
}
/// <summary>
/// Compares the current object with another object of the same type.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has the following meanings: Value Meaning Less than zero This object is less than the <paramref name="other"/> parameter.Zero This object is equal to <paramref name="other"/>. Greater than zero This object is greater than <paramref name="other"/>.
/// </returns>
/// <param name="other">An object to compare with this object.</param>
public int CompareTo(IIndicator<T> other)
{
if (ReferenceEquals(other, null))
{
// everything is greater than null via MSDN
return 1;
}
return Current.CompareTo(other.Current);
}
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the current instance precedes, follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has these meanings: Value Meaning Less than zero This instance precedes <paramref name="obj"/> in the sort order. Zero This instance occurs in the same position in the sort order as <paramref name="obj"/>. Greater than zero This instance follows <paramref name="obj"/> in the sort order.
/// </returns>
/// <param name="obj">An object to compare with this instance. </param><exception cref="T:System.ArgumentException"><paramref name="obj"/> is not the same type as this instance. </exception><filterpriority>2</filterpriority>
public int CompareTo(object obj)
{
var other = obj as IndicatorBase<T>;
if (other == null)
{
throw new ArgumentException("Object must be of type " + GetType().GetBetterTypeName());
}
return CompareTo(other);
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <returns>
/// true if the specified object is equal to the current object; otherwise, false.
/// </returns>
/// <param name="obj">The object to compare with the current object. </param>
public override bool Equals(object obj)
{
// this implementation acts as a liason to prevent inconsistency between the operators
// == and != against primitive types. the core impl for equals between two indicators
// is still reference equality, however, when comparing value types (floats/int, ect..)
// we'll use value type semantics on Current.Value
// because of this, we shouldn't need to override GetHashCode as well since we're still
// solely relying on reference semantics (think hashset/dictionary impls)
if (ReferenceEquals(obj, null)) return false;
var type = obj.GetType();
while (type != null && type != typeof(object))
{
var cur = type.IsGenericType ? type.GetGenericTypeDefinition() : type;
if (typeof(IndicatorBase<>) == cur)
{
return ReferenceEquals(this, obj);
}
type = type.BaseType;
}
try
{
// the obj is not an indicator, so let's check for value types, try converting to decimal
var converted = obj.ConvertInvariant<decimal>();
return Current.Value == converted;
}
catch (InvalidCastException)
{
// conversion failed, return false
return false;
}
}
/// <summary>
/// Get Hash Code for this Object
/// </summary>
/// <returns>Integer Hash Code</returns>
public override int GetHashCode()
{
return base.GetHashCode();
}
/// <summary>
/// ToString Overload for Indicator Base
/// </summary>
/// <returns>String representation of the indicator</returns>
public override string ToString()
{
return Current.Value.ToStringInvariant("#######0.0####");
}
/// <summary>
/// Provides a more detailed string of this indicator in the form of {Name} - {Value}
/// </summary>
/// <returns>A detailed string of this indicator's current state</returns>
public string ToDetailedString()
{
return $"{Name} - {this}";
}
/// <summary>
/// Computes the next value of this indicator from the given state
/// </summary>
/// <param name="input">The input given to the indicator</param>
/// <returns>A new value for this indicator</returns>
protected abstract decimal ComputeNextValue(T input);
/// <summary>
/// Computes the next value of this indicator from the given state
/// and returns an instance of the <see cref="IndicatorResult"/> class
/// </summary>
/// <param name="input">The input given to the indicator</param>
/// <returns>An IndicatorResult object including the status of the indicator</returns>
protected virtual IndicatorResult ValidateAndComputeNextValue(T input)
{
// default implementation always returns IndicatorStatus.Success
return new IndicatorResult(ComputeNextValue(input));
}
/// <summary>
/// Event invocator for the Updated event
/// </summary>
/// <param name="consolidated">This is the new piece of data produced by this indicator</param>
protected virtual void OnUpdated(IndicatorDataPoint consolidated)
{
Updated?.Invoke(this, consolidated);
}
}
}
| |
// 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.Runtime;
using System.Threading;
namespace System.ServiceModel.Security
{
// NOTE: this class does minimum argument checking as it is all internal
internal class TimeBoundedCache
{
private static Action<object> s_purgeCallback;
private Hashtable _entries;
// if there are less than lowWaterMark entries, no purging is done
private int _lowWaterMark;
private DateTime _nextPurgeTimeUtc;
private TimeSpan _purgeInterval;
private PurgingMode _purgingMode;
private Timer _purgingTimer;
private bool _doRemoveNotification;
protected TimeBoundedCache(int lowWaterMark, int maxCacheItems, IEqualityComparer keyComparer, PurgingMode purgingMode, TimeSpan purgeInterval, bool doRemoveNotification)
{
_entries = new Hashtable(keyComparer);
CacheLock = new ReaderWriterLockSlim();
_lowWaterMark = lowWaterMark;
Capacity = maxCacheItems;
_purgingMode = purgingMode;
_purgeInterval = purgeInterval;
_doRemoveNotification = doRemoveNotification;
_nextPurgeTimeUtc = DateTime.UtcNow.Add(_purgeInterval);
}
public int Count
{
get
{
return _entries.Count;
}
}
private static Action<object> PurgeCallback
{
get
{
if (s_purgeCallback == null)
{
s_purgeCallback = new Action<object>(PurgeCallbackStatic);
}
return s_purgeCallback;
}
}
protected int Capacity { get; }
protected Hashtable Entries
{
get
{
return _entries;
}
}
protected ReaderWriterLockSlim CacheLock { get; }
protected bool TryAddItem(object key, object item, DateTime expirationTime, bool replaceExistingEntry)
{
return TryAddItem(key, new ExpirableItem(item, expirationTime), replaceExistingEntry);
}
private void CancelTimerIfNeeded()
{
if (Count == 0 && _purgingTimer != null)
{
_purgingTimer.Change(TimeSpan.FromMilliseconds(-1), TimeSpan.FromMilliseconds(-1));
_purgingTimer.Dispose();
_purgingTimer = null;
}
}
private void StartTimerIfNeeded()
{
if (_purgingMode != PurgingMode.TimerBasedPurge)
{
return;
}
if (_purgingTimer == null)
{
_purgingTimer = new Timer(new TimerCallback(PurgeCallback), this, _purgeInterval, TimeSpan.FromMilliseconds(-1));
}
}
protected bool TryAddItem(object key, IExpirableItem item, bool replaceExistingEntry)
{
bool lockHeld = false;
try
{
try { }
finally
{
CacheLock.EnterWriteLock();
lockHeld = true;
}
PurgeIfNeeded();
EnforceQuota();
IExpirableItem currentItem = _entries[key] as IExpirableItem;
if (currentItem == null || IsExpired(currentItem))
{
_entries[key] = item;
}
else if (!replaceExistingEntry)
{
return false;
}
else
{
_entries[key] = item;
}
if (currentItem != null && _doRemoveNotification)
{
OnRemove(ExtractItem(currentItem));
}
StartTimerIfNeeded();
return true;
}
finally
{
if (lockHeld)
{
CacheLock.ExitWriteLock();
}
}
}
protected bool TryReplaceItem(object key, object item, DateTime expirationTime)
{
bool lockHeld = false;
try
{
try { }
finally
{
CacheLock.EnterWriteLock();
lockHeld = true;
}
PurgeIfNeeded();
EnforceQuota();
IExpirableItem currentItem = _entries[key] as IExpirableItem;
if (currentItem == null || IsExpired(currentItem))
{
return false;
}
else
{
_entries[key] = new ExpirableItem(item, expirationTime);
if (currentItem != null && _doRemoveNotification)
{
OnRemove(ExtractItem(currentItem));
}
StartTimerIfNeeded();
return true;
}
}
finally
{
if (lockHeld)
{
CacheLock.ExitWriteLock();
}
}
}
protected void ClearItems()
{
bool lockHeld = false;
try
{
try { }
finally
{
CacheLock.EnterWriteLock();
lockHeld = true;
}
int count = _entries.Count;
if (_doRemoveNotification)
{
foreach (IExpirableItem item in _entries.Values)
{
OnRemove(ExtractItem(item));
}
}
_entries.Clear();
CancelTimerIfNeeded();
}
finally
{
if (lockHeld)
{
CacheLock.ExitWriteLock();
}
}
}
protected object GetItem(object key)
{
bool lockHeld = false;
try
{
try { }
finally
{
CacheLock.EnterReadLock();
lockHeld = true;
}
IExpirableItem item = _entries[key] as IExpirableItem;
if (item == null)
{
return null;
}
else if (IsExpired(item))
{
// this is a stale item
return null;
}
else
{
return ExtractItem(item);
}
}
finally
{
if (lockHeld)
{
CacheLock.ExitReadLock();
}
}
}
protected virtual ArrayList OnQuotaReached(Hashtable cacheTable)
{
ThrowQuotaReachedException();
return null;
}
protected virtual void OnRemove(object item)
{
}
protected bool TryRemoveItem(object key)
{
bool lockHeld = false;
try
{
try { }
finally
{
CacheLock.EnterWriteLock();
lockHeld = true;
}
PurgeIfNeeded();
IExpirableItem currentItem = _entries[key] as IExpirableItem;
bool result = (currentItem != null) && !IsExpired(currentItem);
if (currentItem != null)
{
_entries.Remove(key);
if (_doRemoveNotification)
{
OnRemove(ExtractItem(currentItem));
}
CancelTimerIfNeeded();
}
return result;
}
finally
{
if (lockHeld)
{
CacheLock.ExitWriteLock();
}
}
}
private void EnforceQuota()
{
if (!(CacheLock.IsWriteLockHeld == true))
{
// we failfast here because if we don't have the lock we could corrupt the cache
Fx.Assert("Cache write lock is not held.");
Environment.FailFast("Cache write lock is not held.");
}
if (Count >= Capacity)
{
ArrayList keysToBeRemoved;
keysToBeRemoved = OnQuotaReached(_entries);
if (keysToBeRemoved != null)
{
for (int i = 0; i < keysToBeRemoved.Count; ++i)
{
_entries.Remove(keysToBeRemoved[i]);
}
}
CancelTimerIfNeeded();
if (Count >= Capacity)
{
ThrowQuotaReachedException();
}
}
}
protected object ExtractItem(IExpirableItem val)
{
ExpirableItem wrapper = (val as ExpirableItem);
if (wrapper != null)
{
return wrapper.Item;
}
else
{
return val;
}
}
private bool IsExpired(IExpirableItem item)
{
Fx.Assert(item.ExpirationTime == DateTime.MaxValue || item.ExpirationTime.Kind == DateTimeKind.Utc, "");
return (item.ExpirationTime <= DateTime.UtcNow);
}
private bool ShouldPurge()
{
if (Count >= Capacity)
{
return true;
}
else if (_purgingMode == PurgingMode.AccessBasedPurge && DateTime.UtcNow > _nextPurgeTimeUtc && Count > _lowWaterMark)
{
return true;
}
else
{
return false;
}
}
private void PurgeIfNeeded()
{
if (!(CacheLock.IsWriteLockHeld == true))
{
// we failfast here because if we don't have the lock we could corrupt the cache
Fx.Assert("Cache write lock is not held.");
Environment.FailFast("Cache write lock is not held.");
}
if (ShouldPurge())
{
PurgeStaleItems();
}
}
/// <summary>
/// This method must be called from within a writer lock
/// </summary>
private void PurgeStaleItems()
{
if (!(CacheLock.IsWriteLockHeld == true))
{
// we failfast here because if we don't have the lock we could corrupt the cache
Fx.Assert("Cache write lock is not held.");
Environment.FailFast("Cache write lock is not held.");
}
ArrayList expiredItems = new ArrayList();
foreach (object key in _entries.Keys)
{
IExpirableItem item = _entries[key] as IExpirableItem;
if (IsExpired(item))
{
// this is a stale item. Remove!
OnRemove(ExtractItem(item));
expiredItems.Add(key);
}
}
for (int i = 0; i < expiredItems.Count; ++i)
{
_entries.Remove(expiredItems[i]);
}
CancelTimerIfNeeded();
_nextPurgeTimeUtc = DateTime.UtcNow.Add(_purgeInterval);
}
private void ThrowQuotaReachedException()
{
string message = SR.Format(SR.CacheQuotaReached, Capacity);
Exception inner = new QuotaExceededException(message);
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(message, inner));
}
private static void PurgeCallbackStatic(object state)
{
TimeBoundedCache self = (TimeBoundedCache)state;
bool lockHeld = false;
try
{
try { }
finally
{
self.CacheLock.EnterWriteLock();
lockHeld = true;
}
if (self._purgingTimer == null)
{
return;
}
self.PurgeStaleItems();
if (self.Count > 0 && self._purgingTimer != null)
{
self._purgingTimer.Change(self._purgeInterval, TimeSpan.FromMilliseconds(-1));
}
}
finally
{
if (lockHeld)
{
self.CacheLock.ExitWriteLock();
}
}
}
internal interface IExpirableItem
{
DateTime ExpirationTime { get; }
}
internal class ExpirableItemComparer : IComparer<IExpirableItem>
{
private static ExpirableItemComparer s_instance;
public static ExpirableItemComparer Default
{
get
{
if (s_instance == null)
{
s_instance = new ExpirableItemComparer();
}
return s_instance;
}
}
// positive, if item1 will expire before item2.
public int Compare(IExpirableItem item1, IExpirableItem item2)
{
if (ReferenceEquals(item1, item2))
{
return 0;
}
Fx.Assert(item1.ExpirationTime.Kind == item2.ExpirationTime.Kind, "");
if (item1.ExpirationTime < item2.ExpirationTime)
{
return 1;
}
else if (item1.ExpirationTime > item2.ExpirationTime)
{
return -1;
}
else
{
return 0;
}
}
}
internal sealed class ExpirableItem : IExpirableItem
{
private object _item;
public ExpirableItem(object item, DateTime expirationTime)
{
_item = item;
Fx.Assert(expirationTime == DateTime.MaxValue || expirationTime.Kind == DateTimeKind.Utc, "");
ExpirationTime = expirationTime;
}
public DateTime ExpirationTime { get; }
public object Item { get { return _item; } }
}
}
internal enum PurgingMode
{
TimerBasedPurge,
AccessBasedPurge
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace AdventOfCode2021;
[Answer(19, slow: true)]
class Day19 : IAnswer
{
[DebuggerDisplay($"{{{nameof(ToString)}(),nq}}")]
class Point
{
public int X;
public int Y;
public int Z;
public int Index;
public int[] Distances = new int[30];
public override string ToString() => $"{X},{Y},{Z}";
};
public (string Part1, string Part2) Solve(string input)
{
var scanners = input.Split("\n\n")
.Select(l => l
.Split('\n')
.Skip(1)
.Select((n, i) =>
{
var p = n
.Split(',')
.Select(n => int.Parse(n))
.ToArray();
return new Point
{
Index = i,
X = p[0],
Y = p[1],
Z = p[2]
};
})
.ToArray()
)
.ToArray();
for (var x = 0; x < scanners.Length; x++)
{
for (var y = 0; y < scanners[x].Length; y++)
{
var a = scanners[x][y];
for (var z = 0; z < y; z++)
{
var b = scanners[x][z];
var dx = Math.Abs(a.X - b.X);
var dy = Math.Abs(a.Y - b.Y);
var dz = Math.Abs(a.Z - b.Z);
var d = dx * dx + dy * dy + dz * dz;
a.Distances[b.Index] = d;
b.Distances[a.Index] = d;
}
}
}
var toBeRotated = scanners.Length - 1;
var scannerPositions = new Point[scanners.Length];
scannerPositions[0] = new Point();
while (toBeRotated > 0)
{
for (var x = 0; x < scanners.Length; x++)
{
for (var y = 0; y < scanners.Length; y++)
{
if (x == y || scannerPositions[x] == null || scannerPositions[y] != null)
{
continue;
}
var scanner1 = scanners[x];
var scanner2 = scanners[y];
var overlap = Intersect(scanner2, scanner1);
if (!overlap.HasValue)
{
continue;
}
var a1 = scanner1[overlap.Value.Item1];
var a2 = scanner1[overlap.Value.Item2];
var b1 = scanner2[overlap.Value.Item3];
var b2 = scanner2[overlap.Value.Item4];
var dx1 = a1.X - a2.X;
var dy1 = a1.Y - a2.Y;
var dz1 = a1.Z - a2.Z;
var dx2 = b2.X - b1.X;
var dy2 = b2.Y - b1.Y;
var dz2 = b2.Z - b1.Z;
var transformX = new Point();
var transformY = new Point();
var transformZ = new Point();
if (dx1 == dx2) transformX.X = 1;
if (dx1 == -dx2) transformX.X = -1;
if (dx1 == dy2) transformX.Y = 1;
if (dx1 == -dy2) transformX.Y = -1;
if (dx1 == dz2) transformX.Z = 1;
if (dx1 == -dz2) transformX.Z = -1;
if (dy1 == dx2) transformY.X = 1;
if (dy1 == -dx2) transformY.X = -1;
if (dy1 == dy2) transformY.Y = 1;
if (dy1 == -dy2) transformY.Y = -1;
if (dy1 == dz2) transformY.Z = 1;
if (dy1 == -dz2) transformY.Z = -1;
if (dz1 == dx2) transformZ.X = 1;
if (dz1 == -dx2) transformZ.X = -1;
if (dz1 == dy2) transformZ.Y = 1;
if (dz1 == -dy2) transformZ.Y = -1;
if (dz1 == dz2) transformZ.Z = 1;
if (dz1 == -dz2) transformZ.Z = -1;
foreach (var signal in scanner2)
{
var prevX = signal.X;
var prevY = signal.Y;
var prevZ = signal.Z;
signal.X = prevX * transformX.X + prevY * transformX.Y + prevZ * transformX.Z;
signal.Y = prevX * transformY.X + prevY * transformY.Y + prevZ * transformY.Z;
signal.Z = prevX * transformZ.X + prevY * transformZ.Y + prevZ * transformZ.Z;
}
var scanner = new Point
{
X = a1.X - b2.X,
Y = a1.Y - b2.Y,
Z = a1.Z - b2.Z
};
foreach (var signal in scanner2)
{
signal.X += scanner.X;
signal.Y += scanner.Y;
signal.Z += scanner.Z;
}
scannerPositions[y] = scanner;
toBeRotated--;
}
}
}
var trueBeacons = new HashSet<int>();
foreach (var beacons in scanners)
{
foreach (var beacon in beacons)
{
trueBeacons.Add(beacon.X * 1000000 + beacon.Y * 100000 + beacon.Z);
}
}
var part1 = trueBeacons.Count;
var part2 = 0;
foreach (var a in scannerPositions)
{
foreach (var b in scannerPositions)
{
var distance = Math.Abs(a.X - b.X) + Math.Abs(a.Y - b.Y) + Math.Abs(a.Z - b.Z);
if (part2 < distance)
{
part2 = distance;
}
}
}
return (part1.ToString(), part2.ToString());
}
(int, int, int, int)? Intersect(Point[] scanner1, Point[] scanner2)
{
for (var p1 = 0; p1 < scanner1.Length; p1++)
{
var a = scanner1[p1];
for (var p2 = 0; p2 < scanner2.Length; p2++)
{
var overlaps = 0;
var b = scanner2[p2];
for (var di = 0; di < a.Distances.Length; di++)
{
var aDist = a.Distances[di];
if (aDist > 0)
{
var otherIndex = Array.IndexOf(b.Distances, aDist);
if (otherIndex > -1 && ++overlaps > 10)
{
return (p2, otherIndex, di, p1);
}
}
}
}
}
return null;
}
}
| |
// 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.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.ExpressionEvaluator;
using Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests;
using Microsoft.VisualStudio.Debugger.Evaluation;
using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation;
using Roslyn.Test.PdbUtilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests
{
public class ResultPropertiesTests : ExpressionCompilerTestBase
{
[Fact]
public void Category()
{
var source = @"
class C
{
int P { get; set; }
int F;
int M() { return 0; }
void Test(int p)
{
int l;
}
}
";
var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.Test");
foreach (var expr in new[] { "this", "null", "1", "F", "p", "l" })
{
Assert.Equal(DkmEvaluationResultCategory.Data, GetResultProperties(context, expr).Category);
}
Assert.Equal(DkmEvaluationResultCategory.Method, GetResultProperties(context, "M()").Category);
Assert.Equal(DkmEvaluationResultCategory.Property, GetResultProperties(context, "P").Category);
});
}
[Fact]
public void StorageType()
{
var source = @"
class C
{
int P { get; set; }
int F;
int M() { return 0; }
static int SP { get; set; }
static int SF;
static int SM() { return 0; }
void Test(int p)
{
int l;
}
}
";
var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.Test");
foreach (var expr in new[] { "this", "null", "1", "P", "F", "M()", "p", "l" })
{
Assert.Equal(DkmEvaluationResultStorageType.None, GetResultProperties(context, expr).StorageType);
}
foreach (var expr in new[] { "SP", "SF", "SM()" })
{
Assert.Equal(DkmEvaluationResultStorageType.Static, GetResultProperties(context, expr).StorageType);
}
});
}
[Fact]
public void AccessType()
{
var ilSource = @"
.class public auto ansi beforefieldinit C
extends [mscorlib]System.Object
{
.field private int32 Private
.field family int32 Protected
.field assembly int32 Internal
.field public int32 Public
.field famorassem int32 ProtectedInternal
.field famandassem int32 ProtectedAndInternal
.method public hidebysig instance void
Test() cil managed
{
ret
}
.method public hidebysig specialname rtspecialname
instance void .ctor() cil managed
{
ldarg.0
call instance void [mscorlib]System.Object::.ctor()
ret
} // end of method C::.ctor
} // end of class C
";
var module = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource);
var runtime = CreateRuntimeInstance(module, new[] { MscorlibRef });
var context = CreateMethodContext(runtime, methodName: "C.Test");
Assert.Equal(DkmEvaluationResultAccessType.Private, GetResultProperties(context, "Private").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Protected, GetResultProperties(context, "Protected").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "Internal").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Public, GetResultProperties(context, "Public").AccessType);
// As in dev12.
Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "ProtectedInternal").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.Internal, GetResultProperties(context, "ProtectedAndInternal").AccessType);
Assert.Equal(DkmEvaluationResultAccessType.None, GetResultProperties(context, "null").AccessType);
}
[Fact]
public void AccessType_Nested()
{
var source = @"
using System;
internal class C
{
public int F;
void Test()
{
}
}
";
var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.Test");
// Used the declared accessibility, rather than the effective accessibility.
Assert.Equal(DkmEvaluationResultAccessType.Public, GetResultProperties(context, "F").AccessType);
});
}
[Fact]
public void ModifierFlags_Virtual()
{
var source = @"
using System;
class C
{
public int P { get; set; }
public int M() { return 0; }
public event Action E;
public virtual int VP { get; set; }
public virtual int VM() { return 0; }
public virtual event Action VE;
void Test()
{
}
}
";
var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.Test");
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "P").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "VP").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "M()").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "VM()").ModifierFlags);
// Field-like events are borderline since they bind as event accesses, but get emitted as field accesses.
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "E").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "VE").ModifierFlags);
});
}
[Fact]
public void ModifierFlags_Virtual_Variations()
{
var source = @"
using System;
abstract class Base
{
public abstract int Override { get; set; }
}
abstract class Derived : Base
{
public override int Override { get; set; }
public abstract int Abstract { get; set; }
void Test()
{
}
}
";
var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "Derived.Test");
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "Abstract").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Virtual, GetResultProperties(context, "Override").ModifierFlags);
});
}
[Fact]
public void ModifierFlags_Constant()
{
var source = @"
using System;
class C
{
int F = 1;
const int CF = 1;
static readonly int SRF = 1;
void Test(int p)
{
int l = 2;
const int cl = 2;
}
}
";
var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.Test");
foreach (var expr in new[] { "null", "1", "1 + 1", "CF", "cl" })
{
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Constant, GetResultProperties(context, expr).ModifierFlags);
}
foreach (var expr in new[] { "this", "F", "SRF", "p", "l" })
{
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, expr).ModifierFlags);
}
});
}
[Fact]
public void ModifierFlags_Volatile()
{
var source = @"
using System;
class C
{
int F = 1;
volatile int VF = 1;
void Test(int p)
{
int l;
}
}
";
var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.Test");
Assert.Equal(DkmEvaluationResultTypeModifierFlags.None, GetResultProperties(context, "F").ModifierFlags);
Assert.Equal(DkmEvaluationResultTypeModifierFlags.Volatile, GetResultProperties(context, "VF").ModifierFlags);
});
}
[Fact]
public void Assignment()
{
var source = @"
class C
{
public virtual int P { get; set; }
void Test()
{
}
}
";
var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.Test");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
context.CompileAssignment("P", "1", NoAliases, DebuggerDiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData);
Assert.Null(error);
Assert.Empty(missingAssemblyIdentities);
Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect, resultProperties.Flags);
Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); // Not Data
Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType); // Not Public
Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType);
Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags); // Not Virtual
});
}
[Fact]
public void LocalDeclaration()
{
var source = @"
class C
{
public virtual int P { get; set; }
void Test()
{
}
}
";
var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.Test");
ResultProperties resultProperties;
string error;
var testData = new CompilationTestData();
ImmutableArray<AssemblyIdentity> missingAssemblyIdentities;
context.CompileExpression(
"int z = 1;",
DkmEvaluationFlags.None,
NoAliases,
DebuggerDiagnosticFormatter.Instance,
out resultProperties,
out error,
out missingAssemblyIdentities,
EnsureEnglishUICulture.PreferredOrNull,
testData);
Assert.Null(error);
Assert.Empty(missingAssemblyIdentities);
Assert.Equal(DkmClrCompilationResultFlags.PotentialSideEffect | DkmClrCompilationResultFlags.ReadOnlyResult, resultProperties.Flags);
Assert.Equal(default(DkmEvaluationResultCategory), resultProperties.Category); // Not Data
Assert.Equal(default(DkmEvaluationResultAccessType), resultProperties.AccessType);
Assert.Equal(default(DkmEvaluationResultStorageType), resultProperties.StorageType);
Assert.Equal(default(DkmEvaluationResultTypeModifierFlags), resultProperties.ModifierFlags);
});
}
[Fact]
public void Error()
{
var source = @"
class C
{
void Test()
{
}
}
";
var comp = CreateStandardCompilation(source, options: TestOptions.DebugDll);
WithRuntimeInstance(comp, runtime =>
{
var context = CreateMethodContext(runtime, methodName: "C.Test");
VerifyErrorResultProperties(context, "x => x");
VerifyErrorResultProperties(context, "Test");
VerifyErrorResultProperties(context, "Missing");
VerifyErrorResultProperties(context, "C");
});
}
private static ResultProperties GetResultProperties(EvaluationContext context, string expr)
{
ResultProperties resultProperties;
string error;
context.CompileExpression(expr, out resultProperties, out error);
Assert.Null(error);
return resultProperties;
}
private static void VerifyErrorResultProperties(EvaluationContext context, string expr)
{
ResultProperties resultProperties;
string error;
context.CompileExpression(expr, out resultProperties, out error);
Assert.NotNull(error);
Assert.Equal(default(ResultProperties), resultProperties);
}
}
}
| |
using Breeze.WebApi;
using SummerBreeze;
using Newtonsoft.Json;
using Ninject;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace SummerBreeze
{
public class SummerBreezeContextProvider<T> : ContextProvider where T : ISummerBreezeDbContext
{
private IKernel _kernel;
private Assembly _assembly = null;
public T Context { get; private set; }
public SummerBreezeContextProvider(string assemblyName = null)
{
/*bind types*/
_kernel = new StandardKernel();
_kernel.Bind<ISummerBreezeDbContext>().To<T>();
Context = (T)_kernel.Get<ISummerBreezeDbContext>();
if (assemblyName == null)
{
_assembly = Assembly.GetCallingAssembly();
}
else
{
try
{
var an = Assembly.GetCallingAssembly().GetReferencedAssemblies().Where(a => a.Name == assemblyName).FirstOrDefault();
_assembly = Assembly.Load(an);
}
catch (Exception ex)
{
throw ex;
}
}
}
/*base overrides*/
protected override string BuildJsonMetadata()
{
return GetMetadataFromAssembly();
}
//protected override List<KeyMapping> SaveChangesCore(Dictionary<Type, List<EntityInfo>> saveMap)
//{
// return _kernel.Get<ISummerBreezeDbContext>().SaveChanges(saveMap);
//}
protected override void SaveChangesCore(SaveWorkState saveWorkState)
{
_kernel.Get<ISummerBreezeDbContext>().SaveChanges(saveWorkState);
}
protected override Dictionary<Type, List<EntityInfo>> BeforeSaveEntities(Dictionary<Type, List<EntityInfo>> saveMap)
{
return _kernel.Get<ISummerBreezeDbContext>().BeforeSaveEntities(saveMap);
}
protected override bool BeforeSaveEntity(EntityInfo entityInfo)
{
return _kernel.Get<ISummerBreezeDbContext>().BeforeSaveEntity(entityInfo);
}
public List<string> GetTrackedEntities()
{
return _kernel.Get<ISummerBreezeDbContext>().GetTrackedEntities();
}
private string GetMetadataFromAssembly()
{
var entityMedatataList = new List<BreezeEntityTypeMetadata>();
var entity = _assembly.GetTypes().Where(x => x.GetCustomAttributes(typeof(BreezeLocalizableAttribute), false).Length > 0).ToList();
entity.ForEach((e) =>
{
entityMedatataList.Add(GetEntityTypeMetadata(e));
});
return JsonConvert.SerializeObject(entityMedatataList);
}
private BreezeEntityTypeMetadata GetEntityTypeMetadata(Type t)
{
var autogeneratedKeyAttr = t.GetCustomAttributes(typeof(BreezeAutoGeneratedKeyTypeAttribute), false) != null ? (t.GetCustomAttributes(typeof(BreezeAutoGeneratedKeyTypeAttribute), false).FirstOrDefault() as BreezeAutoGeneratedKeyTypeAttribute).AutoGeneratedKeyType.ToString() : null;
var allUnmapped = ((t.GetCustomAttributes(typeof(BreezeLocalizableAttribute), false).FirstOrDefault() as BreezeLocalizableAttribute).UnMapAll);
var metadata = new BreezeEntityTypeMetadata();
metadata.shortName = t.Name;
metadata.@namespace = t.Namespace;
metadata.autoGeneratedKeyType = autogeneratedKeyAttr ?? SummerBreezeEnums.AutoGeneratedKeyType.None.ToString();
var datapropertyMetadataList = new List<BreezeDataPropertyMetadata>();
var navigationpropertyMetadataList = new List<BreezeNavigationPropertyMetadata>();
var propertyInfo = GetPropertyInfo(t);
propertyInfo.ForEach((i) =>
{
//Navigation Properties
var nav = i.GetCustomAttributes(typeof(BreezeNavigationPropertyAttribute), false).FirstOrDefault();
if (nav != null)
{
navigationpropertyMetadataList.Add(new BreezeNavigationPropertyMetadata
{
name = i.Name,
entityTypeName = i.PropertyType.GetGenericArguments().FirstOrDefault() == null ? i.PropertyType.Name + ":#" + i.PropertyType.Namespace : i.PropertyType.GetGenericArguments().FirstOrDefault().Name + ":#" + i.PropertyType.GetGenericArguments().FirstOrDefault().Namespace,
isScalar = (nav as BreezeNavigationPropertyAttribute).ForeignKeyNames != null && (nav as BreezeNavigationPropertyAttribute).ForeignKeyNames.Count() > 0,
associationName = (nav as BreezeNavigationPropertyAttribute).Association,
foreignKeyNames = (nav as BreezeNavigationPropertyAttribute).ForeignKeyNames
});
}
else
{
//Data Properties
datapropertyMetadataList.Add(new BreezeDataPropertyMetadata
{
name = i.Name,
dataType = i.PropertyType.Name.Contains("Nullable") ? Nullable.GetUnderlyingType(i.PropertyType).Name : i.PropertyType.GetGenericArguments().FirstOrDefault() == null ? i.PropertyType.Name : i.PropertyType.GetGenericArguments().FirstOrDefault().Name,
isNullable = i.PropertyType.IsGenericType && i.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>),
isPartOfKey = i.GetCustomAttributes(typeof(KeyAttribute), false) != null && i.GetCustomAttributes(typeof(KeyAttribute), false).Count() > 0,
isUnmapped = allUnmapped ? allUnmapped : i.GetCustomAttributes(typeof(BreezeUnmappedAttribute), false) != null && i.GetCustomAttributes(typeof(BreezeUnmappedAttribute), false).Count() > 0,
validators = GetValidatorsForProperty(i)
});
}
//if (i.GetGetMethod().IsVirtual)
//{
// navigationpropertyMetadataList.Add(new NoDbNavigationPropertyMetadata
// {
// name = i.Name,
// entityTypeName = i.PropertyType.Name,
// isScalar = true,
// associationName = "
// });
//}
//add navigation properties
if (navigationpropertyMetadataList.Count > 0)
{
metadata.navigationProperties = navigationpropertyMetadataList;
}
//add data properties
if (datapropertyMetadataList.Count > 0)
{
metadata.dataProperties = datapropertyMetadataList;
}
});
return metadata;
}
private List<string> GetValidatorsForProperty(PropertyInfo i)
{
var validatorsList = new List<string>();
//Required
var required = i.GetCustomAttributes(typeof(RequiredAttribute), false);
if (required != null && required.Length > 0)
{
validatorsList.Add("breeze.Validator.required()");
}
var maxLength = i.GetCustomAttributes(typeof(MaxLengthAttribute), false);
//MaxLength
if (maxLength != null && maxLength.Length > 0)
{
validatorsList.Add("breeze.Validator.maxLength({ maxLength:" + (maxLength.FirstOrDefault() as MaxLengthAttribute).Length + "})");
}
return validatorsList;
}
private List<PropertyInfo> GetPropertyInfo(Type t)
{
List<PropertyInfo> info = null;
t.GetCustomAttributes(typeof(BreezeLocalizableAttribute), true).ToList().ForEach((a) =>
{
var attr = (a as BreezeLocalizableAttribute);
if (attr.Include == null || attr.Include.Length == 0)
info = t.GetProperties().ToList(); //all properties
else
info = t.GetProperties().Where(i => attr.Include.Any(o => o.Equals(i.Name))).ToList(); //cherry picked properties
});
return info;
}
protected override void CloseDbConnection()
{
}
public override System.Data.IDbConnection GetDbConnection()
{
throw new NotImplementedException();
}
protected override void OpenDbConnection()
{
}
}
}
| |
/******************************************************************************
* Copyright (C) Leap Motion, Inc. 2011-2018. *
* Leap Motion proprietary and confidential. *
* *
* Use subject to the terms of the Leap Motion SDK Agreement available at *
* https://developer.leapmotion.com/sdk_agreement, or another agreement *
* between Leap Motion and you, your company or other organization. *
******************************************************************************/
namespace Leap {
using System;
/// <summary>
/// The LeapTransform class represents a transform in three dimensional space.
///
/// Note that the LeapTransform class replaces the Leap.Matrix class.
/// @since 3.1.2
/// </summary>
public struct LeapTransform {
/// <summary>
/// Constructs a new transform from the specified translation and rotation.
/// @since 3.1.2
/// </summary>
public LeapTransform(Vector translation, LeapQuaternion rotation) :
this(translation, rotation, Vector.Ones) {
}
/// <summary>
/// Constructs a new transform from the specified translation, rotation and scale.
/// @since 3.1.2
/// </summary>
public LeapTransform(Vector translation, LeapQuaternion rotation, Vector scale) :
this() {
_scale = scale;
// these are non-trival setters.
this.translation = translation;
this.rotation = rotation; // Calls validateBasis
}
/// <summary>
/// Transforms the specified position vector, applying translation, rotation and scale.
/// @since 3.1.2
/// </summary>
public Vector TransformPoint(Vector point) {
return _xBasisScaled * point.x + _yBasisScaled * point.y + _zBasisScaled * point.z + translation;
}
/// <summary>
/// Transforms the specified direction vector, applying rotation only.
/// @since 3.1.2
/// </summary>
public Vector TransformDirection(Vector direction) {
return _xBasis * direction.x + _yBasis * direction.y + _zBasis * direction.z;
}
/// <summary>
/// Transforms the specified velocity vector, applying rotation and scale.
/// @since 3.1.2
/// </summary>
public Vector TransformVelocity(Vector velocity) {
return _xBasisScaled * velocity.x + _yBasisScaled * velocity.y + _zBasisScaled * velocity.z;
}
/// <summary>
/// Transforms the specified quaternion.
/// Multiplies the quaternion representing the rotational part of this transform by the specified
/// quaternion.
///
/// **Important:** Modifying the basis vectors of this transform directly leaves the underlying quaternion in
/// an indeterminate state. Neither this function nor the LeapTransform.rotation quaternion can be used after
/// the basis vectors are set.
///
/// @since 3.1.2
/// </summary>
public LeapQuaternion TransformQuaternion(LeapQuaternion rhs) {
if (_quaternionDirty)
throw new InvalidOperationException("Calling TransformQuaternion after Basis vectors have been modified.");
if (_flip) {
// Mirror the axis of rotation across the flip axis.
rhs.x *= _flipAxes.x;
rhs.y *= _flipAxes.y;
rhs.z *= _flipAxes.z;
}
LeapQuaternion t = _quaternion.Multiply(rhs);
return t;
}
/// <summary>
/// Mirrors this transform's rotation and scale across the x-axis. Translation is not affected.
/// @since 3.1.2
/// </summary>
public void MirrorX() {
_xBasis = -_xBasis;
_xBasisScaled = -_xBasisScaled;
_flip = true;
_flipAxes.y = -_flipAxes.y;
_flipAxes.z = -_flipAxes.z;
}
/// <summary>
/// Mirrors this transform's rotation and scale across the z-axis. Translation is not affected.
/// @since 3.1.2
/// </summary>
public void MirrorZ() {
_zBasis = -_zBasis;
_zBasisScaled = -_zBasisScaled;
_flip = true;
_flipAxes.x = -_flipAxes.x;
_flipAxes.y = -_flipAxes.y;
}
/// <summary>
/// The x-basis of the transform.
///
/// **Important:** Modifying the basis vectors of this transform directly leaves the underlying quaternion in
/// an indeterminate state. Neither the TransformQuaternion() function nor the LeapTransform.rotation quaternion
/// can be used after the basis vectors are set.
///
/// @since 3.1.2
/// </summary>
public Vector xBasis {
get { return _xBasis; }
set {
_xBasis = value;
_xBasisScaled = value * scale.x;
_quaternionDirty = true;
}
}
/// <summary>
/// The y-basis of the transform.
///
/// **Important:** Modifying the basis vectors of this transform directly leaves the underlying quaternion in
/// an indeterminate state. Neither the TransformQuaternion() function nor the LeapTransform.rotation quaternion
/// can be used after the basis vectors are set.
///
/// @since 3.1.2
/// </summary>
public Vector yBasis {
get { return _yBasis; }
set {
_yBasis = value;
_yBasisScaled = value * scale.y;
_quaternionDirty = true;
}
}
/// <summary>
/// The z-basis of the transform.
///
/// **Important:** Modifying the basis vectors of this transform directly leaves the underlying quaternion in
/// an indeterminate state. Neither the TransformQuaternion() function nor the LeapTransform.rotation quaternion
/// can be used after the basis vectors are set.
///
/// @since 3.1.2
/// </summary>
public Vector zBasis {
get { return _zBasis; }
set {
_zBasis = value;
_zBasisScaled = value * scale.z;
_quaternionDirty = true;
}
}
/// <summary>
/// The translation component of the transform.
/// @since 3.1.2
/// </summary>
public Vector translation {
get { return _translation; }
set {
_translation = value;
}
}
/// <summary>
/// The scale factors of the transform.
/// Scale is kept separate from translation.
/// @since 3.1.2
/// </summary>
public Vector scale {
get { return _scale; }
set {
_scale = value;
_xBasisScaled = _xBasis * scale.x;
_yBasisScaled = _yBasis * scale.y;
_zBasisScaled = _zBasis * scale.z;
}
}
/// <summary>
/// The rotational component of the transform.
///
/// **Important:** Modifying the basis vectors of this transform directly leaves the underlying quaternion in
/// an indeterminate state. This rotation quaternion cannot be accessed after
/// the basis vectors are modified directly.
///
/// @since 3.1.2
/// </summary>
public LeapQuaternion rotation {
get {
if (_quaternionDirty)
throw new InvalidOperationException("Requesting rotation after Basis vectors have been modified.");
return _quaternion;
}
set {
_quaternion = value;
float d = value.MagnitudeSquared;
float s = 2.0f / d;
float xs = value.x * s, ys = value.y * s, zs = value.z * s;
float wx = value.w * xs, wy = value.w * ys, wz = value.w * zs;
float xx = value.x * xs, xy = value.x * ys, xz = value.x * zs;
float yy = value.y * ys, yz = value.y * zs, zz = value.z * zs;
_xBasis = new Vector(1.0f - (yy + zz), xy + wz, xz - wy);
_yBasis = new Vector(xy - wz, 1.0f - (xx + zz), yz + wx);
_zBasis = new Vector(xz + wy, yz - wx, 1.0f - (xx + yy));
_xBasisScaled = _xBasis * scale.x;
_yBasisScaled = _yBasis * scale.y;
_zBasisScaled = _zBasis * scale.z;
_quaternionDirty = false;
_flip = false;
_flipAxes = new Vector(1.0f, 1.0f, 1.0f);
}
}
/// <summary>
/// The identity transform.
/// @since 3.1.2
/// </summary>
public static readonly LeapTransform Identity = new LeapTransform(Vector.Zero, LeapQuaternion.Identity, Vector.Ones);
private Vector _translation;
private Vector _scale;
private LeapQuaternion _quaternion;
private bool _quaternionDirty;
private bool _flip;
private Vector _flipAxes;
private Vector _xBasis;
private Vector _yBasis;
private Vector _zBasis;
private Vector _xBasisScaled;
private Vector _yBasisScaled;
private Vector _zBasisScaled;
}
}
| |
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.IO;
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
using System.Numerics;
#endif
using Medivh.Json.Utilities;
using System.Globalization;
#if NET20
using Medivh.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Medivh.Json
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data.
/// </summary>
public abstract class JsonWriter : IDisposable
{
internal enum State
{
Start = 0,
Property = 1,
ObjectStart = 2,
Object = 3,
ArrayStart = 4,
Array = 5,
ConstructorStart = 6,
Constructor = 7,
Closed = 8,
Error = 9
}
// array that gives a new state based on the current state an the token being written
private static readonly State[][] StateArray;
internal static readonly State[][] StateArrayTempate = new[]
{
// Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error
//
/* None */new[] { State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* StartObject */new[] { State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error },
/* StartArray */new[] { State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error },
/* StartConstructor */new[] { State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error },
/* Property */new[] { State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error },
/* Comment */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Raw */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error },
/* Value (this will be copied) */new[] { State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }
};
internal static State[][] BuildStateArray()
{
var allStates = StateArrayTempate.ToList();
var errorStates = StateArrayTempate[0];
var valueStates = StateArrayTempate[7];
foreach (JsonToken valueToken in EnumUtils.GetValues(typeof(JsonToken)))
{
if (allStates.Count <= (int)valueToken)
{
switch (valueToken)
{
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.Date:
case JsonToken.Bytes:
allStates.Add(valueStates);
break;
default:
allStates.Add(errorStates);
break;
}
}
}
return allStates.ToArray();
}
static JsonWriter()
{
StateArray = BuildStateArray();
}
private List<JsonPosition> _stack;
private JsonPosition _currentPosition;
private State _currentState;
private Formatting _formatting;
/// <summary>
/// Gets or sets a value indicating whether the underlying stream or
/// <see cref="TextReader"/> should be closed when the writer is closed.
/// </summary>
/// <value>
/// true to close the underlying stream or <see cref="TextReader"/> when
/// the writer is closed; otherwise false. The default is true.
/// </value>
public bool CloseOutput { get; set; }
/// <summary>
/// Gets the top.
/// </summary>
/// <value>The top.</value>
protected internal int Top
{
get
{
int depth = (_stack != null) ? _stack.Count : 0;
if (Peek() != JsonContainerType.None)
{
depth++;
}
return depth;
}
}
/// <summary>
/// Gets the state of the writer.
/// </summary>
public WriteState WriteState
{
get
{
switch (_currentState)
{
case State.Error:
return WriteState.Error;
case State.Closed:
return WriteState.Closed;
case State.Object:
case State.ObjectStart:
return WriteState.Object;
case State.Array:
case State.ArrayStart:
return WriteState.Array;
case State.Constructor:
case State.ConstructorStart:
return WriteState.Constructor;
case State.Property:
return WriteState.Property;
case State.Start:
return WriteState.Start;
default:
throw JsonWriterException.Create(this, "Invalid state: " + _currentState, null);
}
}
}
internal string ContainerPath
{
get
{
if (_currentPosition.Type == JsonContainerType.None || _stack == null)
{
return string.Empty;
}
return JsonPosition.BuildPath(_stack, null);
}
}
/// <summary>
/// Gets the path of the writer.
/// </summary>
public string Path
{
get
{
if (_currentPosition.Type == JsonContainerType.None)
{
return string.Empty;
}
bool insideContainer = (_currentState != State.ArrayStart
&& _currentState != State.ConstructorStart
&& _currentState != State.ObjectStart);
JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null;
return JsonPosition.BuildPath(_stack, current);
}
}
private DateFormatHandling _dateFormatHandling;
private DateTimeZoneHandling _dateTimeZoneHandling;
private StringEscapeHandling _stringEscapeHandling;
private FloatFormatHandling _floatFormatHandling;
private string _dateFormatString;
private CultureInfo _culture;
/// <summary>
/// Indicates how JSON text output is formatted.
/// </summary>
public Formatting Formatting
{
get { return _formatting; }
set
{
if (value < Formatting.None || value > Formatting.Indented)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_formatting = value;
}
}
/// <summary>
/// Get or set how dates are written to JSON text.
/// </summary>
public DateFormatHandling DateFormatHandling
{
get { return _dateFormatHandling; }
set
{
if (value < DateFormatHandling.IsoDateFormat || value > DateFormatHandling.MicrosoftDateFormat)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateFormatHandling = value;
}
}
/// <summary>
/// Get or set how <see cref="DateTime"/> time zones are handling when writing JSON text.
/// </summary>
public DateTimeZoneHandling DateTimeZoneHandling
{
get { return _dateTimeZoneHandling; }
set
{
if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_dateTimeZoneHandling = value;
}
}
/// <summary>
/// Get or set how strings are escaped when writing JSON text.
/// </summary>
public StringEscapeHandling StringEscapeHandling
{
get { return _stringEscapeHandling; }
set
{
if (value < StringEscapeHandling.Default || value > StringEscapeHandling.EscapeHtml)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_stringEscapeHandling = value;
OnStringEscapeHandlingChanged();
}
}
internal virtual void OnStringEscapeHandlingChanged()
{
// hacky but there is a calculated value that relies on StringEscapeHandling
}
/// <summary>
/// Get or set how special floating point numbers, e.g. <see cref="F:System.Double.NaN"/>,
/// <see cref="F:System.Double.PositiveInfinity"/> and <see cref="F:System.Double.NegativeInfinity"/>,
/// are written to JSON text.
/// </summary>
public FloatFormatHandling FloatFormatHandling
{
get { return _floatFormatHandling; }
set
{
if (value < FloatFormatHandling.String || value > FloatFormatHandling.DefaultValue)
{
throw new ArgumentOutOfRangeException(nameof(value));
}
_floatFormatHandling = value;
}
}
/// <summary>
/// Get or set how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatting when writing JSON text.
/// </summary>
public string DateFormatString
{
get { return _dateFormatString; }
set { _dateFormatString = value; }
}
/// <summary>
/// Gets or sets the culture used when writing JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>.
/// </summary>
public CultureInfo Culture
{
get { return _culture ?? CultureInfo.InvariantCulture; }
set { _culture = value; }
}
/// <summary>
/// Creates an instance of the <c>JsonWriter</c> class.
/// </summary>
protected JsonWriter()
{
_currentState = State.Start;
_formatting = Formatting.None;
_dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind;
CloseOutput = true;
}
internal void UpdateScopeWithFinishedValue()
{
if (_currentPosition.HasIndex)
{
_currentPosition.Position++;
}
}
private void Push(JsonContainerType value)
{
if (_currentPosition.Type != JsonContainerType.None)
{
if (_stack == null)
{
_stack = new List<JsonPosition>();
}
_stack.Add(_currentPosition);
}
_currentPosition = new JsonPosition(value);
}
private JsonContainerType Pop()
{
JsonPosition oldPosition = _currentPosition;
if (_stack != null && _stack.Count > 0)
{
_currentPosition = _stack[_stack.Count - 1];
_stack.RemoveAt(_stack.Count - 1);
}
else
{
_currentPosition = new JsonPosition();
}
return oldPosition.Type;
}
private JsonContainerType Peek()
{
return _currentPosition.Type;
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying streams and also flushes the underlying stream.
/// </summary>
public abstract void Flush();
/// <summary>
/// Closes this stream and the underlying stream.
/// </summary>
public virtual void Close()
{
AutoCompleteAll();
}
/// <summary>
/// Writes the beginning of a JSON object.
/// </summary>
public virtual void WriteStartObject()
{
InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object);
}
/// <summary>
/// Writes the end of a JSON object.
/// </summary>
public virtual void WriteEndObject()
{
InternalWriteEnd(JsonContainerType.Object);
}
/// <summary>
/// Writes the beginning of a JSON array.
/// </summary>
public virtual void WriteStartArray()
{
InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array);
}
/// <summary>
/// Writes the end of an array.
/// </summary>
public virtual void WriteEndArray()
{
InternalWriteEnd(JsonContainerType.Array);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public virtual void WriteStartConstructor(string name)
{
InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor);
}
/// <summary>
/// Writes the end constructor.
/// </summary>
public virtual void WriteEndConstructor()
{
InternalWriteEnd(JsonContainerType.Constructor);
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
public virtual void WritePropertyName(string name)
{
InternalWritePropertyName(name);
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
/// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param>
public virtual void WritePropertyName(string name, bool escape)
{
WritePropertyName(name);
}
/// <summary>
/// Writes the end of the current JSON object or array.
/// </summary>
public virtual void WriteEnd()
{
WriteEnd(Peek());
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token and its children.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
public void WriteToken(JsonReader reader)
{
WriteToken(reader, true);
}
/// <summary>
/// Writes the current <see cref="JsonReader"/> token.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param>
/// <param name="writeChildren">A flag indicating whether the current token's children should be written.</param>
public void WriteToken(JsonReader reader, bool writeChildren)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
WriteToken(reader, writeChildren, true, true);
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token and its value.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
/// <param name="value">
/// The value to write.
/// A value is only required for tokens that have an associated value, e.g. the <see cref="String"/> property name for <see cref="JsonToken.PropertyName"/>.
/// A null value can be passed to the method for token's that don't have a value, e.g. <see cref="JsonToken.StartObject"/>.</param>
public void WriteToken(JsonToken token, object value)
{
switch (token)
{
case JsonToken.None:
// read to next
break;
case JsonToken.StartObject:
WriteStartObject();
break;
case JsonToken.StartArray:
WriteStartArray();
break;
case JsonToken.StartConstructor:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WriteStartConstructor(value.ToString());
break;
case JsonToken.PropertyName:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WritePropertyName(value.ToString());
break;
case JsonToken.Comment:
WriteComment((value != null) ? value.ToString() : null);
break;
case JsonToken.Integer:
ValidationUtils.ArgumentNotNull(value, nameof(value));
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
if (value is BigInteger)
{
WriteValue((BigInteger)value);
}
else
#endif
{
WriteValue(Convert.ToInt64(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Float:
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value is decimal)
{
WriteValue((decimal)value);
}
else if (value is double)
{
WriteValue((double)value);
}
else if (value is float)
{
WriteValue((float)value);
}
else
{
WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.String:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WriteValue(value.ToString());
break;
case JsonToken.Boolean:
ValidationUtils.ArgumentNotNull(value, nameof(value));
WriteValue(Convert.ToBoolean(value, CultureInfo.InvariantCulture));
break;
case JsonToken.Null:
WriteNull();
break;
case JsonToken.Undefined:
WriteUndefined();
break;
case JsonToken.EndObject:
WriteEndObject();
break;
case JsonToken.EndArray:
WriteEndArray();
break;
case JsonToken.EndConstructor:
WriteEndConstructor();
break;
case JsonToken.Date:
ValidationUtils.ArgumentNotNull(value, nameof(value));
#if !NET20
if (value is DateTimeOffset)
{
WriteValue((DateTimeOffset)value);
}
else
#endif
{
WriteValue(Convert.ToDateTime(value, CultureInfo.InvariantCulture));
}
break;
case JsonToken.Raw:
WriteRawValue((value != null) ? value.ToString() : null);
break;
case JsonToken.Bytes:
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value is Guid)
{
WriteValue((Guid)value);
}
else
{
WriteValue((byte[])value);
}
break;
default:
throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(token), token, "Unexpected token type.");
}
}
/// <summary>
/// Writes the <see cref="JsonToken"/> token.
/// </summary>
/// <param name="token">The <see cref="JsonToken"/> to write.</param>
public void WriteToken(JsonToken token)
{
WriteToken(token, null);
}
internal void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate, bool writeComments)
{
int initialDepth;
if (reader.TokenType == JsonToken.None)
{
initialDepth = -1;
}
else if (!JsonTokenUtils.IsStartToken(reader.TokenType))
{
initialDepth = reader.Depth + 1;
}
else
{
initialDepth = reader.Depth;
}
WriteToken(reader, initialDepth, writeChildren, writeDateConstructorAsDate, writeComments);
}
internal void WriteToken(JsonReader reader, int initialDepth, bool writeChildren, bool writeDateConstructorAsDate, bool writeComments)
{
do
{
// write a JValue date when the constructor is for a date
if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal))
{
WriteConstructorDate(reader);
}
else
{
if (reader.TokenType != JsonToken.Comment || writeComments)
{
WriteToken(reader.TokenType, reader.Value);
}
}
} while (
// stop if we have reached the end of the token being read
initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0)
&& writeChildren
&& reader.Read());
}
private void WriteConstructorDate(JsonReader reader)
{
if (!reader.Read())
{
throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null);
}
if (reader.TokenType != JsonToken.Integer)
{
throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null);
}
long ticks = (long)reader.Value;
DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);
if (!reader.Read())
{
throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null);
}
if (reader.TokenType != JsonToken.EndConstructor)
{
throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected EndConstructor, got " + reader.TokenType, null);
}
WriteValue(date);
}
private void WriteEnd(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
WriteEndObject();
break;
case JsonContainerType.Array:
WriteEndArray();
break;
case JsonContainerType.Constructor:
WriteEndConstructor();
break;
default:
throw JsonWriterException.Create(this, "Unexpected type when writing end: " + type, null);
}
}
private void AutoCompleteAll()
{
while (Top > 0)
{
WriteEnd();
}
}
private JsonToken GetCloseTokenForType(JsonContainerType type)
{
switch (type)
{
case JsonContainerType.Object:
return JsonToken.EndObject;
case JsonContainerType.Array:
return JsonToken.EndArray;
case JsonContainerType.Constructor:
return JsonToken.EndConstructor;
default:
throw JsonWriterException.Create(this, "No close token for type: " + type, null);
}
}
private void AutoCompleteClose(JsonContainerType type)
{
// write closing symbol and calculate new state
int levelsToComplete = 0;
if (_currentPosition.Type == type)
{
levelsToComplete = 1;
}
else
{
int top = Top - 2;
for (int i = top; i >= 0; i--)
{
int currentLevel = top - i;
if (_stack[currentLevel].Type == type)
{
levelsToComplete = i + 2;
break;
}
}
}
if (levelsToComplete == 0)
{
throw JsonWriterException.Create(this, "No token to close.", null);
}
for (int i = 0; i < levelsToComplete; i++)
{
JsonToken token = GetCloseTokenForType(Pop());
if (_currentState == State.Property)
{
WriteNull();
}
if (_formatting == Formatting.Indented)
{
if (_currentState != State.ObjectStart && _currentState != State.ArrayStart)
{
WriteIndent();
}
}
WriteEnd(token);
JsonContainerType currentLevelType = Peek();
switch (currentLevelType)
{
case JsonContainerType.Object:
_currentState = State.Object;
break;
case JsonContainerType.Array:
_currentState = State.Array;
break;
case JsonContainerType.Constructor:
_currentState = State.Array;
break;
case JsonContainerType.None:
_currentState = State.Start;
break;
default:
throw JsonWriterException.Create(this, "Unknown JsonType: " + currentLevelType, null);
}
}
}
/// <summary>
/// Writes the specified end token.
/// </summary>
/// <param name="token">The end token to write.</param>
protected virtual void WriteEnd(JsonToken token)
{
}
/// <summary>
/// Writes indent characters.
/// </summary>
protected virtual void WriteIndent()
{
}
/// <summary>
/// Writes the JSON value delimiter.
/// </summary>
protected virtual void WriteValueDelimiter()
{
}
/// <summary>
/// Writes an indent space.
/// </summary>
protected virtual void WriteIndentSpace()
{
}
internal void AutoComplete(JsonToken tokenBeingWritten)
{
// gets new state based on the current state and what is being written
State newState = StateArray[(int)tokenBeingWritten][(int)_currentState];
if (newState == State.Error)
{
throw JsonWriterException.Create(this, "Token {0} in state {1} would result in an invalid JSON object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()), null);
}
if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment)
{
WriteValueDelimiter();
}
if (_formatting == Formatting.Indented)
{
if (_currentState == State.Property)
{
WriteIndentSpace();
}
// don't indent a property when it is the first token to be written (i.e. at the start)
if ((_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.Constructor || _currentState == State.ConstructorStart)
|| (tokenBeingWritten == JsonToken.PropertyName && _currentState != State.Start))
{
WriteIndent();
}
}
_currentState = newState;
}
#region WriteValue methods
/// <summary>
/// Writes a null value.
/// </summary>
public virtual void WriteNull()
{
InternalWriteValue(JsonToken.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public virtual void WriteUndefined()
{
InternalWriteValue(JsonToken.Undefined);
}
/// <summary>
/// Writes raw JSON without changing the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRaw(string json)
{
InternalWriteRaw();
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public virtual void WriteRawValue(string json)
{
// hack. want writer to change state as if a value had been written
UpdateScopeWithFinishedValue();
AutoComplete(JsonToken.Undefined);
WriteRaw(json);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public virtual void WriteValue(string value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public virtual void WriteValue(int value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public virtual void WriteValue(long value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public virtual void WriteValue(float value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public virtual void WriteValue(double value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public virtual void WriteValue(bool value)
{
InternalWriteValue(JsonToken.Boolean);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public virtual void WriteValue(short value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public virtual void WriteValue(char value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public virtual void WriteValue(byte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte value)
{
InternalWriteValue(JsonToken.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public virtual void WriteValue(decimal value)
{
InternalWriteValue(JsonToken.Float);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public virtual void WriteValue(DateTime value)
{
InternalWriteValue(JsonToken.Date);
}
#if !NET20
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset value)
{
InternalWriteValue(JsonToken.Date);
}
#endif
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public virtual void WriteValue(Guid value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public virtual void WriteValue(TimeSpan value)
{
InternalWriteValue(JsonToken.String);
}
/// <summary>
/// Writes a <see cref="Nullable{Int32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int32}"/> value to write.</param>
public virtual void WriteValue(int? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{UInt32}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt32}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(uint? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Int64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int64}"/> value to write.</param>
public virtual void WriteValue(long? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{UInt64}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt64}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ulong? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Single}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Single}"/> value to write.</param>
public virtual void WriteValue(float? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Double}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Double}"/> value to write.</param>
public virtual void WriteValue(double? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Boolean}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Boolean}"/> value to write.</param>
public virtual void WriteValue(bool? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Int16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Int16}"/> value to write.</param>
public virtual void WriteValue(short? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{UInt16}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{UInt16}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(ushort? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Char}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Char}"/> value to write.</param>
public virtual void WriteValue(char? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Byte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Byte}"/> value to write.</param>
public virtual void WriteValue(byte? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{SByte}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{SByte}"/> value to write.</param>
[CLSCompliant(false)]
public virtual void WriteValue(sbyte? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{Decimal}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Decimal}"/> value to write.</param>
public virtual void WriteValue(decimal? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{DateTime}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTime}"/> value to write.</param>
public virtual void WriteValue(DateTime? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
#if !NET20
/// <summary>
/// Writes a <see cref="Nullable{DateTimeOffset}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{DateTimeOffset}"/> value to write.</param>
public virtual void WriteValue(DateTimeOffset? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
#endif
/// <summary>
/// Writes a <see cref="Nullable{Guid}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{Guid}"/> value to write.</param>
public virtual void WriteValue(Guid? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Nullable{TimeSpan}"/> value.
/// </summary>
/// <param name="value">The <see cref="Nullable{TimeSpan}"/> value to write.</param>
public virtual void WriteValue(TimeSpan? value)
{
if (value == null)
{
WriteNull();
}
else
{
WriteValue(value.GetValueOrDefault());
}
}
/// <summary>
/// Writes a <see cref="Byte"/>[] value.
/// </summary>
/// <param name="value">The <see cref="Byte"/>[] value to write.</param>
public virtual void WriteValue(byte[] value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.Bytes);
}
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public virtual void WriteValue(Uri value)
{
if (value == null)
{
WriteNull();
}
else
{
InternalWriteValue(JsonToken.String);
}
}
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public virtual void WriteValue(object value)
{
if (value == null)
{
WriteNull();
}
else
{
#if !(NET20 || NET35 || PORTABLE || PORTABLE40)
// this is here because adding a WriteValue(BigInteger) to JsonWriter will
// mean the user has to add a reference to System.Numerics.dll
if (value is BigInteger)
{
throw CreateUnsupportedTypeException(this, value);
}
#endif
WriteValue(this, ConvertUtils.GetTypeCode(value.GetType()), value);
}
}
#endregion
/// <summary>
/// Writes out a comment <code>/*...*/</code> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public virtual void WriteComment(string text)
{
InternalWriteComment();
}
/// <summary>
/// Writes out the given white space.
/// </summary>
/// <param name="ws">The string of white space characters.</param>
public virtual void WriteWhitespace(string ws)
{
InternalWriteWhitespace(ws);
}
void IDisposable.Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (_currentState != State.Closed && disposing)
{
Close();
}
}
internal static void WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, object value)
{
switch (typeCode)
{
case PrimitiveTypeCode.Char:
writer.WriteValue((char)value);
break;
case PrimitiveTypeCode.CharNullable:
writer.WriteValue((value == null) ? (char?)null : (char)value);
break;
case PrimitiveTypeCode.Boolean:
writer.WriteValue((bool)value);
break;
case PrimitiveTypeCode.BooleanNullable:
writer.WriteValue((value == null) ? (bool?)null : (bool)value);
break;
case PrimitiveTypeCode.SByte:
writer.WriteValue((sbyte)value);
break;
case PrimitiveTypeCode.SByteNullable:
writer.WriteValue((value == null) ? (sbyte?)null : (sbyte)value);
break;
case PrimitiveTypeCode.Int16:
writer.WriteValue((short)value);
break;
case PrimitiveTypeCode.Int16Nullable:
writer.WriteValue((value == null) ? (short?)null : (short)value);
break;
case PrimitiveTypeCode.UInt16:
writer.WriteValue((ushort)value);
break;
case PrimitiveTypeCode.UInt16Nullable:
writer.WriteValue((value == null) ? (ushort?)null : (ushort)value);
break;
case PrimitiveTypeCode.Int32:
writer.WriteValue((int)value);
break;
case PrimitiveTypeCode.Int32Nullable:
writer.WriteValue((value == null) ? (int?)null : (int)value);
break;
case PrimitiveTypeCode.Byte:
writer.WriteValue((byte)value);
break;
case PrimitiveTypeCode.ByteNullable:
writer.WriteValue((value == null) ? (byte?)null : (byte)value);
break;
case PrimitiveTypeCode.UInt32:
writer.WriteValue((uint)value);
break;
case PrimitiveTypeCode.UInt32Nullable:
writer.WriteValue((value == null) ? (uint?)null : (uint)value);
break;
case PrimitiveTypeCode.Int64:
writer.WriteValue((long)value);
break;
case PrimitiveTypeCode.Int64Nullable:
writer.WriteValue((value == null) ? (long?)null : (long)value);
break;
case PrimitiveTypeCode.UInt64:
writer.WriteValue((ulong)value);
break;
case PrimitiveTypeCode.UInt64Nullable:
writer.WriteValue((value == null) ? (ulong?)null : (ulong)value);
break;
case PrimitiveTypeCode.Single:
writer.WriteValue((float)value);
break;
case PrimitiveTypeCode.SingleNullable:
writer.WriteValue((value == null) ? (float?)null : (float)value);
break;
case PrimitiveTypeCode.Double:
writer.WriteValue((double)value);
break;
case PrimitiveTypeCode.DoubleNullable:
writer.WriteValue((value == null) ? (double?)null : (double)value);
break;
case PrimitiveTypeCode.DateTime:
writer.WriteValue((DateTime)value);
break;
case PrimitiveTypeCode.DateTimeNullable:
writer.WriteValue((value == null) ? (DateTime?)null : (DateTime)value);
break;
#if !NET20
case PrimitiveTypeCode.DateTimeOffset:
writer.WriteValue((DateTimeOffset)value);
break;
case PrimitiveTypeCode.DateTimeOffsetNullable:
writer.WriteValue((value == null) ? (DateTimeOffset?)null : (DateTimeOffset)value);
break;
#endif
case PrimitiveTypeCode.Decimal:
writer.WriteValue((decimal)value);
break;
case PrimitiveTypeCode.DecimalNullable:
writer.WriteValue((value == null) ? (decimal?)null : (decimal)value);
break;
case PrimitiveTypeCode.Guid:
writer.WriteValue((Guid)value);
break;
case PrimitiveTypeCode.GuidNullable:
writer.WriteValue((value == null) ? (Guid?)null : (Guid)value);
break;
case PrimitiveTypeCode.TimeSpan:
writer.WriteValue((TimeSpan)value);
break;
case PrimitiveTypeCode.TimeSpanNullable:
writer.WriteValue((value == null) ? (TimeSpan?)null : (TimeSpan)value);
break;
#if !(PORTABLE || PORTABLE40 || NET35 || NET20)
case PrimitiveTypeCode.BigInteger:
// this will call to WriteValue(object)
writer.WriteValue((BigInteger)value);
break;
case PrimitiveTypeCode.BigIntegerNullable:
// this will call to WriteValue(object)
writer.WriteValue((value == null) ? (BigInteger?)null : (BigInteger)value);
break;
#endif
case PrimitiveTypeCode.Uri:
writer.WriteValue((Uri)value);
break;
case PrimitiveTypeCode.String:
writer.WriteValue((string)value);
break;
case PrimitiveTypeCode.Bytes:
writer.WriteValue((byte[])value);
break;
#if !(PORTABLE || DOTNET)
case PrimitiveTypeCode.DBNull:
writer.WriteNull();
break;
#endif
default:
#if !PORTABLE
if (value is IConvertible)
{
// the value is a non-standard IConvertible
// convert to the underlying value and retry
IConvertible convertable = (IConvertible)value;
TypeInformation typeInformation = ConvertUtils.GetTypeInformation(convertable);
// if convertable has an underlying typecode of Object then attempt to convert it to a string
PrimitiveTypeCode resolvedTypeCode = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? PrimitiveTypeCode.String : typeInformation.TypeCode;
Type resolvedType = (typeInformation.TypeCode == PrimitiveTypeCode.Object) ? typeof(string) : typeInformation.Type;
object convertedValue = convertable.ToType(resolvedType, CultureInfo.InvariantCulture);
WriteValue(writer, resolvedTypeCode, convertedValue);
break;
}
else
#endif
{
throw CreateUnsupportedTypeException(writer, value);
}
}
}
private static JsonWriterException CreateUnsupportedTypeException(JsonWriter writer, object value)
{
return JsonWriterException.Create(writer, "Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null);
}
/// <summary>
/// Sets the state of the JsonWriter,
/// </summary>
/// <param name="token">The JsonToken being written.</param>
/// <param name="value">The value being written.</param>
protected void SetWriteState(JsonToken token, object value)
{
switch (token)
{
case JsonToken.StartObject:
InternalWriteStart(token, JsonContainerType.Object);
break;
case JsonToken.StartArray:
InternalWriteStart(token, JsonContainerType.Array);
break;
case JsonToken.StartConstructor:
InternalWriteStart(token, JsonContainerType.Constructor);
break;
case JsonToken.PropertyName:
if (!(value is string))
{
throw new ArgumentException("A name is required when setting property name state.", nameof(value));
}
InternalWritePropertyName((string)value);
break;
case JsonToken.Comment:
InternalWriteComment();
break;
case JsonToken.Raw:
InternalWriteRaw();
break;
case JsonToken.Integer:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Boolean:
case JsonToken.Date:
case JsonToken.Bytes:
case JsonToken.Null:
case JsonToken.Undefined:
InternalWriteValue(token);
break;
case JsonToken.EndObject:
InternalWriteEnd(JsonContainerType.Object);
break;
case JsonToken.EndArray:
InternalWriteEnd(JsonContainerType.Array);
break;
case JsonToken.EndConstructor:
InternalWriteEnd(JsonContainerType.Constructor);
break;
default:
throw new ArgumentOutOfRangeException(nameof(token));
}
}
internal void InternalWriteEnd(JsonContainerType container)
{
AutoCompleteClose(container);
}
internal void InternalWritePropertyName(string name)
{
_currentPosition.PropertyName = name;
AutoComplete(JsonToken.PropertyName);
}
internal void InternalWriteRaw()
{
}
internal void InternalWriteStart(JsonToken token, JsonContainerType container)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
Push(container);
}
internal void InternalWriteValue(JsonToken token)
{
UpdateScopeWithFinishedValue();
AutoComplete(token);
}
internal void InternalWriteWhitespace(string ws)
{
if (ws != null)
{
if (!StringUtils.IsWhiteSpace(ws))
{
throw JsonWriterException.Create(this, "Only white space characters should be used.", null);
}
}
}
internal void InternalWriteComment()
{
AutoComplete(JsonToken.Comment);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Net.Http;
using System.Text;
using Xunit;
namespace WinHttpHandlerTests
{
public class WinHttpResponseStreamTests
{
public WinHttpResponseStreamTests()
{
TestControl.ResetAll();
}
[Fact]
public void CanRead_WhenCreated_ReturnsTrue()
{
Stream stream = MakeResponseStream();
bool result = stream.CanRead;
Assert.True(result);
}
[Fact]
public void CanRead_WhenDisposed_ReturnsFalse()
{
Stream stream = MakeResponseStream();
stream.Dispose();
bool result = stream.CanRead;
Assert.False(result);
}
[Fact]
public void CanSeek_Always_ReturnsFalse()
{
Stream stream = MakeResponseStream();
bool result = stream.CanSeek;
Assert.False(result);
}
[Fact]
public void CanWrite_Always_ReturnsFalse()
{
Stream stream = MakeResponseStream();
bool result = stream.CanWrite;
Assert.False(result);
}
[Fact]
public void Length_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => { long result = stream.Length; });
}
[Fact]
public void Length_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { long result = stream.Length; });
}
[Fact]
public void Position_WhenCreatedDoGet_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => { long result = stream.Position; });
}
[Fact]
public void Position_WhenDisposedDoGet_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { long result = stream.Position; });
}
[Fact]
public void Position_WhenCreatedDoSet_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => { stream.Position = 0; });
}
[Fact]
public void Position_WhenDisposedDoSet_ThrowsObjectDisposedExceptionException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { stream.Position = 0; });
}
[Fact]
public void Seek_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => { stream.Seek(0, SeekOrigin.Begin); });
}
[Fact]
public void Seek_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { stream.Seek(0, SeekOrigin.Begin); });
}
[Fact]
public void SetLength_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => { stream.SetLength(0); });
}
[Fact]
public void SetLength_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { stream.SetLength(0); });
}
[Fact]
public void Write_WhenCreated_ThrowsNotSupportedException()
{
Stream stream = MakeResponseStream();
Assert.Throws<NotSupportedException>(() => { stream.Write(new byte[1], 0, 1); });
}
[Fact]
public void Write_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { stream.Write(new byte[1], 0, 1); });
}
[Fact]
public void Read_BufferIsNull_ThrowsArgumentNullException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentNullException>(() => { stream.Read(null, 0, 1); });
}
[Fact]
public void Read_OffsetIsNegative_ThrowsArgumentOutOfRangeException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Read(new byte[1], -1, 1); });
}
[Fact]
public void Read_CountIsNegative_ThrowsArgumentOutOfRangeException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentOutOfRangeException>(() => { stream.Read(new byte[1], 0, -1); });
}
[Fact]
public void Read_OffsetPlusCountExceedsBufferLength_ThrowsArgumentException()
{
Stream stream = MakeResponseStream();
Assert.Throws<ArgumentException>(() => { stream.Read(new byte[1], int.MaxValue, int.MaxValue); });
}
[Fact]
public void Read_WhenDisposed_ThrowsObjectDisposedException()
{
Stream stream = MakeResponseStream();
stream.Dispose();
Assert.Throws<ObjectDisposedException>(() => { stream.Read(new byte[1], 0, 1); });
}
[Fact]
public void Read_NetworkFails_ThrowsIOException()
{
Stream stream = MakeResponseStream();
TestControl.WinHttpAPIFail = true;
Assert.Throws<IOException>(() => { stream.Read(new byte[1], 0, 1); });
}
[Fact]
public void Read_NoOffsetAndNotEndOfData_FillsBuffer()
{
Stream stream = MakeResponseStream();
byte[] testData = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
TestServer.ResponseBody = testData;
byte[] buffer = new byte[testData.Length];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
Assert.Equal(buffer.Length, bytesRead);
for (int i = 0; i < buffer.Length; i++)
{
Assert.Equal(testData[i], buffer[i]);
}
}
[Fact]
public void Read_UsingOffsetAndNotEndOfData_FillsBufferFromOffset()
{
Stream stream = MakeResponseStream();
byte[] testData = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZ");
TestServer.ResponseBody = testData;
byte[] buffer = new byte[testData.Length];
int offset = 5;
int bytesRead = stream.Read(buffer, offset, buffer.Length - offset);
Assert.Equal(buffer.Length - offset, bytesRead);
for (int i = 0; i < offset; i++)
{
Assert.Equal(0, buffer[i]);
}
for (int i = offset; i < buffer.Length; i++)
{
Assert.Equal(testData[i - offset], buffer[i]);
}
}
internal Stream MakeResponseStream()
{
var sessionHandle = new FakeSafeWinHttpHandle(true);
var connectHandle = new FakeSafeWinHttpHandle(true);
var requestHandle = new FakeSafeWinHttpHandle(true);
return new WinHttpResponseStream(sessionHandle, connectHandle, requestHandle);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
namespace System
{
public static partial class PlatformDetection
{
//
// Do not use the " { get; } = <expression> " pattern here. Having all the initialization happen in the type initializer
// means that one exception anywhere means all tests using PlatformDetection fail. If you feel a value is worth latching,
// do it in a way that failures don't cascade.
//
public static bool IsFullFramework => RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase);
public static bool IsWindows => RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
public static bool IsWindows7 => IsWindows && GetWindowsVersion() == 6 && GetWindowsMinorVersion() == 1;
public static bool IsWindows8x => IsWindows && GetWindowsVersion() == 6 && (GetWindowsMinorVersion() == 2 || GetWindowsMinorVersion() == 3);
public static bool IsOSX => RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
public static bool IsNetBSD => RuntimeInformation.IsOSPlatform(OSPlatform.Create("NETBSD"));
public static bool IsOpenSUSE => IsDistroAndVersion("opensuse");
public static bool IsUbuntu => IsDistroAndVersion("ubuntu");
public static bool IsNotWindowsNanoServer => (!IsWindows ||
File.Exists(Path.Combine(Environment.GetEnvironmentVariable("windir"), "regedit.exe")));
public static bool IsWindows10Version1607OrGreater => IsWindows &&
GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 14393;
public static bool IsWindows10Version1703OrGreater => IsWindows &&
GetWindowsVersion() == 10 && GetWindowsMinorVersion() == 0 && GetWindowsBuildNumber() >= 15063;
// Windows OneCoreUAP SKU doesn't have httpapi.dll
public static bool HasHttpApi => (IsWindows &&
File.Exists(Path.Combine(Environment.GetEnvironmentVariable("windir"), "System32", "httpapi.dll")));
public static bool IsNotOneCoreUAP => (!IsWindows ||
File.Exists(Path.Combine(Environment.GetEnvironmentVariable("windir"), "System32", "httpapi.dll")));
public static int WindowsVersion => GetWindowsVersion();
private static int s_isWinRT = -1;
public static bool IsWinRT
{
get
{
if (s_isWinRT != -1)
return s_isWinRT == 1;
if (!IsWindows || IsWindows7)
{
s_isWinRT = 0;
return false;
}
byte[] buffer = new byte[0];
uint bufferSize = 0;
try
{
int result = GetCurrentApplicationUserModelId(ref bufferSize, buffer);
switch (result)
{
case 15703: // APPMODEL_ERROR_NO_APPLICATION
s_isWinRT = 0;
break;
case 0: // ERROR_SUCCESS
case 122: // ERROR_INSUFFICIENT_BUFFER
// Success is actually insufficent buffer as we're really only looking for
// not NO_APPLICATION and we're not actually giving a buffer here. The
// API will always return NO_APPLICATION if we're not running under a
// WinRT process, no matter what size the buffer is.
s_isWinRT = 1;
break;
default:
throw new InvalidOperationException($"Failed to get AppId, result was {result}.");
}
}
catch (Exception e)
{
// We could catch this here, being friendly with older portable surface area should we
// desire to use this method elsewhere.
if (e.GetType().FullName.Equals("System.EntryPointNotFoundException", StringComparison.Ordinal))
{
// API doesn't exist, likely pre Win8
s_isWinRT = 0;
}
else
{
throw;
}
}
return s_isWinRT == 1;
}
}
private static Lazy<bool> m_isWindowsSubsystemForLinux = new Lazy<bool>(GetIsWindowsSubsystemForLinux);
public static bool IsWindowsSubsystemForLinux => m_isWindowsSubsystemForLinux.Value;
public static bool IsNotWindowsSubsystemForLinux => !IsWindowsSubsystemForLinux;
public static bool IsNotFedoraOrRedHatOrCentos => !IsDistroAndVersion("fedora") && !IsDistroAndVersion("rhel") && !IsDistroAndVersion("centos");
public static bool IsFedora => IsDistroAndVersion("fedora");
private static bool GetIsWindowsSubsystemForLinux()
{
// https://github.com/Microsoft/BashOnWindows/issues/423#issuecomment-221627364
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
const string versionFile = "/proc/version";
if (File.Exists(versionFile))
{
string s = File.ReadAllText(versionFile);
if (s.Contains("Microsoft") || s.Contains("WSL"))
{
return true;
}
}
}
return false;
}
public static bool IsDebian8 => IsDistroAndVersion("debian", "8");
public static bool IsUbuntu1404 => IsDistroAndVersion("ubuntu", "14.04");
public static bool IsUbuntu1510 => IsDistroAndVersion("ubuntu", "15.10");
public static bool IsUbuntu1604 => IsDistroAndVersion("ubuntu", "16.04");
public static bool IsUbuntu1610 => IsDistroAndVersion("ubuntu", "16.10");
public static bool IsFedora24 => IsDistroAndVersion("fedora", "24");
public static bool IsFedora25 => IsDistroAndVersion("fedora", "25");
public static bool IsFedora26 => IsDistroAndVersion("fedora", "26");
public static bool IsCentos7 => IsDistroAndVersion("centos", "7");
/// <summary>
/// Get whether the OS platform matches the given Linux distro and optional version.
/// </summary>
/// <param name="distroId">The distribution id.</param>
/// <param name="versionId">The distro version. If omitted, compares the distro only.</param>
/// <returns>Whether the OS platform matches the given Linux distro and optional version.</returns>
private static bool IsDistroAndVersion(string distroId, string versionId = null)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
IdVersionPair v = ParseOsReleaseFile();
if (v.Id == distroId && (versionId == null || v.VersionId == versionId))
{
return true;
}
}
return false;
}
private static IdVersionPair ParseOsReleaseFile()
{
Debug.Assert(RuntimeInformation.IsOSPlatform(OSPlatform.Linux));
IdVersionPair ret = new IdVersionPair();
ret.Id = "";
ret.VersionId = "";
if (File.Exists("/etc/os-release"))
{
foreach (string line in File.ReadLines("/etc/os-release"))
{
if (line.StartsWith("ID=", System.StringComparison.Ordinal))
{
ret.Id = line.Substring("ID=".Length);
}
else if (line.StartsWith("VERSION_ID=", System.StringComparison.Ordinal))
{
ret.VersionId = line.Substring("VERSION_ID=".Length);
}
}
}
string versionId = ret.VersionId;
if (versionId.Length >= 2 && versionId[0] == '"' && versionId[versionId.Length - 1] == '"')
{
// Remove quotes.
ret.VersionId = versionId.Substring(1, versionId.Length - 2);
}
if (ret.Id.Length >= 2 && ret.Id[0] == '"' && ret.Id[ret.Id.Length - 1] == '"')
{
// Remove quotes.
ret.Id = ret.Id.Substring(1, ret.Id.Length - 2);
}
return ret;
}
private struct IdVersionPair
{
public string Id { get; set; }
public string VersionId { get; set; }
}
private static int GetWindowsVersion()
{
if (IsWindows)
{
RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX();
osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
Assert.Equal(0, RtlGetVersion(out osvi));
return (int)osvi.dwMajorVersion;
}
return -1;
}
private static int GetWindowsMinorVersion()
{
if (IsWindows)
{
RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX();
osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
Assert.Equal(0, RtlGetVersion(out osvi));
return (int)osvi.dwMinorVersion;
}
return -1;
}
private static int GetWindowsBuildNumber()
{
if (IsWindows)
{
RTL_OSVERSIONINFOEX osvi = new RTL_OSVERSIONINFOEX();
osvi.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi);
Assert.Equal(0, RtlGetVersion(out osvi));
return (int)osvi.dwBuildNumber;
}
return -1;
}
[DllImport("ntdll.dll")]
private static extern int RtlGetVersion(out RTL_OSVERSIONINFOEX lpVersionInformation);
[StructLayout(LayoutKind.Sequential)]
private struct RTL_OSVERSIONINFOEX
{
internal uint dwOSVersionInfoSize;
internal uint dwMajorVersion;
internal uint dwMinorVersion;
internal uint dwBuildNumber;
internal uint dwPlatformId;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
internal string szCSDVersion;
}
private static int s_isWindowsElevated = -1;
public static bool IsWindowsAndElevated
{
get
{
if (s_isWindowsElevated != -1)
return s_isWindowsElevated == 1;
if (!IsWindows || IsWinRT)
{
s_isWindowsElevated = 0;
return false;
}
IntPtr processToken;
Assert.True(OpenProcessToken(GetCurrentProcess(), TOKEN_READ, out processToken));
try
{
uint tokenInfo;
uint returnLength;
Assert.True(GetTokenInformation(
processToken, TokenElevation, out tokenInfo, sizeof(uint), out returnLength));
s_isWindowsElevated = tokenInfo == 0 ? 0 : 1;
}
finally
{
CloseHandle(processToken);
}
return s_isWindowsElevated == 1;
}
}
private const uint TokenElevation = 20;
private const uint STANDARD_RIGHTS_READ = 0x00020000;
private const uint TOKEN_QUERY = 0x0008;
private const uint TOKEN_READ = STANDARD_RIGHTS_READ | TOKEN_QUERY;
[DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)]
public static extern bool GetTokenInformation(
IntPtr TokenHandle,
uint TokenInformationClass,
out uint TokenInformation,
uint TokenInformationLength,
out uint ReturnLength);
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
public static extern bool CloseHandle(
IntPtr handle);
[DllImport("advapi32.dll", SetLastError = true, ExactSpelling = true)]
public static extern bool OpenProcessToken(
IntPtr ProcessHandle,
uint DesiredAccesss,
out IntPtr TokenHandle);
// The process handle does NOT need closing
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll", ExactSpelling = true)]
public static extern int GetCurrentApplicationUserModelId(
ref uint applicationUserModelIdLength,
byte[] applicationUserModelId);
public static bool IsNonZeroLowerBoundArraySupported
{
get
{
if (s_lazyNonZeroLowerBoundArraySupported == null)
{
bool nonZeroLowerBoundArraysSupported = false;
try
{
Array.CreateInstance(typeof(int), new int[] { 5 }, new int[] { 5 });
nonZeroLowerBoundArraysSupported = true;
}
catch (PlatformNotSupportedException)
{
}
s_lazyNonZeroLowerBoundArraySupported = Tuple.Create<bool>(nonZeroLowerBoundArraysSupported);
}
return s_lazyNonZeroLowerBoundArraySupported.Item1;
}
}
private static volatile Tuple<bool> s_lazyNonZeroLowerBoundArraySupported;
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Graphics.Textures;
using osu.Framework.IO.Stores;
using osu.Framework.Testing;
using osu.Framework.Timing;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.Formats;
using osu.Game.IO;
using osu.Game.Rulesets;
using osu.Game.Rulesets.Objects;
using osu.Game.Screens.Ranking;
using osu.Game.Skinning;
using osu.Game.Storyboards;
using osu.Game.Tests.Visual;
using osu.Game.Users;
namespace osu.Game.Tests.Beatmaps
{
[HeadlessTest]
public abstract class HitObjectSampleTest : PlayerTestScene, IStorageResourceProvider
{
protected abstract IResourceStore<byte[]> RulesetResources { get; }
protected LegacySkin Skin { get; private set; }
[Resolved]
private RulesetStore rulesetStore { get; set; }
private readonly SkinInfo userSkinInfo = new SkinInfo();
private readonly BeatmapInfo beatmapInfo = new BeatmapInfo
{
BeatmapSet = new BeatmapSetInfo(),
Metadata = new BeatmapMetadata
{
Author = User.SYSTEM_USER
}
};
private readonly TestResourceStore userSkinResourceStore = new TestResourceStore();
private readonly TestResourceStore beatmapSkinResourceStore = new TestResourceStore();
private SkinSourceDependencyContainer dependencies;
private IBeatmap currentTestBeatmap;
protected sealed override bool HasCustomSteps => true;
protected override bool Autoplay => true;
protected sealed override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent)
=> new DependencyContainer(dependencies = new SkinSourceDependencyContainer(base.CreateChildDependencies(parent)));
protected sealed override IBeatmap CreateBeatmap(RulesetInfo ruleset) => currentTestBeatmap;
protected sealed override WorkingBeatmap CreateWorkingBeatmap(IBeatmap beatmap, Storyboard storyboard = null)
=> new TestWorkingBeatmap(beatmapInfo, beatmapSkinResourceStore, beatmap, storyboard, Clock, this);
protected override TestPlayer CreatePlayer(Ruleset ruleset) => new TestPlayer(false);
protected void CreateTestWithBeatmap(string filename)
{
CreateTest(() =>
{
AddStep("clear performed lookups", () =>
{
userSkinResourceStore.PerformedLookups.Clear();
beatmapSkinResourceStore.PerformedLookups.Clear();
});
AddStep($"load {filename}", () =>
{
using (var reader = new LineBufferedReader(RulesetResources.GetStream($"Resources/SampleLookups/{filename}")))
currentTestBeatmap = Decoder.GetDecoder<Beatmap>(reader).Decode(reader);
// populate ruleset for beatmap converters that require it to be present.
currentTestBeatmap.BeatmapInfo.Ruleset = rulesetStore.GetRuleset(currentTestBeatmap.BeatmapInfo.RulesetID);
});
});
AddStep("seek to completion", () => Player.GameplayClockContainer.Seek(Player.DrawableRuleset.Objects.Last().GetEndTime()));
AddUntilStep("results displayed", () => Stack.CurrentScreen is ResultsScreen);
}
protected void SetupSkins(string beatmapFile, string userFile)
{
AddStep("setup skins", () =>
{
userSkinInfo.Files = new List<SkinFileInfo>
{
new SkinFileInfo
{
Filename = userFile,
FileInfo = new IO.FileInfo { Hash = userFile }
}
};
beatmapInfo.BeatmapSet.Files = new List<BeatmapSetFileInfo>
{
new BeatmapSetFileInfo
{
Filename = beatmapFile,
FileInfo = new IO.FileInfo { Hash = beatmapFile }
}
};
// Need to refresh the cached skin source to refresh the skin resource store.
dependencies.SkinSource = new SkinProvidingContainer(Skin = new LegacySkin(userSkinInfo, this));
});
}
protected void AssertBeatmapLookup(string name) => AddAssert($"\"{name}\" looked up from beatmap skin",
() => !userSkinResourceStore.PerformedLookups.Contains(name) && beatmapSkinResourceStore.PerformedLookups.Contains(name));
protected void AssertUserLookup(string name) => AddAssert($"\"{name}\" looked up from user skin",
() => !beatmapSkinResourceStore.PerformedLookups.Contains(name) && userSkinResourceStore.PerformedLookups.Contains(name));
protected void AssertNoLookup(string name) => AddAssert($"\"{name}\" not looked up",
() => !beatmapSkinResourceStore.PerformedLookups.Contains(name) && !userSkinResourceStore.PerformedLookups.Contains(name));
#region IResourceStorageProvider
public AudioManager AudioManager => Audio;
public IResourceStore<byte[]> Files => userSkinResourceStore;
public new IResourceStore<byte[]> Resources => base.Resources;
public IResourceStore<TextureUpload> CreateTextureLoaderStore(IResourceStore<byte[]> underlyingStore) => null;
#endregion
private class SkinSourceDependencyContainer : IReadOnlyDependencyContainer
{
public ISkinSource SkinSource;
private readonly IReadOnlyDependencyContainer fallback;
public SkinSourceDependencyContainer(IReadOnlyDependencyContainer fallback)
{
this.fallback = fallback;
}
public object Get(Type type)
{
if (type == typeof(ISkinSource))
return SkinSource;
return fallback.Get(type);
}
public object Get(Type type, CacheInfo info)
{
if (type == typeof(ISkinSource))
return SkinSource;
return fallback.Get(type, info);
}
public void Inject<T>(T instance) where T : class
{
// Never used directly
}
}
private class TestResourceStore : IResourceStore<byte[]>
{
public readonly List<string> PerformedLookups = new List<string>();
public byte[] Get(string name)
{
markLookup(name);
return Array.Empty<byte>();
}
public Task<byte[]> GetAsync(string name)
{
markLookup(name);
return Task.FromResult(Array.Empty<byte>());
}
public Stream GetStream(string name)
{
markLookup(name);
return new MemoryStream();
}
private void markLookup(string name) => PerformedLookups.Add(name.Substring(name.LastIndexOf(Path.DirectorySeparatorChar) + 1));
public IEnumerable<string> GetAvailableResources() => Enumerable.Empty<string>();
public void Dispose()
{
}
}
private class TestWorkingBeatmap : ClockBackedTestWorkingBeatmap
{
private readonly BeatmapInfo skinBeatmapInfo;
private readonly IResourceStore<byte[]> resourceStore;
private readonly IStorageResourceProvider resources;
public TestWorkingBeatmap(BeatmapInfo skinBeatmapInfo, IResourceStore<byte[]> resourceStore, IBeatmap beatmap, Storyboard storyboard, IFrameBasedClock referenceClock, IStorageResourceProvider resources)
: base(beatmap, storyboard, referenceClock, resources.AudioManager)
{
this.skinBeatmapInfo = skinBeatmapInfo;
this.resourceStore = resourceStore;
this.resources = resources;
}
protected internal override ISkin GetSkin() => new LegacyBeatmapSkin(skinBeatmapInfo, resourceStore, resources);
}
}
}
| |
// Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// 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
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading;
using Microsoft.PythonTools.Infrastructure;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudio;
using Microsoft.VisualStudio.Imaging;
using Microsoft.VisualStudio.Imaging.Interop;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudioTools.Project;
using NativeMethods = Microsoft.VisualStudioTools.Project.NativeMethods;
using OleConstants = Microsoft.VisualStudio.OLE.Interop.Constants;
using VsCommands = Microsoft.VisualStudio.VSConstants.VSStd97CmdID;
using VsMenus = Microsoft.VisualStudioTools.Project.VsMenus;
namespace Microsoft.PythonTools.Project {
/// <summary>
/// Represents a package installed in a virtual env as a node in the Solution Explorer.
/// </summary>
[ComVisible(true)]
internal class InterpretersPackageNode : HierarchyNode {
private static readonly Regex PipFreezeRegex = new Regex(
"^(?<name>[^=]+)==(?<version>.+)$",
RegexOptions.Compiled | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase
);
private static readonly IEnumerable<string> CannotUninstall = new[] { "pip", "wsgiref" };
private readonly bool _canUninstall;
private readonly PackageSpec _package;
private readonly string _caption;
private readonly string _packageName;
public InterpretersPackageNode(PythonProjectNode project, PackageSpec spec)
: base(project, new VirtualProjectElement(project)) {
ExcludeNodeFromScc = true;
_package = spec.Clone();
_packageName = spec.FullSpec;
if (spec.ExactVersion.IsEmpty) {
_caption = spec.Name;
_canUninstall = false;
} else {
_caption = string.Format("{0} ({1})", spec.Name, spec.ExactVersion);
_canUninstall = !CannotUninstall.Contains(spec.Name);
}
}
public override int MenuCommandId {
get { return PythonConstants.EnvironmentPackageMenuId; }
}
public override Guid MenuGroupId {
get { return GuidList.guidPythonToolsCmdSet; }
}
public override string Url {
get { return _packageName; }
}
public override Guid ItemTypeGuid {
get { return PythonConstants.InterpretersPackageItemTypeGuid; }
}
public new PythonProjectNode ProjectMgr {
get {
return (PythonProjectNode)base.ProjectMgr;
}
}
internal override bool CanDeleteItem(__VSDELETEITEMOPERATION deleteOperation) {
return _canUninstall && deleteOperation == __VSDELETEITEMOPERATION.DELITEMOP_RemoveFromProject;
}
protected internal override void ShowDeleteMessage(IList<HierarchyNode> nodes, __VSDELETEITEMOPERATION action, out bool cancel, out bool useStandardDialog) {
if (nodes.All(n => n is InterpretersPackageNode) &&
nodes.Cast<InterpretersPackageNode>().All(n => n.Parent == Parent)) {
string message;
if (nodes.Count == 1) {
message = Strings.UninstallPackage.FormatUI(
Caption,
Parent._factory.Configuration.Description,
Parent._factory.Configuration.PrefixPath
);
} else {
message = Strings.UninstallPackages.FormatUI(
string.Join(Environment.NewLine, nodes.Select(n => n.Caption)),
Parent._factory.Configuration.Description,
Parent._factory.Configuration.PrefixPath
);
}
useStandardDialog = false;
cancel = VsShellUtilities.ShowMessageBox(
ProjectMgr.Site,
string.Empty,
message,
OLEMSGICON.OLEMSGICON_WARNING,
OLEMSGBUTTON.OLEMSGBUTTON_OKCANCEL,
OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST
) != NativeMethods.IDOK;
} else {
useStandardDialog = false;
cancel = true;
}
}
public override bool Remove(bool removeFromStorage) {
RemoveAsync()
.SilenceException<OperationCanceledException>()
.HandleAllExceptions(ProjectMgr.Site, GetType())
.DoNotWait();
return true;
}
private async System.Threading.Tasks.Task RemoveAsync() {
var pm = Parent._factory.PackageManager;
if (pm == null) {
Debug.Fail("Should not be able to remove a package without a package manager");
return;
}
var provider = ProjectMgr.Site;
var statusBar = (IVsStatusbar)provider.GetService(typeof(SVsStatusbar));
try {
statusBar.SetText(Strings.PackageUninstallingSeeOutputWindow.FormatUI(_packageName));
bool success = await pm.UninstallAsync(
_package,
new VsPackageManagerUI(provider),
CancellationToken.None
);
statusBar.SetText((success ? Strings.PackageUninstallSucceeded : Strings.PackageUninstallFailed).FormatUI(
_packageName
));
} catch (OperationCanceledException) {
} catch (Exception ex) when (!ex.IsCriticalException()) {
statusBar.SetText(Strings.PackageUninstallFailed.FormatUI(_packageName));
}
}
public new InterpretersNode Parent {
get {
return (InterpretersNode)base.Parent;
}
}
/// <summary>
/// Show the name of the package.
/// </summary>
public override string Caption {
get {
return _caption;
}
}
/// <summary>
/// Disable inline editing of Caption of a package node
/// </summary>
public override string GetEditLabel() {
return null;
}
protected override bool SupportsIconMonikers {
get { return true; }
}
protected override ImageMoniker GetIconMoniker(bool open) {
return KnownMonikers.PythonPackage;
}
/// <summary>
/// Package node cannot be dragged.
/// </summary>
protected internal override string PrepareSelectedNodesForClipBoard() {
return null;
}
/// <summary>
/// Package node cannot be excluded.
/// </summary>
internal override int ExcludeFromProject() {
return (int)OleConstants.OLECMDERR_E_NOTSUPPORTED;
}
internal override int QueryStatusOnNode(Guid cmdGroup, uint cmd, IntPtr pCmdText, ref QueryStatusResult result) {
if (cmdGroup == VsMenus.guidStandardCommandSet97) {
switch ((VsCommands)cmd) {
case VsCommands.Copy:
case VsCommands.Cut:
result |= QueryStatusResult.SUPPORTED | QueryStatusResult.INVISIBLE;
return VSConstants.S_OK;
case VsCommands.Delete:
if (!_canUninstall) {
// If we can't uninstall the package, still show the
// item but disable it. Otherwise, let the default
// query handle it, which will display "Remove".
result |= QueryStatusResult.SUPPORTED;
return VSConstants.S_OK;
}
break;
}
}
return base.QueryStatusOnNode(cmdGroup, cmd, pCmdText, ref result);
}
/// <summary>
/// Defines whether this node is valid node for painting the package icon.
/// </summary>
/// <returns></returns>
protected override bool CanShowDefaultIcon() {
return true;
}
public override bool CanAddFiles {
get {
return false;
}
}
protected override NodeProperties CreatePropertiesObject() {
return new InterpretersPackageNodeProperties(this);
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.Utilities.Collections;
namespace Org.BouncyCastle.Bcpg.OpenPgp
{
/// <remarks>General class to handle a PGP public key object.</remarks>
public class PgpPublicKey : IPgpPublicKey
{
private static readonly int[] _masterKeyCertificationTypes = new[]
{
PgpSignature.PositiveCertification,
PgpSignature.CasualCertification,
PgpSignature.NoCertification,
PgpSignature.DefaultCertification
};
private byte[] _fingerprint;
private IPublicKeyPacket _publicPk;
private readonly ITrustPacket _trustPk;
private readonly IList<IPgpSignature> _keySigs = Platform.CreateArrayList<IPgpSignature>();
private readonly IList _ids = Platform.CreateArrayList();
private readonly IList<ITrustPacket> _idTrusts = Platform.CreateArrayList<ITrustPacket>();
private readonly IList<IList<IPgpSignature>> _idSigs = Platform.CreateArrayList<IList<IPgpSignature>>();
private readonly IList<IPgpSignature> _subSigs;
private void Init()
{
var key = _publicPk.Key;
if (_publicPk.Version <= 3)
{
var rK = (RsaPublicBcpgKey)key;
_fingerprint = BuildFingerprintMd5(_publicPk);
this.KeyId = rK.Modulus.LongValue;
this.BitStrength = rK.Modulus.BitLength;
}
else
{
_fingerprint = BuildFingerprintSha1(_publicPk);
this.KeyId = (long)(((ulong)_fingerprint[_fingerprint.Length - 8] << 56)
| ((ulong)_fingerprint[_fingerprint.Length - 7] << 48)
| ((ulong)_fingerprint[_fingerprint.Length - 6] << 40)
| ((ulong)_fingerprint[_fingerprint.Length - 5] << 32)
| ((ulong)_fingerprint[_fingerprint.Length - 4] << 24)
| ((ulong)_fingerprint[_fingerprint.Length - 3] << 16)
| ((ulong)_fingerprint[_fingerprint.Length - 2] << 8)
| (ulong)_fingerprint[_fingerprint.Length - 1]);
this.BitStrength = key.BitStrength;
}
}
/// <summary>
/// Create a PgpPublicKey from the passed in lightweight one.
/// </summary>
/// <remarks>
/// Note: the time passed in affects the value of the key's keyId, so you probably only want
/// to do this once for a lightweight key, or make sure you keep track of the time you used.
/// </remarks>
/// <param name="algorithm">Asymmetric algorithm type representing the public key.</param>
/// <param name="pubKey">Actual public key to associate.</param>
/// <param name="time">Date of creation.</param>
/// <exception cref="ArgumentException">If <c>pubKey</c> is not public.</exception>
/// <exception cref="PgpException">On key creation problem.</exception>
public PgpPublicKey(PublicKeyAlgorithmTag algorithm, IAsymmetricKeyParameter pubKey, DateTime time)
{
if (pubKey.IsPrivate)
throw new ArgumentException(@"Expected a public key", "pubKey");
IBcpgPublicKey bcpgKey;
if (pubKey is RsaKeyParameters)
{
var rK = (RsaKeyParameters)pubKey;
bcpgKey = new RsaPublicBcpgKey(rK.Modulus, rK.Exponent);
}
else if (pubKey is DsaPublicKeyParameters)
{
var dK = (DsaPublicKeyParameters)pubKey;
var dP = dK.Parameters;
bcpgKey = new DsaPublicBcpgKey(dP.P, dP.Q, dP.G, dK.Y);
}
else if (pubKey is ElGamalPublicKeyParameters)
{
var eK = (ElGamalPublicKeyParameters)pubKey;
var eS = eK.Parameters;
bcpgKey = new ElGamalPublicBcpgKey(eS.P, eS.G, eK.Y);
}
else if (pubKey is ECDHPublicKeyParameters)
{
var ecdh = (ECDHPublicKeyParameters)pubKey;
bcpgKey = new ECDHPublicBcpgKey(ecdh.Q, ecdh.PublicKeyParamSet, ecdh.HashAlgorithm, ecdh.SymmetricKeyAlgorithm);
}
else if (pubKey is ECPublicKeyParameters)
{
var ecdsa = (ECPublicKeyParameters)pubKey;
bcpgKey = new ECDSAPublicBcpgKey(ecdsa.Q, ecdsa.PublicKeyParamSet);
}
else
{
throw new PgpException("unknown key class");
}
_publicPk = new PublicKeyPacket(algorithm, time, bcpgKey);
_ids = Platform.CreateArrayList();
_idSigs = Platform.CreateArrayList<IList<IPgpSignature>>();
try
{
Init();
}
catch (IOException e)
{
throw new PgpException("exception calculating keyId", e);
}
}
/// <summary>Constructor for a sub-key.</summary>
internal PgpPublicKey(IPublicKeyPacket publicPk, ITrustPacket trustPk, IList<IPgpSignature> sigs)
{
_publicPk = publicPk;
_trustPk = trustPk;
_subSigs = sigs;
Init();
}
internal PgpPublicKey(IPgpPublicKey key, ITrustPacket trust, IList<IPgpSignature> subSigs)
{
_publicPk = key.PublicKeyPacket;
_trustPk = trust;
_subSigs = subSigs;
_fingerprint = key.GetFingerprint();
KeyId = key.KeyId;
BitStrength = key.BitStrength;
}
/// <summary>Copy constructor.</summary>
/// <param name="pubKey">The public key to copy.</param>
internal PgpPublicKey(IPgpPublicKey pubKey)
{
_publicPk = pubKey.PublicKeyPacket;
_keySigs = Platform.CreateArrayList(pubKey.KeySigs);
_ids = Platform.CreateArrayList(pubKey.Ids);
_idTrusts = Platform.CreateArrayList(pubKey.IdTrusts);
_idSigs = Platform.CreateArrayList(pubKey.IdSigs);
if (pubKey.SubSigs != null)
{
_subSigs = Platform.CreateArrayList(pubKey.SubSigs);
}
_fingerprint = pubKey.GetFingerprint();
KeyId = pubKey.KeyId;
BitStrength = pubKey.BitStrength;
}
internal PgpPublicKey(IPublicKeyPacket publicPk, ITrustPacket trustPk, IList<IPgpSignature> keySigs, IList ids, IList<ITrustPacket> idTrusts, IList<IList<IPgpSignature>> idSigs)
{
_publicPk = publicPk;
_trustPk = trustPk;
_keySigs = keySigs;
_ids = ids;
_idTrusts = idTrusts;
_idSigs = idSigs;
Init();
}
internal PgpPublicKey(IPublicKeyPacket publicPk, IList ids, IList<IList<IPgpSignature>> idSigs)
{
_publicPk = publicPk;
_ids = ids;
_idSigs = idSigs;
Init();
}
/// <summary>The version of this key.</summary>
public int Version
{
get { return _publicPk.Version; }
}
/// <summary>The creation time of this key.</summary>
public DateTime CreationTime
{
get { return _publicPk.GetTime(); }
}
/// <summary>The number of valid days from creation time - zero means no expiry.</summary>
public int ValidDays
{
get
{
if (_publicPk.Version > 3)
{
return (int)(GetValidSeconds() / (24 * 60 * 60));
}
return _publicPk.ValidDays;
}
}
public IPublicKeyPacket PublicKeyPacket
{
get { return _publicPk; }
internal set { _publicPk = value; }
}
public ITrustPacket TrustPaket
{
get { return _trustPk; }
}
public IList<IPgpSignature> KeySigs
{
get { return _keySigs; }
}
public IList Ids
{
get { return _ids; }
}
public IList<ITrustPacket> IdTrusts
{
get { return _idTrusts; }
}
public IList<IList<IPgpSignature>> IdSigs
{
get { return _idSigs; }
}
public IList<IPgpSignature> SubSigs
{
get { return _subSigs; }
}
/// <summary>Return the trust data associated with the public key, if present.</summary>
/// <returns>A byte array with trust data, null otherwise.</returns>
public byte[] GetTrustData()
{
return _trustPk == null ? null : _trustPk.GetLevelAndTrustAmount();
}
/// <summary>The number of valid seconds from creation time - zero means no expiry.</summary>
public long GetValidSeconds()
{
if (_publicPk.Version > 3)
{
if (IsMasterKey)
{
for (var i = 0; i != _masterKeyCertificationTypes.Length; i++)
{
var seconds = GetExpirationTimeFromSig(true, _masterKeyCertificationTypes[i]);
if (seconds >= 0)
{
return seconds;
}
}
}
else
{
var seconds = GetExpirationTimeFromSig(false, PgpSignature.SubkeyBinding);
if (seconds >= 0)
{
return seconds;
}
}
return 0;
}
return (long)_publicPk.ValidDays * 24 * 60 * 60;
}
private long GetExpirationTimeFromSig(bool selfSigned, int signatureType)
{
foreach (PgpSignature sig in GetSignaturesOfType(signatureType))
{
if (selfSigned && sig.KeyId != KeyId)
continue;
var hashed = sig.GetHashedSubPackets();
return hashed != null ? hashed.GetKeyExpirationTime() : 0;
}
return -1;
}
/// <summary>The keyId associated with the public key.</summary>
public long KeyId { get; private set; }
/// <summary>The fingerprint of the key</summary>
public byte[] GetFingerprint()
{
return (byte[])_fingerprint.Clone();
}
/// <summary>
/// Check if this key has an algorithm type that makes it suitable to use for encryption.
/// </summary>
/// <remarks>
/// Note: with version 4 keys KeyFlags subpackets should also be considered when present for
/// determining the preferred use of the key.
/// </remarks>
/// <returns>
/// <c>true</c> if this key algorithm is suitable for encryption.
/// </returns>
public bool IsEncryptionKey
{
get
{
switch (_publicPk.Algorithm)
{
case PublicKeyAlgorithmTag.ElGamalEncrypt:
case PublicKeyAlgorithmTag.ElGamalGeneral:
case PublicKeyAlgorithmTag.RsaEncrypt:
case PublicKeyAlgorithmTag.RsaGeneral:
case PublicKeyAlgorithmTag.Ecdh:
return true;
default:
return false;
}
}
}
/// <summary>True, if this is a master key.</summary>
public bool IsMasterKey
{
get { return _subSigs == null; }
}
/// <summary>The algorithm code associated with the public key.</summary>
public PublicKeyAlgorithmTag Algorithm
{
get { return _publicPk.Algorithm; }
}
/// <summary>The strength of the key in bits.</summary>
public int BitStrength { get; private set; }
/// <summary>The public key contained in the object.</summary>
/// <returns>A lightweight public key.</returns>
/// <exception cref="PgpException">If the key algorithm is not recognised.</exception>
public IAsymmetricKeyParameter GetKey()
{
try
{
switch (_publicPk.Algorithm)
{
case PublicKeyAlgorithmTag.RsaEncrypt:
case PublicKeyAlgorithmTag.RsaGeneral:
case PublicKeyAlgorithmTag.RsaSign:
var rsaK = (RsaPublicBcpgKey)_publicPk.Key;
return new RsaKeyParameters(false, rsaK.Modulus, rsaK.PublicExponent);
case PublicKeyAlgorithmTag.Dsa:
var dsaK = (DsaPublicBcpgKey)_publicPk.Key;
return new DsaPublicKeyParameters(dsaK.Y, new DsaParameters(dsaK.P, dsaK.Q, dsaK.G));
case PublicKeyAlgorithmTag.ElGamalEncrypt:
case PublicKeyAlgorithmTag.ElGamalGeneral:
var elK = (ElGamalPublicBcpgKey)_publicPk.Key;
return new ElGamalPublicKeyParameters(elK.Y, new ElGamalParameters(elK.P, elK.G));
case PublicKeyAlgorithmTag.Ecdsa:
var ecdsaK = (ECDSAPublicBcpgKey)_publicPk.Key;
return new ECPublicKeyParameters(_publicPk.Algorithm.ToString(), ecdsaK.Point, ecdsaK.Oid);
case PublicKeyAlgorithmTag.Ecdh:
var edhK = (ECDHPublicBcpgKey)_publicPk.Key;
return new ECDHPublicKeyParameters(edhK.Point, edhK.Oid, edhK.HashAlgorithm, edhK.SymmetricKeyAlgorithm);
default:
throw new PgpException("unknown public key algorithm encountered");
}
}
catch (PgpException)
{
throw;
}
catch (Exception e)
{
throw new PgpException("exception constructing public key", e);
}
}
/// <summary>Allows enumeration of any user IDs associated with the key.</summary>
/// <returns>An <c>IEnumerable</c> of <c>string</c> objects.</returns>
public IEnumerable GetUserIds()
{
IList temp = Platform.CreateArrayList();
foreach (object o in _ids)
{
if (o is string)
{
temp.Add(o);
}
}
return new EnumerableProxy(temp);
}
public string[] UserIdentities
{
get
{
return _ids.OfType<string>().ToArray();
}
}
/// <summary>Allows enumeration of any user attribute vectors associated with the key.</summary>
/// <returns>An <c>IEnumerable</c> of <c>PgpUserAttributeSubpacketVector</c> objects.</returns>
public IEnumerable<IPgpUserAttributeSubpacketVector> GetUserAttributes()
{
return _ids.OfType<IPgpUserAttributeSubpacketVector>();
}
/// <summary>Allows enumeration of any signatures associated with the passed in id.</summary>
/// <param name="id">The ID to be matched.</param>
/// <returns>An <c>IEnumerable</c> of <c>PgpSignature</c> objects.</returns>
public IEnumerable<IPgpSignature> GetSignaturesForId(string id)
{
if (id == null)
throw new ArgumentNullException("id");
for (var i = 0; i != _ids.Count; i++)
{
if (id.Equals(_ids[i]))
{
return _idSigs[i];
}
}
return null;
}
/// <summary>Allows enumeration of signatures associated with the passed in user attributes.</summary>
/// <param name="userAttributes">The vector of user attributes to be matched.</param>
/// <returns>An <c>IEnumerable</c> of <c>PgpSignature</c> objects.</returns>
public IEnumerable<IPgpSignature> GetSignaturesForUserAttribute(IPgpUserAttributeSubpacketVector userAttributes)
{
for (var i = 0; i != _ids.Count; i++)
{
if (userAttributes.Equals(_ids[i]))
{
return _idSigs[i];
}
}
return null;
}
/// <summary>Allows enumeration of signatures of the passed in type that are on this key.</summary>
/// <param name="signatureType">The type of the signature to be returned.</param>
/// <returns>An <c>IEnumerable</c> of <c>PgpSignature</c> objects.</returns>
public IEnumerable<IPgpSignature> GetSignaturesOfType(int signatureType)
{
return this.GetSignatures().Where(sig => sig.SignatureType == signatureType);
}
/// <summary>Allows enumeration of all signatures/certifications associated with this key.</summary>
/// <returns>An <c>IEnumerable</c> with all signatures/certifications.</returns>
public IEnumerable<IPgpSignature> GetSignatures()
{
IList<IPgpSignature> sigs;
if (_subSigs != null)
{
sigs = _subSigs;
}
else
{
sigs = Platform.CreateArrayList(_keySigs);
foreach (var extraSigs in _idSigs)
{
CollectionUtilities.AddRange(sigs, extraSigs);
}
}
return sigs;
}
public byte[] GetEncoded()
{
using (var bOut = new MemoryStream())
{
Encode(bOut);
return bOut.ToArray();
}
}
public void Encode(Stream outStr)
{
var bcpgOut = BcpgOutputStream.Wrap(outStr);
bcpgOut.WritePacket(_publicPk);
if (_trustPk != null)
{
bcpgOut.WritePacket(_trustPk);
}
if (_subSigs == null) // not a sub-key
{
foreach (PgpSignature keySig in _keySigs)
{
keySig.Encode(bcpgOut);
}
for (var i = 0; i != _ids.Count; i++)
{
var id = _ids[i] as string;
if (id != null)
{
bcpgOut.WritePacket(new UserIdPacket(id));
}
else
{
var v = (IPgpUserAttributeSubpacketVector)_ids[i];
bcpgOut.WritePacket(new UserAttributePacket(v.ToSubpacketArray()));
}
if (_idTrusts[i] != null)
{
bcpgOut.WritePacket((ContainedPacket)_idTrusts[i]);
}
foreach (var sig in _idSigs[i])
{
sig.Encode(bcpgOut);
}
}
}
else
{
foreach (PgpSignature subSig in _subSigs)
{
subSig.Encode(bcpgOut);
}
}
}
/// <summary>
/// Check whether this (sub)key has a revocation signature on it.
/// </summary>
/// <returns>
/// True, if this (sub)key has been revoked.
/// </returns>
public bool IsRevoked()
{
var ns = 0;
var revoked = false;
if (IsMasterKey) // Master key
{
while (!revoked && (ns < _keySigs.Count))
{
if (((PgpSignature)_keySigs[ns++]).SignatureType == PgpSignature.KeyRevocation)
{
revoked = true;
}
}
}
else // Sub-key
{
while (!revoked && (ns < _subSigs.Count))
{
if (((PgpSignature)_subSigs[ns++]).SignatureType == PgpSignature.SubkeyRevocation)
{
revoked = true;
}
}
}
return revoked;
}
/// <summary>
/// Add a certification for an id to the given public key.
/// </summary>
/// <param name="key">The key the certification is to be added to.</param>
/// <param name="id">The ID the certification is associated with.</param>
/// <param name="certification">The new certification.</param>
/// <returns>
/// The re-certified key.
/// </returns>
public static PgpPublicKey AddCertification(IPgpPublicKey key, string id, PgpSignature certification)
{
return AddCert(key, id, certification);
}
/// <summary>
/// Add a certification for the given UserAttributeSubpackets to the given public key.
/// </summary>
/// <param name="key">The key the certification is to be added to.</param>
/// <param name="userAttributes">The attributes the certification is associated with.</param>
/// <param name="certification">The new certification.</param>
/// <returns>
/// The re-certified key.
/// </returns>
public static PgpPublicKey AddCertification(IPgpPublicKey key, IPgpUserAttributeSubpacketVector userAttributes, IPgpSignature certification)
{
return AddCert(key, userAttributes, certification);
}
private static PgpPublicKey AddCert(IPgpPublicKey key, object id, IPgpSignature certification)
{
var returnKey = new PgpPublicKey(key);
IList<IPgpSignature> sigList = null;
for (var i = 0; i != returnKey.Ids.Count; i++)
{
if (id.Equals(returnKey.Ids[i]))
{
sigList = returnKey.IdSigs[i];
}
}
if (sigList != null)
{
sigList.Add(certification);
}
else
{
sigList = Platform.CreateArrayList<IPgpSignature>();
sigList.Add(certification);
returnKey.Ids.Add(id);
returnKey.IdTrusts.Add(null);
returnKey.IdSigs.Add(sigList);
}
return returnKey;
}
/// <summary>
/// Remove any certifications associated with a user attribute subpacket on a key.
/// </summary>
/// <param name="key">The key the certifications are to be removed from.</param>
/// <param name="userAttributes">The attributes to be removed.</param>
/// <returns>
/// The re-certified key, or null if the user attribute subpacket was not found on the key.
/// </returns>
public static IPgpPublicKey RemoveCertification(IPgpPublicKey key, PgpUserAttributeSubpacketVector userAttributes)
{
return RemoveCert(key, userAttributes);
}
/// <summary>Remove any certifications associated with a given ID on a key.</summary>
/// <param name="key">The key the certifications are to be removed from.</param>
/// <param name="id">The ID that is to be removed.</param>
/// <returns>The re-certified key, or null if the ID was not found on the key.</returns>
public static IPgpPublicKey RemoveCertification(IPgpPublicKey key, string id)
{
return RemoveCert(key, id);
}
private static IPgpPublicKey RemoveCert(IPgpPublicKey key, object id)
{
var returnKey = new PgpPublicKey(key);
var found = false;
for (var i = 0; i < returnKey._ids.Count; i++)
{
if (!id.Equals(returnKey._ids[i]))
continue;
found = true;
returnKey.Ids.RemoveAt(i);
returnKey.IdTrusts.RemoveAt(i);
returnKey.IdSigs.RemoveAt(i);
}
return found ? returnKey : null;
}
/// <summary>Remove a certification associated with a given ID on a key.</summary>
/// <param name="key">The key the certifications are to be removed from.</param>
/// <param name="id">The ID that the certfication is to be removed from.</param>
/// <param name="certification">The certfication to be removed.</param>
/// <returns>The re-certified key, or null if the certification was not found.</returns>
public static PgpPublicKey RemoveCertification(IPgpPublicKey key, string id, PgpSignature certification)
{
return RemoveCert(key, id, certification);
}
/// <summary>Remove a certification associated with a given user attributes on a key.</summary>
/// <param name="key">The key the certifications are to be removed from.</param>
/// <param name="userAttributes">The user attributes that the certfication is to be removed from.</param>
/// <param name="certification">The certification to be removed.</param>
/// <returns>The re-certified key, or null if the certification was not found.</returns>
public static PgpPublicKey RemoveCertification(IPgpPublicKey key, IPgpUserAttributeSubpacketVector userAttributes, PgpSignature certification)
{
return RemoveCert(key, userAttributes, certification);
}
private static PgpPublicKey RemoveCert(IPgpPublicKey key, object id, PgpSignature certification)
{
var returnKey = new PgpPublicKey(key);
var found = false;
for (var i = 0; i < returnKey._ids.Count; i++)
{
if (!id.Equals(returnKey._ids[i]))
continue;
var certs = returnKey.IdSigs[i];
found = certs.Contains(certification);
if (found)
{
certs.Remove(certification);
}
}
return found ? returnKey : null;
}
/// <summary>Add a revocation or some other key certification to a key.</summary>
/// <param name="key">The key the revocation is to be added to.</param>
/// <param name="certification">The key signature to be added.</param>
/// <returns>The new changed public key object.</returns>
public static PgpPublicKey AddCertification(IPgpPublicKey key, PgpSignature certification)
{
if (key.IsMasterKey)
{
if (certification.SignatureType == PgpSignature.SubkeyRevocation)
{
throw new ArgumentException("signature type incorrect for master key revocation.");
}
}
else
{
if (certification.SignatureType == PgpSignature.KeyRevocation)
{
throw new ArgumentException("signature type incorrect for sub-key revocation.");
}
}
var returnKey = new PgpPublicKey(key);
if (returnKey.SubSigs != null)
{
returnKey.SubSigs.Add(certification);
}
else
{
returnKey.KeySigs.Add(certification);
}
return returnKey;
}
/// <summary>Remove a certification from the key.</summary>
/// <param name="key">The key the certifications are to be removed from.</param>
/// <param name="certification">The certfication to be removed.</param>
/// <returns>The modified key, null if the certification was not found.</returns>
public static PgpPublicKey RemoveCertification(PgpPublicKey key, PgpSignature certification)
{
var returnKey = new PgpPublicKey(key);
var sigs = returnKey.SubSigs ?? returnKey.KeySigs;
// bool found = sigs.Remove(certification);
var pos = sigs.IndexOf(certification);
var found = pos >= 0;
if (found)
{
sigs.RemoveAt(pos);
}
else
{
foreach (string id in key.GetUserIds())
{
foreach (var sig in key.GetSignaturesForId(id))
{
// TODO Is this the right type of equality test?
if (certification != sig)
continue;
found = true;
returnKey = PgpPublicKey.RemoveCertification(returnKey, id, certification);
}
}
if (!found)
{
foreach (IPgpUserAttributeSubpacketVector id in key.GetUserAttributes())
{
foreach (var sig in key.GetSignaturesForUserAttribute(id))
{
// TODO Is this the right type of equality test?
if (certification != sig) continue;
// found = true;
returnKey = PgpPublicKey.RemoveCertification(returnKey, id, certification);
}
}
}
}
return returnKey;
}
public static byte[] BuildFingerprint(IPublicKeyPacket publicPk)
{
return publicPk.Version <= 3 ? BuildFingerprintMd5(publicPk) : BuildFingerprintSha1(publicPk);
}
private static byte[] BuildFingerprintMd5(IPublicKeyPacket publicPk)
{
var rK = (RsaPublicBcpgKey)publicPk.Key;
try
{
var digest = DigestUtilities.GetDigest("MD5");
var bytes = rK.Modulus.ToByteArrayUnsigned();
digest.BlockUpdate(bytes, 0, bytes.Length);
bytes = rK.PublicExponent.ToByteArrayUnsigned();
digest.BlockUpdate(bytes, 0, bytes.Length);
return DigestUtilities.DoFinal(digest);
}
catch (Exception e)
{
throw new IOException("can't find MD5", e);
}
}
private static byte[] BuildFingerprintSha1(IPublicKeyPacket publicPk)
{
var kBytes = publicPk.GetEncodedContents();
try
{
var digest = DigestUtilities.GetDigest("SHA1");
digest.Update(0x99);
digest.Update((byte)(kBytes.Length >> 8));
digest.Update((byte)kBytes.Length);
digest.BlockUpdate(kBytes, 0, kBytes.Length);
return DigestUtilities.DoFinal(digest);
}
catch (Exception e)
{
throw new IOException("can't find SHA1", e);
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace System.Management.Automation.Internal
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Management.Automation;
using System.Reflection;
/// <summary>
/// Helper to access Microsoft.PowerShell.GraphicalHost.dll (which references on WPF) using reflection, since
/// we do not want System.Management.Automation.dll or Microsoft.PowerShell.Commands.Utility.dll to reference WPF.
/// Microsoft.PowerShell.GraphicalHost.dll contains:
/// 1) out-gridview window implementation (the actual cmdlet is in Microsoft.PowerShell.Commands.Utility.dll)
/// 2) show-command window implementation (the actual cmdlet is in Microsoft.PowerShell.Commands.Utility.dll)
/// 3) the help window used in the System.Management.Automation.dll's get-help cmdlet when -ShowWindow is specified.
/// </summary>
internal class GraphicalHostReflectionWrapper
{
/// <summary>
/// Initialized in GetGraphicalHostReflectionWrapper with the Microsoft.PowerShell.GraphicalHost.dll assembly.
/// </summary>
private Assembly _graphicalHostAssembly;
/// <summary>
/// A type in Microsoft.PowerShell.GraphicalHost.dll we want to invoke members on.
/// </summary>
private Type _graphicalHostHelperType;
/// <summary>
/// An object in Microsoft.PowerShell.GraphicalHost.dll of type graphicalHostHelperType.
/// </summary>
private object _graphicalHostHelperObject;
/// <summary>
/// Prevents a default instance of the GraphicalHostReflectionWrapper class from being created.
/// </summary>
private GraphicalHostReflectionWrapper()
{
}
/// <summary>
/// Retrieves a wrapper used to invoke members of the type with name <paramref name="graphicalHostHelperTypeName"/>
/// in Microsoft.PowerShell.GraphicalHost.dll.
/// </summary>
/// <param name="parentCmdlet">The cmdlet requesting the wrapper (used to throw terminating errors).</param>
/// <param name="graphicalHostHelperTypeName">The type name we want to invoke members from.</param>
/// <returns>
/// wrapper used to invoke members of the type with name <paramref name="graphicalHostHelperTypeName"/>
/// in Microsoft.PowerShell.GraphicalHost.dll
/// </returns>
/// <exception cref="RuntimeException">When it was not possible to load Microsoft.PowerShell.GraphicalHost.dlly.</exception>
internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper(PSCmdlet parentCmdlet, string graphicalHostHelperTypeName)
{
return GraphicalHostReflectionWrapper.GetGraphicalHostReflectionWrapper(parentCmdlet, graphicalHostHelperTypeName, parentCmdlet.CommandInfo.Name);
}
/// <summary>
/// Retrieves a wrapper used to invoke members of the type with name <paramref name="graphicalHostHelperTypeName"/>
/// in Microsoft.PowerShell.GraphicalHost.dll.
/// </summary>
/// <param name="parentCmdlet">The cmdlet requesting the wrapper (used to throw terminating errors).</param>
/// <param name="graphicalHostHelperTypeName">The type name we want to invoke members from.</param>
/// <param name="featureName">Used for error messages.</param>
/// <returns>
/// wrapper used to invoke members of the type with name <paramref name="graphicalHostHelperTypeName"/>
/// in Microsoft.PowerShell.GraphicalHost.dll
/// </returns>
/// <exception cref="RuntimeException">When it was not possible to load Microsoft.PowerShell.GraphicalHost.dlly.</exception>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Assembly.Load has been found to throw unadvertised exceptions")]
internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper(PSCmdlet parentCmdlet, string graphicalHostHelperTypeName, string featureName)
{
GraphicalHostReflectionWrapper returnValue = new GraphicalHostReflectionWrapper();
if (GraphicalHostReflectionWrapper.IsInputFromRemoting(parentCmdlet))
{
ErrorRecord error = new ErrorRecord(
new NotSupportedException(StringUtil.Format(HelpErrors.RemotingNotSupportedForFeature, featureName)),
"RemotingNotSupported",
ErrorCategory.InvalidOperation,
parentCmdlet);
parentCmdlet.ThrowTerminatingError(error);
}
// Prepare the full assembly name.
AssemblyName graphicalHostAssemblyName = new AssemblyName();
graphicalHostAssemblyName.Name = "Microsoft.PowerShell.GraphicalHost";
graphicalHostAssemblyName.Version = new Version(3, 0, 0, 0);
graphicalHostAssemblyName.CultureInfo = new CultureInfo(string.Empty); // Neutral culture
graphicalHostAssemblyName.SetPublicKeyToken(new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 });
try
{
returnValue._graphicalHostAssembly = Assembly.Load(graphicalHostAssemblyName);
}
catch (FileNotFoundException fileNotFoundEx)
{
// This exception is thrown if the Microsoft.PowerShell.GraphicalHost.dll could not be found (was not installed).
string errorMessage = StringUtil.Format(
HelpErrors.GraphicalHostAssemblyIsNotFound,
featureName,
fileNotFoundEx.Message);
parentCmdlet.ThrowTerminatingError(
new ErrorRecord(
new NotSupportedException(errorMessage, fileNotFoundEx),
"ErrorLoadingAssembly",
ErrorCategory.ObjectNotFound,
graphicalHostAssemblyName));
}
catch (Exception e)
{
parentCmdlet.ThrowTerminatingError(
new ErrorRecord(
e,
"ErrorLoadingAssembly",
ErrorCategory.ObjectNotFound,
graphicalHostAssemblyName));
}
returnValue._graphicalHostHelperType = returnValue._graphicalHostAssembly.GetType(graphicalHostHelperTypeName);
Diagnostics.Assert(returnValue._graphicalHostHelperType != null, "the type exists in Microsoft.PowerShell.GraphicalHost");
ConstructorInfo constructor = returnValue._graphicalHostHelperType.GetConstructor(
BindingFlags.NonPublic | BindingFlags.Instance,
null,
new Type[] { },
null);
if (constructor != null)
{
returnValue._graphicalHostHelperObject = constructor.Invoke(new object[] { });
Diagnostics.Assert(returnValue._graphicalHostHelperObject != null, "the constructor does not throw anything");
}
return returnValue;
}
/// <summary>
/// Used to escape characters that are not friendly to WPF binding.
/// </summary>
/// <param name="propertyName">Property name to be used in binding.</param>
/// <returns>String with escaped characters.</returns>
internal static string EscapeBinding(string propertyName)
{
return propertyName.Replace("/", " ").Replace(".", " ");
}
/// <summary>
/// Calls an instance method with name <paramref name="methodName"/> passing the <paramref name="arguments"/>
/// </summary>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="arguments">Arguments to call the method with.</param>
/// <returns>The method return value.</returns>
internal object CallMethod(string methodName, params object[] arguments)
{
Diagnostics.Assert(_graphicalHostHelperObject != null, "there should be a constructor in order to call an instance method");
MethodInfo method = _graphicalHostHelperType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance);
Diagnostics.Assert(method != null, "method " + methodName + " exists in graphicalHostHelperType is verified by caller");
return method.Invoke(_graphicalHostHelperObject, arguments);
}
/// <summary>
/// Calls a static method with name <paramref name="methodName"/> passing the <paramref name="arguments"/>
/// </summary>
/// <param name="methodName">Name of the method to call.</param>
/// <param name="arguments">Arguments to call the method with.</param>
/// <returns>The method return value.</returns>
internal object CallStaticMethod(string methodName, params object[] arguments)
{
MethodInfo method = _graphicalHostHelperType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Static);
Diagnostics.Assert(method != null, "method " + methodName + " exists in graphicalHostHelperType is verified by caller");
return method.Invoke(null, arguments);
}
/// <summary>
/// Gets the value of an instance property with name <paramref name="propertyName"/>
/// </summary>
/// <param name="propertyName">Name of the instance property to get the value from.</param>
/// <returns>The value of an instance property with name <paramref name="propertyName"/></returns>
internal object GetPropertyValue(string propertyName)
{
Diagnostics.Assert(_graphicalHostHelperObject != null, "there should be a constructor in order to get an instance property value");
PropertyInfo property = _graphicalHostHelperType.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Instance);
Diagnostics.Assert(property != null, "property " + propertyName + " exists in graphicalHostHelperType is verified by caller");
return property.GetValue(_graphicalHostHelperObject, new object[] { });
}
/// <summary>
/// Gets the value of a static property with name <paramref name="propertyName"/>
/// </summary>
/// <param name="propertyName">Name of the static property to get the value from.</param>
/// <returns>The value of a static property with name <paramref name="propertyName"/></returns>
internal object GetStaticPropertyValue(string propertyName)
{
PropertyInfo property = _graphicalHostHelperType.GetProperty(propertyName, BindingFlags.NonPublic | BindingFlags.Static);
Diagnostics.Assert(property != null, "property " + propertyName + " exists in graphicalHostHelperType is verified by caller");
return property.GetValue(null, new object[] { });
}
/// <summary>
/// Returns true if the <paramref name="parentCmdlet"/> is being run remotely.
/// </summary>
/// <param name="parentCmdlet">Cmdlet we want to see if is running remotely.</param>
/// <returns>True if the <paramref name="parentCmdlet"/> is being run remotely.</returns>
private static bool IsInputFromRemoting(PSCmdlet parentCmdlet)
{
Diagnostics.Assert(parentCmdlet.SessionState != null, "SessionState should always be available.");
PSVariable senderInfo = parentCmdlet.SessionState.PSVariable.Get("PSSenderInfo");
return senderInfo != null;
}
}
}
| |
//
// Encog(tm) Core v3.3 - .Net Version (unit test)
// 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 Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Encog.MathUtil.Matrices
{
[TestClass]
public class TestMatrix
{
[TestMethod]
public void RowsAndCols()
{
var matrix = new Matrix(6, 3);
Assert.AreEqual(matrix.Rows, 6);
Assert.AreEqual(matrix.Cols, 3);
matrix[1, 2] = 1.5;
Assert.AreEqual(matrix[1, 2], 1.5);
}
[TestMethod]
public void RowAndColRangeUnder()
{
var matrix = new Matrix(6, 3);
// make sure set registers error on under-bound row
try
{
matrix[-1, 0] = 1;
Assert.IsTrue(false); // should have thrown an exception
}
catch (MatrixError)
{
}
// make sure set registers error on under-bound col
try
{
matrix[0, -1] = 1;
Assert.IsTrue(false); // should have thrown an exception
}
catch (MatrixError)
{
}
// make sure get registers error on under-bound row
try
{
double d = matrix[-1, 0];
matrix[0, 0] = d;
Assert.IsTrue(false); // should have thrown an exception
}
catch (MatrixError)
{
}
// make sure set registers error on under-bound col
try
{
double d = matrix[0, -1];
matrix[0, 0] = d;
Assert.IsTrue(false); // should have thrown an exception
}
catch (MatrixError)
{
}
}
[TestMethod]
public void RowAndColRangeOver()
{
var matrix = new Matrix(6, 3);
// make sure set registers error on under-bound row
try
{
matrix[6, 0] = 1;
Assert.IsTrue(false); // should have thrown an exception
}
catch (MatrixError)
{
}
// make sure set registers error on under-bound col
try
{
matrix[0, 3] = 1;
Assert.IsTrue(false); // should have thrown an exception
}
catch (MatrixError)
{
}
// make sure get registers error on under-bound row
try
{
double d = matrix[6, 0];
matrix[0, 0] = d;
Assert.IsTrue(false); // should have thrown an exception
}
catch (MatrixError)
{
}
// make sure set registers error on under-bound col
try
{
double d = matrix[0, 3];
matrix[0, 0] = d;
Assert.IsTrue(false); // should have thrown an exception
}
catch (MatrixError)
{
}
}
[TestMethod]
public void MatrixConstruct()
{
double[][] m = {
new[] {1.0, 2.0, 3.0, 4.0},
new[] {5.0, 6.0, 7.0, 8.0},
new[] {9.0, 10.0, 11.0, 12.0},
new[] {13.0, 14.0, 15.0, 16.0}
};
var matrix = new Matrix(m);
Assert.AreEqual(matrix.Rows, 4);
Assert.AreEqual(matrix.Cols, 4);
}
[TestMethod]
public void MatrixEquals()
{
double[][] m1 = {
new[] {1.0, 2.0},
new[] {3.0, 4.0}
};
double[][] m2 = {
new[] {0.0, 2.0},
new[] {3.0, 4.0}
};
var matrix1 = new Matrix(m1);
var matrix2 = new Matrix(m1);
Assert.IsTrue(matrix1.Equals(matrix2));
matrix2 = new Matrix(m2);
Assert.IsFalse(matrix1.Equals(matrix2));
}
[TestMethod]
public void MatrixEqualsPrecision()
{
double[][] m1 = {
new[] {1.1234, 2.123},
new[] {3.123, 4.123}
};
double[][] m2 = {
new[] {1.123, 2.123},
new[] {3.123, 4.123}
};
var matrix1 = new Matrix(m1);
var matrix2 = new Matrix(m2);
Assert.IsTrue(matrix1.equals(matrix2, 3));
Assert.IsFalse(matrix1.equals(matrix2, 4));
double[][] m3 = {
new[] {1.1, 2.1},
new[] {3.1, 4.1}
};
double[][] m4 = {
new[] {1.2, 2.1},
new[] {3.1, 4.1}
};
var matrix3 = new Matrix(m3);
var matrix4 = new Matrix(m4);
Assert.IsTrue(matrix3.equals(matrix4, 0));
Assert.IsFalse(matrix3.equals(matrix4, 1));
try
{
matrix3.equals(matrix4, -1);
Assert.IsTrue(false);
}
catch (MatrixError)
{
}
try
{
matrix3.equals(matrix4, 19);
Assert.IsTrue(false);
}
catch (MatrixError)
{
}
}
[TestMethod]
public void MatrixMultiply()
{
double[][] a = {
new[] {1.0, 0.0, 2.0},
new[] {-1.0, 3.0, 1.0}
};
double[][] b = {
new[] {3.0, 1.0},
new[] {2.0, 1.0},
new[] {1.0, 0.0}
};
double[][] c = {
new[] {5.0, 1.0},
new[] {4.0, 2.0}
};
var matrixA = new Matrix(a);
var matrixB = new Matrix(b);
var matrixC = new Matrix(c);
var result = (Matrix) matrixA.Clone();
result.ToString();
result = MatrixMath.Multiply(matrixA, matrixB);
Assert.IsTrue(result.Equals(matrixC));
double[][] a2 = {
new[] {1.0, 2.0, 3.0, 4.0},
new[] {5.0, 6.0, 7.0, 8.0}
};
double[][] b2 = {
new[] {1.0, 2.0, 3.0},
new[] {4.0, 5.0, 6.0},
new[] {7.0, 8.0, 9.0},
new[] {10.0, 11.0, 12.0}
};
double[][] c2 = {
new[] {70.0, 80.0, 90.0},
new[] {158.0, 184.0, 210.0}
};
matrixA = new Matrix(a2);
matrixB = new Matrix(b2);
matrixC = new Matrix(c2);
result = MatrixMath.Multiply(matrixA, matrixB);
Assert.IsTrue(result.Equals(matrixC));
matrixB.Clone();
try
{
MatrixMath.Multiply(matrixB, matrixA);
Assert.IsTrue(false);
}
catch (MatrixError)
{
}
}
[TestMethod]
public void Boolean()
{
bool[][] matrixDataBoolean = {
new[] {true, false},
new[] {false, true}
};
double[][] matrixDataDouble = {
new[] {1.0, -1.0},
new[] {-1.0, 1.0},
};
var matrixBoolean = new Matrix(matrixDataBoolean);
var matrixDouble = new Matrix(matrixDataDouble);
Assert.IsTrue(matrixBoolean.Equals(matrixDouble));
}
[TestMethod]
public void GetRow()
{
double[][] matrixData1 = {
new[] {1.0, 2.0},
new[] {3.0, 4.0}
};
double[][] matrixData2 = {
new[] {3.0, 4.0}
};
var matrix1 = new Matrix(matrixData1);
var matrix2 = new Matrix(matrixData2);
Matrix matrixRow = matrix1.GetRow(1);
Assert.IsTrue(matrixRow.Equals(matrix2));
try
{
matrix1.GetRow(3);
Assert.IsTrue(false);
}
catch (MatrixError)
{
Assert.IsTrue(true);
}
}
[TestMethod]
public void GetCol()
{
double[][] matrixData1 = {
new[] {1.0, 2.0},
new[] {3.0, 4.0}
};
double[][] matrixData2 = {
new[] {2.0},
new[] {4.0}
};
var matrix1 = new Matrix(matrixData1);
var matrix2 = new Matrix(matrixData2);
Matrix matrixCol = matrix1.GetCol(1);
Assert.IsTrue(matrixCol.Equals(matrix2));
try
{
matrix1.GetCol(3);
Assert.IsTrue(false);
}
catch (MatrixError)
{
Assert.IsTrue(true);
}
}
[TestMethod]
public void Zero()
{
double[][] doubleData = {
new[] {0.0, 0.0},
new[] {0.0, 0.0}
};
var matrix = new Matrix(doubleData);
Assert.IsTrue(matrix.IsZero());
}
[TestMethod]
public void Sum()
{
double[][] doubleData = {
new[] {1.0, 2.0},
new[] {3.0, 4.0}
};
var matrix = new Matrix(doubleData);
Assert.AreEqual((int) matrix.Sum(), 1 + 2 + 3 + 4);
}
[TestMethod]
public void RowMatrix()
{
double[] matrixData = {1.0, 2.0, 3.0, 4.0};
Matrix matrix = Matrix.CreateRowMatrix(matrixData);
Assert.AreEqual(matrix[0, 0], 1.0);
Assert.AreEqual(matrix[0, 1], 2.0);
Assert.AreEqual(matrix[0, 2], 3.0);
Assert.AreEqual(matrix[0, 3], 4.0);
}
[TestMethod]
public void ColumnMatrix()
{
double[] matrixData = {1.0, 2.0, 3.0, 4.0};
Matrix matrix = Matrix.CreateColumnMatrix(matrixData);
Assert.AreEqual(matrix[0, 0], 1.0);
Assert.AreEqual(matrix[1, 0], 2.0);
Assert.AreEqual(matrix[2, 0], 3.0);
Assert.AreEqual(matrix[3, 0], 4.0);
}
[TestMethod]
public void Add()
{
double[] matrixData = {1.0, 2.0, 3.0, 4.0};
Matrix matrix = Matrix.CreateColumnMatrix(matrixData);
matrix.Add(0, 0, 1);
Assert.AreEqual(matrix[0, 0], 2.0);
}
[TestMethod]
public void Clear()
{
double[] matrixData = {1.0, 2.0, 3.0, 4.0};
Matrix matrix = Matrix.CreateColumnMatrix(matrixData);
matrix.Clear();
Assert.AreEqual(matrix[0, 0], 0.0);
Assert.AreEqual(matrix[1, 0], 0.0);
Assert.AreEqual(matrix[2, 0], 0.0);
Assert.AreEqual(matrix[3, 0], 0.0);
}
[TestMethod]
public void IsVector()
{
double[] matrixData = {1.0, 2.0, 3.0, 4.0};
Matrix matrixCol = Matrix.CreateColumnMatrix(matrixData);
Matrix matrixRow = Matrix.CreateRowMatrix(matrixData);
Assert.IsTrue(matrixCol.IsVector());
Assert.IsTrue(matrixRow.IsVector());
double[][] matrixData2 = {
new[] {1.0, 2.0},
new[] {3.0, 4.0}
};
var matrix = new Matrix(matrixData2);
Assert.IsFalse(matrix.IsVector());
}
[TestMethod]
public void IsZero()
{
double[] matrixData = {1.0, 2.0, 3.0, 4.0};
Matrix matrix = Matrix.CreateColumnMatrix(matrixData);
Assert.IsFalse(matrix.IsZero());
double[] matrixData2 = {0.0, 0.0, 0.0, 0.0};
Matrix matrix2 = Matrix.CreateColumnMatrix(matrixData2);
Assert.IsTrue(matrix2.IsZero());
}
[TestMethod]
public void PackedArray()
{
double[][] matrixData = {
new[] {1.0, 2.0},
new[] {3.0, 4.0}
};
var matrix = new Matrix(matrixData);
double[] matrixData2 = matrix.ToPackedArray();
Assert.AreEqual(4, matrixData2.Length);
Assert.AreEqual(1.0, matrix[0, 0]);
Assert.AreEqual(2.0, matrix[0, 1]);
Assert.AreEqual(3.0, matrix[1, 0]);
Assert.AreEqual(4.0, matrix[1, 1]);
var matrix2 = new Matrix(2, 2);
matrix2.FromPackedArray(matrixData2, 0);
Assert.IsTrue(matrix.Equals(matrix2));
}
[TestMethod]
public void PackedArray2()
{
double[] data = {1.0, 2.0, 3.0, 4.0};
var matrix = new Matrix(1, 4);
matrix.FromPackedArray(data, 0);
Assert.AreEqual(1.0, matrix[0, 0]);
Assert.AreEqual(2.0, matrix[0, 1]);
Assert.AreEqual(3.0, matrix[0, 2]);
}
[TestMethod]
public void Size()
{
double[][] data = {
new[] {1.0, 2.0},
new[] {3.0, 4.0}
};
var matrix = new Matrix(data);
Assert.AreEqual(4, matrix.Size);
}
[TestMethod]
public void Randomize()
{
const double min = 1.0;
const double max = 10.0;
var matrix = new Matrix(10, 10);
matrix.Ramdomize(min, max);
var array = matrix.ToPackedArray();
foreach (double t in array)
{
if (t < min || t > max)
Assert.IsFalse(true);
}
}
[TestMethod]
public void VectorLength()
{
double[] vectorData = {1.0, 2.0, 3.0, 4.0};
Matrix vector = Matrix.CreateRowMatrix(vectorData);
Assert.AreEqual(5, (int) MatrixMath.VectorLength(vector));
var nonVector = new Matrix(2, 2);
try
{
MatrixMath.VectorLength(nonVector);
Assert.IsTrue(false);
}
catch (MatrixError)
{
}
}
}
}
| |
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Copyright (c) 2008 - 2015 Jb Evain
// Copyright (c) 2008 - 2011 Novell, Inc.
//
// Licensed under the MIT/X11 license.
//
using System;
using System.Collections.Generic;
using Mono.Collections.Generic;
using SR = System.Reflection;
using Mono.Cecil.Metadata;
namespace Mono.Cecil {
#if !READ_ONLY
public interface IMetadataImporterProvider {
IMetadataImporter GetMetadataImporter (ModuleDefinition module);
}
public interface IMetadataImporter {
AssemblyNameReference ImportReference (AssemblyNameReference reference);
TypeReference ImportReference (TypeReference type, IGenericParameterProvider context);
FieldReference ImportReference (FieldReference field, IGenericParameterProvider context);
MethodReference ImportReference (MethodReference method, IGenericParameterProvider context);
}
public interface IReflectionImporterProvider {
IReflectionImporter GetReflectionImporter (ModuleDefinition module);
}
public interface IReflectionImporter {
AssemblyNameReference ImportReference (SR.AssemblyName reference);
TypeReference ImportReference (Type type, IGenericParameterProvider context);
FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context);
MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context);
}
struct ImportGenericContext {
Collection<IGenericParameterProvider> stack;
public bool IsEmpty { get { return stack == null; } }
public ImportGenericContext (IGenericParameterProvider provider)
{
if (provider == null)
throw new ArgumentNullException ("provider");
stack = null;
Push (provider);
}
public void Push (IGenericParameterProvider provider)
{
if (stack == null)
stack = new Collection<IGenericParameterProvider> (1) { provider };
else
stack.Add (provider);
}
public void Pop ()
{
stack.RemoveAt (stack.Count - 1);
}
public TypeReference MethodParameter (string method, int position)
{
for (int i = stack.Count - 1; i >= 0; i--) {
var candidate = stack [i] as MethodReference;
if (candidate == null)
continue;
if (method != NormalizeMethodName (candidate))
continue;
return candidate.GenericParameters [position];
}
throw new InvalidOperationException ();
}
public string NormalizeMethodName (MethodReference method)
{
return method.DeclaringType.GetElementType ().FullName + "." + method.Name;
}
public TypeReference TypeParameter (string type, int position)
{
for (int i = stack.Count - 1; i >= 0; i--) {
var candidate = GenericTypeFor (stack [i]);
if (candidate.FullName != type)
continue;
return candidate.GenericParameters [position];
}
throw new InvalidOperationException ();
}
static TypeReference GenericTypeFor (IGenericParameterProvider context)
{
var type = context as TypeReference;
if (type != null)
return type.GetElementType ();
var method = context as MethodReference;
if (method != null)
return method.DeclaringType.GetElementType ();
throw new InvalidOperationException ();
}
public static ImportGenericContext For (IGenericParameterProvider context)
{
return context != null ? new ImportGenericContext (context) : default (ImportGenericContext);
}
}
public class DefaultReflectionImporter : IReflectionImporter {
readonly protected ModuleDefinition module;
public DefaultReflectionImporter (ModuleDefinition module)
{
Mixin.CheckModule (module);
this.module = module;
}
enum ImportGenericKind {
Definition,
Open,
}
static readonly Dictionary<Type, ElementType> type_etype_mapping = new Dictionary<Type, ElementType> (18) {
{ typeof (void), ElementType.Void },
{ typeof (bool), ElementType.Boolean },
{ typeof (char), ElementType.Char },
{ typeof (sbyte), ElementType.I1 },
{ typeof (byte), ElementType.U1 },
{ typeof (short), ElementType.I2 },
{ typeof (ushort), ElementType.U2 },
{ typeof (int), ElementType.I4 },
{ typeof (uint), ElementType.U4 },
{ typeof (long), ElementType.I8 },
{ typeof (ulong), ElementType.U8 },
{ typeof (float), ElementType.R4 },
{ typeof (double), ElementType.R8 },
{ typeof (string), ElementType.String },
#if !NET_CORE
{ typeof (TypedReference), ElementType.TypedByRef },
#endif
{ typeof (IntPtr), ElementType.I },
{ typeof (UIntPtr), ElementType.U },
{ typeof (object), ElementType.Object },
};
TypeReference ImportType (Type type, ImportGenericContext context)
{
return ImportType (type, context, ImportGenericKind.Open);
}
TypeReference ImportType (Type type, ImportGenericContext context, ImportGenericKind import_kind)
{
if (IsTypeSpecification (type) || ImportOpenGenericType (type, import_kind))
return ImportTypeSpecification (type, context);
var reference = new TypeReference (
string.Empty,
type.Name,
module,
ImportScope (type),
type.IsValueType ());
reference.etype = ImportElementType (type);
if (IsNestedType (type))
reference.DeclaringType = ImportType (type.DeclaringType, context, import_kind);
else
reference.Namespace = type.Namespace ?? string.Empty;
if (type.IsGenericType ())
ImportGenericParameters (reference, type.GetGenericArguments ());
return reference;
}
protected virtual IMetadataScope ImportScope (Type type)
{
return ImportScope (type.Assembly ());
}
static bool ImportOpenGenericType (Type type, ImportGenericKind import_kind)
{
return type.IsGenericType () && type.IsGenericTypeDefinition () && import_kind == ImportGenericKind.Open;
}
static bool ImportOpenGenericMethod (SR.MethodBase method, ImportGenericKind import_kind)
{
return method.IsGenericMethod && method.IsGenericMethodDefinition && import_kind == ImportGenericKind.Open;
}
static bool IsNestedType (Type type)
{
return type.IsNested;
}
TypeReference ImportTypeSpecification (Type type, ImportGenericContext context)
{
if (type.IsByRef)
return new ByReferenceType (ImportType (type.GetElementType (), context));
if (type.IsPointer)
return new PointerType (ImportType (type.GetElementType (), context));
if (type.IsArray)
return new ArrayType (ImportType (type.GetElementType (), context), type.GetArrayRank ());
if (type.IsGenericType ())
return ImportGenericInstance (type, context);
if (type.IsGenericParameter)
return ImportGenericParameter (type, context);
throw new NotSupportedException (type.FullName);
}
static TypeReference ImportGenericParameter (Type type, ImportGenericContext context)
{
if (context.IsEmpty)
throw new InvalidOperationException ();
if (type.DeclaringMethod () != null)
return context.MethodParameter (NormalizeMethodName (type.DeclaringMethod ()), type.GenericParameterPosition);
if (type.DeclaringType != null)
return context.TypeParameter (NormalizeTypeFullName (type.DeclaringType), type.GenericParameterPosition);
throw new InvalidOperationException();
}
static string NormalizeMethodName (SR.MethodBase method)
{
return NormalizeTypeFullName (method.DeclaringType) + "." + method.Name;
}
static string NormalizeTypeFullName (Type type)
{
if (IsNestedType (type))
return NormalizeTypeFullName (type.DeclaringType) + "/" + type.Name;
return type.FullName;
}
TypeReference ImportGenericInstance (Type type, ImportGenericContext context)
{
var element_type = ImportType (type.GetGenericTypeDefinition (), context, ImportGenericKind.Definition);
var instance = new GenericInstanceType (element_type);
var arguments = type.GetGenericArguments ();
var instance_arguments = instance.GenericArguments;
context.Push (element_type);
try {
for (int i = 0; i < arguments.Length; i++)
instance_arguments.Add (ImportType (arguments [i], context));
return instance;
} finally {
context.Pop ();
}
}
static bool IsTypeSpecification (Type type)
{
return type.HasElementType
|| IsGenericInstance (type)
|| type.IsGenericParameter;
}
static bool IsGenericInstance (Type type)
{
return type.IsGenericType () && !type.IsGenericTypeDefinition ();
}
static ElementType ImportElementType (Type type)
{
ElementType etype;
if (!type_etype_mapping.TryGetValue (type, out etype))
return ElementType.None;
return etype;
}
protected AssemblyNameReference ImportScope (SR.Assembly assembly)
{
return ImportReference (assembly.GetName ());
}
public virtual AssemblyNameReference ImportReference (SR.AssemblyName name)
{
Mixin.CheckName (name);
AssemblyNameReference reference;
if (TryGetAssemblyNameReference (name, out reference))
return reference;
reference = new AssemblyNameReference (name.Name, name.Version)
{
PublicKeyToken = name.GetPublicKeyToken (),
#if !NET_CORE
Culture = name.CultureInfo.Name,
HashAlgorithm = (AssemblyHashAlgorithm) name.HashAlgorithm,
#endif
};
module.AssemblyReferences.Add (reference);
return reference;
}
bool TryGetAssemblyNameReference (SR.AssemblyName name, out AssemblyNameReference assembly_reference)
{
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (name.FullName != reference.FullName) // TODO compare field by field
continue;
assembly_reference = reference;
return true;
}
assembly_reference = null;
return false;
}
FieldReference ImportField (SR.FieldInfo field, ImportGenericContext context)
{
var declaring_type = ImportType (field.DeclaringType, context);
if (IsGenericInstance (field.DeclaringType))
field = ResolveFieldDefinition (field);
context.Push (declaring_type);
try {
return new FieldReference {
Name = field.Name,
DeclaringType = declaring_type,
FieldType = ImportType (field.FieldType, context),
};
} finally {
context.Pop ();
}
}
static SR.FieldInfo ResolveFieldDefinition (SR.FieldInfo field)
{
#if NET_CORE
throw new NotImplementedException ();
#else
return field.Module.ResolveField (field.MetadataToken);
#endif
}
static SR.MethodBase ResolveMethodDefinition (SR.MethodBase method)
{
#if NET_CORE
throw new NotImplementedException ();
#else
return method.Module.ResolveMethod (method.MetadataToken);
#endif
}
MethodReference ImportMethod (SR.MethodBase method, ImportGenericContext context, ImportGenericKind import_kind)
{
if (IsMethodSpecification (method) || ImportOpenGenericMethod (method, import_kind))
return ImportMethodSpecification (method, context);
var declaring_type = ImportType (method.DeclaringType, context);
if (IsGenericInstance (method.DeclaringType))
method = ResolveMethodDefinition (method);
var reference = new MethodReference {
Name = method.Name,
HasThis = HasCallingConvention (method, SR.CallingConventions.HasThis),
ExplicitThis = HasCallingConvention (method, SR.CallingConventions.ExplicitThis),
DeclaringType = ImportType (method.DeclaringType, context, ImportGenericKind.Definition),
};
if (HasCallingConvention (method, SR.CallingConventions.VarArgs))
reference.CallingConvention &= MethodCallingConvention.VarArg;
if (method.IsGenericMethod)
ImportGenericParameters (reference, method.GetGenericArguments ());
context.Push (reference);
try {
var method_info = method as SR.MethodInfo;
reference.ReturnType = method_info != null
? ImportType (method_info.ReturnType, context)
: ImportType (typeof (void), default (ImportGenericContext));
var parameters = method.GetParameters ();
var reference_parameters = reference.Parameters;
for (int i = 0; i < parameters.Length; i++)
reference_parameters.Add (
new ParameterDefinition (ImportType (parameters [i].ParameterType, context)));
reference.DeclaringType = declaring_type;
return reference;
} finally {
context.Pop ();
}
}
static void ImportGenericParameters (IGenericParameterProvider provider, Type [] arguments)
{
var provider_parameters = provider.GenericParameters;
for (int i = 0; i < arguments.Length; i++)
provider_parameters.Add (new GenericParameter (arguments [i].Name, provider));
}
static bool IsMethodSpecification (SR.MethodBase method)
{
return method.IsGenericMethod && !method.IsGenericMethodDefinition;
}
MethodReference ImportMethodSpecification (SR.MethodBase method, ImportGenericContext context)
{
var method_info = method as SR.MethodInfo;
if (method_info == null)
throw new InvalidOperationException ();
var element_method = ImportMethod (method_info.GetGenericMethodDefinition (), context, ImportGenericKind.Definition);
var instance = new GenericInstanceMethod (element_method);
var arguments = method.GetGenericArguments ();
var instance_arguments = instance.GenericArguments;
context.Push (element_method);
try {
for (int i = 0; i < arguments.Length; i++)
instance_arguments.Add (ImportType (arguments [i], context));
return instance;
} finally {
context.Pop ();
}
}
static bool HasCallingConvention (SR.MethodBase method, SR.CallingConventions conventions)
{
return (method.CallingConvention & conventions) != 0;
}
public virtual TypeReference ImportReference (Type type, IGenericParameterProvider context)
{
Mixin.CheckType (type);
return ImportType (
type,
ImportGenericContext.For (context),
context != null ? ImportGenericKind.Open : ImportGenericKind.Definition);
}
public virtual FieldReference ImportReference (SR.FieldInfo field, IGenericParameterProvider context)
{
Mixin.CheckField (field);
return ImportField (field, ImportGenericContext.For (context));
}
public virtual MethodReference ImportReference (SR.MethodBase method, IGenericParameterProvider context)
{
Mixin.CheckMethod (method);
return ImportMethod (method,
ImportGenericContext.For (context),
context != null ? ImportGenericKind.Open : ImportGenericKind.Definition);
}
}
public class DefaultMetadataImporter : IMetadataImporter {
readonly protected ModuleDefinition module;
public DefaultMetadataImporter (ModuleDefinition module)
{
Mixin.CheckModule (module);
this.module = module;
}
TypeReference ImportType (TypeReference type, ImportGenericContext context)
{
if (type.IsTypeSpecification ())
return ImportTypeSpecification (type, context);
var reference = new TypeReference (
type.Namespace,
type.Name,
module,
ImportScope (type),
type.IsValueType);
MetadataSystem.TryProcessPrimitiveTypeReference (reference);
if (type.IsNested)
reference.DeclaringType = ImportType (type.DeclaringType, context);
if (type.HasGenericParameters)
ImportGenericParameters (reference, type);
return reference;
}
protected virtual IMetadataScope ImportScope (TypeReference type)
{
return ImportScope (type.Scope);
}
protected IMetadataScope ImportScope (IMetadataScope scope)
{
switch (scope.MetadataScopeType) {
case MetadataScopeType.AssemblyNameReference:
return ImportReference ((AssemblyNameReference) scope);
case MetadataScopeType.ModuleDefinition:
if (scope == module) return scope;
return ImportReference (((ModuleDefinition) scope).Assembly.Name);
case MetadataScopeType.ModuleReference:
throw new NotImplementedException ();
}
throw new NotSupportedException ();
}
public virtual AssemblyNameReference ImportReference (AssemblyNameReference name)
{
Mixin.CheckName (name);
AssemblyNameReference reference;
if (module.TryGetAssemblyNameReference (name, out reference))
return reference;
reference = new AssemblyNameReference (name.Name, name.Version) {
Culture = name.Culture,
HashAlgorithm = name.HashAlgorithm,
IsRetargetable = name.IsRetargetable,
IsWindowsRuntime = name.IsWindowsRuntime,
};
var pk_token = !name.PublicKeyToken.IsNullOrEmpty ()
? new byte [name.PublicKeyToken.Length]
: Empty<byte>.Array;
if (pk_token.Length > 0)
Buffer.BlockCopy (name.PublicKeyToken, 0, pk_token, 0, pk_token.Length);
reference.PublicKeyToken = pk_token;
module.AssemblyReferences.Add (reference);
return reference;
}
static void ImportGenericParameters (IGenericParameterProvider imported, IGenericParameterProvider original)
{
var parameters = original.GenericParameters;
var imported_parameters = imported.GenericParameters;
for (int i = 0; i < parameters.Count; i++)
imported_parameters.Add (new GenericParameter (parameters [i].Name, imported));
}
TypeReference ImportTypeSpecification (TypeReference type, ImportGenericContext context)
{
switch (type.etype) {
case ElementType.SzArray:
var vector = (ArrayType) type;
return new ArrayType (ImportType (vector.ElementType, context));
case ElementType.Ptr:
var pointer = (PointerType) type;
return new PointerType (ImportType (pointer.ElementType, context));
case ElementType.ByRef:
var byref = (ByReferenceType) type;
return new ByReferenceType (ImportType (byref.ElementType, context));
case ElementType.Pinned:
var pinned = (PinnedType) type;
return new PinnedType (ImportType (pinned.ElementType, context));
case ElementType.Sentinel:
var sentinel = (SentinelType) type;
return new SentinelType (ImportType (sentinel.ElementType, context));
case ElementType.FnPtr:
var fnptr = (FunctionPointerType) type;
var imported_fnptr = new FunctionPointerType () {
HasThis = fnptr.HasThis,
ExplicitThis = fnptr.ExplicitThis,
CallingConvention = fnptr.CallingConvention,
ReturnType = ImportType (fnptr.ReturnType, context),
};
if (!fnptr.HasParameters)
return imported_fnptr;
for (int i = 0; i < fnptr.Parameters.Count; i++)
imported_fnptr.Parameters.Add (new ParameterDefinition (
ImportType (fnptr.Parameters [i].ParameterType, context)));
return imported_fnptr;
case ElementType.CModOpt:
var modopt = (OptionalModifierType) type;
return new OptionalModifierType (
ImportType (modopt.ModifierType, context),
ImportType (modopt.ElementType, context));
case ElementType.CModReqD:
var modreq = (RequiredModifierType) type;
return new RequiredModifierType (
ImportType (modreq.ModifierType, context),
ImportType (modreq.ElementType, context));
case ElementType.Array:
var array = (ArrayType) type;
var imported_array = new ArrayType (ImportType (array.ElementType, context));
if (array.IsVector)
return imported_array;
var dimensions = array.Dimensions;
var imported_dimensions = imported_array.Dimensions;
imported_dimensions.Clear ();
for (int i = 0; i < dimensions.Count; i++) {
var dimension = dimensions [i];
imported_dimensions.Add (new ArrayDimension (dimension.LowerBound, dimension.UpperBound));
}
return imported_array;
case ElementType.GenericInst:
var instance = (GenericInstanceType) type;
var element_type = ImportType (instance.ElementType, context);
var imported_instance = new GenericInstanceType (element_type);
var arguments = instance.GenericArguments;
var imported_arguments = imported_instance.GenericArguments;
for (int i = 0; i < arguments.Count; i++)
imported_arguments.Add (ImportType (arguments [i], context));
return imported_instance;
case ElementType.Var:
var var_parameter = (GenericParameter) type;
if (var_parameter.DeclaringType == null)
throw new InvalidOperationException ();
return context.TypeParameter (var_parameter.DeclaringType.FullName, var_parameter.Position);
case ElementType.MVar:
var mvar_parameter = (GenericParameter) type;
if (mvar_parameter.DeclaringMethod == null)
throw new InvalidOperationException ();
return context.MethodParameter (context.NormalizeMethodName (mvar_parameter.DeclaringMethod), mvar_parameter.Position);
}
throw new NotSupportedException (type.etype.ToString ());
}
FieldReference ImportField (FieldReference field, ImportGenericContext context)
{
var declaring_type = ImportType (field.DeclaringType, context);
context.Push (declaring_type);
try {
return new FieldReference {
Name = field.Name,
DeclaringType = declaring_type,
FieldType = ImportType (field.FieldType, context),
};
} finally {
context.Pop ();
}
}
MethodReference ImportMethod (MethodReference method, ImportGenericContext context)
{
if (method.IsGenericInstance)
return ImportMethodSpecification (method, context);
var declaring_type = ImportType (method.DeclaringType, context);
var reference = new MethodReference {
Name = method.Name,
HasThis = method.HasThis,
ExplicitThis = method.ExplicitThis,
DeclaringType = declaring_type,
CallingConvention = method.CallingConvention,
};
if (method.HasGenericParameters)
ImportGenericParameters (reference, method);
context.Push (reference);
try {
reference.ReturnType = ImportType (method.ReturnType, context);
if (!method.HasParameters)
return reference;
var parameters = method.Parameters;
var reference_parameters = reference.parameters = new ParameterDefinitionCollection (reference, parameters.Count);
for (int i = 0; i < parameters.Count; i++)
reference_parameters.Add (
new ParameterDefinition (ImportType (parameters [i].ParameterType, context)));
return reference;
} finally {
context.Pop();
}
}
MethodSpecification ImportMethodSpecification (MethodReference method, ImportGenericContext context)
{
if (!method.IsGenericInstance)
throw new NotSupportedException ();
var instance = (GenericInstanceMethod) method;
var element_method = ImportMethod (instance.ElementMethod, context);
var imported_instance = new GenericInstanceMethod (element_method);
var arguments = instance.GenericArguments;
var imported_arguments = imported_instance.GenericArguments;
for (int i = 0; i < arguments.Count; i++)
imported_arguments.Add (ImportType (arguments [i], context));
return imported_instance;
}
public virtual TypeReference ImportReference (TypeReference type, IGenericParameterProvider context)
{
Mixin.CheckType (type);
return ImportType (type, ImportGenericContext.For (context));
}
public virtual FieldReference ImportReference (FieldReference field, IGenericParameterProvider context)
{
Mixin.CheckField (field);
return ImportField (field, ImportGenericContext.For (context));
}
public virtual MethodReference ImportReference (MethodReference method, IGenericParameterProvider context)
{
Mixin.CheckMethod (method);
return ImportMethod (method, ImportGenericContext.For (context));
}
}
#endif
static partial class Mixin {
public static void CheckModule (ModuleDefinition module)
{
if (module == null)
throw new ArgumentNullException (Argument.module.ToString ());
}
public static bool TryGetAssemblyNameReference (this ModuleDefinition module, AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference)
{
var references = module.AssemblyReferences;
for (int i = 0; i < references.Count; i++) {
var reference = references [i];
if (!Equals (name_reference, reference))
continue;
assembly_reference = reference;
return true;
}
assembly_reference = null;
return false;
}
static bool Equals (byte [] a, byte [] b)
{
if (ReferenceEquals (a, b))
return true;
if (a == null)
return false;
if (a.Length != b.Length)
return false;
for (int i = 0; i < a.Length; i++)
if (a [i] != b [i])
return false;
return true;
}
static bool Equals<T> (T a, T b) where T : class, IEquatable<T>
{
if (ReferenceEquals (a, b))
return true;
if (a == null)
return false;
return a.Equals (b);
}
static bool Equals (AssemblyNameReference a, AssemblyNameReference b)
{
if (ReferenceEquals (a, b))
return true;
if (a.Name != b.Name)
return false;
if (!Equals (a.Version, b.Version))
return false;
if (a.Culture != b.Culture)
return false;
if (!Equals (a.PublicKeyToken, b.PublicKeyToken))
return false;
return true;
}
}
}
| |
#region License
/*
* WebSocketFrame.cs
*
* The MIT License
*
* Copyright (c) 2012-2014 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace WebSocketSharp
{
internal class WebSocketFrame : IEnumerable<byte>
{
#region Private Fields
private byte [] _extPayloadLength;
private Fin _fin;
private Mask _mask;
private byte [] _maskingKey;
private Opcode _opcode;
private PayloadData _payloadData;
private byte _payloadLength;
private Rsv _rsv1;
private Rsv _rsv2;
private Rsv _rsv3;
#endregion
#region Internal Static Fields
internal static readonly byte [] EmptyUnmaskPingData;
#endregion
#region Static Constructor
static WebSocketFrame ()
{
EmptyUnmaskPingData = CreatePingFrame (Mask.Unmask).ToByteArray ();
}
#endregion
#region Private Constructors
private WebSocketFrame ()
{
}
#endregion
#region Public Constructors
public WebSocketFrame (Opcode opcode, PayloadData payload)
: this (Fin.Final, opcode, Mask.Mask, payload, false)
{
}
public WebSocketFrame (Opcode opcode, Mask mask, PayloadData payload)
: this (Fin.Final, opcode, mask, payload, false)
{
}
public WebSocketFrame (Fin fin, Opcode opcode, Mask mask, PayloadData payload)
: this (fin, opcode, mask, payload, false)
{
}
public WebSocketFrame (Fin fin, Opcode opcode, Mask mask, PayloadData payload, bool compressed)
{
_fin = fin;
_rsv1 = isData (opcode) && compressed ? Rsv.On : Rsv.Off;
_rsv2 = Rsv.Off;
_rsv3 = Rsv.Off;
_opcode = opcode;
_mask = mask;
var len = payload.Length;
if (len < 126) {
_payloadLength = (byte) len;
_extPayloadLength = new byte [0];
}
else if (len < 0x010000) {
_payloadLength = (byte) 126;
_extPayloadLength = ((ushort) len).ToByteArrayInternally (ByteOrder.Big);
}
else {
_payloadLength = (byte) 127;
_extPayloadLength = len.ToByteArrayInternally (ByteOrder.Big);
}
if (mask == Mask.Mask) {
_maskingKey = createMaskingKey ();
payload.Mask (_maskingKey);
}
else {
_maskingKey = new byte [0];
}
_payloadData = payload;
}
#endregion
#region Public Properties
public byte [] ExtendedPayloadLength {
get {
return _extPayloadLength;
}
}
public Fin Fin {
get {
return _fin;
}
}
public bool IsBinary {
get {
return _opcode == Opcode.Binary;
}
}
public bool IsClose {
get {
return _opcode == Opcode.Close;
}
}
public bool IsCompressed {
get {
return _rsv1 == Rsv.On;
}
}
public bool IsContinuation {
get {
return _opcode == Opcode.Cont;
}
}
public bool IsControl {
get {
return _opcode == Opcode.Close || _opcode == Opcode.Ping || _opcode == Opcode.Pong;
}
}
public bool IsData {
get {
return _opcode == Opcode.Binary || _opcode == Opcode.Text;
}
}
public bool IsFinal {
get {
return _fin == Fin.Final;
}
}
public bool IsFragmented {
get {
return _fin == Fin.More || _opcode == Opcode.Cont;
}
}
public bool IsMasked {
get {
return _mask == Mask.Mask;
}
}
public bool IsPerMessageCompressed {
get {
return (_opcode == Opcode.Binary || _opcode == Opcode.Text) && _rsv1 == Rsv.On;
}
}
public bool IsPing {
get {
return _opcode == Opcode.Ping;
}
}
public bool IsPong {
get {
return _opcode == Opcode.Pong;
}
}
public bool IsText {
get {
return _opcode == Opcode.Text;
}
}
public ulong Length {
get {
return 2 + (ulong) (_extPayloadLength.Length + _maskingKey.Length) + _payloadData.Length;
}
}
public Mask Mask {
get {
return _mask;
}
}
public byte [] MaskingKey {
get {
return _maskingKey;
}
}
public Opcode Opcode {
get {
return _opcode;
}
}
public PayloadData PayloadData {
get {
return _payloadData;
}
}
public byte PayloadLength {
get {
return _payloadLength;
}
}
public Rsv Rsv1 {
get {
return _rsv1;
}
}
public Rsv Rsv2 {
get {
return _rsv2;
}
}
public Rsv Rsv3 {
get {
return _rsv3;
}
}
#endregion
#region Private Methods
private static byte [] createMaskingKey ()
{
var key = new byte [4];
var rand = new Random ();
rand.NextBytes (key);
return key;
}
private static string dump (WebSocketFrame frame)
{
var len = frame.Length;
var cnt = (long) (len / 4);
var rem = (int) (len % 4);
int cntDigit;
string cntFmt;
if (cnt < 10000) {
cntDigit = 4;
cntFmt = "{0,4}";
}
else if (cnt < 0x010000) {
cntDigit = 4;
cntFmt = "{0,4:X}";
}
else if (cnt < 0x0100000000) {
cntDigit = 8;
cntFmt = "{0,8:X}";
}
else {
cntDigit = 16;
cntFmt = "{0,16:X}";
}
var spFmt = String.Format ("{{0,{0}}}", cntDigit);
var headerFmt = String.Format (
@"{0} 01234567 89ABCDEF 01234567 89ABCDEF
{0}+--------+--------+--------+--------+\n", spFmt);
var lineFmt = String.Format ("{0}|{{1,8}} {{2,8}} {{3,8}} {{4,8}}|\n", cntFmt);
var footerFmt = String.Format ("{0}+--------+--------+--------+--------+", spFmt);
var output = new StringBuilder (64);
Func<Action<string, string, string, string>> linePrinter = () => {
long lineCnt = 0;
return (arg1, arg2, arg3, arg4) =>
output.AppendFormat (lineFmt, ++lineCnt, arg1, arg2, arg3, arg4);
};
output.AppendFormat (headerFmt, String.Empty);
var printLine = linePrinter ();
var frameAsBytes = frame.ToByteArray ();
for (long i = 0; i <= cnt; i++) {
var j = i * 4;
if (i < cnt)
printLine (
Convert.ToString (frameAsBytes [j], 2).PadLeft (8, '0'),
Convert.ToString (frameAsBytes [j + 1], 2).PadLeft (8, '0'),
Convert.ToString (frameAsBytes [j + 2], 2).PadLeft (8, '0'),
Convert.ToString (frameAsBytes [j + 3], 2).PadLeft (8, '0'));
else if (rem > 0)
printLine (
Convert.ToString (frameAsBytes [j], 2).PadLeft (8, '0'),
rem >= 2 ? Convert.ToString (frameAsBytes [j + 1], 2).PadLeft (8, '0') : String.Empty,
rem == 3 ? Convert.ToString (frameAsBytes [j + 2], 2).PadLeft (8, '0') : String.Empty,
String.Empty);
}
output.AppendFormat (footerFmt, String.Empty);
return output.ToString ();
}
private static bool isControl (Opcode opcode)
{
return opcode == Opcode.Close || opcode == Opcode.Ping || opcode == Opcode.Pong;
}
private static bool isData (Opcode opcode)
{
return opcode == Opcode.Text || opcode == Opcode.Binary;
}
private static WebSocketFrame parse (byte [] header, Stream stream, bool unmask)
{
/* Header */
// FIN
var fin = (header [0] & 0x80) == 0x80 ? Fin.Final : Fin.More;
// RSV1
var rsv1 = (header [0] & 0x40) == 0x40 ? Rsv.On : Rsv.Off;
// RSV2
var rsv2 = (header [0] & 0x20) == 0x20 ? Rsv.On : Rsv.Off;
// RSV3
var rsv3 = (header [0] & 0x10) == 0x10 ? Rsv.On : Rsv.Off;
// Opcode
var opcode = (Opcode) (header [0] & 0x0f);
// MASK
var mask = (header [1] & 0x80) == 0x80 ? Mask.Mask : Mask.Unmask;
// Payload Length
var payloadLen = (byte) (header [1] & 0x7f);
// Check if correct frame.
var incorrect = isControl (opcode) && fin == Fin.More
? "A control frame is fragmented."
: !isData (opcode) && rsv1 == Rsv.On
? "A non data frame is compressed."
: null;
if (incorrect != null)
throw new WebSocketException (CloseStatusCode.IncorrectData, incorrect);
// Check if consistent frame.
if (isControl (opcode) && payloadLen > 125)
throw new WebSocketException (
CloseStatusCode.InconsistentData,
"The length of payload data of a control frame is greater than 125 bytes.");
var frame = new WebSocketFrame ();
frame._fin = fin;
frame._rsv1 = rsv1;
frame._rsv2 = rsv2;
frame._rsv3 = rsv3;
frame._opcode = opcode;
frame._mask = mask;
frame._payloadLength = payloadLen;
/* Extended Payload Length */
var size = payloadLen < 126
? 0
: payloadLen == 126
? 2
: 8;
var extPayloadLen = size > 0 ? stream.ReadBytes (size) : new byte [0];
if (size > 0 && extPayloadLen.Length != size)
throw new WebSocketException (
"The 'Extended Payload Length' of a frame cannot be read from the data source.");
frame._extPayloadLength = extPayloadLen;
/* Masking Key */
var masked = mask == Mask.Mask;
var maskingKey = masked ? stream.ReadBytes (4) : new byte [0];
if (masked && maskingKey.Length != 4)
throw new WebSocketException (
"The 'Masking Key' of a frame cannot be read from the data source.");
frame._maskingKey = maskingKey;
/* Payload Data */
ulong len = payloadLen < 126
? payloadLen
: payloadLen == 126
? extPayloadLen.ToUInt16 (ByteOrder.Big)
: extPayloadLen.ToUInt64 (ByteOrder.Big);
byte [] data = null;
if (len > 0) {
// Check if allowable payload data length.
if (payloadLen > 126 && len > PayloadData.MaxLength)
throw new WebSocketException (
CloseStatusCode.TooBig,
"The length of 'Payload Data' of a frame is greater than the allowable length.");
data = payloadLen > 126
? stream.ReadBytes ((long) len, 1024)
: stream.ReadBytes ((int) len);
if (data.LongLength != (long) len)
throw new WebSocketException (
"The 'Payload Data' of a frame cannot be read from the data source.");
}
else {
data = new byte [0];
}
var payload = new PayloadData (data, masked);
if (masked && unmask) {
payload.Mask (maskingKey);
frame._mask = Mask.Unmask;
frame._maskingKey = new byte [0];
}
frame._payloadData = payload;
return frame;
}
private static string print (WebSocketFrame frame)
{
/* Opcode */
var opcode = frame._opcode.ToString ();
/* Payload Length */
var payloadLen = frame._payloadLength;
/* Extended Payload Length */
var ext = frame._extPayloadLength;
var size = ext.Length;
var extPayloadLen = size == 2
? ext.ToUInt16 (ByteOrder.Big).ToString ()
: size == 8
? ext.ToUInt64 (ByteOrder.Big).ToString ()
: String.Empty;
/* Masking Key */
var masked = frame.IsMasked;
var maskingKey = masked ? BitConverter.ToString (frame._maskingKey) : String.Empty;
/* Payload Data */
var payload = payloadLen == 0
? String.Empty
: size > 0
? String.Format ("A {0} frame.", opcode.ToLower ())
: !masked && !frame.IsFragmented && frame.IsText
? Encoding.UTF8.GetString (frame._payloadData.ApplicationData)
: frame._payloadData.ToString ();
var format =
@" FIN: {0}
RSV1: {1}
RSV2: {2}
RSV3: {3}
Opcode: {4}
MASK: {5}
Payload Length: {6}
Extended Payload Length: {7}
Masking Key: {8}
Payload Data: {9}";
return String.Format (
format,
frame._fin,
frame._rsv1,
frame._rsv2,
frame._rsv3,
opcode,
frame._mask,
payloadLen,
extPayloadLen,
maskingKey,
payload);
}
#endregion
#region Internal Methods
internal static WebSocketFrame CreateCloseFrame (Mask mask, PayloadData payload)
{
return new WebSocketFrame (Opcode.Close, mask, payload);
}
internal static WebSocketFrame CreatePongFrame (Mask mask, PayloadData payload)
{
return new WebSocketFrame (Opcode.Pong, mask, payload);
}
#endregion
#region Public Methods
public static WebSocketFrame CreateCloseFrame (Mask mask, byte [] data)
{
return new WebSocketFrame (Opcode.Close, mask, new PayloadData (data));
}
public static WebSocketFrame CreateCloseFrame (Mask mask, CloseStatusCode code, string reason)
{
return new WebSocketFrame (
Opcode.Close, mask, new PayloadData (((ushort) code).Append (reason)));
}
public static WebSocketFrame CreateFrame (
Fin fin, Opcode opcode, Mask mask, byte [] data, bool compressed)
{
return new WebSocketFrame (fin, opcode, mask, new PayloadData (data), compressed);
}
public static WebSocketFrame CreatePingFrame (Mask mask)
{
return new WebSocketFrame (Opcode.Ping, mask, new PayloadData ());
}
public static WebSocketFrame CreatePingFrame (Mask mask, byte [] data)
{
return new WebSocketFrame (Opcode.Ping, mask, new PayloadData (data));
}
public IEnumerator<byte> GetEnumerator ()
{
foreach (var b in ToByteArray ())
yield return b;
}
public static WebSocketFrame Parse (byte [] src)
{
return Parse (src, true);
}
public static WebSocketFrame Parse (Stream stream)
{
return Parse (stream, true);
}
public static WebSocketFrame Parse (byte [] src, bool unmask)
{
using (var stream = new MemoryStream (src))
return Parse (stream, unmask);
}
public static WebSocketFrame Parse (Stream stream, bool unmask)
{
var header = stream.ReadBytes (2);
if (header.Length != 2)
throw new WebSocketException (
"The header part of a frame cannot be read from the data source.");
return parse (header, stream, unmask);
}
public static void ParseAsync (Stream stream, Action<WebSocketFrame> completed)
{
ParseAsync (stream, true, completed, null);
}
public static void ParseAsync (
Stream stream, Action<WebSocketFrame> completed, Action<Exception> error)
{
ParseAsync (stream, true, completed, error);
}
public static void ParseAsync (
Stream stream, bool unmask, Action<WebSocketFrame> completed, Action<Exception> error)
{
stream.ReadBytesAsync (
2,
header => {
if (header.Length != 2)
throw new WebSocketException (
"The header part of a frame cannot be read from the data source.");
var frame = parse (header, stream, unmask);
if (completed != null)
completed (frame);
},
error);
}
public void Print (bool dumped)
{
Console.WriteLine (dumped ? dump (this) : print (this));
}
public string PrintToString (bool dumped)
{
return dumped
? dump (this)
: print (this);
}
public byte [] ToByteArray ()
{
using (var buff = new MemoryStream ()) {
var header = (int) _fin;
header = (header << 1) + (int) _rsv1;
header = (header << 1) + (int) _rsv2;
header = (header << 1) + (int) _rsv3;
header = (header << 4) + (int) _opcode;
header = (header << 1) + (int) _mask;
header = (header << 7) + (int) _payloadLength;
buff.Write (((ushort) header).ToByteArrayInternally (ByteOrder.Big), 0, 2);
if (_payloadLength > 125)
buff.Write (_extPayloadLength, 0, _extPayloadLength.Length);
if (_mask == Mask.Mask)
buff.Write (_maskingKey, 0, _maskingKey.Length);
if (_payloadLength > 0) {
var payload = _payloadData.ToByteArray ();
if (_payloadLength < 127)
buff.Write (payload, 0, payload.Length);
else
buff.WriteBytes (payload);
}
buff.Close ();
return buff.ToArray ();
}
}
public override string ToString ()
{
return BitConverter.ToString (ToByteArray ());
}
#endregion
#region Explicitly Implemented Interface Members
IEnumerator IEnumerable.GetEnumerator ()
{
return GetEnumerator ();
}
#endregion
}
}
| |
/*
* Copyright (c) InWorldz Halcyon Developers
* Copyright (c) Contributors, http://opensimulator.org/
*
* 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 OpenSim 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;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Authentication;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Communications;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Region.Communications.Local;
using System.Threading.Tasks;
namespace OpenSim.Region.Communications.OGS1
{
public class OGS1GridServices : IGridServices
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private bool m_useRemoteRegionCache = true;
/// <summary>
/// Encapsulate local backend services for manipulation of local regions
/// </summary>
private LocalBackEndServices m_localBackend = new LocalBackEndServices();
struct RegionInfoCacheEntry
{
public RegionInfo Info;
public DateTime CachedTime;
public bool Exists;
}
private Dictionary<ulong, RegionInfoCacheEntry> m_remoteRegionInfoCache = new Dictionary<ulong, RegionInfoCacheEntry>();
private Dictionary<string, string> m_queuedGridSettings = new Dictionary<string, string>();
private List<RegionInfo> m_regionsOnInstance = new List<RegionInfo>();
public BaseHttpServer httpListener;
public NetworkServersInfo serversInfo;
public BaseHttpServer httpServer;
public string gdebugRegionName
{
get { return m_localBackend.gdebugRegionName; }
set { m_localBackend.gdebugRegionName = value; }
}
public string rdebugRegionName
{
get { return _rdebugRegionName; }
set { _rdebugRegionName = value; }
}
private string _rdebugRegionName = String.Empty;
public bool RegionLoginsEnabled
{
get { return m_localBackend.RegionLoginsEnabled; }
set { m_localBackend.RegionLoginsEnabled = value; }
}
/// <summary>
/// Contructor. Adds "expect_user" and "check" xmlrpc method handlers
/// </summary>
/// <param name="servers_info"></param>
/// <param name="httpServe"></param>
public OGS1GridServices(NetworkServersInfo servers_info, BaseHttpServer httpServe)
{
serversInfo = servers_info;
httpServer = httpServe;
//Respond to Grid Services requests
httpServer.AddXmlRPCHandler("check", PingCheckReply);
httpServer.AddXmlRPCHandler("land_data", LandData);
// New Style
httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("check"), PingCheckReply));
httpServer.AddStreamHandler(new XmlRpcStreamHandler("POST", Util.XmlRpcRequestPrefix("land_data"), LandData));
}
// see IGridServices
public RegionCommsListener RegisterRegion(RegionInfo regionInfo)
{
if (m_regionsOnInstance.Contains(regionInfo))
{
m_log.Debug("[OGS1 GRID SERVICES]: Error - region already registered " + regionInfo.RegionName);
Exception e = new Exception(String.Format("Unable to register region"));
throw e;
}
m_regionsOnInstance.Add(regionInfo);
m_log.InfoFormat(
"[OGS1 GRID SERVICES]: Attempting to register region {0} with grid at {1}",
regionInfo.RegionName, serversInfo.GridURL);
Hashtable GridParams = new Hashtable();
// Login / Authentication
GridParams["authkey"] = serversInfo.GridSendKey;
GridParams["recvkey"] = serversInfo.GridRecvKey;
GridParams["UUID"] = regionInfo.RegionID.ToString();
GridParams["sim_ip"] = regionInfo.ExternalHostName;
GridParams["sim_port"] = regionInfo.InternalEndPoint.Port.ToString();
GridParams["region_locx"] = regionInfo.RegionLocX.ToString();
GridParams["region_locy"] = regionInfo.RegionLocY.ToString();
GridParams["sim_name"] = regionInfo.RegionName;
GridParams["http_port"] = serversInfo.HttpListenerPort.ToString();
GridParams["remoting_port"] = ConfigSettings.DefaultRegionRemotingPort.ToString();
GridParams["map-image-id"] = regionInfo.RegionSettings.TerrainImageID.ToString();
GridParams["originUUID"] = regionInfo.originRegionID.ToString();
GridParams["region_secret"] = regionInfo.regionSecret;
GridParams["major_interface_version"] = VersionInfo.MajorInterfaceVersion.ToString();
if (regionInfo.MasterAvatarAssignedUUID != UUID.Zero)
GridParams["master_avatar_uuid"] = regionInfo.MasterAvatarAssignedUUID.ToString();
else
GridParams["master_avatar_uuid"] = regionInfo.EstateSettings.EstateOwner.ToString();
GridParams["maturity"] = regionInfo.RegionSettings.Maturity.ToString();
GridParams["product"] = Convert.ToInt32(regionInfo.Product).ToString();
if (regionInfo.OutsideIP != null) GridParams["outside_ip"] = regionInfo.OutsideIP;
// Package into an XMLRPC Request
ArrayList SendParams = new ArrayList();
SendParams.Add(GridParams);
// Send Request
string methodName = "simulator_login";
XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse GridResp;
try
{
// The timeout should always be significantly larger than the timeout for the grid server to request
// the initial status of the region before confirming registration.
GridResp = GridReq.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 90000);
}
catch (Exception e)
{
Exception e2
= new Exception(
String.Format(
"Unable to register region with grid at {0}. Grid service not running?",
serversInfo.GridURL),
e);
throw e2;
}
Hashtable GridRespData = (Hashtable)GridResp.Value;
// Hashtable griddatahash = GridRespData;
// Process Response
if (GridRespData.ContainsKey("error"))
{
string errorstring = (string) GridRespData["error"];
Exception e = new Exception(
String.Format("Unable to connect to grid at {0}: {1}", serversInfo.GridURL, errorstring));
throw e;
}
else
{
// m_knownRegions = RequestNeighbours(regionInfo.RegionLocX, regionInfo.RegionLocY);
if (GridRespData.ContainsKey("allow_forceful_banlines"))
{
if ((string) GridRespData["allow_forceful_banlines"] != "TRUE")
{
//m_localBackend.SetForcefulBanlistsDisallowed(regionInfo.RegionHandle);
if (!m_queuedGridSettings.ContainsKey("allow_forceful_banlines"))
m_queuedGridSettings.Add("allow_forceful_banlines", "FALSE");
}
}
m_log.InfoFormat(
"[OGS1 GRID SERVICES]: Region {0} successfully registered with grid at {1}",
regionInfo.RegionName, serversInfo.GridURL);
}
return m_localBackend.RegisterRegion(regionInfo);
}
// see IGridServices
public bool DeregisterRegion(RegionInfo regionInfo)
{
Hashtable GridParams = new Hashtable();
GridParams["UUID"] = regionInfo.RegionID.ToString();
// Package into an XMLRPC Request
ArrayList SendParams = new ArrayList();
SendParams.Add(GridParams);
// Send Request
string methodName = "simulator_after_region_moved";
XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse GridResp = null;
try
{
GridResp = GridReq.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 10000);
}
catch (Exception e)
{
Exception e2
= new Exception(
String.Format(
"Unable to deregister region with grid at {0}. Grid service not running?",
serversInfo.GridURL),
e);
throw e2;
}
Hashtable GridRespData = (Hashtable) GridResp.Value;
// Hashtable griddatahash = GridRespData;
// Process Response
if (GridRespData != null && GridRespData.ContainsKey("error"))
{
string errorstring = (string)GridRespData["error"];
m_log.Error("Unable to connect to grid: " + errorstring);
return false;
}
return m_localBackend.DeregisterRegion(regionInfo);
}
public virtual Dictionary<string, string> GetGridSettings()
{
Dictionary<string, string> returnGridSettings = new Dictionary<string, string>();
lock (m_queuedGridSettings)
{
foreach (string Dictkey in m_queuedGridSettings.Keys)
{
returnGridSettings.Add(Dictkey, m_queuedGridSettings[Dictkey]);
}
m_queuedGridSettings.Clear();
}
return returnGridSettings;
}
// see IGridServices
public List<SimpleRegionInfo> RequestNeighbours(uint x, uint y)
{
Hashtable respData = MapBlockQuery((int) x - 1, (int) y - 1, (int) x + 1, (int) y + 1);
return ExtractRegionInfoFromMapBlockQuery(x, y, respData);
}
private static List<SimpleRegionInfo> ExtractRegionInfoFromMapBlockQuery(uint x, uint y, Hashtable respData)
{
List<SimpleRegionInfo> neighbours = new List<SimpleRegionInfo>();
foreach (ArrayList neighboursList in respData.Values)
{
foreach (Hashtable neighbourData in neighboursList)
{
uint regX = Convert.ToUInt32(neighbourData["x"]);
uint regY = Convert.ToUInt32(neighbourData["y"]);
if ((x != regX) || (y != regY))
{
string simIp = (string)neighbourData["sim_ip"];
uint port = Convert.ToUInt32(neighbourData["sim_port"]);
SimpleRegionInfo sri = new SimpleRegionInfo(regX, regY, simIp, port);
sri.RegionID = new UUID((string)neighbourData["uuid"]);
sri.RemotingPort = Convert.ToUInt32(neighbourData["remoting_port"]);
if (neighbourData.ContainsKey("http_port"))
{
sri.HttpPort = Convert.ToUInt32(neighbourData["http_port"]);
}
if (neighbourData.ContainsKey("outside_ip"))
{
sri.OutsideIP = (string)neighbourData["outside_ip"];
}
neighbours.Add(sri);
}
}
}
return neighbours;
}
// More efficient call to see if there is a neighbour there, than fetching all neighbours and DNS lookups
// Return true if region at (x,y) has (nx,ny) as a neighbour.
public bool HasNeighbour(uint x, uint y, uint nx, uint ny)
{
Hashtable respData = MapBlockQuery((int)x - 1, (int)y - 1, (int)x + 1, (int)y + 1);
List<SimpleRegionInfo> neighbours = new List<SimpleRegionInfo>();
foreach (ArrayList neighboursList in respData.Values)
{
foreach (Hashtable neighbourData in neighboursList)
{
uint regX = Convert.ToUInt32(neighbourData["x"]);
uint regY = Convert.ToUInt32(neighbourData["y"]);
if ((nx == regX) && (ny == regY))
return true;
}
}
return false;
}
/// <summary>
/// Request information about a region.
/// </summary>
/// <param name="regionHandle"></param>
/// <returns>
/// null on a failure to contact or get a response from the grid server
/// FIXME: Might be nicer to return a proper exception here since we could inform the client more about the
/// nature of the faiulre.
/// </returns>
public RegionInfo RequestNeighbourInfo(UUID Region_UUID)
{
// don't ask the gridserver about regions on this instance...
foreach (RegionInfo info in m_regionsOnInstance)
{
if (info.RegionID == Region_UUID) return info;
}
// didn't find it so far, we have to go the long way
RegionInfo regionInfo;
Hashtable requestData = new Hashtable();
requestData["region_UUID"] = Region_UUID.ToString();
requestData["authkey"] = serversInfo.GridSendKey;
ArrayList SendParams = new ArrayList();
SendParams.Add(requestData);
string methodName = "simulator_data_request";
XmlRpcRequest gridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse gridResp = null;
try
{
gridResp = gridReq.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 3000);
}
catch (Exception e)
{
m_log.ErrorFormat(
"[OGS1 GRID SERVICES]: Communication with the grid server at {0} failed, {1}",
serversInfo.GridURL, e);
return null;
}
Hashtable responseData = (Hashtable)gridResp.Value;
if (responseData.ContainsKey("error"))
{
// this happens all the time normally and pollutes the log
// m_log.WarnFormat("[OGS1 GRID SERVICES]: Error received from grid server: {0}", responseData["error"]);
if (m_useRemoteRegionCache)
{
RegionInfoCacheEntry cacheEntry = new RegionInfoCacheEntry
{
CachedTime = DateTime.Now,
Info = null,
Exists = false
};
lock (m_remoteRegionInfoCache)
{
m_remoteRegionInfoCache[Convert.ToUInt64((string)requestData["regionHandle"])] = cacheEntry;
}
}
return null;
}
regionInfo = buildRegionInfo(responseData, String.Empty);
if ((m_useRemoteRegionCache) && (requestData.ContainsKey("regionHandle")))
{
RegionInfoCacheEntry cacheEntry = new RegionInfoCacheEntry
{
CachedTime = DateTime.Now,
Info = regionInfo,
Exists = true
};
lock (m_remoteRegionInfoCache)
{
m_remoteRegionInfoCache[Convert.ToUInt64((string)requestData["regionHandle"])] = cacheEntry;
}
}
return regionInfo;
}
/// <summary>
/// Request information about a region.
/// </summary>
/// <param name="regionHandle"></param>
/// <returns></returns>
public RegionInfo RequestNeighbourInfo(ulong regionHandle)
{
RegionInfo regionInfo = m_localBackend.RequestNeighbourInfo(regionHandle);
if (regionInfo != null)
{
return regionInfo;
}
if (m_useRemoteRegionCache)
{
lock (m_remoteRegionInfoCache)
{
RegionInfoCacheEntry entry;
if (m_remoteRegionInfoCache.TryGetValue(regionHandle, out entry))
{
if (DateTime.Now - entry.CachedTime < TimeSpan.FromMinutes(15.0))
{
if (entry.Exists)
{
return entry.Info;
}
else
{
return null;
}
}
else
{
m_remoteRegionInfoCache.Remove(regionHandle);
}
}
}
}
try
{
Hashtable requestData = new Hashtable();
requestData["region_handle"] = regionHandle.ToString();
requestData["authkey"] = serversInfo.GridSendKey;
ArrayList SendParams = new ArrayList();
SendParams.Add(requestData);
string methodName = "simulator_data_request";
XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 3000);
Hashtable responseData = (Hashtable) GridResp.Value;
if (responseData.ContainsKey("error"))
{
m_log.Error("[OGS1 GRID SERVICES]: Error received from grid server: " + responseData["error"]);
if (m_useRemoteRegionCache)
{
lock (m_remoteRegionInfoCache)
{
if (!m_remoteRegionInfoCache.ContainsKey(regionHandle))
{
RegionInfoCacheEntry entry = new RegionInfoCacheEntry
{
CachedTime = DateTime.Now,
Info = null,
Exists = false
};
m_remoteRegionInfoCache[regionHandle] = entry;
}
}
}
return null;
}
uint regX = Convert.ToUInt32((string) responseData["region_locx"]);
uint regY = Convert.ToUInt32((string) responseData["region_locy"]);
string externalHostName = (string) responseData["sim_ip"];
uint simPort = Convert.ToUInt32(responseData["sim_port"]);
string regionName = (string)responseData["region_name"];
UUID regionID = new UUID((string)responseData["region_UUID"]);
uint remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]);
uint httpPort = 9000;
if (responseData.ContainsKey("http_port"))
{
httpPort = Convert.ToUInt32((string)responseData["http_port"]);
}
string outsideIp = null;
if (responseData.ContainsKey("outside_ip"))
outsideIp = (string)responseData["outside_ip"];
//IPEndPoint neighbourInternalEndPoint = new IPEndPoint(IPAddress.Parse(internalIpStr), (int) port);
regionInfo = RegionInfo.Create(regionID, regionName, regX, regY, externalHostName, httpPort, simPort, remotingPort, outsideIp);
if (requestData.ContainsKey("product"))
regionInfo.Product = (ProductRulesUse)Convert.ToInt32(requestData["product"]);
if (m_useRemoteRegionCache)
{
lock (m_remoteRegionInfoCache)
{
if (!m_remoteRegionInfoCache.ContainsKey(regionHandle))
{
RegionInfoCacheEntry entry = new RegionInfoCacheEntry
{
CachedTime = DateTime.Now,
Info = regionInfo,
Exists = true
};
m_remoteRegionInfoCache[regionHandle] = entry;
}
}
}
}
catch (Exception e)
{
m_log.Error("[OGS1 GRID SERVICES]: " +
"Region lookup failed for: " + regionHandle.ToString() +
" - Is the GridServer down?" + e.ToString());
return null;
}
return regionInfo;
}
/// <summary>
/// Get information about a neighbouring region
/// </summary>
/// <param name="regionHandle"></param>
/// <returns></returns>
public RegionInfo RequestNeighbourInfo(string name)
{
// Not implemented yet
return null;
}
public RegionInfo RequestClosestRegion(string regionName)
{
if (m_useRemoteRegionCache)
{
lock (m_remoteRegionInfoCache)
{
foreach (RegionInfoCacheEntry ri in m_remoteRegionInfoCache.Values)
{
if (ri.Exists && ri.Info != null)
if (ri.Info.RegionName == regionName)
return ri.Info; // .Info is not valid if Exists is false
}
}
}
RegionInfo regionInfo = null;
try
{
Hashtable requestData = new Hashtable();
requestData["region_name_search"] = regionName;
requestData["authkey"] = serversInfo.GridSendKey;
ArrayList SendParams = new ArrayList();
SendParams.Add(requestData);
string methodName = "simulator_data_request";
XmlRpcRequest GridReq = new XmlRpcRequest(methodName, SendParams);
XmlRpcResponse GridResp = GridReq.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 3000);
Hashtable responseData = (Hashtable) GridResp.Value;
if (responseData.ContainsKey("error"))
{
m_log.ErrorFormat("[OGS1 GRID SERVICES]: Error received from grid server: ", responseData["error"]);
#if NEEDS_REPLACEMENT
lock (m_remoteRegionInfoCache)
{
m_remoteRegionInfoCache[regionInfo.RegionHandle] = new RegionInfoCacheEntry
{
CachedTime = DateTime.Now,
Info = null,
Exists = false
};
}
#endif
return null;
}
regionInfo = buildRegionInfo(responseData, "");
if (m_useRemoteRegionCache)
{
lock (m_remoteRegionInfoCache)
{
m_remoteRegionInfoCache[regionInfo.RegionHandle] = new RegionInfoCacheEntry {
CachedTime = DateTime.Now,
Exists = true,
Info = regionInfo
};
}
}
}
catch
{
m_log.Error("[OGS1 GRID SERVICES]: " +
"Region lookup failed for: " + regionName +
" - Is the GridServer down?");
}
return regionInfo;
}
/// <summary>
///
/// </summary>
/// <param name="minX"></param>
/// <param name="minY"></param>
/// <param name="maxX"></param>
/// <param name="maxY"></param>
/// <returns></returns>
public List<MapBlockData> RequestNeighbourMapBlocks(int minX, int minY, int maxX, int maxY)
{
int temp = 0;
if (minX > maxX)
{
temp = minX;
minX = maxX;
maxX = temp;
}
if (minY > maxY)
{
temp = minY;
minY = maxY;
maxY = temp;
}
Hashtable respData = MapBlockQuery(minX, minY, maxX, maxY);
List<MapBlockData> neighbours = new List<MapBlockData>();
foreach (ArrayList a in respData.Values)
{
foreach (Hashtable n in a)
{
MapBlockData neighbour = new MapBlockData();
neighbour.X = Convert.ToUInt16(n["x"]);
neighbour.Y = Convert.ToUInt16(n["y"]);
neighbour.Name = (string) n["name"];
neighbour.Access = Convert.ToByte(n["access"]);
neighbour.RegionFlags = Convert.ToUInt32(n["region-flags"]);
neighbour.WaterHeight = Convert.ToByte(n["water-height"]);
neighbour.MapImageId = new UUID((string) n["map-image-id"]);
neighbours.Add(neighbour);
}
}
return neighbours;
}
/// <summary>
/// Performs a XML-RPC query against the grid server returning mapblock information in the specified coordinates
/// </summary>
/// <param name="minX">Minimum X value</param>
/// <param name="minY">Minimum Y value</param>
/// <param name="maxX">Maximum X value</param>
/// <param name="maxY">Maximum Y value</param>
/// <returns>Hashtable of hashtables containing map data elements</returns>
private Hashtable MapBlockQuery(int minX, int minY, int maxX, int maxY)
{
Hashtable param = new Hashtable();
param["xmin"] = minX;
param["ymin"] = minY;
param["xmax"] = maxX;
param["ymax"] = maxY;
IList parameters = new ArrayList();
parameters.Add(param);
try
{
string methodName = "map_block";
XmlRpcRequest req = new XmlRpcRequest(methodName, parameters);
XmlRpcResponse resp = req.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 10000);
Hashtable respData = (Hashtable)resp.Value;
if (respData != null && respData.Contains("faultCode"))
{
m_log.ErrorFormat("[OGS1 GRID SERVICES]: Got an error while contacting GridServer: {0}", respData["faultString"]);
return null;
}
return respData;
}
catch (Exception e)
{
m_log.Error("MapBlockQuery XMLRPC failure: " + e);
return new Hashtable();
}
}
/// <summary>
/// A ping / version check
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse PingCheckReply(XmlRpcRequest request,IPEndPoint remoteClient)
{
XmlRpcResponse response = new XmlRpcResponse();
Hashtable respData = new Hashtable();
respData["online"] = "true";
m_localBackend.PingCheckReply(respData);
response.Value = respData;
return response;
}
/// <summary>
/// Received from the user server when a user starts logging in. This call allows
/// the region to prepare for direct communication from the client. Sends back an empty
/// xmlrpc response on completion.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse ExpectUser(XmlRpcRequest request)
{
Hashtable requestData = (Hashtable) request.Params[0];
AgentCircuitData agentData = new AgentCircuitData();
agentData.SessionID = new UUID((string) requestData["session_id"]);
agentData.SecureSessionID = new UUID((string) requestData["secure_session_id"]);
agentData.FirstName = (string) requestData["firstname"];
agentData.LastName = (string) requestData["lastname"];
agentData.AgentID = new UUID((string) requestData["agent_id"]);
agentData.CircuitCode = Convert.ToUInt32(requestData["circuit_code"]);
agentData.CapsPath = (string)requestData["caps_path"];
ulong regionHandle = Convert.ToUInt64((string) requestData["regionhandle"]);
// Appearance
if (requestData.ContainsKey("appearance"))
agentData.Appearance = new AvatarAppearance((Hashtable)requestData["appearance"]);
m_log.DebugFormat(
"[CLIENT]: Told by user service to prepare for a connection from {0} {1} {2}, circuit {3}",
agentData.FirstName, agentData.LastName, agentData.AgentID, agentData.CircuitCode);
if (requestData.ContainsKey("child_agent") && requestData["child_agent"].Equals("1"))
{
//m_log.Debug("[CLIENT]: Child agent detected");
agentData.child = true;
}
else
{
//m_log.Debug("[CLIENT]: Main agent detected");
agentData.startpos =
new Vector3((float)Convert.ToDouble((string)requestData["startpos_x"]),
(float)Convert.ToDouble((string)requestData["startpos_y"]),
(float)Convert.ToDouble((string)requestData["startpos_z"]));
agentData.child = false;
}
XmlRpcResponse resp = new XmlRpcResponse();
if (!RegionLoginsEnabled)
{
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because region login is currently disabled",
agentData.FirstName, agentData.LastName);
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = "region login currently disabled";
resp.Value = respdata;
}
else
{
RegionInfo[] regions = m_regionsOnInstance.ToArray();
bool banned = false;
for (int i = 0; i < regions.Length; i++)
{
if (regions[i] != null)
{
if (regions[i].RegionHandle == regionHandle)
{
if (regions[i].EstateSettings.IsBanned(agentData.AgentID))
{
banned = true;
break;
}
}
}
}
if (banned)
{
m_log.InfoFormat(
"[CLIENT]: Denying access for user {0} {1} because user is banned",
agentData.FirstName, agentData.LastName);
Hashtable respdata = new Hashtable();
respdata["success"] = "FALSE";
respdata["reason"] = "banned";
resp.Value = respdata;
}
else
{
m_localBackend.TriggerExpectUser(regionHandle, agentData);
Hashtable respdata = new Hashtable();
respdata["success"] = "TRUE";
resp.Value = respdata;
}
}
return resp;
}
// Grid Request Processing
/// <summary>
/// Ooops, our Agent must be dead if we're getting this request!
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse LogOffUser(XmlRpcRequest request)
{
m_log.Debug("[CONNECTION DEBUGGING]: LogOff User Called");
Hashtable requestData = (Hashtable)request.Params[0];
string message = (string)requestData["message"];
UUID agentID = UUID.Zero;
UUID RegionSecret = UUID.Zero;
UUID.TryParse((string)requestData["agent_id"], out agentID);
UUID.TryParse((string)requestData["region_secret"], out RegionSecret);
ulong regionHandle = Convert.ToUInt64((string)requestData["regionhandle"]);
m_localBackend.TriggerLogOffUser(regionHandle, agentID, RegionSecret,message);
return new XmlRpcResponse();
}
private LandData RequestLandData(ulong regionHandle, uint x, uint y, int localLandID)
{
LandData landData = null;
Hashtable hash = new Hashtable();
hash["region_handle"] = regionHandle.ToString();
hash["x"] = x.ToString();
hash["y"] = y.ToString();
hash["land_id"] = localLandID.ToString();
IList paramList = new ArrayList();
paramList.Add(hash);
try
{
// this might be cached, as we probably requested it just a moment ago...
RegionInfo info = RequestNeighbourInfo(regionHandle);
if (info != null) // just to be sure
{
string methodName = "land_data";
XmlRpcRequest request = new XmlRpcRequest(methodName, paramList);
string uri = "http://" + info.ExternalHostName + ":" + info.HttpPort + "/";
XmlRpcResponse response = request.Send(Util.XmlRpcRequestURI(uri, methodName), 10000);
if (response.IsFault)
{
m_log.ErrorFormat("[OGS1 GRID SERVICES]: remote call returned an error: {0}", response.FaultString);
}
else
{
hash = (Hashtable)response.Value;
try
{
landData = new LandData();
landData.AABBMax = Vector3.Parse((string)hash["AABBMax"]);
landData.AABBMin = Vector3.Parse((string)hash["AABBMin"]);
landData.Area = Convert.ToInt32(hash["Area"]);
landData.AuctionID = Convert.ToUInt32(hash["AuctionID"]);
landData.Description = (string)hash["Description"];
landData.Flags = Convert.ToUInt32(hash["Flags"]);
landData.GlobalID = new UUID((string)hash["GlobalID"]);
landData.Name = (string)hash["Name"];
landData.OwnerID = new UUID((string)hash["OwnerID"]);
landData.SalePrice = Convert.ToInt32(hash["SalePrice"]);
landData.SnapshotID = new UUID((string)hash["SnapshotID"]);
landData.UserLocation = Vector3.Parse((string)hash["UserLocation"]);
// LandingType and UserLookAt were not included in the hash data prior to R1670.
// LandingType 0 means blocked, so where communicating with an older server, return 2 (anywhere).
landData.LandingType = hash.ContainsKey("LandingType") ? Convert.ToByte(hash["LandingType"]) : (byte)2;
landData.UserLookAt = hash.ContainsKey("UserLookAt") ? Vector3.Parse((string)hash["UserLookAt"]) : Vector3.Zero;
m_log.DebugFormat("[OGS1 GRID SERVICES]: Got land data for parcel {0}", landData.Name);
}
catch (Exception e)
{
m_log.Error("[OGS1 GRID SERVICES]: Got exception while parsing land-data:", e);
landData = null;
}
}
}
else m_log.WarnFormat("[OGS1 GRID SERVICES]: Couldn't find region with handle {0}", regionHandle);
}
catch (WebException)
{
m_log.WarnFormat("[OGS1 GRID SERVICES]: Couldn't contact region {0}: Region may be down.", regionHandle);
}
catch (Exception e)
{
m_log.ErrorFormat("[OGS1 GRID SERVICES]: Couldn't contact region {0}: {1}", regionHandle, e);
}
return landData;
}
public LandData RequestLandData(ulong regionHandle, uint x, uint y)
{
// m_log.DebugFormat("[OGS1 GRID SERVICES]: requests land data in {0}, at {1}, {2}", regionHandle, x, y);
LandData landData = m_localBackend.RequestLandData(regionHandle, x, y);
if (landData == null)
landData = RequestLandData(regionHandle, x, y, -1);
return landData;
}
public LandData RequestLandData(ulong regionHandle, int localLandID)
{
// m_log.DebugFormat("[OGS1 GRID SERVICES]: requests land data in {0}, with ID {1}", regionHandle, localLandID);
LandData landData = m_localBackend.RequestLandData(regionHandle, localLandID);
if (landData == null)
landData = RequestLandData(regionHandle, 128, 128, localLandID);
return landData;
}
// Grid Request Processing
/// <summary>
/// Someone asked us about parcel-information
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public XmlRpcResponse LandData(XmlRpcRequest request, IPEndPoint remoteClient)
{
LandData landData = null;
Hashtable requestData = (Hashtable)request.Params[0];
ulong regionHandle = Convert.ToUInt64(requestData["region_handle"]);
uint x = Convert.ToUInt32(requestData["x"]);
uint y = Convert.ToUInt32(requestData["y"]);
int localLandID = -1;
if (requestData.ContainsKey("land_id"))
{
localLandID = Convert.ToInt32(requestData["land_id"]);
}
if (localLandID == -1)
{
// look up by x/y coordinates
m_log.DebugFormat("[OGS1 GRID SERVICES]: Got XML request for land data at {0}, {1} in region {2}", x, y, regionHandle);
landData = m_localBackend.RequestLandData(regionHandle, x, y);
}
else
{
// look up by local land ID
m_log.DebugFormat("[OGS1 GRID SERVICES]: Got XML request for land data with ID {0} in region {1}", localLandID, regionHandle);
landData = m_localBackend.RequestLandData(regionHandle, localLandID);
}
Hashtable hash = new Hashtable();
if (landData != null)
{
// for now, only push out the data we need for answering a ParcelInfoReqeust
hash["AABBMax"] = landData.AABBMax.ToString();
hash["AABBMin"] = landData.AABBMin.ToString();
hash["Area"] = landData.Area.ToString();
hash["AuctionID"] = landData.AuctionID.ToString();
hash["Description"] = landData.Description;
hash["Flags"] = landData.Flags.ToString();
hash["GlobalID"] = landData.GlobalID.ToString();
hash["LandingType"] = landData.LandingType.ToString();
hash["Name"] = landData.Name;
hash["OwnerID"] = landData.OwnerID.ToString();
hash["SalePrice"] = landData.SalePrice.ToString();
hash["SnapshotID"] = landData.SnapshotID.ToString();
hash["UserLocation"] = landData.UserLocation.ToString();
hash["UserLookAt"] = landData.UserLookAt.ToString();
}
XmlRpcResponse response = new XmlRpcResponse();
response.Value = hash;
return response;
}
public List<RegionInfo> RequestNamedRegions (string name, int maxNumber)
{
// no asking of the local backend first, here, as we have to ask the gridserver anyway.
Hashtable hash = new Hashtable();
hash["name"] = name;
hash["maxNumber"] = maxNumber.ToString();
IList paramList = new ArrayList();
paramList.Add(hash);
Hashtable result = XmlRpcSearchForRegionByName(paramList);
if (result == null) return null;
uint numberFound = Convert.ToUInt32(result["numFound"]);
List<RegionInfo> infos = new List<RegionInfo>();
for (int i = 0; i < numberFound; ++i)
{
string prefix = "region" + i + ".";
RegionInfo info = buildRegionInfo(result, prefix);
infos.Add(info);
}
return infos;
}
private RegionInfo buildRegionInfo(Hashtable responseData, string prefix)
{
uint regX = Convert.ToUInt32((string) responseData[prefix + "region_locx"]);
uint regY = Convert.ToUInt32((string) responseData[prefix + "region_locy"]);
string internalIpStr = (string) responseData[prefix + "sim_ip"];
uint port = Convert.ToUInt32(responseData[prefix + "sim_port"]);
IPEndPoint neighbourInternalEndPoint = new IPEndPoint(Util.GetHostFromDNS(internalIpStr), (int) port);
RegionInfo regionInfo = new RegionInfo(regX, regY, neighbourInternalEndPoint, internalIpStr);
regionInfo.RemotingPort = Convert.ToUInt32((string) responseData[prefix + "remoting_port"]);
regionInfo.RemotingAddress = internalIpStr;
if (responseData.ContainsKey(prefix + "http_port"))
{
regionInfo.HttpPort = Convert.ToUInt32((string) responseData[prefix + "http_port"]);
}
regionInfo.RegionID = new UUID((string) responseData[prefix + "region_UUID"]);
regionInfo.RegionName = (string) responseData[prefix + "region_name"];
regionInfo.RegionSettings.TerrainImageID = new UUID((string) responseData[prefix + "map_UUID"]);
return regionInfo;
}
private Hashtable XmlRpcSearchForRegionByName(IList parameters)
{
try
{
string methodName = "search_for_region_by_name";
XmlRpcRequest request = new XmlRpcRequest(methodName, parameters);
XmlRpcResponse resp = request.Send(Util.XmlRpcRequestURI(serversInfo.GridURL, methodName), 10000);
Hashtable respData = (Hashtable) resp.Value;
if (respData != null && respData.Contains("faultCode"))
{
m_log.WarnFormat("[OGS1 GRID SERVICES]: Got an error while contacting GridServer: {0}", respData["faultString"]);
return null;
}
return respData;
}
catch (Exception e)
{
m_log.Error("[OGS1 GRID SERVICES]: MapBlockQuery XMLRPC failure: ", e);
return null;
}
}
public System.Threading.Tasks.Task<List<SimpleRegionInfo>> RequestNeighbors2Async(uint x, uint y, int maxDD)
{
Task<List<SimpleRegionInfo>> requestTask = new Task<List<SimpleRegionInfo>>(() =>
{
uint xmin, xmax, ymin, ymax;
Util.GetDrawDistanceBasedRegionRectangle((uint)maxDD, x, y, out xmin, out xmax, out ymin, out ymax);
Hashtable block = MapBlockQuery((int)xmin, (int)ymin, (int)xmax, (int)ymax);
if (block == null)
return new List<SimpleRegionInfo>();
return ExtractRegionInfoFromMapBlockQuery(x, y, block);
}
);
requestTask.Start();
return requestTask;
}
}
}
| |
// 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.Diagnostics;
using System.Globalization;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.CoreServices.Settings;
using OpenLiveWriter.Interop.Windows;
namespace OpenLiveWriter.FileDestinations
{
/// <summary>
/// Manages the storage of publish and destination settings in the Windows Registry.
/// </summary>
public class DestinationProfileManager
{
public DestinationProfileManager() : this(FILE_DESTINATIONS_KEY)
{
}
public DestinationProfileManager(string destinationKey)
{
_destinationKey = destinationKey;
}
#region Destination Settings Management
public bool HasProfile(string key)
{
if (key == string.Empty)
return false;
SettingsPersisterHelper settings = SettingsRoot;
return settings.HasSubSettings(_destinationKey + @"\" + key);
}
/// <summary>
/// Returns the profile associated with the key, or null if no such profile exists.
/// </summary>
/// <param name="key">The name of the registry key to define the profile under.</param>
/// <returns></returns>
public DestinationProfile loadProfile(String key)
{
SettingsPersisterHelper settings = getProfileSettings(key);
if(settings.GetNames().Length == 0)
{
return null;
}
DestinationProfile profile = new DestinationProfile();
profile.Id = key;
profile.Name = settings.GetString(PROFILE_NAME_KEY, "");
profile.WebsiteURL = settings.GetString(PROFILE_WEBSITE_URL_KEY, "");
profile.FtpServer = settings.GetString(PROFILE_FTP_SERVER_KEY, "");
profile.UserName = settings.GetString(PROFILE_FTP_USER_KEY, "");
profile.FtpPublishPath = settings.GetString(PROFILE_FTP_PUBLISH_DIR_KEY, "");
profile.LocalPublishPath = settings.GetString(PROFILE_PUBLISH_DIR_KEY, "");
profile.Type = (DestinationProfile.DestType)settings.GetInt32(PROFILE_DESTINATION_TYPE_KEY, 0);
//load the decrypted password
try
{
profile.Password = settings.GetEncryptedString(PROFILE_FTP_PASSWORD_KEY);
}
catch(Exception e)
{
Trace.Fail("Failed to decrypt password: " + e);
}
return profile;
}
/// <summary>
/// Saves a destination profile into the registry.
/// </summary>
/// <param name="key"></param>
/// <param name="profile"></param>
public void saveProfile(String key, DestinationProfile profile)
{
SettingsPersisterHelper settings = getProfileSettings(key);
profile.Id = key;
settings.SetString(PROFILE_NAME_KEY, profile.Name);
settings.SetString(PROFILE_WEBSITE_URL_KEY, profile.WebsiteURL);
settings.SetString(PROFILE_FTP_SERVER_KEY, profile.FtpServer);
settings.SetString(PROFILE_FTP_PUBLISH_DIR_KEY, profile.FtpPublishPath);
settings.SetString(PROFILE_FTP_USER_KEY, profile.UserName);
settings.SetString(PROFILE_PUBLISH_DIR_KEY, profile.LocalPublishPath);
settings.SetInt32(PROFILE_DESTINATION_TYPE_KEY, (short)profile.Type) ;
//save an encrypted password
try
{
settings.SetEncryptedString(PROFILE_FTP_PASSWORD_KEY, profile.Password);
}
catch(Exception e)
{
//if an exception occurs, just leave the password empty
Trace.Fail("Failed to encrypt password: " + e.Message, e.StackTrace);
}
}
/// <summary>
/// Remove the destination profile associated with the specified key.
/// </summary>
/// <param name="key"></param>
public void deleteProfile(string key)
{
SettingsPersisterHelper settings = SettingsRoot ;
settings = settings.GetSubSettings(_destinationKey);
settings.SettingsPersister.UnsetSubSettingsTree(key);
}
/// <summary>
/// Returns all of the available destination profiles.
/// </summary>
/// <returns>an array of all available profiles</returns>
public DestinationProfile[] Profiles
{
get
{
SettingsPersisterHelper settings = SettingsRoot;
settings = settings.GetSubSettings(_destinationKey);
string[] keys = settings.GetSubSettingNames();
DestinationProfile[] profiles = new DestinationProfile[keys.Length];
for(int i=0; i<profiles.Length; i++)
{
profiles[i] = loadProfile(keys[i]);
}
return profiles;
}
}
/// <summary>
/// Returns ID profile designated as the default profile
/// </summary>
public string DefaultProfileId
{
get
{
SettingsPersisterHelper settings = SettingsRoot;
settings = settings.GetSubSettings(_destinationKey);
string key = settings.GetString(PROFILE_DEFAULT_PROFILE_KEY, null);
return key;
}
set
{
SettingsPersisterHelper settings = SettingsRoot;
settings = settings.GetSubSettings(_destinationKey);
settings.SetString(PROFILE_DEFAULT_PROFILE_KEY, value);
}
}
/// <summary>
/// Returns the registry subtree for a specified profile.
/// </summary>
/// <param name="profileKey"></param>
/// <returns></returns>
private SettingsPersisterHelper getProfileSettings(string profileKey)
{
SettingsPersisterHelper settings = SettingsRoot;
settings = settings.GetSubSettings(_destinationKey + @"\" + profileKey);
return settings;
}
#endregion
#region Class Configuration (location of settings, etc)
/// <summary>
/// Allow configuration of the settings root to be used by the DestinationProfileManager
/// (defaults to product settings key)
/// </summary>
public static SettingsPersisterHelper SettingsRoot
{
get
{
return ApplicationEnvironment.UserSettingsRoot;
}
}
private string _destinationKey;
#endregion
#region Constants
// root key
private const string FILE_DESTINATIONS_KEY = @"FileDestinations" ;
//destination settings keys
private const string PROFILE_NAME_KEY = "Name";
private const string PROFILE_WEBSITE_URL_KEY = "URL";
private const string PROFILE_FTP_SERVER_KEY = "FtpServer";
private const string PROFILE_FTP_USER_KEY = "FtpUserName";
private const string PROFILE_FTP_PASSWORD_KEY = "FtpPassword";
private const string PROFILE_FTP_PUBLISH_DIR_KEY = "FtpPublishDir";
private const string PROFILE_PUBLISH_DIR_KEY = "PublishDir";
private const string PROFILE_DESTINATION_TYPE_KEY = "DestinationType";
private const string PROFILE_RSS_FEED_KEY = "RssFeed";
private const string PROFILE_DEFAULT_PROFILE_KEY = "DefaultProfile";
#endregion
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2.1
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = DocuSign.eSign.Client.SwaggerDateConverter;
namespace DocuSign.eSign.Model
{
/// <summary>
/// BulkSendBatchSummaries
/// </summary>
[DataContract]
public partial class BulkSendBatchSummaries : IEquatable<BulkSendBatchSummaries>, IValidatableObject
{
public BulkSendBatchSummaries()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="BulkSendBatchSummaries" /> class.
/// </summary>
/// <param name="BatchSizeLimit">BatchSizeLimit.</param>
/// <param name="BulkBatchSummaries">BulkBatchSummaries.</param>
/// <param name="BulkProcessQueueLimit">BulkProcessQueueLimit.</param>
/// <param name="BulkProcessTotalQueued">BulkProcessTotalQueued.</param>
/// <param name="EndPosition">The last position in the result set. .</param>
/// <param name="NextUri">The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. .</param>
/// <param name="PreviousUri">The postal code for the billing address..</param>
/// <param name="QueueLimit">QueueLimit.</param>
/// <param name="ResultSetSize">The number of results returned in this response. .</param>
/// <param name="StartPosition">Starting position of the current result set..</param>
/// <param name="TotalQueued">TotalQueued.</param>
/// <param name="TotalSetSize">The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response..</param>
public BulkSendBatchSummaries(string BatchSizeLimit = default(string), List<BulkSendBatchSummary> BulkBatchSummaries = default(List<BulkSendBatchSummary>), string BulkProcessQueueLimit = default(string), string BulkProcessTotalQueued = default(string), string EndPosition = default(string), string NextUri = default(string), string PreviousUri = default(string), string QueueLimit = default(string), string ResultSetSize = default(string), string StartPosition = default(string), string TotalQueued = default(string), string TotalSetSize = default(string))
{
this.BatchSizeLimit = BatchSizeLimit;
this.BulkBatchSummaries = BulkBatchSummaries;
this.BulkProcessQueueLimit = BulkProcessQueueLimit;
this.BulkProcessTotalQueued = BulkProcessTotalQueued;
this.EndPosition = EndPosition;
this.NextUri = NextUri;
this.PreviousUri = PreviousUri;
this.QueueLimit = QueueLimit;
this.ResultSetSize = ResultSetSize;
this.StartPosition = StartPosition;
this.TotalQueued = TotalQueued;
this.TotalSetSize = TotalSetSize;
}
/// <summary>
/// Gets or Sets BatchSizeLimit
/// </summary>
[DataMember(Name="batchSizeLimit", EmitDefaultValue=false)]
public string BatchSizeLimit { get; set; }
/// <summary>
/// Gets or Sets BulkBatchSummaries
/// </summary>
[DataMember(Name="bulkBatchSummaries", EmitDefaultValue=false)]
public List<BulkSendBatchSummary> BulkBatchSummaries { get; set; }
/// <summary>
/// Gets or Sets BulkProcessQueueLimit
/// </summary>
[DataMember(Name="bulkProcessQueueLimit", EmitDefaultValue=false)]
public string BulkProcessQueueLimit { get; set; }
/// <summary>
/// Gets or Sets BulkProcessTotalQueued
/// </summary>
[DataMember(Name="bulkProcessTotalQueued", EmitDefaultValue=false)]
public string BulkProcessTotalQueued { get; set; }
/// <summary>
/// The last position in the result set.
/// </summary>
/// <value>The last position in the result set. </value>
[DataMember(Name="endPosition", EmitDefaultValue=false)]
public string EndPosition { get; set; }
/// <summary>
/// The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null.
/// </summary>
/// <value>The URI to the next chunk of records based on the search request. If the endPosition is the entire results of the search, this is null. </value>
[DataMember(Name="nextUri", EmitDefaultValue=false)]
public string NextUri { get; set; }
/// <summary>
/// The postal code for the billing address.
/// </summary>
/// <value>The postal code for the billing address.</value>
[DataMember(Name="previousUri", EmitDefaultValue=false)]
public string PreviousUri { get; set; }
/// <summary>
/// Gets or Sets QueueLimit
/// </summary>
[DataMember(Name="queueLimit", EmitDefaultValue=false)]
public string QueueLimit { get; set; }
/// <summary>
/// The number of results returned in this response.
/// </summary>
/// <value>The number of results returned in this response. </value>
[DataMember(Name="resultSetSize", EmitDefaultValue=false)]
public string ResultSetSize { get; set; }
/// <summary>
/// Starting position of the current result set.
/// </summary>
/// <value>Starting position of the current result set.</value>
[DataMember(Name="startPosition", EmitDefaultValue=false)]
public string StartPosition { get; set; }
/// <summary>
/// Gets or Sets TotalQueued
/// </summary>
[DataMember(Name="totalQueued", EmitDefaultValue=false)]
public string TotalQueued { get; set; }
/// <summary>
/// The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.
/// </summary>
/// <value>The total number of items available in the result set. This will always be greater than or equal to the value of the property returning the results in the in the response.</value>
[DataMember(Name="totalSetSize", EmitDefaultValue=false)]
public string TotalSetSize { 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 BulkSendBatchSummaries {\n");
sb.Append(" BatchSizeLimit: ").Append(BatchSizeLimit).Append("\n");
sb.Append(" BulkBatchSummaries: ").Append(BulkBatchSummaries).Append("\n");
sb.Append(" BulkProcessQueueLimit: ").Append(BulkProcessQueueLimit).Append("\n");
sb.Append(" BulkProcessTotalQueued: ").Append(BulkProcessTotalQueued).Append("\n");
sb.Append(" EndPosition: ").Append(EndPosition).Append("\n");
sb.Append(" NextUri: ").Append(NextUri).Append("\n");
sb.Append(" PreviousUri: ").Append(PreviousUri).Append("\n");
sb.Append(" QueueLimit: ").Append(QueueLimit).Append("\n");
sb.Append(" ResultSetSize: ").Append(ResultSetSize).Append("\n");
sb.Append(" StartPosition: ").Append(StartPosition).Append("\n");
sb.Append(" TotalQueued: ").Append(TotalQueued).Append("\n");
sb.Append(" TotalSetSize: ").Append(TotalSetSize).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as BulkSendBatchSummaries);
}
/// <summary>
/// Returns true if BulkSendBatchSummaries instances are equal
/// </summary>
/// <param name="other">Instance of BulkSendBatchSummaries to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(BulkSendBatchSummaries other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.BatchSizeLimit == other.BatchSizeLimit ||
this.BatchSizeLimit != null &&
this.BatchSizeLimit.Equals(other.BatchSizeLimit)
) &&
(
this.BulkBatchSummaries == other.BulkBatchSummaries ||
this.BulkBatchSummaries != null &&
this.BulkBatchSummaries.SequenceEqual(other.BulkBatchSummaries)
) &&
(
this.BulkProcessQueueLimit == other.BulkProcessQueueLimit ||
this.BulkProcessQueueLimit != null &&
this.BulkProcessQueueLimit.Equals(other.BulkProcessQueueLimit)
) &&
(
this.BulkProcessTotalQueued == other.BulkProcessTotalQueued ||
this.BulkProcessTotalQueued != null &&
this.BulkProcessTotalQueued.Equals(other.BulkProcessTotalQueued)
) &&
(
this.EndPosition == other.EndPosition ||
this.EndPosition != null &&
this.EndPosition.Equals(other.EndPosition)
) &&
(
this.NextUri == other.NextUri ||
this.NextUri != null &&
this.NextUri.Equals(other.NextUri)
) &&
(
this.PreviousUri == other.PreviousUri ||
this.PreviousUri != null &&
this.PreviousUri.Equals(other.PreviousUri)
) &&
(
this.QueueLimit == other.QueueLimit ||
this.QueueLimit != null &&
this.QueueLimit.Equals(other.QueueLimit)
) &&
(
this.ResultSetSize == other.ResultSetSize ||
this.ResultSetSize != null &&
this.ResultSetSize.Equals(other.ResultSetSize)
) &&
(
this.StartPosition == other.StartPosition ||
this.StartPosition != null &&
this.StartPosition.Equals(other.StartPosition)
) &&
(
this.TotalQueued == other.TotalQueued ||
this.TotalQueued != null &&
this.TotalQueued.Equals(other.TotalQueued)
) &&
(
this.TotalSetSize == other.TotalSetSize ||
this.TotalSetSize != null &&
this.TotalSetSize.Equals(other.TotalSetSize)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.BatchSizeLimit != null)
hash = hash * 59 + this.BatchSizeLimit.GetHashCode();
if (this.BulkBatchSummaries != null)
hash = hash * 59 + this.BulkBatchSummaries.GetHashCode();
if (this.BulkProcessQueueLimit != null)
hash = hash * 59 + this.BulkProcessQueueLimit.GetHashCode();
if (this.BulkProcessTotalQueued != null)
hash = hash * 59 + this.BulkProcessTotalQueued.GetHashCode();
if (this.EndPosition != null)
hash = hash * 59 + this.EndPosition.GetHashCode();
if (this.NextUri != null)
hash = hash * 59 + this.NextUri.GetHashCode();
if (this.PreviousUri != null)
hash = hash * 59 + this.PreviousUri.GetHashCode();
if (this.QueueLimit != null)
hash = hash * 59 + this.QueueLimit.GetHashCode();
if (this.ResultSetSize != null)
hash = hash * 59 + this.ResultSetSize.GetHashCode();
if (this.StartPosition != null)
hash = hash * 59 + this.StartPosition.GetHashCode();
if (this.TotalQueued != null)
hash = hash * 59 + this.TotalQueued.GetHashCode();
if (this.TotalSetSize != null)
hash = hash * 59 + this.TotalSetSize.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
//
// The original content was ported from the C language from the 4.6 version of Proj4 libraries.
// Frank Warmerdam has released the full content of that version under the MIT license which is
// recognized as being approximately equivalent to public domain. The original work was done
// mostly by Gerald Evenden. The latest versions of the C libraries can be obtained here:
// http://trac.osgeo.org/proj/
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 8/12/2009 10:15:38 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
using System;
namespace DotSpatial.Projections.Transforms
{
public class AlbersEqualArea : Transform
{
#region Private Variables
private const int N_ITER = 15;
private const double EPSILON = 1.0E-7;
private const double TOL = 1E-10;
private const double TOL7 = 1E-7;
private double _c;
private double _dd;
private double _ec;
private double _n;
private double _n2;
private double _phi1;
private double _phi2;
private double _rho;
private double _rho0;
#endregion
#region Constructors
/// <summary>
/// Creates a new instance of AlbersEqualArea
/// </summary>
public AlbersEqualArea()
{
Name = "Albers";
Proj4Name = "aea";
}
#endregion
#region Methods
/// <inheritdoc />
protected override void OnForward(double[] lp, double[] xy, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
if ((_rho = _c - (IsElliptical
? _n * Proj.Qsfn(Math.Sin(lp[phi]),
E, OneEs)
: _n2 * Math.Sin(lp[phi]))) < 0)
{
xy[x] = double.NaN;
xy[y] = double.NaN;
continue;
//throw new ProjectionException(20);
}
_rho = _dd * Math.Sqrt(_rho);
xy[x] = _rho * Math.Sin(lp[lam] *= _n);
xy[y] = _rho0 - _rho * Math.Cos(lp[lam]);
}
}
private static double PhiFn(double qs, double te, double toneEs)
{
double dphi;
double myPhi = Math.Asin(.5 * qs);
if (te < EPSILON) return (myPhi);
int i = N_ITER;
do
{
double sinpi = Math.Sin(myPhi);
double cospi = Math.Cos(myPhi);
double con = te * sinpi;
double com = 1 - con * con;
dphi = .5 * com * com / cospi * (qs / toneEs -
sinpi / com + .5 / te * Math.Log((1 - con) / (1 + con)));
myPhi += dphi;
}
while (Math.Abs(dphi) > TOL && --i > 0);
return (i != 0 ? myPhi : double.MaxValue);
}
/// <inheritdoc />
protected override void OnInverse(double[] xy, double[] lp, int startIndex, int numPoints)
{
for (int i = startIndex; i < startIndex + numPoints; i++)
{
int phi = i * 2 + PHI;
int lam = i * 2 + LAMBDA;
int x = i * 2 + X;
int y = i * 2 + Y;
if ((_rho = Proj.Hypot(xy[x], xy[y] = _rho0 - xy[y])) != 0.0)
{
if (_n < 0)
{
_rho = -_rho;
xy[x] = -xy[x];
xy[y] = -xy[y];
}
lp[phi] = _rho / _dd;
if (IsElliptical)
{
lp[phi] = (_c - lp[phi] * lp[phi]) / _n;
if (Math.Abs(_ec - Math.Abs(lp[phi])) > TOL7)
{
if ((lp[phi] = PhiFn(lp[phi], E, OneEs)) == double.MaxValue)
{
lp[phi] = double.NaN;
lp[lam] = double.NaN;
continue;
//throw new ProjectionException(20);
}
}
else
{
lp[phi] = lp[phi] < 0 ? -HALF_PI : HALF_PI;
}
}
else if (Math.Abs(lp[phi] = (_c - lp[phi] * lp[phi]) / _n2) <= 1)
{
lp[phi] = Math.Asin(lp[phi]);
}
else
{
lp[phi] = lp[phi] < 0 ? -HALF_PI : HALF_PI;
}
lp[lam] = Math.Atan2(xy[x], xy[y]) / _n;
}
else
{
lp[lam] = 0;
lp[phi] = _n > 0 ? HALF_PI : -HALF_PI;
}
}
}
/// <summary>
/// Initializes the transform using the parameters from the specified coordinate system information
/// </summary>
/// <param name="projInfo">A ProjectionInfo class contains all the standard and custom parameters needed to initialize this transform</param>
protected override void OnInit(ProjectionInfo projInfo)
{
_phi1 = projInfo.Phi1;
_phi2 = projInfo.Phi2;
Setup();
}
/// <summary>
/// Internal code handling the setup operations for the transform
/// </summary>
protected void Setup()
{
double sinphi;
if (Math.Abs(_phi1 + _phi2) < EPS10)
{
throw new ProjectionException(-21);
}
_n = sinphi = Math.Sin(_phi1);
double cosphi = Math.Cos(_phi1);
bool secant = Math.Abs(_phi1 - _phi2) >= EPS10;
if (IsElliptical)
{
double m1 = Proj.Msfn(sinphi, cosphi, Es);
double ml1 = Proj.Qsfn(sinphi, E, OneEs);
if (secant)
{ /* secant cone */
sinphi = Math.Sin(_phi2);
cosphi = Math.Cos(_phi2);
double m2 = Proj.Msfn(sinphi, cosphi, Es);
double ml2 = Proj.Qsfn(sinphi, E, OneEs);
_n = (m1 * m1 - m2 * m2) / (ml2 - ml1);
}
_ec = 1 - .5 * OneEs * Math.Log((1 - E) / (1 + E)) / E;
_c = m1 * m1 + _n * ml1;
_dd = 1 / _n;
_rho0 = _dd * Math.Sqrt(_c - _n * Proj.Qsfn(Math.Sin(Phi0), E, OneEs));
}
else
{
if (secant) _n = .5 * (_n + Math.Sin(_phi2));
_n2 = _n + _n;
_c = cosphi * cosphi + _n2 * sinphi;
_dd = 1 / _n;
_rho0 = _dd * Math.Sqrt(_c - _n2 * Math.Sin(Phi0));
}
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the Phi1 parameter
/// </summary>
protected double Phi1
{
get { return _phi1; }
set { _phi1 = value; }
}
/// <summary>
/// Gets or sets the Phi2 parameter
/// </summary>
protected double Phi2
{
get { return _phi2; }
set { _phi2 = value; }
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Text;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.Protocols.TestTools.StackSdk.Security.Cryptographic;
using Microsoft.Protocols.TestTools.StackSdk.Security.Spng;
using Microsoft.Protocols.TestTools.StackSdk.Asn1;
namespace Microsoft.Protocols.TestTools.StackSdk.Security.KerberosLib
{
/// <summary>
/// A static class provides some helper functions. It is called by KerberosPdu and KileDecoder.
/// </summary>
public static class KerberosUtility
{
#region Encryption / Decryption
// The same as its overload that getToBeSignedDateCallback = null
public static byte[] Encrypt(EncryptionType type, byte[] sessionKey, byte[] plainData, int usage)
{
return Encrypt(type, sessionKey, plainData, usage, null);
}
/// <summary>
/// Encrypt the plain text with the session key which can be obtained
/// from response message. The usage indicated in section 7 of RFC4210
/// and section 3 of RFC4757 is used to derive key from the session key.
/// </summary>
/// <param name="type">The encryption type selected.</param>
/// <param name="sessionKey">A session key used to encrypt and it can be obtained
/// from the KDC's response. This key size should be equal to the symmetric algorithm
/// key size. This argument can be null. If it is null, null will be returned.</param>
/// <param name="plainData">The text to be encrypted. This argument can be null.
/// If it is null, null will be returned.</param>
/// <param name="usage">A 32 bits integer used to derive the key.</param>
/// <param name="getToBeSignedDateCallback">
/// A callback to get to-be-signed data.
/// The method will use plain-text data directly if this parameter is null.
/// </param>
/// <returns>The cipher text.</returns>
public static byte[] Encrypt(EncryptionType type, byte[] sessionKey, byte[] plainData, int usage, GetToBeSignedDataFunc getToBeSignedDateCallback)
{
switch (type)
{
case EncryptionType.AES128_CTS_HMAC_SHA1_96:
return AesCtsHmacSha1Crypto.Encrypt(sessionKey, plainData, usage, AesKeyType.Aes128BitsKey, getToBeSignedDateCallback);
case EncryptionType.AES256_CTS_HMAC_SHA1_96:
return AesCtsHmacSha1Crypto.Encrypt(sessionKey, plainData, usage, AesKeyType.Aes256BitsKey, getToBeSignedDateCallback);
case EncryptionType.DES_CBC_CRC:
return DesCbcCrypto.Encrypt(sessionKey, plainData, EncryptionType.DES_CBC_CRC, getToBeSignedDateCallback);
case EncryptionType.DES_CBC_MD5:
return DesCbcCrypto.Encrypt(sessionKey, plainData, EncryptionType.DES_CBC_MD5, getToBeSignedDateCallback);
case EncryptionType.RC4_HMAC:
return Rc4HmacCrypto.Encrypt(sessionKey, plainData, usage, EncryptionType.RC4_HMAC, getToBeSignedDateCallback);
case EncryptionType.RC4_HMAC_EXP:
return Rc4HmacCrypto.Encrypt(sessionKey, plainData, usage, EncryptionType.RC4_HMAC_EXP, getToBeSignedDateCallback);
default:
throw new ArgumentException("Unsupported encryption type.");
}
}
// The same as its overload that getToBeSignedDateCallback = null
public static byte[] Decrypt(EncryptionType type, byte[] sessionKey, byte[] cipherData, int usage)
{
return Decrypt(type, sessionKey, cipherData, usage, null);
}
/// <summary>
/// Decrypt the cipher text with the session key. The usage indicated
/// in section 7 of RFC4210 and section 3 of RFC4757 is used to derive key
/// from the session key.
/// </summary>
/// <param name="type">The decryption type selected.</param>
/// <param name="sessionKey">An session key used to decrypt and it can be obtained
/// from the KDC's response. This key size should be equal to the symmetric algorithm
/// key size. This argument can be null. If it is null, null will be returned.</param>
/// <param name="cipherData">The text to be decrypted. This argument can be null.
/// If it is null, null will be returned.</param>
/// <param name="usage">A 32 bits integer used to derive the key.</param>
/// <param name="getToBeSignedDateCallback">
/// A callback to get to-be-signed data.
/// The method will use decrypted data directly if this parameter is null.
/// </param>
/// <returns>The plain text.</returns>
public static byte[] Decrypt(EncryptionType type, byte[] sessionKey, byte[] cipherData, int usage, GetToBeSignedDataFunc getToBeSignedDateCallback)
{
switch (type)
{
case EncryptionType.AES128_CTS_HMAC_SHA1_96:
return AesCtsHmacSha1Crypto.Decrypt(sessionKey, cipherData, usage, AesKeyType.Aes128BitsKey, getToBeSignedDateCallback);
case EncryptionType.AES256_CTS_HMAC_SHA1_96:
return AesCtsHmacSha1Crypto.Decrypt(sessionKey, cipherData, usage, AesKeyType.Aes256BitsKey, getToBeSignedDateCallback);
case EncryptionType.DES_CBC_CRC:
return DesCbcCrypto.Decrypt(sessionKey, cipherData, EncryptionType.DES_CBC_CRC, getToBeSignedDateCallback);
case EncryptionType.DES_CBC_MD5:
return DesCbcCrypto.Decrypt(sessionKey, cipherData, EncryptionType.DES_CBC_MD5, getToBeSignedDateCallback);
case EncryptionType.RC4_HMAC:
return Rc4HmacCrypto.Decrypt(sessionKey, cipherData, usage, EncryptionType.RC4_HMAC, getToBeSignedDateCallback);
case EncryptionType.RC4_HMAC_EXP:
return Rc4HmacCrypto.Decrypt(sessionKey, cipherData, usage, EncryptionType.RC4_HMAC_EXP, getToBeSignedDateCallback);
default:
throw new ArgumentException("Unsupported encryption type.");
}
}
/// <summary>
/// Generate checksum supported by MS-KILE
/// </summary>
/// <param name="key">the key</param>
/// <param name="input">input data</param>
/// <param name="usage">key usage number</param>
/// <param name="checksumType">checksum type</param>
/// <returns>the caculated checksum</returns>
/// <exception cref="ArgumentException">thrown if the checksum type is not supported</exception>
public static byte[] GetChecksum(
byte[] key,
byte[] input,
int usage,
ChecksumType checksumType)
{
switch (checksumType)
{
case ChecksumType.CRC32:
case ChecksumType.rsa_md4:
case ChecksumType.rsa_md5:
case ChecksumType.sha1:
return UnkeyedChecksum.GetMic(input, checksumType);
case ChecksumType.hmac_sha1_96_aes128:
return HmacSha1AesChecksum.GetMic(
key, input, usage, AesKeyType.Aes128BitsKey);
case ChecksumType.hmac_sha1_96_aes256:
return HmacSha1AesChecksum.GetMic(
key, input, usage, AesKeyType.Aes256BitsKey);
case ChecksumType.hmac_md5_string:
return HmacMd5StringChecksum.GetMic(key, input, usage);
default:
throw new ArgumentException("Unsupported checksum type.");
}
}
public static ChecksumType GetChecksumType(EncryptionType eType)
{
switch (eType)
{
case EncryptionType.AES128_CTS_HMAC_SHA1_96:
return ChecksumType.hmac_sha1_96_aes128;
case EncryptionType.AES256_CTS_HMAC_SHA1_96:
return ChecksumType.hmac_sha1_96_aes256;
case EncryptionType.RC4_HMAC:
return ChecksumType.hmac_md5_string;
case EncryptionType.DES_CBC_MD5:
return ChecksumType.rsa_md5;
case EncryptionType.DES_CBC_CRC:
return ChecksumType.CRC32;
}
throw new NotImplementedException();
}
#endregion Encryption / Decryption
#region Encode / Decode
public static byte[] AddGssApiTokenHeader(KerberosApRequest request,
KerberosConstValue.OidPkt oidPkt = KerberosConstValue.OidPkt.KerberosToken,
KerberosConstValue.GSSToken gssToken = KerberosConstValue.GSSToken.GSSSPNG)
{
byte[] encoded = request.ToBytes();
byte[] token = KerberosUtility.AddGssApiTokenHeader(ArrayUtility.ConcatenateArrays(
BitConverter.GetBytes(KerberosUtility.ConvertEndian((ushort)TOK_ID.KRB_AP_REQ)), encoded), oidPkt, gssToken);
return token;
}
/// <summary>
/// Add a token header for AP request/response, wrap token or getmic token to make them a complete token.
/// </summary>
/// <param name="tokenBody">The AP request/response, wrap token or getmic token.
/// This argument can be null.</param>
/// <returns>The completed token.</returns>
public static byte[] AddGssApiTokenHeader(byte[] tokenBody,
KerberosConstValue.OidPkt oidPkt = KerberosConstValue.OidPkt.KerberosToken,
KerberosConstValue.GSSToken gssToken = KerberosConstValue.GSSToken.GSSSPNG)
{
List<byte> gssDataList = new List<byte>();
gssDataList.Add(KerberosConstValue.KERBEROS_TAG);
// kerberos oid (1.2.840.113554.1.2.2)
byte[] oid;
oid = KerberosConstValue.GetKerberosOid();
if (tokenBody == null)
{
tokenBody = new byte[0];
}
int length = tokenBody.Length + oid.Length;
if (length > 127)
{
// If the indicated value is 128 or more, it shall be represented in two or more octets,
// with bit 8 of the first octet set to "1" and the remaining bits of the first octet
// specifying the number of additional octets. The subsequent octets carry the value,
// 8 bits per octet, most significant digit first. [rfc 2743]
int temp = length;
int index = 1;
List<byte> lengthList = new List<byte>();
lengthList.Add((byte)(temp & 0xFF));
while ((temp >>= 8) != 0)
{
index++;
lengthList.Add((byte)(temp & 0xFF));
}
gssDataList.Add((byte)(0x80 | index));
lengthList.Reverse();
gssDataList.AddRange(lengthList.ToArray());
}
else
{
// If the indicated value is less than 128, it shall be represented in a single octet with bit 8
// (high order) set to "0" and the remaining bits representing the value. [rfc 2743]
gssDataList.Add((byte)length);
}
gssDataList.AddRange(oid);
gssDataList.AddRange(tokenBody);
if (gssToken == KerberosConstValue.GSSToken.GSSAPI)
return gssDataList.ToArray();
else
return KerberosUtility.EncodeInitialNegToken(gssDataList.ToArray(), oidPkt);
}
/// <summary>
/// Verify and remove a token header from AP request/response,
/// wrap token or getmic token.
/// </summary>
/// <param name="completeToken">The complete token got from application message.
/// This argument can be null. If it is null, null will be returned.</param>
/// <returns>The token body without the header.</returns>
/// <exception cref="System.FormatException">Throw FormatException if the token header is incorrect.</exception>
public static byte[] VerifyGssApiTokenHeader(byte[] completeToken, KerberosConstValue.OidPkt oidPkt = KerberosConstValue.OidPkt.KerberosToken)
{
byte[] oid;
oid = KerberosConstValue.GetKerberosOid();
if (completeToken == null || completeToken.Length < KerberosConstValue.GetKerberosOid().Length)
{
throw new FormatException("The GSS-API token header is incomplete!");
}
if (completeToken[0] != KerberosConstValue.KERBEROS_TAG)
{
throw new FormatException("The GSS-API token header is incorrect!");
}
int length = 0;
int index = 2; // the tag and length fields
// If the length value is 128 or more.
if ((completeToken[1] & 0x80) == 0x80)
{
// If the indicated value is 128 or more, it shall be represented in two or more octets,
// with bit 8 of the first octet set to "1" and the remaining bits of the first octet
// specifying the number of additional octets. The subsequent octets carry the value,
// 8 bits per octet, most significant digit first.
int num = completeToken[1] & 0x7F;
index += num;
if (num < 1 || num > 4)
{
throw new FormatException("The GSS-API token length is incorrect!");
}
for (int i = 0; i < num; ++i)
{
length = (length << 8) | completeToken[2 + i];
}
}
else
{
// If the indicated value is less than 128, it shall be represented in a single octet with bit 8
// (high order) set to "0" and the remaining bits representing the value. [rfc 2743]
length = completeToken[1];
}
if (!ArrayUtility.CompareArrays(oid, ArrayUtility.SubArray(completeToken, index, oid.Length)))
{
throw new FormatException("The GSS-API token oid is incorrect!");
}
byte[] tokenBody = ArrayUtility.SubArray(completeToken, index + oid.Length);
return tokenBody;
}
/// <summary>
/// Compute the multiple size of the input length.
/// </summary>
/// <param name="length">The input length.</param>
/// <param name="blockSize">The block size.</param>
/// <returns>The multiple size of the input length.</returns>
public static int RoundUp(int length, int blockSize)
{
return (length + blockSize - 1) / blockSize * blockSize;
}
/// <summary>
/// Wrap a length before the buffer.
/// </summary>
/// <param name="buffer">The buffer to be wrapped.</param>
/// <param name="isBigEndian">Specify if the length is Big-Endian.</param>
/// <returns>The buffer added length.</returns>
public static byte[] WrapLength(byte[] buffer, bool isBigEndian)
{
if (isBigEndian)
{
return ArrayUtility.ConcatenateArrays(
BitConverter.GetBytes(KerberosUtility.ConvertEndian((uint)buffer.Length)), buffer);
}
else
{
return ArrayUtility.ConcatenateArrays(BitConverter.GetBytes(buffer.Length), buffer);
}
}
/// <summary>
/// convert string to _SeqOfKerberosString
/// </summary>
/// <param name="sourceString">source string that will be converted.</param>
/// <returns>a _SeqOfKerberosString string</returns>
public static Asn1SequenceOf<KerberosString> String2SeqKerbString(params string[] sourceString)
{
if (sourceString == null)
{
return null;
}
List<KerberosString> kerberosStringList = new List<KerberosString>();
foreach (string source in sourceString)
{
if (source != null)
{
kerberosStringList.Add(new KerberosString(source));
}
}
Asn1SequenceOf<KerberosString> seqString = new Asn1SequenceOf<KerberosString>(kerberosStringList.ToArray());
return seqString;
}
public static string PrincipalName2String(PrincipalName name)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < name.name_string.Elements.Length; i++)
{
sb.Append(name.name_string.Elements[i]);
if (i != name.name_string.Elements.Length - 1)
sb.Append("/");
}
return sb.ToString();
}
/// <summary>
/// Convert the flags in the format such as Hex string: "'0fa56920014abc'H"
/// </summary>
/// <param name="flags">an int value</param>
/// <returns>A hex string of the flags.</returns>
public static string ConvertInt2Flags(int flags)
{
string output = flags.ToString("x8");
output = "'" + output + "'H";
return output;
}
/// <summary>
/// This method will be used to get the Current UTC Time of the client machine.
/// </summary>
/// <returns>current time in string </returns>
public static string GetCurrentUTCTime()
{
DateTime currTime = DateTime.Now.ToUniversalTime();
// year+Month+day+hour+minute+second
return currTime.ToString("yyyyMMddHHmmss");
}
/// <summary>
/// Get the current timestamp in the format of yyyyMMddhhmmss.
/// </summary>
public static KerberosTime CurrentKerberosTime
{
get
{
string timeStamp = GetCurrentUTCTime() + "Z";
return new KerberosTime(timeStamp, true);
}
}
/// <summary>
/// Generate a random byte array.
/// </summary>
/// <param name="size">The size of byte array.</param>
/// <returns>The bytes generated.</returns>
public static byte[] GenerateRandomBytes(uint size)
{
byte[] randomBytes = new byte[size];
Random random = new Random(DateTime.Now.Millisecond);
random.NextBytes(randomBytes);
return randomBytes;
}
/// <summary>
/// Get Authorization Data from Ticket in AS/TGS response
/// </summary>
/// <param name="ticket">Ticket part that includes Auth Data.</param>
/// <param name="key">The key that encrypts ticket part.</param>
/// <returns>Authorization Data in the ticket</returns>
public static AuthorizationData GetAuthDataInTicket(Ticket ticket, byte[] key)
{
EncryptionType encryptType = (EncryptionType)ticket.enc_part.etype.Value;
byte[] clearText = KerberosUtility.Decrypt(
encryptType,
key,
ticket.enc_part.cipher.ByteArrayValue,
(int)KeyUsageNumber.AS_REP_TicketAndTGS_REP_Ticket);
// Decode the ticket.
Asn1DecodingBuffer decodeBuffer = new Asn1DecodingBuffer(clearText);
EncTicketPart encTicketPart = new EncTicketPart();
encTicketPart.BerDecode(decodeBuffer);
return encTicketPart.authorization_data;
}
/// <summary>
/// Update the Authorization Data part in Ticket with new value.
/// </summary>
/// <param name="ticket">Ticket to be updated with new authorizationData</param>
/// <param name="key">The key that encrypts ticket part.</param>
/// <param name="authorizationData">New authorizationData to update.</param>
public static void UpdateAuthDataInTicket(Ticket ticket, byte[] key, AuthorizationData authorizationData)
{
EncryptionType encryptType = (EncryptionType)ticket.enc_part.etype.Value;
byte[] clearText = KerberosUtility.Decrypt(
encryptType,
key,
ticket.enc_part.cipher.ByteArrayValue,
(int)KeyUsageNumber.AS_REP_TicketAndTGS_REP_Ticket);
// Decode the ticket.
Asn1DecodingBuffer decodeBuffer = new Asn1DecodingBuffer(clearText);
EncTicketPart encTicketPart = new EncTicketPart();
encTicketPart.BerDecode(decodeBuffer);
// Set with new authorization data
encTicketPart.authorization_data = authorizationData;
Asn1BerEncodingBuffer ticketBerBuffer = new Asn1BerEncodingBuffer();
encTicketPart.BerEncode(ticketBerBuffer, true);
byte[] cipherData = KerberosUtility.Encrypt(
encryptType,
key,
ticketBerBuffer.Data,
(int)KeyUsageNumber.AS_REP_TicketAndTGS_REP_Ticket);
ticket.enc_part = new EncryptedData(new KerbInt32((int)encryptType), null, new Asn1OctetString(cipherData));
}
#endregion Encode / Decode
#region token [rfc4121]
/// <summary>
/// Swap lower byte and higher byte.
/// </summary>
/// <param name="num">The number to be converted.</param>
/// <returns>The converted number.</returns>
public static ushort ConvertEndian(ushort num)
{
return (ushort)((num >> 8) | (num << 8));
}
/// <summary>
/// Swap lower byte and higher byte.
/// </summary>
/// <param name="num">The number to be converted.</param>
/// <returns>The converted number.</returns>
public static uint ConvertEndian(uint num)
{
return (uint)(ConvertEndian((ushort)((num & 0xFFFF0000) >> 16))
| (ConvertEndian((ushort)(num & 0xFFFF)) << 16));
}
/// <summary>
/// Swap lower byte and higher byte.
/// </summary>
/// <param name="num">The number to be converted.</param>
/// <returns>The converted number.</returns>
public static ulong ConvertEndian(ulong num)
{
const ulong mask = 0xFFFFFFFF00000000;
return ConvertEndian((uint)((num & mask) >> 32))
| ((ulong)ConvertEndian((uint)(num & ~mask)) << 32);
}
/// <summary>
/// do right rotation for a buffer.
/// </summary>
/// <param name="buf">buffer to do right rotation</param>
/// <param name="rrc">right rotation count</param>
public static void RotateRight(byte[] buf, int rrc)
{
// Assume that the RRC value is 3 and the token before the rotation is
// {"header" | aa | bb | cc | dd | ee | ff | gg | hh}. The token after
// rotation would be {"header" | ff | gg | hh | aa | bb | cc | dd | ee },
// where {aa | bb | cc |...| hh} would be used to indicate the octet sequence.
rrc = rrc % buf.Length;
byte[] temp = ArrayUtility.ConcatenateArrays(ArrayUtility.SubArray(buf, buf.Length - rrc),
ArrayUtility.SubArray(buf, 0, buf.Length - rrc));
Array.Copy(temp, buf, buf.Length);
}
/// <summary>
/// Method to covert structure to byte[]
/// </summary>
/// <param name="structp">The structure prepare to covert</param>
/// <returns>the got byte array converted from structure</returns>
public static byte[] StructToBytes(object structp)
{
IntPtr ptr = IntPtr.Zero;
byte[] buffer = null;
try
{
int size = Marshal.SizeOf(structp.GetType());
ptr = Marshal.AllocHGlobal(size);
buffer = new byte[size];
Marshal.StructureToPtr(structp, ptr, false);
Marshal.Copy(ptr, buffer, 0, size);
}
finally
{
if (ptr != IntPtr.Zero)
{
Marshal.FreeHGlobal(ptr);
}
}
return buffer;
}
/// <summary>
/// Method to covert byte[] to structure.
/// </summary>
/// <param name="buffer">The buffer to be converted.</param>
/// <returns>The structure.</returns>
public static T ToStruct<T>(byte[] buffer)
{
T ret;
IntPtr intPtr = IntPtr.Zero;
try
{
intPtr = Marshal.AllocHGlobal(buffer.Length);
Marshal.Copy(buffer, 0, intPtr, buffer.Length);
ret = (T)Marshal.PtrToStructure(intPtr, typeof(T));
}
finally
{
Marshal.FreeHGlobal(intPtr);
}
return ret;
}
#endregion token [rfc4121]
#region token [rfc4757] and [rfc1964]
/// <summary>
/// Compute HMAC.
/// </summary>
/// <param name="key">The key of HMAC.</param>
/// <param name="buf">The data to be computed.</param>
/// <returns>The computed result.</returns>
public static byte[] HMAC(byte[] key, byte[] buf)
{
return CryptoUtility.ComputeMd5Hmac(key, buf);
}
/// <summary>
/// Compute HMAC.
/// </summary>
/// <param name="key">The key of HMAC.</param>
/// <param name="n">The data to be computed.</param>
/// <returns>The computed result.</returns>
public static byte[] HMAC(byte[] key, int n)
{
byte[] buf = BitConverter.GetBytes(n);
return HMAC(key, buf);
}
/// <summary>
/// Compute HMAC.
/// </summary>
/// <param name="key">The key of HMAC.</param>
/// <param name="str">The data to be computed.</param>
/// <returns>The computed result.</returns>
public static byte[] HMAC(byte[] key, string str)
{
byte[] buf = System.Text.Encoding.ASCII.GetBytes(str);
return HMAC(key, buf);
}
/// <summary>
/// Compute HMAC.
/// </summary>
/// <param name="key">The key of HMAC.</param>
/// <param name="str">The data to be computed.</param>
/// <param name="n">The data to be computed.</param>
/// <returns>The computed result.</returns>
public static byte[] HMAC(byte[] key, string str, int n)
{
byte[] buf = System.Text.Encoding.ASCII.GetBytes(str);
return HMAC(key, ArrayUtility.ConcatenateArrays(buf, BitConverter.GetBytes(n)));
}
/// <summary>
/// Compute RC4.
/// </summary>
/// <param name="key">The key of RC4.</param>
/// <param name="data">The data to be computed.</param>
/// <returns>The computed result.</returns>
public static byte[] RC4(byte[] key, byte[] data)
{
RC4CryptoServiceProvider rc4Enc = new RC4CryptoServiceProvider();
byte[] result = new byte[data.Length];
ICryptoTransform rc4Encrypt = rc4Enc.CreateEncryptor(key, null);
rc4Encrypt.TransformBlock(data, 0, data.Length, result, 0);
return result;
}
/// <summary>
/// Compute RC4HMAC.
/// </summary>
/// <param name="key">The key to do RC4HMAC.</param>
/// <param name="macContent">The content to do HMAC.</param>
/// <param name="data">The data to be computed.</param>
/// <param name="isExport">True for EncryptionType.RC4_HMAC_EXP, false for EncryptionType.RC4_HMAC.</param>
/// <returns>The computed result.</returns>
public static byte[] RC4HMAC(byte[] key, byte[] macContent, byte[] data, bool isExport)
{
byte[] Kseq = null;
if (isExport) // EncryptionType.RC4_HMAC_EXP
{
// Kseq = HMAC(Kss, "fortybits", (int32)0);
Kseq = KerberosUtility.HMAC(key, KerberosConstValue.FORTY_BITS, 0);
// memset(Kseq+7, 0xab, 9)
for (int i = 0; i < 9; ++i)
{
Kseq[i + 7] = 0xab;
}
}
else // EncryptionType.RC4_HMAC
{
Kseq = KerberosUtility.HMAC(key, 0);
}
Kseq = HMAC(Kseq, macContent);
return KerberosUtility.RC4(Kseq, data);
}
/// <summary>
/// Do MD2.5 described in [RFC 1964].
/// </summary>
/// <param name="key">The key of DES.</param>
/// <param name="data">The data to be computed.</param>
/// <returns>The computed result.</returns>
public static byte[] MD2_5(byte[] key, byte[] data)
{
// The checksum is formed by first DES-CBC encrypting a
// 16-byte zero-block, using a zero IV and a key formed by reversing the
// bytes of the context key (i.e., if the original key is the 8-byte
// sequence {aa, bb, cc, dd, ee, ff, gg, hh}, the checksum key will be
// {hh, gg, ff, ee, dd, cc, bb, aa}). The resulting 16-byte value is
// logically pre-pended to the "to-be-signed data". A standard MD5
// checksum is calculated over the combined data, and the first 8 bytes
// of the result are stored in the SGN_CKSUM field.
byte[] reversedKey = new byte[key.Length];
Array.Copy(key, reversedKey, reversedKey.Length);
Array.Reverse(reversedKey);
byte[] preData = DesCbcEncrypt(reversedKey, new byte[KerberosConstValue.DES_BLOCK_SIZE], new byte[16]);
byte[] result = ArrayUtility.ConcatenateArrays(preData, data);
MD5CryptoServiceProvider md5CryptoServiceProvider = new MD5CryptoServiceProvider();
byte[] md5 = md5CryptoServiceProvider.ComputeHash(result);
return md5;
}
/// <summary>
/// Do DES-CBC MAC.
/// </summary>
/// <param name="key">The key of DES.</param>
/// <param name="iv">The IV of DES.</param>
/// <param name="data">The data to be computed.</param>
/// <returns>The computed result.</returns>
public static byte[] DesCbcMac(byte[] key, byte[] iv, byte[] data)
{
DESCryptoServiceProvider desEncrypt = new DESCryptoServiceProvider();
desEncrypt.IV = iv;
desEncrypt.Key = key;
desEncrypt.Mode = CipherMode.CBC;
desEncrypt.Padding = PaddingMode.Zeros;
byte[] result = desEncrypt.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
byte[] lastBlock = ArrayUtility.SubArray(result, result.Length - KerberosConstValue.DES_BLOCK_SIZE);
return lastBlock;
}
/// <summary>
/// Encrypt DES in CBC mode.
/// </summary>
/// <param name="key">The key of DES.</param>
/// <param name="iv">The IV of DES.</param>
/// <param name="data">The data to be computed.</param>
/// <returns>The computed result.</returns>
public static byte[] DesCbcEncrypt(byte[] key, byte[] iv, byte[] data)
{
DESCryptoServiceProvider desEncrypt = new DESCryptoServiceProvider();
desEncrypt.IV = iv;
desEncrypt.Key = key;
desEncrypt.Mode = CipherMode.CBC;
desEncrypt.Padding = PaddingMode.None;
byte[] result = desEncrypt.CreateEncryptor().TransformFinalBlock(data, 0, data.Length);
return result;
}
/// <summary>
/// Decrypt DES in CBC mode.
/// </summary>
/// <param name="key">The key of DES.</param>
/// <param name="iv">The IV of DES.</param>
/// <param name="data">The data to be computed.</param>
/// <returns>The computed result.</returns>
public static byte[] DesCbcDecrypt(byte[] key, byte[] iv, byte[] data)
{
DESCryptoServiceProvider desDecrypt = new DESCryptoServiceProvider();
desDecrypt.IV = iv;
desDecrypt.Key = key;
desDecrypt.Mode = CipherMode.CBC;
desDecrypt.Padding = PaddingMode.None;
byte[] result = desDecrypt.CreateDecryptor().TransformFinalBlock(data, 0, data.Length);
return result;
}
#endregion token [rfc4757] and [rfc1964]
#region Packet api
/// <summary>
/// Generate client account's salt.
/// </summary>
/// <param name="domain">The realm part of the client's principal identifier.
/// This argument cannot be null.</param>
/// <param name="cName">The account to logon the remote machine. Either user account or computer account
/// This argument cannot be null.</param>
/// <param name="accountType">The type of the logon account. User or Computer</param>
/// <returns>Client account's salt</returns>
/// <exception cref="System.ArgumentNullException">Thrown when the input parameter is null.</exception>
/// <exception cref="System.NotSupportedException">Thrown when the account type is neither user nor computer.
/// </exception>
public static string GenerateSalt(string domain, string cName, KerberosAccountType accountType)
{
if (domain == null)
{
throw new ArgumentNullException("domain");
}
if (cName == null)
{
throw new ArgumentNullException("cName");
}
string salt;
if (accountType == KerberosAccountType.User)
{
salt = domain.ToUpper() + cName;
}
else if (accountType == KerberosAccountType.Device)
{
string computerName = cName;
if (cName.EndsWith("$"))
{
computerName = cName.Substring(0, cName.Length - 1);
}
salt = domain.ToUpper() + "host" + computerName.ToLower() + "." + domain.ToLower();
}
else
{
throw new NotSupportedException("Kile only support user or computer account.");
}
return salt;
}
#endregion
#region Generate Key
/// <summary>
/// Make fast armor key
/// </summary>
/// <param name="type">Encryption type</param>
/// <param name="subkey">Subkey, generated by client</param>
/// <param name="sessionKey">Session key, generated by kdc</param>
/// <returns></returns>
public static byte[] MakeArmorKey(EncryptionType type, byte[] subkey, byte[] sessionKey)
{
return KeyGenerator.KrbFxCf2(type, subkey, sessionKey, "subkeyarmor", "ticketarmor");
}
public static EncryptionKey KrbFxCf2(EncryptionKey protocolKey1, EncryptionKey protocolKey2, string pepper1, string pepper2)
{
return new EncryptionKey(new KerbInt32(protocolKey1.keytype.Value),
new Asn1OctetString(KeyGenerator.KrbFxCf2(
(EncryptionType)protocolKey1.keytype.Value,
protocolKey1.keyvalue.ByteArrayValue,
protocolKey2.keyvalue.ByteArrayValue,
pepper1,
pepper2)));
}
/// <summary>
/// Generate a new key, the key type and key length are based on the input key
/// </summary>
/// <param name="baseKey">Base key for generation</param>
/// <returns></returns>
public static EncryptionKey GenerateKey(EncryptionKey baseKey)
{
if (baseKey == null || baseKey.keytype == null
|| baseKey.keyvalue == null || baseKey.keyvalue.Value == null)
{
return null;
}
byte[] keyBuffer = KerberosUtility.GenerateRandomBytes((uint)baseKey.keyvalue.ByteArrayValue.Length);
EncryptionKey newKey = new EncryptionKey(new KerbInt32(baseKey.keytype.Value), new Asn1OctetString(keyBuffer));
return newKey;
}
public static EncryptionKey MakeKey(EncryptionType type, string password, string salt)
{
EncryptionKey key = new EncryptionKey(new KerbInt32((long)type), new Asn1OctetString(KeyGenerator.MakeKey(type, password, salt)));
return key;
}
#endregion
#region Flags [RFC4120]
/// <summary>
/// Convert byte array Kerberos Flags to Integer
/// </summary>
/// <param name="flags">Kerberos Flags</param>
/// <returns>Integer</returns>
public static int ConvertFlags2Int(byte[] flags)
{
if (flags == null || flags.Length == 0)
return 0;
else
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < flags.Length; i++)
{
sb.AppendFormat("{0:x2}", flags[i]);
}
return int.Parse(sb.ToString(), System.Globalization.NumberStyles.HexNumber);
}
}
/// <summary>
/// Compare two checksums. Return true if the same, otherwise return false.
/// If one of the two checksum is null, return false.
/// </summary>
/// <param name="chksum1">A checksum.</param>
/// <param name="chksum2">Another checksum.</param>
/// <returns></returns>
public static bool CompareChecksum(Checksum chksum1, Checksum chksum2)
{
if (chksum1 == null || chksum2 == null) return false;
if (chksum1.cksumtype.Value != chksum2.cksumtype.Value) return false;
if (chksum1.checksum.Value.Length != chksum2.checksum.Value.Length) return false;
for (int i = 0; i < chksum1.checksum.Value.Length; i++)
{
if (chksum1.checksum.Value[i] != chksum2.checksum.Value[i]) return false;
}
return true;
}
#endregion
#region Spng
public static byte[] DecodeNegotiationToken(byte[] token)
{
NegotiationToken decoder = new NegotiationToken();
decoder.BerDecode(new Asn1DecodingBuffer(token));
Asn1Object type = decoder.GetData();
switch (decoder.SelectedChoice)
{
case NegotiationToken.negTokenInit:
return ((NegTokenInit)type).mechToken.ByteArrayValue;
case NegotiationToken.negTokenResp:
return ((NegTokenResp)type).responseToken.ByteArrayValue;
case NegotiationToken.negTokenInit2:
return ((NegTokenInit2)type).mechToken.ByteArrayValue;
default:
return null;
}
}
public static byte[] EncodeInitialNegToken(byte[] token,
KerberosConstValue.OidPkt oidPkt)
{
int[] oidInt;
if (oidPkt == KerberosConstValue.OidPkt.KerberosToken)
oidInt = KerberosConstValue.GetKerberosOidInt();
else if (oidPkt == KerberosConstValue.OidPkt.MSKerberosToken)
oidInt = KerberosConstValue.GetMsKerberosOidInt();
else
{
throw new NotSupportedException("oid not support");
}
MechTypeList mechTypeList = new MechTypeList(
new MechType[]
{
new MechType(oidInt)
}
);
Asn1OctetString octetString = new Asn1OctetString(token);
NegTokenInit init = new NegTokenInit(mechTypeList, null, new Asn1OctetString(octetString.ByteArrayValue), new Asn1OctetString((byte[])null));
NegotiationToken negToken = new NegotiationToken(NegotiationToken.negTokenInit, init);
MechType spnegoMech = new MechType(KerberosConstValue.GetSpngOidInt());
InitialNegToken initToken = new InitialNegToken(spnegoMech, negToken);
Asn1BerEncodingBuffer buffer = new Asn1BerEncodingBuffer();
initToken.BerEncode(buffer);
return buffer.Data;
}
#endregion
#region Message Dumping
/// <summary>
/// Specify to what level should the message be dumped.
/// </summary>
public enum DumpLevel
{
/// <summary>
/// The message is a whole message on the wire.
/// </summary>
WholeMessage = 0,
/// <summary>
/// The message is a part of a whole message.
/// </summary>
PartialMessage = 1
}
/// <summary>
/// Handler of the Dump Message event
/// </summary>
/// <param name="messageName">Name of the message</param>
/// <param name="messageDescription">Description of the message</param>
/// <param name="dumpLevel">Dump Level</param>
/// <param name="payload">A byte array representing
/// the real data of the message</param>
public delegate void DumpMessageEventHandler(string messageName,
string messageDescription,
DumpLevel dumpLevel,
byte[] payload);
/// <summary>
/// Occur when messages are ready for dumping
/// </summary>
public static event DumpMessageEventHandler DumpMessage;
/// <summary>
/// Dump messages using the existing handler.
/// If no handler exists, no action would be taken.
/// </summary>
/// <param name="messageName">Name of the message</param>
/// <param name="messageDescription">Description of the message</param>
/// <param name="dumpLevel">Dump Level</param>
/// <param name="payload">A byte array representing
/// the real data of the message</param>
public static void OnDumpMessage(string messageName,
string messageDescription,
DumpLevel dumpLevel,
byte[] payload)
{
if (DumpMessage != null)
{
DumpMessage(messageName, messageDescription,
dumpLevel, payload);
}
}
#endregion
}
}
| |
/* Copyright (c) Citrix Systems, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms,
* with or without modification, are permitted provided
* that the following conditions are met:
*
* * Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
// ============================================================================
// Description: Utilitiy functions built on top of libxen for use in all
// providers.
// ============================================================================
// ------------------------------------------------------------------------------
// <auto-generated>
// Generated by Xsd2Code. Version 2.1.3177.19956
// <NameSpace>OvfDefinitions</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>False</EnableSummaryComment>
// <auto-generated>
// ------------------------------------------------------------------------------
namespace XenOvf.Definitions
{
using System;
using System.Diagnostics;
using System.Xml.Serialization;
using System.Collections;
using System.Xml.Schema;
using System.ComponentModel;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "1.0.3177.19956")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.dmtf.org/ovf/environment/1")]
[System.Xml.Serialization.XmlRootAttribute("Environment", Namespace="http://tempuri.org/OVFSchema.xsd", IsNullable=false)]
public partial class Environment_Type {
[XmlAttribute(AttributeName = "xml:lang")]
public string lang;
private Section_Type1[] itemsField;
private System.Xml.XmlElement[] anyField;
private Entity_Type[] entityField;
private string idField;
private System.Xml.XmlAttribute[] anyAttrField;
public Environment_Type() {
this.idField = "";
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("PlatformSection", typeof(PlatformSection_Type))]
[System.Xml.Serialization.XmlElementAttribute("PropertySection", typeof(PropertySection_Type))]
[System.Xml.Serialization.XmlElementAttribute("Section", typeof(Section_Type1))]
public Section_Type1[] Items
{
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Entity")]
public Entity_Type[] Entity {
get {
return this.entityField;
}
set {
this.entityField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any
{
get
{
return this.anyField;
}
set
{
this.anyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified)]
[System.ComponentModel.DefaultValueAttribute("")]
public string id {
get {
return this.idField;
}
set {
this.idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAnyAttributeAttribute()]
public System.Xml.XmlAttribute[] AnyAttr {
get {
return this.anyAttrField;
}
set {
this.anyAttrField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "1.0.3177.19956")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.dmtf.org/ovf/environment/1")]
[System.Xml.Serialization.XmlRootAttribute("PlatformSection", Namespace = "http://schemas.dmtf.org/ovf/environment/1", IsNullable = false)]
public partial class PlatformSection_Type : Section_Type1 {
private cimString kindField;
private cimString versionField;
private cimString vendorField;
private cimString localeField;
private int timezoneField;
private bool timezoneFieldSpecified;
private System.Xml.XmlElement[] anyField;
/// <remarks/>
public cimString Kind {
get {
return this.kindField;
}
set {
this.kindField = value;
}
}
/// <remarks/>
public cimString Version {
get {
return this.versionField;
}
set {
this.versionField = value;
}
}
/// <remarks/>
public cimString Vendor {
get {
return this.vendorField;
}
set {
this.vendorField = value;
}
}
/// <remarks/>
public cimString Locale {
get {
return this.localeField;
}
set {
this.localeField = value;
}
}
/// <remarks/>
public int Timezone {
get {
return this.timezoneField;
}
set {
this.timezoneField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIgnoreAttribute()]
public bool TimezoneSpecified {
get {
return this.timezoneFieldSpecified;
}
set {
this.timezoneFieldSpecified = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any
{
get
{
return this.anyField;
}
set
{
this.anyField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "1.0.3177.19956")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.dmtf.org/ovf/environment/1")]
public partial class Entity_Type {
private Section_Type1[] itemsField;
private System.Xml.XmlElement[] anyField;
private string idField;
private System.Xml.XmlAttribute[] anyAttrField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("PlatformSection", typeof(PlatformSection_Type))]
[System.Xml.Serialization.XmlElementAttribute("PropertySection", typeof(PropertySection_Type))]
[System.Xml.Serialization.XmlElementAttribute("Section", typeof(Section_Type1))]
public Section_Type1[] Items
{
get {
return this.itemsField;
}
set {
this.itemsField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any
{
get
{
return this.anyField;
}
set
{
this.anyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified)]
public string id {
get {
return this.idField;
}
set {
this.idField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAnyAttributeAttribute()]
public System.Xml.XmlAttribute[] AnyAttr {
get {
return this.anyAttrField;
}
set {
this.anyAttrField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "1.0.3177.19956")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://schemas.dmtf.org/ovf/environment/1")]
[System.Xml.Serialization.XmlRootAttribute("PropertySection", Namespace = "http://schemas.dmtf.org/ovf/environment/1", IsNullable = false)]
public partial class PropertySection_Type : Section_Type1
{
private PropertySection_TypeProperty[] propertyField;
private System.Xml.XmlElement[] anyField;
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("Property")]
public PropertySection_TypeProperty[] Property {
get {
return this.propertyField;
}
set {
this.propertyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAnyElementAttribute()]
public System.Xml.XmlElement[] Any
{
get
{
return this.anyField;
}
set
{
this.anyField = value;
}
}
}
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "1.0.3177.19956")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://schemas.dmtf.org/ovf/environment/1")]
public partial class PropertySection_TypeProperty {
private string keyField;
private string valueField;
private System.Xml.XmlAttribute[] anyAttrField;
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified)]
public string key {
get {
return this.keyField;
}
set {
this.keyField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAttributeAttribute(Form=System.Xml.Schema.XmlSchemaForm.Qualified)]
public string value {
get {
return this.valueField;
}
set {
this.valueField = value;
}
}
/// <remarks/>
[System.Xml.Serialization.XmlAnyAttributeAttribute()]
public System.Xml.XmlAttribute[] AnyAttr {
get {
return this.anyAttrField;
}
set {
this.anyAttrField = value;
}
}
}
/// <remarks/>
[System.Xml.Serialization.XmlIncludeAttribute(typeof(PlatformSection_Type))]
[System.Xml.Serialization.XmlIncludeAttribute(typeof(PropertySection_Type))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "1.0.3177.19956")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.Xml.Serialization.XmlTypeAttribute(TypeName="Section_Type", Namespace="http://schemas.dmtf.org/ovf/environment/1")]
public abstract partial class Section_Type1 {
private System.Xml.XmlAttribute[] anyAttrField;
/// <remarks/>
[System.Xml.Serialization.XmlAnyAttributeAttribute()]
public System.Xml.XmlAttribute[] AnyAttr {
get {
return this.anyAttrField;
}
set {
this.anyAttrField = value;
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Reflection;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
#else
using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
#endif
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
/// <summary>
/// TraceLogging: Type handler for empty or unsupported types.
/// </summary>
internal sealed class NullTypeInfo : TraceLoggingTypeInfo
{
public NullTypeInfo() : base(typeof(EmptyStruct)) { }
public override void WriteMetadata(
TraceLoggingMetadataCollector collector,
string name,
EventFieldFormat format)
{
collector.AddGroup(name);
}
public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
{
return;
}
public override object GetData(object value)
{
return null;
}
}
/// <summary>
/// Type handler for simple scalar types.
/// </summary>
sealed class ScalarTypeInfo : TraceLoggingTypeInfo
{
Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc;
TraceLoggingDataType nativeFormat;
private ScalarTypeInfo(
Type type,
Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc,
TraceLoggingDataType nativeFormat)
: base(type)
{
this.formatFunc = formatFunc;
this.nativeFormat = nativeFormat;
}
public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format)
{
collector.AddScalar(name, formatFunc(format, nativeFormat));
}
public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
{
collector.AddScalar(value);
}
public static TraceLoggingTypeInfo Boolean() { return new ScalarTypeInfo(typeof(Boolean), Statics.Format8, TraceLoggingDataType.Boolean8); }
public static TraceLoggingTypeInfo Byte() { return new ScalarTypeInfo(typeof(Byte), Statics.Format8, TraceLoggingDataType.UInt8); }
public static TraceLoggingTypeInfo SByte() { return new ScalarTypeInfo(typeof(SByte), Statics.Format8, TraceLoggingDataType.Int8); }
public static TraceLoggingTypeInfo Char() { return new ScalarTypeInfo(typeof(Char), Statics.Format16, TraceLoggingDataType.Char16); }
public static TraceLoggingTypeInfo Int16() { return new ScalarTypeInfo(typeof(Int16), Statics.Format16, TraceLoggingDataType.Int16); }
public static TraceLoggingTypeInfo UInt16() { return new ScalarTypeInfo(typeof(UInt16), Statics.Format16, TraceLoggingDataType.UInt16); }
public static TraceLoggingTypeInfo Int32() { return new ScalarTypeInfo(typeof(Int32), Statics.Format32, TraceLoggingDataType.Int32); }
public static TraceLoggingTypeInfo UInt32() { return new ScalarTypeInfo(typeof(UInt32), Statics.Format32, TraceLoggingDataType.UInt32); }
public static TraceLoggingTypeInfo Int64() { return new ScalarTypeInfo(typeof(Int64), Statics.Format64, TraceLoggingDataType.Int64); }
public static TraceLoggingTypeInfo UInt64() { return new ScalarTypeInfo(typeof(UInt64), Statics.Format64, TraceLoggingDataType.UInt64); }
public static TraceLoggingTypeInfo IntPtr() { return new ScalarTypeInfo(typeof(IntPtr), Statics.FormatPtr, Statics.IntPtrType); }
public static TraceLoggingTypeInfo UIntPtr() { return new ScalarTypeInfo(typeof(UIntPtr), Statics.FormatPtr, Statics.UIntPtrType); }
public static TraceLoggingTypeInfo Single() { return new ScalarTypeInfo(typeof(Single), Statics.Format32, TraceLoggingDataType.Float); }
public static TraceLoggingTypeInfo Double() { return new ScalarTypeInfo(typeof(Double), Statics.Format64, TraceLoggingDataType.Double); }
public static TraceLoggingTypeInfo Guid() { return new ScalarTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid); }
}
/// <summary>
/// Type handler for arrays of scalars
/// </summary>
internal sealed class ScalarArrayTypeInfo : TraceLoggingTypeInfo
{
Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc;
TraceLoggingDataType nativeFormat;
int elementSize;
private ScalarArrayTypeInfo(
Type type,
Func<EventFieldFormat, TraceLoggingDataType, TraceLoggingDataType> formatFunc,
TraceLoggingDataType nativeFormat,
int elementSize)
: base(type)
{
this.formatFunc = formatFunc;
this.nativeFormat = nativeFormat;
this.elementSize = elementSize;
}
public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format)
{
collector.AddArray(name, formatFunc(format, nativeFormat));
}
public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
{
collector.AddArray(value, elementSize);
}
public static TraceLoggingTypeInfo Boolean() { return new ScalarArrayTypeInfo(typeof(Boolean[]), Statics.Format8, TraceLoggingDataType.Boolean8, sizeof(Boolean)); }
public static TraceLoggingTypeInfo Byte() { return new ScalarArrayTypeInfo(typeof(Byte[]), Statics.Format8, TraceLoggingDataType.UInt8, sizeof(Byte)); }
public static TraceLoggingTypeInfo SByte() { return new ScalarArrayTypeInfo(typeof(SByte[]), Statics.Format8, TraceLoggingDataType.Int8, sizeof(SByte)); }
public static TraceLoggingTypeInfo Char() { return new ScalarArrayTypeInfo(typeof(Char[]), Statics.Format16, TraceLoggingDataType.Char16, sizeof(Char)); }
public static TraceLoggingTypeInfo Int16() { return new ScalarArrayTypeInfo(typeof(Int16[]), Statics.Format16, TraceLoggingDataType.Int16, sizeof(Int16)); }
public static TraceLoggingTypeInfo UInt16() { return new ScalarArrayTypeInfo(typeof(UInt16[]), Statics.Format16, TraceLoggingDataType.UInt16, sizeof(UInt16)); }
public static TraceLoggingTypeInfo Int32() { return new ScalarArrayTypeInfo(typeof(Int32[]), Statics.Format32, TraceLoggingDataType.Int32, sizeof(Int32)); }
public static TraceLoggingTypeInfo UInt32() { return new ScalarArrayTypeInfo(typeof(UInt32[]), Statics.Format32, TraceLoggingDataType.UInt32, sizeof(UInt32)); }
public static TraceLoggingTypeInfo Int64() { return new ScalarArrayTypeInfo(typeof(Int64[]), Statics.Format64, TraceLoggingDataType.Int64, sizeof(Int64)); }
public static TraceLoggingTypeInfo UInt64() { return new ScalarArrayTypeInfo(typeof(UInt64[]), Statics.Format64, TraceLoggingDataType.UInt64, sizeof(UInt64)); }
public static TraceLoggingTypeInfo IntPtr() { return new ScalarArrayTypeInfo(typeof(IntPtr[]), Statics.FormatPtr, Statics.IntPtrType, System.IntPtr.Size); }
public static TraceLoggingTypeInfo UIntPtr() { return new ScalarArrayTypeInfo(typeof(UIntPtr[]), Statics.FormatPtr, Statics.UIntPtrType, System.IntPtr.Size); }
public static TraceLoggingTypeInfo Single() { return new ScalarArrayTypeInfo(typeof(Single[]), Statics.Format32, TraceLoggingDataType.Float, sizeof(Single)); }
public static TraceLoggingTypeInfo Double() { return new ScalarArrayTypeInfo(typeof(Double[]), Statics.Format64, TraceLoggingDataType.Double, sizeof(Double)); }
public unsafe static TraceLoggingTypeInfo Guid() { return new ScalarArrayTypeInfo(typeof(Guid), (f, t) => Statics.MakeDataType(TraceLoggingDataType.Guid, f), TraceLoggingDataType.Guid, sizeof(Guid)); }
}
/// <summary>
/// TraceLogging: Type handler for String.
/// </summary>
internal sealed class StringTypeInfo : TraceLoggingTypeInfo
{
public StringTypeInfo() : base(typeof(string)) { }
public override void WriteMetadata(
TraceLoggingMetadataCollector collector,
string name,
EventFieldFormat format)
{
collector.AddBinary(name, Statics.MakeDataType(TraceLoggingDataType.CountedUtf16String, format));
}
public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
{
collector.AddBinary((string)value.ReferenceValue);
}
public override object GetData(object value)
{
if(value == null)
{
return "";
}
return value;
}
}
/// <summary>
/// TraceLogging: Type handler for DateTime.
/// </summary>
internal sealed class DateTimeTypeInfo : TraceLoggingTypeInfo
{
public DateTimeTypeInfo() : base(typeof(DateTime)) { }
public override void WriteMetadata(
TraceLoggingMetadataCollector collector,
string name,
EventFieldFormat format)
{
collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.FileTime, format));
}
public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
{
var ticks = value.ScalarValue.AsDateTime.Ticks;
collector.AddScalar(ticks < 504911232000000000 ? 0 : ticks - 504911232000000000);
}
}
/// <summary>
/// TraceLogging: Type handler for DateTimeOffset.
/// </summary>
internal sealed class DateTimeOffsetTypeInfo : TraceLoggingTypeInfo
{
public DateTimeOffsetTypeInfo() : base(typeof(DateTimeOffset)) { }
public override void WriteMetadata(TraceLoggingMetadataCollector collector, string name, EventFieldFormat format)
{
var group = collector.AddGroup(name);
group.AddScalar("Ticks", Statics.MakeDataType(TraceLoggingDataType.FileTime, format));
group.AddScalar("Offset", TraceLoggingDataType.Int64);
}
public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
{
var dateTimeOffset = value.ScalarValue.AsDateTimeOffset;
var ticks = dateTimeOffset.Ticks;
collector.AddScalar(ticks < 504911232000000000 ? 0 : ticks - 504911232000000000);
collector.AddScalar(dateTimeOffset.Offset.Ticks);
}
}
/// <summary>
/// TraceLogging: Type handler for TimeSpan.
/// </summary>
internal sealed class TimeSpanTypeInfo : TraceLoggingTypeInfo
{
public TimeSpanTypeInfo() : base(typeof(TimeSpan)) { }
public override void WriteMetadata(
TraceLoggingMetadataCollector collector,
string name,
EventFieldFormat format)
{
collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Int64, format));
}
public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
{
collector.AddScalar(value.ScalarValue.AsTimeSpan.Ticks);
}
}
/// <summary>
/// TraceLogging: Type handler for Decimal. (Note: not full-fidelity, exposed as Double.)
/// </summary>
internal sealed class DecimalTypeInfo : TraceLoggingTypeInfo
{
public DecimalTypeInfo() : base(typeof(Decimal)) { }
public override void WriteMetadata(
TraceLoggingMetadataCollector collector,
string name,
EventFieldFormat format)
{
collector.AddScalar(name, Statics.MakeDataType(TraceLoggingDataType.Double, format));
}
public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
{
collector.AddScalar((double)value.ScalarValue.AsDecimal);
}
}
/// <summary>
/// TraceLogging: Type handler for Nullable.
/// </summary>
internal sealed class NullableTypeInfo : TraceLoggingTypeInfo
{
private readonly TraceLoggingTypeInfo valueInfo;
private readonly Func<PropertyValue, PropertyValue> hasValueGetter;
private readonly Func<PropertyValue, PropertyValue> valueGetter;
public NullableTypeInfo(Type type, List<Type> recursionCheck)
: base(type)
{
var typeArgs = type.GenericTypeArguments;
Contract.Assert(typeArgs.Length == 1);
this.valueInfo = TraceLoggingTypeInfo.GetInstance(typeArgs[0], recursionCheck);
this.hasValueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("HasValue"));
this.valueGetter = PropertyValue.GetPropertyGetter(type.GetTypeInfo().GetDeclaredProperty("Value"));
}
public override void WriteMetadata(
TraceLoggingMetadataCollector collector,
string name,
EventFieldFormat format)
{
var group = collector.AddGroup(name);
group.AddScalar("HasValue", TraceLoggingDataType.Boolean8);
this.valueInfo.WriteMetadata(group, "Value", format);
}
public override void WriteData(TraceLoggingDataCollector collector, PropertyValue value)
{
var hasValue = hasValueGetter(value);
collector.AddScalar(hasValue);
var val = hasValue.ScalarValue.AsBoolean ? valueGetter(value) : valueInfo.PropertyValueFactory(Activator.CreateInstance(valueInfo.DataType));
this.valueInfo.WriteData(collector, val);
}
}
}
| |
using System;
using System.Data;
using System.Data.Odbc;
using ByteFX.Data.MySqlClient;
using ByteFX.Data;
using System.Collections;
using System.Threading;
using JCSLA;
using System.Timers;
namespace QED.Business{
public class Times : BusinessCollectionBase {
#region Instance Data
#endregion
const string _table = "times";
MySqlDBLayer _dbLayer;
BusinessBase _parent;
#region Collection Members
public Time Add(Time obj) {
obj.BusinessCollection = this;
List.Add(obj); return obj;
}
public bool Contains(Time obj) {
foreach(Time child in List) {
if (obj.Equals(child)){
return true;
}
}
return false;
}
public Time this[int id] {
get{
return (Time) List[id];
}
}
public Time item(int id) {
foreach(Time obj in List) {
if (obj.Id == id)
return obj;
}
return null;
}
public Time item(Rollout rollout) {
foreach(Time obj in List) {
if (obj.ForRollout){
if (rollout.Id == obj.Rollout.Id){
return obj;
}
}
}
return null;
}
public Time item(Effort eff) {
foreach(Time obj in List) {
if (obj.ForEffort){
if (eff.Id == obj.Effort.Id){
return obj;
}
}
}
return null;
}
#endregion
#region DB Access and ctors
public Times() {
}
public Times(Effort parent) {
Time obj;
_parent = parent;
using(MySqlConnection conn = Connections.Inst.item("QED_DB").MySqlConnection){
using(MySqlDataReader dr = MySqlDBLayer.LoadWhereColumnIs(conn, _table, "effId", parent.Id)){
while(dr.Read()) {
obj = new Time(dr);
obj.BusinessCollection = this;
List.Add(obj);
}
}
}
}
public Times(Rollout parent) {
Time obj;
_parent = parent;
using(MySqlConnection conn = Connections.Inst.item("QED_DB").MySqlConnection){
using(MySqlDataReader dr = MySqlDBLayer.LoadWhereColumnIs(conn, _table, "rollId", parent.Id)){
while(dr.Read()) {
obj = new Time(dr);
obj.BusinessCollection = this;
List.Add(obj);
}
}
}
}
public BusinessBase Parent{
get{
return _parent;
}
}
public void Update() {
foreach (Time obj in List) {
obj.Update();
}
}
#endregion
#region Business Members
public int Total{
get{
int total = 0;
foreach(Time time in this)
total += time.Minutes;
return total;
}
}
#endregion
#region System.Object overrides
public override string ToString(){
return this.ToString();
}
#endregion
}
public class Time : BusinessBase {
#region Instance Data
string _table = "times";
int _id;
MySqlDBLayer _dbLayer;
BusinessCollectionBase _businessCollection;
Effort _effort; int _effId = -1;
Rollout _roll; int _rollId = -1;
string _text = "";
string _user = "";
int _minutes = 0;
System.Timers.Timer _timer;
DateTime _date = DateTime.MinValue;
DateTime _timerStarted = DateTime.MinValue;
public delegate void OnMinuteChangeHandler(Time time, EventArgs e);
public OnMinuteChangeHandler OnMinuteChange;
#endregion
#region DB Access / ctors
public override string Table {
get {
return _table;
}
}
public override object Conn {
get {
return Connections.Inst.item("QED_DB").MySqlConnection;
}
}
private void Setup() {
if (_dbLayer == null) {
_dbLayer = new MySqlDBLayer(this);
}
}
public override void SetId(int id) {
/* This function is public for technical reasons. It is intended to be used only by the db
* layer*/
_id = id;
}
public override BusinessCollectionBase BusinessCollection {
get{
return _businessCollection;
}
set {
_businessCollection = value;
}
}
public Time() {
Setup();
base.MarkNew();
}
public Time(Rollout roll) {
Setup();
this.Rollout = roll;
base.MarkNew();
}
public Time(Effort eff) {
this.Effort = eff;
Setup();
base.MarkNew();
}
public Time(int id) {
Setup();
this.Load(id);
}
public Time(MySqlDataReader dr) {
this.Load(dr);
}
public void Load(int id) {
SetId(id);
using(MySqlConnection conn = (MySqlConnection) this.Conn)
conn.Open();
MySqlCommand cmd = new MySqlCommand("SELECT * FROM " + this.Table + " WHERE ID = @ID", (MySqlConnection) this.Conn);
cmd.Parameters.Add("@Id", this.Id);
using(MySqlDataReader dr = cmd.ExecuteReader()){
if (dr.HasRows) {
dr.Read();
this.Load(dr);
}else{
throw new Exception("Time " + id + " doesn't exist.");
}
}
}
public void Load(MySqlDataReader dr) {
Setup();
SetId(Convert.ToInt32(dr["Id"]));
this._effId = Convert.ToInt32(dr["effId"]);
this._rollId = Convert.ToInt32(dr["rollId"]);
this._minutes = Convert.ToInt32(dr["minutes"]);
this._date = Convert.ToDateTime(dr["date"]);
this._user = Convert.ToString(dr["user"]);
this._text = Convert.ToString(dr["text"]);
MarkOld();
}
public override void Update(){
_dbLayer.Update();
}
public override Hashtable ParamHash {
get {
Hashtable paramHash = new Hashtable();
paramHash.Add("@Id", this.Id);
paramHash.Add("@effId", this._effId);
paramHash.Add("@rollId", this._rollId);
paramHash.Add("@minutes", this.Minutes);
paramHash.Add("@date", this.Date);
paramHash.Add("@user", this.User);
paramHash.Add("@text", this.Text);
return paramHash;
}
}
#endregion
#region Business Properties
public override int Id{
get{
return _id;
}
}
public Effort Effort{
get{
return _effort;
}
set{
BusinessBase bb = (BusinessBase)_effort;
SetValue(ref bb, (BusinessBase)value, ref _effId);
_effort = (Effort)bb;
}
}
public bool ForEffort{
get{
return (_effort != null && _roll == null);
}
}
public Rollout Rollout{
get{
return _roll;
}
set{
BusinessBase bb = (BusinessBase)_roll;
SetValue(ref bb, (BusinessBase)value, ref _rollId);
_roll = (Rollout)bb;
}
}
public bool ForRollout{
get{
return (_effort == null && _roll != null);
}
}
public string Text{
get{
return _text;
}
set{
SetValue(ref _text, value);
}
}
public int Minutes{
get{
return _minutes;
}
set{
SetValue(ref _minutes, value);
}
}
public DateTime Date{
get{
return _date;
}
set{
SetValue(ref _date, value);
}
}
public string User{
get{
return _user;
}
set{
SetValue(ref _user, value);
}
}
#endregion
#region Timer Members
public void StartTimer(){
if (_timer == null){
_timer = new System.Timers.Timer(1000);
_timer.Elapsed += new System.Timers.ElapsedEventHandler(OnTimedEvent);
}
_timer.Enabled = true;
if (_timerStarted == DateTime.MinValue){
_timerStarted = DateTime.Now;
}
}
public void RestartTimer(){
_timer.Enabled = true;
this.Minutes = 0;
_timerStarted = DateTime.Now;
}
public void StopTimer(){
if (_timer != null){
_timer.Enabled = false;
}else{
throw new Exception ("Can't stop timer because timer hasn't been instantiated");
}
}
public void OnTimedEvent(object source, ElapsedEventArgs e){
TimeSpan ts = e.SignalTime.Subtract(_timerStarted);
int minutes = int.Parse(ts.TotalMinutes.ToString().Split('.')[0]);
if (minutes != this.Minutes){
this.Minutes = minutes;
OnMinuteChange(this, new EventArgs());
}
}
public bool IsTimerRunning{
get{
return (_timer != null && _timer.Enabled);
}
}
#endregion
#region Validation Management
public override bool IsValid {
get {
return (this.BrokenRules.Count == 0);
}
}
public override BrokenRules BrokenRules {
get {
System.Security.Principal.IPrincipal p = Thread.CurrentPrincipal;
bool man = p.IsInRole("manager");
bool admin = p.IsInRole("admin");
BrokenRules br = new BrokenRules();
br.Assert("Only managers or admins can edit time entries for other users.", this.User != p.Identity.Name && (!man && !admin));
return br;
}
}
#endregion
#region System.Object overrides
public override string ToString(){
return base.ToString();
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.IO;
using OpenMetaverse;
namespace OpenSim.Framework
{
public class RegionSettings
{
private ConfigurationMember configMember;
public delegate void SaveDelegate(RegionSettings rs);
public event SaveDelegate OnSave;
/// <value>
/// These appear to be terrain textures that are shipped with the client.
/// </value>
public static readonly UUID DEFAULT_TERRAIN_TEXTURE_1 = new UUID("b8d3965a-ad78-bf43-699b-bff8eca6c975");
public static readonly UUID DEFAULT_TERRAIN_TEXTURE_2 = new UUID("abb783e6-3e93-26c0-248a-247666855da3");
public static readonly UUID DEFAULT_TERRAIN_TEXTURE_3 = new UUID("179cdabd-398a-9b6b-1391-4dc333ba321f");
public static readonly UUID DEFAULT_TERRAIN_TEXTURE_4 = new UUID("beb169c7-11ea-fff2-efe5-0f24dc881df2");
public RegionSettings()
{
if (configMember == null)
{
try
{
configMember = new ConfigurationMember(Path.Combine(Util.configDir(), "estate_settings.xml"), "ESTATE SETTINGS", LoadConfigurationOptions, HandleIncomingConfiguration, true);
configMember.performConfigurationRetrieve();
}
catch (Exception)
{
}
}
}
public void LoadConfigurationOptions()
{
configMember.addConfigurationOption("region_flags",
ConfigurationOption.ConfigurationTypes.TYPE_UINT32,
String.Empty, "336723974", true);
configMember.addConfigurationOption("max_agents",
ConfigurationOption.ConfigurationTypes.TYPE_INT32,
String.Empty, "40", true);
configMember.addConfigurationOption("object_bonus_factor",
ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE,
String.Empty, "1.0", true);
configMember.addConfigurationOption("sim_access",
ConfigurationOption.ConfigurationTypes.TYPE_INT32,
String.Empty, "21", true);
configMember.addConfigurationOption("terrain_base_0",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, DEFAULT_TERRAIN_TEXTURE_1.ToString(), true);
configMember.addConfigurationOption("terrain_base_1",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, DEFAULT_TERRAIN_TEXTURE_2.ToString(), true);
configMember.addConfigurationOption("terrain_base_2",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, DEFAULT_TERRAIN_TEXTURE_3.ToString(), true);
configMember.addConfigurationOption("terrain_base_3",
ConfigurationOption.ConfigurationTypes.TYPE_UUID,
String.Empty, DEFAULT_TERRAIN_TEXTURE_4.ToString(), true);
configMember.addConfigurationOption("terrain_start_height_0",
ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE,
String.Empty, "10.0", true);
configMember.addConfigurationOption("terrain_start_height_1",
ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE,
String.Empty, "10.0", true);
configMember.addConfigurationOption("terrain_start_height_2",
ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE,
String.Empty, "10.0", true);
configMember.addConfigurationOption("terrain_start_height_3",
ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE,
String.Empty, "10.0", true);
configMember.addConfigurationOption("terrain_height_range_0",
ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE,
String.Empty, "60.0", true);
configMember.addConfigurationOption("terrain_height_range_1",
ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE,
String.Empty, "60.0", true);
configMember.addConfigurationOption("terrain_height_range_2",
ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE,
String.Empty, "60.0", true);
configMember.addConfigurationOption("terrain_height_range_3",
ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE,
String.Empty, "60.0", true);
configMember.addConfigurationOption("region_water_height",
ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE,
String.Empty, "20.0", true);
configMember.addConfigurationOption("terrain_raise_limit",
ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE,
String.Empty, "100.0", true);
configMember.addConfigurationOption("terrain_lower_limit",
ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE,
String.Empty, "-100.0", true);
configMember.addConfigurationOption("sun_hour",
ConfigurationOption.ConfigurationTypes.TYPE_DOUBLE,
String.Empty, "0.0", true);
}
public bool HandleIncomingConfiguration(string key, object value)
{
switch (key)
{
case "region_flags":
RegionFlags flags = (RegionFlags)(uint)value;
m_BlockTerraform =
(flags & RegionFlags.BlockTerraform) != 0;
m_BlockFly =
(flags & RegionFlags.NoFly) != 0;
m_AllowDamage =
(flags & RegionFlags.AllowDamage) != 0;
m_RestrictPushing =
(flags & RegionFlags.RestrictPushObject) != 0;
m_AllowLandResell =
(flags & RegionFlags.BlockLandResell) == 0;
m_AllowLandJoinDivide =
(flags & RegionFlags.AllowParcelChanges) != 0;
m_BlockShowInSearch =
((uint)flags & (1 << 29)) != 0;
m_DisableScripts =
(flags & RegionFlags.SkipScripts) != 0;
m_DisableCollisions =
(flags & RegionFlags.SkipCollisions) != 0;
m_DisablePhysics =
(flags & RegionFlags.SkipPhysics) != 0;
m_FixedSun =
(flags & RegionFlags.SunFixed) != 0;
m_Sandbox =
(flags & RegionFlags.Sandbox) != 0;
break;
case "max_agents":
m_AgentLimit = (int)value;
break;
case "object_bonus_factor":
m_ObjectBonus = (double)value;
break;
case "sim_access":
int access = (int)value;
if (access <= 13)
m_Maturity = 0;
else
m_Maturity = 1;
break;
case "terrain_base_0":
m_TerrainTexture1 = (UUID)value;
break;
case "terrain_base_1":
m_TerrainTexture2 = (UUID)value;
break;
case "terrain_base_2":
m_TerrainTexture3 = (UUID)value;
break;
case "terrain_base_3":
m_TerrainTexture4 = (UUID)value;
break;
case "terrain_start_height_0":
m_Elevation1SW = (double)value;
break;
case "terrain_start_height_1":
m_Elevation1NW = (double)value;
break;
case "terrain_start_height_2":
m_Elevation1SE = (double)value;
break;
case "terrain_start_height_3":
m_Elevation1NE = (double)value;
break;
case "terrain_height_range_0":
m_Elevation2SW = (double)value;
break;
case "terrain_height_range_1":
m_Elevation2NW = (double)value;
break;
case "terrain_height_range_2":
m_Elevation2SE = (double)value;
break;
case "terrain_height_range_3":
m_Elevation2NE = (double)value;
break;
case "region_water_height":
m_WaterHeight = (double)value;
break;
case "terrain_raise_limit":
m_TerrainRaiseLimit = (double)value;
break;
case "terrain_lower_limit":
m_TerrainLowerLimit = (double)value;
break;
case "sun_hour":
m_SunPosition = (double)value;
break;
}
return true;
}
public void Save()
{
if (OnSave != null)
OnSave(this);
}
private UUID m_RegionUUID = UUID.Zero;
public UUID RegionUUID
{
get { return m_RegionUUID; }
set { m_RegionUUID = value; }
}
private bool m_BlockTerraform = false;
public bool BlockTerraform
{
get { return m_BlockTerraform; }
set { m_BlockTerraform = value; }
}
private bool m_BlockFly = false;
public bool BlockFly
{
get { return m_BlockFly; }
set { m_BlockFly = value; }
}
private bool m_AllowDamage = false;
public bool AllowDamage
{
get { return m_AllowDamage; }
set { m_AllowDamage = value; }
}
private bool m_RestrictPushing = false;
public bool RestrictPushing
{
get { return m_RestrictPushing; }
set { m_RestrictPushing = value; }
}
private bool m_AllowLandResell = true;
public bool AllowLandResell
{
get { return m_AllowLandResell; }
set { m_AllowLandResell = value; }
}
private bool m_AllowLandJoinDivide = true;
public bool AllowLandJoinDivide
{
get { return m_AllowLandJoinDivide; }
set { m_AllowLandJoinDivide = value; }
}
private bool m_BlockShowInSearch = false;
public bool BlockShowInSearch
{
get { return m_BlockShowInSearch; }
set { m_BlockShowInSearch = value; }
}
private int m_AgentLimit = 40;
public int AgentLimit
{
get { return m_AgentLimit; }
set { m_AgentLimit = value; }
}
private double m_ObjectBonus = 1.0;
public double ObjectBonus
{
get { return m_ObjectBonus; }
set { m_ObjectBonus = value; }
}
private int m_Maturity = 1;
public int Maturity
{
get { return m_Maturity; }
set { m_Maturity = value; }
}
private bool m_DisableScripts = false;
public bool DisableScripts
{
get { return m_DisableScripts; }
set { m_DisableScripts = value; }
}
private bool m_DisableCollisions = false;
public bool DisableCollisions
{
get { return m_DisableCollisions; }
set { m_DisableCollisions = value; }
}
private bool m_DisablePhysics = false;
public bool DisablePhysics
{
get { return m_DisablePhysics; }
set { m_DisablePhysics = value; }
}
private UUID m_TerrainTexture1 = UUID.Zero;
public UUID TerrainTexture1
{
get { return m_TerrainTexture1; }
set
{
if (value == UUID.Zero)
m_TerrainTexture1 = DEFAULT_TERRAIN_TEXTURE_1;
else
m_TerrainTexture1 = value;
}
}
private UUID m_TerrainTexture2 = UUID.Zero;
public UUID TerrainTexture2
{
get { return m_TerrainTexture2; }
set
{
if (value == UUID.Zero)
m_TerrainTexture2 = DEFAULT_TERRAIN_TEXTURE_2;
else
m_TerrainTexture2 = value;
}
}
private UUID m_TerrainTexture3 = UUID.Zero;
public UUID TerrainTexture3
{
get { return m_TerrainTexture3; }
set
{
if (value == UUID.Zero)
m_TerrainTexture3 = DEFAULT_TERRAIN_TEXTURE_3;
else
m_TerrainTexture3 = value;
}
}
private UUID m_TerrainTexture4 = UUID.Zero;
public UUID TerrainTexture4
{
get { return m_TerrainTexture4; }
set
{
if (value == UUID.Zero)
m_TerrainTexture4 = DEFAULT_TERRAIN_TEXTURE_4;
else
m_TerrainTexture4 = value;
}
}
private double m_Elevation1NW = 10;
public double Elevation1NW
{
get { return m_Elevation1NW; }
set { m_Elevation1NW = value; }
}
private double m_Elevation2NW = 60;
public double Elevation2NW
{
get { return m_Elevation2NW; }
set { m_Elevation2NW = value; }
}
private double m_Elevation1NE = 10;
public double Elevation1NE
{
get { return m_Elevation1NE; }
set { m_Elevation1NE = value; }
}
private double m_Elevation2NE = 60;
public double Elevation2NE
{
get { return m_Elevation2NE; }
set { m_Elevation2NE = value; }
}
private double m_Elevation1SE = 10;
public double Elevation1SE
{
get { return m_Elevation1SE; }
set { m_Elevation1SE = value; }
}
private double m_Elevation2SE = 60;
public double Elevation2SE
{
get { return m_Elevation2SE; }
set { m_Elevation2SE = value; }
}
private double m_Elevation1SW = 10;
public double Elevation1SW
{
get { return m_Elevation1SW; }
set { m_Elevation1SW = value; }
}
private double m_Elevation2SW = 60;
public double Elevation2SW
{
get { return m_Elevation2SW; }
set { m_Elevation2SW = value; }
}
private double m_WaterHeight = 20;
public double WaterHeight
{
get { return m_WaterHeight; }
set { m_WaterHeight = value; }
}
private double m_TerrainRaiseLimit = 100;
public double TerrainRaiseLimit
{
get { return m_TerrainRaiseLimit; }
set { m_TerrainRaiseLimit = value; }
}
private double m_TerrainLowerLimit = -100;
public double TerrainLowerLimit
{
get { return m_TerrainLowerLimit; }
set { m_TerrainLowerLimit = value; }
}
private bool m_UseEstateSun = true;
public bool UseEstateSun
{
get { return m_UseEstateSun; }
set { m_UseEstateSun = value; }
}
private bool m_Sandbox = false;
public bool Sandbox
{
get { return m_Sandbox; }
set { m_Sandbox = value; }
}
private Vector3 m_SunVector;
public Vector3 SunVector
{
get { return m_SunVector; }
set { m_SunVector = value; }
}
private UUID m_TerrainImageID;
public UUID TerrainImageID
{
get { return m_TerrainImageID; }
set { m_TerrainImageID = value; }
}
private bool m_FixedSun = false;
public bool FixedSun
{
get { return m_FixedSun; }
set { m_FixedSun = value; }
}
private double m_SunPosition = 0.0;
public double SunPosition
{
get { return m_SunPosition; }
set { m_SunPosition = value; }
}
private UUID m_Covenant = UUID.Zero;
public UUID Covenant
{
get { return m_Covenant; }
set { m_Covenant = value; }
}
private int m_LoadedCreationDateTime;
public int LoadedCreationDateTime
{
get { return m_LoadedCreationDateTime; }
set { m_LoadedCreationDateTime = value; }
}
public String LoadedCreationDate
{
get
{
TimeSpan ts = new TimeSpan(0, 0, LoadedCreationDateTime);
DateTime stamp = new DateTime(1970, 1, 1) + ts;
return stamp.ToLongDateString();
}
}
public String LoadedCreationTime
{
get
{
TimeSpan ts = new TimeSpan(0, 0, LoadedCreationDateTime);
DateTime stamp = new DateTime(1970, 1, 1) + ts;
return stamp.ToLongTimeString();
}
}
private String m_LoadedCreationID;
public String LoadedCreationID
{
get { return m_LoadedCreationID; }
set { m_LoadedCreationID = value; }
}
}
}
| |
/* Copyright (c) 2006 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#region Using directives
#define USE_TRACING
using System;
using System.Xml;
using System.Globalization;
using System.ComponentModel;
using System.Runtime.InteropServices;
#endregion
//////////////////////////////////////////////////////////////////////
// <summary>Contains AtomGenerator, an object to represent the
// atom:generator element</summary>
//////////////////////////////////////////////////////////////////////
namespace Google.GData.Client
{
#if WindowsCE || PocketPC
#else
//////////////////////////////////////////////////////////////////////
/// <summary>TypeConverter, so that AtomGenerator shows up in the property pages
/// </summary>
//////////////////////////////////////////////////////////////////////
[ComVisible(false)]
public class AtomGeneratorConverter : ExpandableObjectConverter
{
///<summary>Standard type converter method</summary>
public override bool CanConvertTo(ITypeDescriptorContext context, System.Type destinationType)
{
if (destinationType == typeof(AtomGenerator))
return true;
return base.CanConvertTo(context, destinationType);
}
///<summary>Standard type converter method</summary>
public override object ConvertTo(ITypeDescriptorContext context,CultureInfo culture, object value, System.Type destinationType)
{
AtomGenerator generator = value as AtomGenerator;
if (destinationType == typeof(System.String) && generator != null)
{
return generator.Text;
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>Represents the Generator element /feed/generator in Atom. In RSS, only the name property is used.
/// </summary>
//////////////////////////////////////////////////////////////////////
[TypeConverterAttribute(typeof(AtomGeneratorConverter)), DescriptionAttribute("Expand to see the feed generator object.")]
#endif
public class AtomGenerator : AtomBase
{
/// <summary>text part of the Generator element</summary>
private string text;
/// <summary>Uri attribute of the Generator element</summary>
private AtomUri uri;
/// <summary>version attribute of the Generator element</summary>
private string version;
//////////////////////////////////////////////////////////////////////
/// <summary>standard constructor, not used right now
/// atomGenerator = element atom:generator {
/// atomCommonAttributes,
/// attribute url { atomUri }?,
/// attribute version { text }?,
/// text
/// }
/// </summary>
//////////////////////////////////////////////////////////////////////
public AtomGenerator()
{
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>public AtomGenerator(string text)</summary>
/// <param name="text">the human readable representation of the generator</param>
//////////////////////////////////////////////////////////////////////
public AtomGenerator(string text)
{
this.Text = text;
}
/////////////////////////////////////////////////////////////////////////////
#region Persistence overloads
//////////////////////////////////////////////////////////////////////
/// <summary>Returns the constant representing this XML element.</summary>
//////////////////////////////////////////////////////////////////////
public override string XmlName
{
get { return AtomParserNameTable.XmlGeneratorElement; }
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>overridden to save attributes for this(XmlWriter writer)</summary>
/// <param name="writer">the xmlwriter to save into </param>
//////////////////////////////////////////////////////////////////////
protected override void SaveXmlAttributes(XmlWriter writer)
{
WriteEncodedAttributeString(writer, AtomParserNameTable.XmlUriElement, this.Uri);
WriteEncodedAttributeString(writer, AtomParserNameTable.XmlAttributeVersion, this.Version);
// call base later as base takes care of writing out extension elements that might close the attribute list
base.SaveXmlAttributes(writer);
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>saves the inner state of the element</summary>
/// <param name="writer">the xmlWriter to save into </param>
//////////////////////////////////////////////////////////////////////
protected override void SaveInnerXml(XmlWriter writer)
{
base.SaveInnerXml(writer);
WriteEncodedString(writer, this.text);
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>figures out if this object should be persisted</summary>
/// <returns> true, if it's worth saving</returns>
//////////////////////////////////////////////////////////////////////
public override bool ShouldBePersisted()
{
if (base.ShouldBePersisted() == false)
{
if (this.uri != null && Utilities.IsPersistable(this.uri.ToString()))
{
return true;
}
if (Utilities.IsPersistable(this.version) || Utilities.IsPersistable(this.text))
{
return true;
}
return false;
}
return true;
}
/////////////////////////////////////////////////////////////////////////////
#endregion
#region property accessors
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public string Text</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Text
{
get {return this.text;}
set {this.Dirty = true; this.text = value;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public Uri Uri</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public AtomUri Uri
{
get {return this.uri;}
set {this.Dirty = true; this.uri = value;}
}
/////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
/// <summary>accessor method public string Version</summary>
/// <returns> </returns>
//////////////////////////////////////////////////////////////////////
public string Version
{
get {return this.version;}
set {this.Dirty = true; this.version = value;}
}
/////////////////////////////////////////////////////////////////////////////
#endregion end of property accessors
}
/////////////////////////////////////////////////////////////////////////////
}
| |
//---------------------------------------------------------------------------
//
// <copyright file="BindingOperations.cs" company="Microsoft">
// Copyright (C) Microsoft Corporation. All rights reserved.
// </copyright>
//
// Description: Helper operations for data bindings.
//
// See spec at http://avalon/connecteddata/Specs/Data%20Binding.mht
//
//---------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.ComponentModel;
using System.Globalization;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Threading;
using MS.Internal.Data;
namespace System.Windows.Data
{
/// <summary>
/// Operations to manipulate data bindings.
/// </summary>
public static class BindingOperations
{
//------------------------------------------------------
//
// Public Properties
//
//------------------------------------------------------
/// <summary>
/// A sentinel object. WPF assigns this as the DataContext of elements
/// that leave an ItemsControl because (a) the corresponding item is
/// removed from the ItemsSource collection, or (b) the element is
/// scrolled out of view and re-virtualized. Bindings that use DataContext
/// react by unhooking from property-changed events. This keeps the
/// discarded elements from interfering with the still-visible elements.
/// </summary>
public static object DisconnectedSource
{
get { return BindingExpressionBase.DisconnectedItem; }
}
//------------------------------------------------------
//
// Public Methods
//
//------------------------------------------------------
/// <summary>
/// Attach a BindingExpression to a property.
/// </summary>
/// <remarks>
/// A new BindingExpression is created from the given description, and attached to
/// the given property of the given object. This method is the way to
/// attach a Binding to an arbitrary DependencyObject that may not expose
/// its own SetBinding method.
/// </remarks>
/// <param name="target">object on which to attach the Binding</param>
/// <param name="dp">property to which to attach the Binding</param>
/// <param name="binding">description of the Binding</param>
/// <exception cref="ArgumentNullException"> target and dp and binding cannot be null </exception>
public static BindingExpressionBase SetBinding(DependencyObject target, DependencyProperty dp, BindingBase binding)
{
if (target == null)
throw new ArgumentNullException("target");
if (dp == null)
throw new ArgumentNullException("dp");
if (binding == null)
throw new ArgumentNullException("binding");
// target.VerifyAccess();
BindingExpressionBase bindExpr = binding.CreateBindingExpression(target, dp);
//
target.SetValue(dp, bindExpr);
return bindExpr;
}
/// <summary>
/// Retrieve a BindingBase.
/// </summary>
/// <remarks>
/// This method returns null if no Binding has been set on the given
/// property.
/// </remarks>
/// <param name="target">object from which to retrieve the binding</param>
/// <param name="dp">property from which to retrieve the binding</param>
/// <exception cref="ArgumentNullException"> target and dp cannot be null </exception>
public static BindingBase GetBindingBase(DependencyObject target, DependencyProperty dp)
{
BindingExpressionBase b = GetBindingExpressionBase(target, dp);
return (b != null) ? b.ParentBindingBase : null;
}
/// <summary>
/// Retrieve a Binding.
/// </summary>
/// <remarks>
/// This method returns null if no Binding has been set on the given
/// property.
/// </remarks>
/// <param name="target">object from which to retrieve the binding</param>
/// <param name="dp">property from which to retrieve the binding</param>
/// <exception cref="ArgumentNullException"> target and dp cannot be null </exception>
public static Binding GetBinding(DependencyObject target, DependencyProperty dp)
{
return GetBindingBase(target, dp) as Binding;
}
/// <summary>
/// Retrieve a PriorityBinding.
/// </summary>
/// <remarks>
/// This method returns null if no Binding has been set on the given
/// property.
/// </remarks>
/// <param name="target">object from which to retrieve the binding</param>
/// <param name="dp">property from which to retrieve the binding</param>
/// <exception cref="ArgumentNullException"> target and dp cannot be null </exception>
public static PriorityBinding GetPriorityBinding(DependencyObject target, DependencyProperty dp)
{
return GetBindingBase(target, dp) as PriorityBinding;
}
/// <summary>
/// Retrieve a MultiBinding.
/// </summary>
/// <remarks>
/// This method returns null if no Binding has been set on the given
/// property.
/// </remarks>
/// <param name="target">object from which to retrieve the binding</param>
/// <param name="dp">property from which to retrieve the binding</param>
/// <exception cref="ArgumentNullException"> target and dp cannot be null </exception>
public static MultiBinding GetMultiBinding(DependencyObject target, DependencyProperty dp)
{
return GetBindingBase(target, dp) as MultiBinding;
}
/// <summary>
/// Retrieve a BindingExpressionBase.
/// </summary>
/// <remarks>
/// This method returns null if no Binding has been set on the given
/// property.
/// </remarks>
/// <param name="target">object from which to retrieve the BindingExpression</param>
/// <param name="dp">property from which to retrieve the BindingExpression</param>
/// <exception cref="ArgumentNullException"> target and dp cannot be null </exception>
public static BindingExpressionBase GetBindingExpressionBase(DependencyObject target, DependencyProperty dp)
{
if (target == null)
throw new ArgumentNullException("target");
if (dp == null)
throw new ArgumentNullException("dp");
// target.VerifyAccess();
Expression expr = StyleHelper.GetExpression(target, dp);
return expr as BindingExpressionBase;
}
/// <summary>
/// Retrieve a BindingExpression.
/// </summary>
/// <remarks>
/// This method returns null if no Binding has been set on the given
/// property.
/// </remarks>
/// <param name="target">object from which to retrieve the BindingExpression</param>
/// <param name="dp">property from which to retrieve the BindingExpression</param>
/// <exception cref="ArgumentNullException"> target and dp cannot be null </exception>
public static BindingExpression GetBindingExpression(DependencyObject target, DependencyProperty dp)
{
BindingExpressionBase expr = GetBindingExpressionBase(target, dp);
PriorityBindingExpression pb = expr as PriorityBindingExpression;
if (pb != null)
expr = pb.ActiveBindingExpression;
return expr as BindingExpression;
}
/// <summary>
/// Retrieve a MultiBindingExpression.
/// </summary>
/// <remarks>
/// This method returns null if no MultiBinding has been set on the given
/// property.
/// </remarks>
/// <param name="target">object from which to retrieve the MultiBindingExpression</param>
/// <param name="dp">property from which to retrieve the MultiBindingExpression</param>
/// <exception cref="ArgumentNullException"> target and dp cannot be null </exception>
public static MultiBindingExpression GetMultiBindingExpression(DependencyObject target, DependencyProperty dp)
{
return GetBindingExpressionBase(target, dp) as MultiBindingExpression;
}
/// <summary>
/// Retrieve a PriorityBindingExpression.
/// </summary>
/// <remarks>
/// This method returns null if no PriorityBinding has been set on the given
/// property.
/// </remarks>
/// <param name="target">object from which to retrieve the PriorityBindingExpression</param>
/// <param name="dp">property from which to retrieve the PriorityBindingExpression</param>
/// <exception cref="ArgumentNullException"> target and dp cannot be null </exception>
public static PriorityBindingExpression GetPriorityBindingExpression(DependencyObject target, DependencyProperty dp)
{
return GetBindingExpressionBase(target, dp) as PriorityBindingExpression;
}
/// <summary>
/// Remove data Binding (if any) from a property.
/// </summary>
/// <remarks>
/// If the given property is data-bound, via a Binding, PriorityBinding or MultiBinding,
/// the BindingExpression is removed, and the property's value changes to what it
/// would be as if no local value had ever been set.
/// If the given property is not data-bound, this method has no effect.
/// </remarks>
/// <param name="target">object from which to remove Binding</param>
/// <param name="dp">property from which to remove Binding</param>
/// <exception cref="ArgumentNullException"> target and dp cannot be null </exception>
public static void ClearBinding(DependencyObject target, DependencyProperty dp)
{
if (target == null)
throw new ArgumentNullException("target");
if (dp == null)
throw new ArgumentNullException("dp");
// target.VerifyAccess();
if (IsDataBound(target, dp))
target.ClearValue(dp);
}
/// <summary>
/// Remove all data Binding (if any) from a DependencyObject.
/// </summary>
/// <param name="target">object from which to remove bindings</param>
/// <exception cref="ArgumentNullException"> DependencyObject target cannot be null </exception>
public static void ClearAllBindings(DependencyObject target)
{
if (target == null)
throw new ArgumentNullException("target");
// target.VerifyAccess();
LocalValueEnumerator lve = target.GetLocalValueEnumerator();
// Batch properties that have BindingExpressions since clearing
// during a local value enumeration is illegal
ArrayList batch = new ArrayList(8);
while (lve.MoveNext())
{
LocalValueEntry entry = lve.Current;
if (IsDataBound(target, entry.Property))
{
batch.Add(entry.Property);
}
}
// Clear all properties that are storing BindingExpressions
for (int i = 0; i < batch.Count; i++)
{
target.ClearValue((DependencyProperty)batch[i]);
}
}
/// <summary>Return true if the property is currently data-bound</summary>
/// <exception cref="ArgumentNullException"> DependencyObject target cannot be null </exception>
public static bool IsDataBound(DependencyObject target, DependencyProperty dp)
{
if (target == null)
throw new ArgumentNullException("target");
if (dp == null)
throw new ArgumentNullException("dp");
// target.VerifyAccess();
object o = StyleHelper.GetExpression(target, dp);
return (o is BindingExpressionBase);
}
/// <summary>
/// Register a callback used to synchronize access to a given collection.
/// </summary>
/// <param name="collection"> The collection that needs synchronized access. </param>
/// </param name="context"> An arbitrary object. This object is passed back into
/// the callback; it is not used otherwise. It provides a way for the
/// application to store information it knows at registration time, which it
/// can then use at collection-access time. Typically this information will
/// help the application determine the synchronization mechanism used to
/// control access to the given collection. </param>
/// <param name="synchronizationCallback"> The callback to be invoked whenever
/// access to the collection is required. </param>
public static void EnableCollectionSynchronization(
IEnumerable collection,
object context,
CollectionSynchronizationCallback synchronizationCallback)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (synchronizationCallback == null)
throw new ArgumentNullException("synchronizationCallback");
ViewManager.Current.RegisterCollectionSynchronizationCallback(
collection, context, synchronizationCallback);
}
/// <summary>
/// Register a lock object used to synchronize access to a given collection.
/// </summary>
/// <param name="collection"> The collection that needs synchronized access. </param>
/// <param name="lockObject"> The object to lock when accessing the collection. </param>
public static void EnableCollectionSynchronization(
IEnumerable collection,
object lockObject)
{
if (collection == null)
throw new ArgumentNullException("collection");
if (lockObject == null)
throw new ArgumentNullException("lockObject");
ViewManager.Current.RegisterCollectionSynchronizationCallback(
collection, lockObject, null);
}
/// <summary>
/// Remove the synchronization registered for a given collection. Any subsequent
/// access to the collection will be unsynchronized.
/// </summary>
/// <param name="collection"> The collection that needs its synchronized access removed. </param>
public static void DisableCollectionSynchronization(
IEnumerable collection)
{
if (collection == null)
throw new ArgumentNullException("collection");
ViewManager.Current.RegisterCollectionSynchronizationCallback(
collection, null, null);
}
/// <summary>
/// A caller can use this method to access a collection using the
/// synchronization that the application has registered for that collection.
/// If no synchronization is registered, the access method is simply called
/// directly.
/// </summary>
/// <notes>
/// 1. This method is provided chiefly for collection views, which need to
/// redirect access through the application-provided synchronization pattern.
/// An application typically doesn't need to call it, as the application
/// can use its synchronization directly.
/// 2. It is usually convenient to provide a closure as the access
/// method. This closure will have access to local variables at the
/// site of the call. For example, the following code reads _collection[3]:
/// void MyMethod()
/// {
/// int index = 3;
/// int result = 0;
/// BindingOperations.AccessCollection(
/// _collection,
/// () => { result = _collection[index]; },
/// false); // read-access
/// }
/// Note that the access method refers to local variables (index, result)
/// of MyMethod, as well as to an instance variable (_collection) of the
/// 'this' object.
/// </notes>
public static void AccessCollection(
IEnumerable collection,
Action accessMethod,
bool writeAccess)
{
ViewManager vm = ViewManager.Current;
if (vm == null)
throw new InvalidOperationException(SR.Get(SRID.AccessCollectionAfterShutDown, collection));
vm.AccessCollection(collection, accessMethod, writeAccess);
}
/// <summary>
/// Returns a list of all binding expressions that are:
/// a) top-level (do not belong to a parent MultiBindingExpression or BindingGroup)
/// b) source-updating (binding mode is TwoWay or OneWayToSource)
/// c) currently dirty or invalid
/// and d) attached to a descendant of the given DependencyObject (if non-null).
/// These are the bindings that may need attention before executing a command.
/// </summary>
public static ReadOnlyCollection<BindingExpressionBase> GetSourceUpdatingBindings(DependencyObject root)
{
List<BindingExpressionBase> list = DataBindEngine.CurrentDataBindEngine.CommitManager.GetBindingsInScope(root);
return new ReadOnlyCollection<BindingExpressionBase>(list);
}
/// <summary>
/// Returns a list of all BindingGroups that are:
/// a) currently dirty or invalid
/// and b) attached to a descendant of the given DependencyObject (if non-null).
/// </summary>
public static ReadOnlyCollection<BindingGroup> GetSourceUpdatingBindingGroups(DependencyObject root)
{
List<BindingGroup> list = DataBindEngine.CurrentDataBindEngine.CommitManager.GetBindingGroupsInScope(root);
return new ReadOnlyCollection<BindingGroup>(list);
}
//------------------------------------------------------
//
// Public Events
//
//------------------------------------------------------
/// <summary>
/// This event is raised when a collection is first noticed by the data-binding system.
/// It provides an opportunity to register information about the collection,
/// before the data-binding system begins to use the collection.
/// </summary>
/// <notes>
/// In an application with multiple UI threads (i.e. multiple Dispatchers),
/// this event is raised independently on each thread the first time the
/// collection is noticed on that thread.
/// </notes>
public static event EventHandler<CollectionRegisteringEventArgs> CollectionRegistering;
/// <summary>
/// This event is raised when a collection view is first noticed by the data-binding system.
/// It provides an opportunity to modify the collection view,
/// before the data-binding system begins to use it.
/// </summary>
/// <notes>
/// In an application with multiple UI threads (i.e. multiple Dispatchers),
/// each thread has its own set of collection views. This event is raised
/// on the thread that owns the given collection view.
/// </notes>
public static event EventHandler<CollectionViewRegisteringEventArgs> CollectionViewRegistering;
//------------------------------------------------------
//
// Internal Methods
//
//------------------------------------------------------
// return false if this is an invalid value for UpdateSourceTrigger
internal static bool IsValidUpdateSourceTrigger(UpdateSourceTrigger value)
{
switch (value)
{
case UpdateSourceTrigger.Default:
case UpdateSourceTrigger.PropertyChanged:
case UpdateSourceTrigger.LostFocus:
case UpdateSourceTrigger.Explicit:
return true;
default:
return false;
}
}
// The following properties and methods have no internal callers. They
// can be called by suitably privileged external callers via reflection.
// They are intended to be used by test programs and the DRT.
// Enable or disable the cleanup pass. For use by tests that measure
// perf, to avoid noise from the cleanup pass.
internal static bool IsCleanupEnabled
{
get { return DataBindEngine.CurrentDataBindEngine.CleanupEnabled; }
set { DataBindEngine.CurrentDataBindEngine.CleanupEnabled = value; }
}
// Force a cleanup pass (even if IsCleanupEnabled is true). For use
// by leak-detection tests, to avoid false leak reports about objects
// held by the DataBindEngine that can be cleaned up. Returns true
// if something was actually cleaned up.
internal static bool Cleanup()
{
return DataBindEngine.CurrentDataBindEngine.Cleanup();
}
// Print various interesting statistics
internal static void PrintStats()
{
DataBindEngine.CurrentDataBindEngine.AccessorTable.PrintStats();
}
// Trace the size of the accessor table after each generation
internal static bool TraceAccessorTableSize
{
get { return DataBindEngine.CurrentDataBindEngine.AccessorTable.TraceSize; }
set { DataBindEngine.CurrentDataBindEngine.AccessorTable.TraceSize = value; }
}
// Raise the CollectionRegistering event
internal static void OnCollectionRegistering(IEnumerable collection, object parent)
{
if (CollectionRegistering != null)
CollectionRegistering(null, new CollectionRegisteringEventArgs(collection, parent));
}
// Raise the CollectionViewRegistering event
internal static void OnCollectionViewRegistering(CollectionView view)
{
if (CollectionViewRegistering != null)
CollectionViewRegistering(null, new CollectionViewRegisteringEventArgs(view));
}
#if LiveShapingInstrumentation
public static void SetNodeSize(int nodeSize)
{
LiveShapingBlock.SetNodeSize(nodeSize);
}
public static void SetQuickSortThreshold(int threshold)
{
LiveShapingTree.SetQuickSortThreshold(threshold);
}
public static void SetBinarySearchThreshold(int threshold)
{
LiveShapingTree.SetBinarySearchThreshold(threshold);
}
public static void ResetComparisons(ListCollectionView lcv)
{
lcv.ResetComparisons();
}
public static void ResetCopies(ListCollectionView lcv)
{
lcv.ResetCopies();
}
public static void ResetAverageCopy(ListCollectionView lcv)
{
lcv.ResetAverageCopy();
}
public static int GetComparisons(ListCollectionView lcv)
{
return lcv.GetComparisons();
}
public static int GetCopies(ListCollectionView lcv)
{
return lcv.GetCopies();
}
public static double GetAverageCopy(ListCollectionView lcv)
{
return lcv.GetAverageCopy();
}
#endif // LiveShapingInstrumentation
}
}
| |
// 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 gcav = Google.Cloud.AIPlatform.V1;
using sys = System;
namespace Google.Cloud.AIPlatform.V1
{
/// <summary>Resource name for the <c>IndexEndpoint</c> resource.</summary>
public sealed partial class IndexEndpointName : gax::IResourceName, sys::IEquatable<IndexEndpointName>
{
/// <summary>The possible contents of <see cref="IndexEndpointName"/>.</summary>
public enum ResourceNameType
{
/// <summary>An unparsed resource name.</summary>
Unparsed = 0,
/// <summary>
/// A resource name with pattern <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>
/// .
/// </summary>
ProjectLocationIndexEndpoint = 1,
}
private static gax::PathTemplate s_projectLocationIndexEndpoint = new gax::PathTemplate("projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}");
/// <summary>Creates a <see cref="IndexEndpointName"/> containing an unparsed resource name.</summary>
/// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param>
/// <returns>
/// A new instance of <see cref="IndexEndpointName"/> containing the provided
/// <paramref name="unparsedResourceName"/>.
/// </returns>
public static IndexEndpointName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) =>
new IndexEndpointName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName)));
/// <summary>
/// Creates a <see cref="IndexEndpointName"/> with the pattern
/// <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="indexEndpointId">The <c>IndexEndpoint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>A new instance of <see cref="IndexEndpointName"/> constructed from the provided ids.</returns>
public static IndexEndpointName FromProjectLocationIndexEndpoint(string projectId, string locationId, string indexEndpointId) =>
new IndexEndpointName(ResourceNameType.ProjectLocationIndexEndpoint, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), indexEndpointId: gax::GaxPreconditions.CheckNotNullOrEmpty(indexEndpointId, nameof(indexEndpointId)));
/// <summary>
/// Formats the IDs into the string representation of this <see cref="IndexEndpointName"/> with pattern
/// <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="indexEndpointId">The <c>IndexEndpoint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="IndexEndpointName"/> with pattern
/// <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>.
/// </returns>
public static string Format(string projectId, string locationId, string indexEndpointId) =>
FormatProjectLocationIndexEndpoint(projectId, locationId, indexEndpointId);
/// <summary>
/// Formats the IDs into the string representation of this <see cref="IndexEndpointName"/> with pattern
/// <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>.
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="indexEndpointId">The <c>IndexEndpoint</c> ID. Must not be <c>null</c> or empty.</param>
/// <returns>
/// The string representation of this <see cref="IndexEndpointName"/> with pattern
/// <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>.
/// </returns>
public static string FormatProjectLocationIndexEndpoint(string projectId, string locationId, string indexEndpointId) =>
s_projectLocationIndexEndpoint.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(indexEndpointId, nameof(indexEndpointId)));
/// <summary>
/// Parses the given resource name string into a new <see cref="IndexEndpointName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="indexEndpointName">The resource name in string form. Must not be <c>null</c>.</param>
/// <returns>The parsed <see cref="IndexEndpointName"/> if successful.</returns>
public static IndexEndpointName Parse(string indexEndpointName) => Parse(indexEndpointName, false);
/// <summary>
/// Parses the given resource name string into a new <see cref="IndexEndpointName"/> instance; optionally
/// allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="indexEndpointName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <returns>The parsed <see cref="IndexEndpointName"/> if successful.</returns>
public static IndexEndpointName Parse(string indexEndpointName, bool allowUnparsed) =>
TryParse(indexEndpointName, allowUnparsed, out IndexEndpointName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern.");
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="IndexEndpointName"/> instance.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c></description>
/// </item>
/// </list>
/// </remarks>
/// <param name="indexEndpointName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="result">
/// When this method returns, the parsed <see cref="IndexEndpointName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string indexEndpointName, out IndexEndpointName result) =>
TryParse(indexEndpointName, false, out result);
/// <summary>
/// Tries to parse the given resource name string into a new <see cref="IndexEndpointName"/> instance;
/// optionally allowing an unparseable resource name.
/// </summary>
/// <remarks>
/// To parse successfully, the resource name must be formatted as one of the following:
/// <list type="bullet">
/// <item>
/// <description><c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c></description>
/// </item>
/// </list>
/// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>.
/// </remarks>
/// <param name="indexEndpointName">The resource name in string form. Must not be <c>null</c>.</param>
/// <param name="allowUnparsed">
/// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/>
/// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is
/// specified.
/// </param>
/// <param name="result">
/// When this method returns, the parsed <see cref="IndexEndpointName"/>, or <c>null</c> if parsing failed.
/// </param>
/// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns>
public static bool TryParse(string indexEndpointName, bool allowUnparsed, out IndexEndpointName result)
{
gax::GaxPreconditions.CheckNotNull(indexEndpointName, nameof(indexEndpointName));
gax::TemplatedResourceName resourceName;
if (s_projectLocationIndexEndpoint.TryParseName(indexEndpointName, out resourceName))
{
result = FromProjectLocationIndexEndpoint(resourceName[0], resourceName[1], resourceName[2]);
return true;
}
if (allowUnparsed)
{
if (gax::UnparsedResourceName.TryParse(indexEndpointName, out gax::UnparsedResourceName unparsedResourceName))
{
result = FromUnparsed(unparsedResourceName);
return true;
}
}
result = null;
return false;
}
private IndexEndpointName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string indexEndpointId = null, string locationId = null, string projectId = null)
{
Type = type;
UnparsedResource = unparsedResourceName;
IndexEndpointId = indexEndpointId;
LocationId = locationId;
ProjectId = projectId;
}
/// <summary>
/// Constructs a new instance of a <see cref="IndexEndpointName"/> class from the component parts of pattern
/// <c>projects/{project}/locations/{location}/indexEndpoints/{index_endpoint}</c>
/// </summary>
/// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param>
/// <param name="indexEndpointId">The <c>IndexEndpoint</c> ID. Must not be <c>null</c> or empty.</param>
public IndexEndpointName(string projectId, string locationId, string indexEndpointId) : this(ResourceNameType.ProjectLocationIndexEndpoint, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), indexEndpointId: gax::GaxPreconditions.CheckNotNullOrEmpty(indexEndpointId, nameof(indexEndpointId)))
{
}
/// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary>
public ResourceNameType Type { get; }
/// <summary>
/// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an
/// unparsed resource name.
/// </summary>
public gax::UnparsedResourceName UnparsedResource { get; }
/// <summary>
/// The <c>IndexEndpoint</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource
/// name.
/// </summary>
public string IndexEndpointId { get; }
/// <summary>
/// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string LocationId { get; }
/// <summary>
/// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name.
/// </summary>
public string ProjectId { get; }
/// <summary>Whether this instance contains a resource name with a known pattern.</summary>
public bool IsKnownPattern => Type != ResourceNameType.Unparsed;
/// <summary>The string representation of the resource name.</summary>
/// <returns>The string representation of the resource name.</returns>
public override string ToString()
{
switch (Type)
{
case ResourceNameType.Unparsed: return UnparsedResource.ToString();
case ResourceNameType.ProjectLocationIndexEndpoint: return s_projectLocationIndexEndpoint.Expand(ProjectId, LocationId, IndexEndpointId);
default: throw new sys::InvalidOperationException("Unrecognized resource-type.");
}
}
/// <summary>Returns a hash code for this resource name.</summary>
public override int GetHashCode() => ToString().GetHashCode();
/// <inheritdoc/>
public override bool Equals(object obj) => Equals(obj as IndexEndpointName);
/// <inheritdoc/>
public bool Equals(IndexEndpointName other) => ToString() == other?.ToString();
/// <inheritdoc/>
public static bool operator ==(IndexEndpointName a, IndexEndpointName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false);
/// <inheritdoc/>
public static bool operator !=(IndexEndpointName a, IndexEndpointName b) => !(a == b);
}
public partial class IndexEndpoint
{
/// <summary>
/// <see cref="gcav::IndexEndpointName"/>-typed view over the <see cref="Name"/> resource name property.
/// </summary>
public gcav::IndexEndpointName IndexEndpointName
{
get => string.IsNullOrEmpty(Name) ? null : gcav::IndexEndpointName.Parse(Name, allowUnparsed: true);
set => Name = value?.ToString() ?? "";
}
}
public partial class DeployedIndex
{
/// <summary><see cref="IndexName"/>-typed view over the <see cref="Index"/> resource name property.</summary>
public IndexName IndexAsIndexName
{
get => string.IsNullOrEmpty(Index) ? null : IndexName.Parse(Index, allowUnparsed: true);
set => Index = value?.ToString() ?? "";
}
}
}
| |
// Copyright (c) Duende Software. All rights reserved.
// See LICENSE in the project root for license information.
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using System;
using Duende.IdentityServer.Events;
using Duende.IdentityServer.Extensions;
using Duende.IdentityServer.Models;
using Duende.IdentityServer.Services;
using Duende.IdentityServer.Validation;
namespace IdentityServerHost.Quickstart.UI
{
/// <summary>
/// This controller processes the consent UI
/// </summary>
[SecurityHeaders]
[Authorize]
public class ConsentController : Controller
{
private readonly IIdentityServerInteractionService _interaction;
private readonly IEventService _events;
private readonly ILogger<ConsentController> _logger;
public ConsentController(
IIdentityServerInteractionService interaction,
IEventService events,
ILogger<ConsentController> logger)
{
_interaction = interaction;
_events = events;
_logger = logger;
}
/// <summary>
/// Shows the consent screen
/// </summary>
/// <param name="returnUrl"></param>
/// <returns></returns>
[HttpGet]
public async Task<IActionResult> Index(string returnUrl)
{
var vm = await BuildViewModelAsync(returnUrl);
if (vm != null)
{
return View("Index", vm);
}
return View("Error");
}
/// <summary>
/// Handles the consent screen postback
/// </summary>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Index(ConsentInputModel model)
{
var result = await ProcessConsent(model);
if (result.IsRedirect)
{
var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
if (context?.IsNativeClient() == true)
{
// The client is native, so this change in how to
// return the response is for better UX for the end user.
return this.LoadingPage("Redirect", result.RedirectUri);
}
return Redirect(result.RedirectUri);
}
if (result.HasValidationError)
{
ModelState.AddModelError(string.Empty, result.ValidationError);
}
if (result.ShowView)
{
return View("Index", result.ViewModel);
}
return View("Error");
}
/*****************************************/
/* helper APIs for the ConsentController */
/*****************************************/
private async Task<ProcessConsentResult> ProcessConsent(ConsentInputModel model)
{
var result = new ProcessConsentResult();
// validate return url is still valid
var request = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);
if (request == null) return result;
ConsentResponse grantedConsent = null;
// user clicked 'no' - send back the standard 'access_denied' response
if (model?.Button == "no")
{
grantedConsent = new ConsentResponse { Error = AuthorizationError.AccessDenied };
// emit event
await _events.RaiseAsync(new ConsentDeniedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues));
}
// user clicked 'yes' - validate the data
else if (model?.Button == "yes")
{
// if the user consented to some scope, build the response model
if (model.ScopesConsented != null && model.ScopesConsented.Any())
{
var scopes = model.ScopesConsented;
if (ConsentOptions.EnableOfflineAccess == false)
{
scopes = scopes.Where(x => x != Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess);
}
grantedConsent = new ConsentResponse
{
RememberConsent = model.RememberConsent,
ScopesValuesConsented = scopes.ToArray(),
Description = model.Description
};
// emit event
await _events.RaiseAsync(new ConsentGrantedEvent(User.GetSubjectId(), request.Client.ClientId, request.ValidatedResources.RawScopeValues, grantedConsent.ScopesValuesConsented, grantedConsent.RememberConsent));
}
else
{
result.ValidationError = ConsentOptions.MustChooseOneErrorMessage;
}
}
else
{
result.ValidationError = ConsentOptions.InvalidSelectionErrorMessage;
}
if (grantedConsent != null)
{
// communicate outcome of consent back to identityserver
await _interaction.GrantConsentAsync(request, grantedConsent);
// indicate that's it ok to redirect back to authorization endpoint
result.RedirectUri = model.ReturnUrl;
result.Client = request.Client;
}
else
{
// we need to redisplay the consent UI
result.ViewModel = await BuildViewModelAsync(model.ReturnUrl, model);
}
return result;
}
private async Task<ConsentViewModel> BuildViewModelAsync(string returnUrl, ConsentInputModel model = null)
{
var request = await _interaction.GetAuthorizationContextAsync(returnUrl);
if (request != null)
{
return CreateConsentViewModel(model, returnUrl, request);
}
else
{
_logger.LogError("No consent request matching request: {0}", returnUrl);
}
return null;
}
private ConsentViewModel CreateConsentViewModel(
ConsentInputModel model, string returnUrl,
AuthorizationRequest request)
{
var vm = new ConsentViewModel
{
RememberConsent = model?.RememberConsent ?? true,
ScopesConsented = model?.ScopesConsented ?? Enumerable.Empty<string>(),
Description = model?.Description,
ReturnUrl = returnUrl,
ClientName = request.Client.ClientName ?? request.Client.ClientId,
ClientUrl = request.Client.ClientUri,
ClientLogoUrl = request.Client.LogoUri,
AllowRememberConsent = request.Client.AllowRememberConsent
};
vm.IdentityScopes = request.ValidatedResources.Resources.IdentityResources.Select(x => CreateScopeViewModel(x, vm.ScopesConsented.Contains(x.Name) || model == null)).ToArray();
var apiScopes = new List<ScopeViewModel>();
foreach(var parsedScope in request.ValidatedResources.ParsedScopes)
{
var apiScope = request.ValidatedResources.Resources.FindApiScope(parsedScope.ParsedName);
if (apiScope != null)
{
var scopeVm = CreateScopeViewModel(parsedScope, apiScope, vm.ScopesConsented.Contains(parsedScope.RawValue) || model == null);
apiScopes.Add(scopeVm);
}
}
if (ConsentOptions.EnableOfflineAccess && request.ValidatedResources.Resources.OfflineAccess)
{
apiScopes.Add(GetOfflineAccessScope(vm.ScopesConsented.Contains(Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess) || model == null));
}
vm.ApiScopes = apiScopes;
return vm;
}
private ScopeViewModel CreateScopeViewModel(IdentityResource identity, bool check)
{
return new ScopeViewModel
{
Value = identity.Name,
DisplayName = identity.DisplayName ?? identity.Name,
Description = identity.Description,
Emphasize = identity.Emphasize,
Required = identity.Required,
Checked = check || identity.Required
};
}
public ScopeViewModel CreateScopeViewModel(ParsedScopeValue parsedScopeValue, ApiScope apiScope, bool check)
{
var displayName = apiScope.DisplayName ?? apiScope.Name;
if (!String.IsNullOrWhiteSpace(parsedScopeValue.ParsedParameter))
{
displayName += ":" + parsedScopeValue.ParsedParameter;
}
return new ScopeViewModel
{
Value = parsedScopeValue.RawValue,
DisplayName = displayName,
Description = apiScope.Description,
Emphasize = apiScope.Emphasize,
Required = apiScope.Required,
Checked = check || apiScope.Required
};
}
private ScopeViewModel GetOfflineAccessScope(bool check)
{
return new ScopeViewModel
{
Value = Duende.IdentityServer.IdentityServerConstants.StandardScopes.OfflineAccess,
DisplayName = ConsentOptions.OfflineAccessDisplayName,
Description = ConsentOptions.OfflineAccessDescription,
Emphasize = true,
Checked = check
};
}
}
}
| |
// 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.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.NodejsTools;
using Microsoft.NodejsTools.Repl;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestUtilities;
using TestUtilities.Mocks;
namespace NodejsTests
{
[TestClass]
public class ReplWindowTests
{
[ClassInitialize]
public static void DoDeployment(TestContext context)
{
AssertListener.Initialize();
if (!File.Exists("visualstudio_nodejs_repl.js"))
{
using (StreamReader reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream("NodejsTests.visualstudio_nodejs_repl.js")))
{
File.WriteAllText(
"visualstudio_nodejs_repl.js",
reader.ReadToEnd()
);
}
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void Number()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("42");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual(window.Output, "42");
}
}
private static NodejsReplEvaluator ProjectlessEvaluator()
{
return new NodejsReplEvaluator(TestNodejsReplSite.Instance);
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void Require()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("require('http').constructor");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("[Function: Object]", window.Output);
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void FunctionDefinition()
{
var whitespaces = new[] { "", "\r\n", " ", "\r\n " };
using (var eval = ProjectlessEvaluator())
{
foreach (var whitespace in whitespaces)
{
Console.WriteLine("Whitespace: {0}", whitespace);
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText(whitespace + "function f() { }");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("undefined", window.Output);
window.ClearScreen();
res = eval.ExecuteText("f");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("[Function: f]", window.Output);
}
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void ConsoleLog()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("console.log('hi')");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("hi\r\nundefined", window.Output);
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void ConsoleWarn()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("console.warn('hi')");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("hi\r\n", window.Error);
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void ConsoleError()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("console.error('hi')");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("hi\r\n", window.Error);
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore"), TestCategory("Ignore")]
public void ConsoleDir()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("console.dir({'abc': {'foo': [1,2,3,4,5,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40]}})");
var expected = @"{ abc:
{ foo:
[ 1,
2,
3,
4,
5,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40 ] } }
undefined";
Assert.IsTrue(res.Wait(10000));
var received = window.Output;
AreEqual(expected, received);
}
}
private static void AreEqual(string expected, string received)
{
for (int i = 0; i < expected.Length && i < received.Length; i++)
{
Assert.AreEqual(expected[i], received[i], String.Format("Mismatch at {0}: expected {1} got {2} in <{3}>", i, expected[i], received[i], received));
}
Assert.AreEqual(expected.Length, received.Length, "strings differ by length");
}
//
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void LargeOutput()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("var x = 'abc'; for(i = 0; i<12; i++) { x += x; }; x");
string expected = "abc";
for (int i = 0; i < 12; i++)
{
expected += expected;
}
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("'" + expected + "'", window.Output);
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void Exception()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("throw 'an error';");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("an error", window.Error);
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void ExceptionNull()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("throw null;");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("undefined", window.Output);
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void ExceptionUndefined()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("throw undefined;");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("undefined", window.Output);
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void ProcessExit()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("process.exit(0);");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("The process has exited" + Environment.NewLine, window.Error);
window.ClearScreen();
res = eval.ExecuteText("42");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("Current interactive window is disconnected - please reset the process.\r\n", window.Error);
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void Reset()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("1");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("1", window.Output);
res = window.Reset();
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("The process has exited" + Environment.NewLine, window.Error);
window.ClearScreen();
Assert.AreEqual("", window.Output);
Assert.AreEqual("", window.Error);
//Check to ensure the REPL continues to work after Reset
res = eval.ExecuteText("var a = 1");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("undefined", window.Output);
res = eval.ExecuteText("a");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("undefined1", window.Output);
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void SaveNoFile()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("function f() { }");
Assert.IsTrue(res.Wait(10000));
res = eval.ExecuteText("function g() { }");
Assert.IsTrue(res.Wait(10000));
new SaveReplCommand().Execute(window, "").Wait(10000);
Assert.IsTrue(window.Error.Contains("save requires a filename"));
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void SaveBadFile()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("function f() { }");
Assert.IsTrue(res.Wait(10000));
res = eval.ExecuteText("function g() { }");
Assert.IsTrue(res.Wait(10000));
new SaveReplCommand().Execute(window, "<foo>").Wait(10000);
Assert.IsTrue(window.Error.Contains("Invalid filename: <foo>"));
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void Save()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval, NodejsConstants.JavaScript);
window.ClearScreen();
var res = window.Execute("function f() { }");
Assert.IsTrue(res.Wait(10000));
res = window.Execute("function g() { }");
Assert.IsTrue(res.Wait(10000));
var path = Path.GetTempFileName();
File.Delete(path);
new SaveReplCommand().Execute(window, path).Wait(10000);
Assert.IsTrue(File.Exists(path));
var saved = File.ReadAllText(path);
Assert.IsTrue(saved.IndexOf("function f") != -1);
Assert.IsTrue(saved.IndexOf("function g") != -1);
Assert.IsTrue(window.Output.Contains("Session saved to:"));
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void BadSave()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("function f() { }");
Assert.IsTrue(res.Wait(10000));
res = eval.ExecuteText("function g() { }");
Assert.IsTrue(res.Wait(10000));
new SaveReplCommand().Execute(window, "C:\\Some\\Directory\\That\\Does\\Not\\Exist\\foo.js").Wait(10000);
Assert.IsTrue(window.Error.Contains("Failed to save: "));
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void ReplEvaluatorProvider()
{
var provider = new NodejsReplEvaluatorProvider();
Assert.AreEqual(null, provider.GetEvaluator("Unknown"));
Assert.AreNotEqual(null, provider.GetEvaluator("{E4AC36B7-EDC5-4AD2-B758-B5416D520705}"));
}
private static string[] _partialInputs = { "function f(",
"function f() {",
"x = {foo:",
"{\r\nfoo:42",
"function () {",
"for(var i = 0; i<10; i++) {",
"for(var i = 0; i<10; i++) {\r\nconsole.log('hi');",
"while(true) {",
"while(true) {\r\nbreak;",
"do {",
"do {\r\nbreak;",
"if(true) {",
"if(true) {\r\nconsole.log('hi');",
"if(true) {\r\nconsole.log('hi');\r\n}else{",
"if(true) {\r\nconsole.log('hi');\r\n}else{\r\nconsole.log('bye');",
"switch(\"abc\") {",
"switch(\"abc\") {\r\ncase \"foo\":",
"switch(\"abc\") {\r\ncase \"foo\":\r\nbreak;",
"switch(\"abc\") {\r\ncase \"foo\":\r\nbreak;\r\ncase \"abc\":",
"switch(\"abc\") {\r\ncase \"foo\":\r\nbreak;\r\ncase \"abc\":console.log('hi');",
"switch(\"abc\") {\r\ncase \"foo\":\r\nbreak;\r\ncase \"abc\":console.log('hi');\r\nbreak;",
"[1,",
"[1,\r\n2,",
"var net = require('net'),"
};
private static string[] _completeInputs = { "try {\r\nconsole.log('hi')\r\n} catch {\r\n}",
"try {\r\nconsole.log('hi')\r\n} catch(a) {\r\n}",
"function f(\r\na) {\r\n}\r\n\r\n};",
"x = {foo}",
"x = {foo:42}",
"{x:42}",
"{\r\nfoo:42\r\n}",
"function () {\r\nconsole.log('hi');\r\n}",
"for(var i = 0; i<10; i++) {\r\nconsole.log('hi');\r\n}",
"while(true) {\r\nbreak;\r\n}",
"do {\r\nbreak;\r\n}while(true);",
"if(true) {\r\nconsole.log('hi');\r\n}",
"if(true) {\r\nconsole.log('hi');\r\n}else{\r\nconsole.log('bye');\r\n}",
"switch('abc') {\r\ncase 'foo':\r\nbreak;\r\ncase 'abc':\r\nconsole.log('hi');\r\nbreak;\r\n}",
"[1,\r\n2,\r\n3]",
"var net = require('net'),\r\n repl = require('repl');",
};
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void PartialInputs()
{
using (var eval = ProjectlessEvaluator())
{
foreach (var partialInput in _partialInputs)
{
Assert.AreEqual(false, eval.CanExecuteText(partialInput), "Partial input successfully parsed: " + partialInput);
}
foreach (var completeInput in _completeInputs)
{
Assert.AreEqual(true, eval.CanExecuteText(completeInput), "Complete input failed to parse: " + completeInput);
}
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore"), TestCategory("Ignore")]
public void VarI()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("i");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("ReferenceError: i is not defined", window.Error);
Assert.AreEqual("", window.Output);
res = eval.ExecuteText("var i = 987654;");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("undefined", window.Output);
res = eval.ExecuteText("i");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("undefined987654", window.Output);
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void ObjectLiteral()
{
using (var eval = ProjectlessEvaluator())
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("{x:42}");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual("{ x: 42 }", window.Output);
}
}
/// <summary>
/// https://nodejstools.codeplex.com/workitem/279
/// </summary>
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore")]
public void RequireInProject()
{
string testDir;
do
{
testDir = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
} while (Directory.Exists(testDir));
Directory.CreateDirectory(testDir);
var moduleDir = Path.Combine(testDir, "node_modules");
Directory.CreateDirectory(moduleDir);
File.WriteAllText(Path.Combine(moduleDir, "foo.js"), "exports.foo = function(a, b, c) { }");
File.WriteAllText(Path.Combine(testDir, "bar.js"), "exports.bar = function(a, b, c) { }");
try
{
using (var eval = new NodejsReplEvaluator(new TestNodejsReplSite(null, testDir)))
{
var window = new MockReplWindow(eval);
window.ClearScreen();
var res = eval.ExecuteText("require('foo.js');");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual(window.Output, "{ foo: [Function] }");
window.ClearScreen();
res = eval.ExecuteText("require('./bar.js');");
Assert.IsTrue(res.Wait(10000));
Assert.AreEqual(window.Output, "{ bar: [Function] }");
}
}
finally
{
try
{
Directory.Delete(testDir, true);
}
catch (IOException)
{
}
}
}
// https://nodejstools.codeplex.com/workitem/1575
[TestMethod, Priority(0), Timeout(180000), TestCategory("Ignore")]
public async Task TestNpmReplCommandProcessExitSucceeds()
{
var npmPath = Nodejs.GetPathToNodeExecutableFromEnvironment("npm.cmd");
using (var eval = ProjectlessEvaluator())
{
var mockWindow = new MockReplWindow(eval)
{
ShowAnsiCodes = true
};
mockWindow.ClearScreen();
var redirector = new NpmReplCommand.NpmReplRedirector(mockWindow);
for (int j = 0; j < 200; j++)
{
await NpmReplCommand.ExecuteNpmCommandAsync(
redirector,
npmPath,
null,
new[] { "config", "get", "registry" },
null);
}
}
}
[TestMethod, Priority(0), TestCategory("AppVeyorIgnore"), TestCategory("Ignore")]
public void NpmReplRedirector()
{
using (var eval = ProjectlessEvaluator())
{
var mockWindow = new MockReplWindow(eval)
{
ShowAnsiCodes = true
};
mockWindow.ClearScreen();
var redirector = new NpmReplCommand.NpmReplRedirector(mockWindow);
redirector.WriteLine("npm The sky is at a stable equilibrium");
var expectedInfoLine =
NpmReplCommand.NpmReplRedirector.NormalAnsiColor + "npm The sky is at a stable equilibrium" +
Environment.NewLine;
Assert.AreEqual(expectedInfoLine, mockWindow.Output);
Assert.IsFalse(redirector.HasErrors);
mockWindow.ClearScreen();
redirector.WriteLine("npm WARN The sky is at an unstable equilibrium!");
var expectedWarnLine =
NpmReplCommand.NpmReplRedirector.WarnAnsiColor + "npm WARN" +
NpmReplCommand.NpmReplRedirector.NormalAnsiColor + " The sky is at an unstable equilibrium!" +
Environment.NewLine;
Assert.AreEqual(expectedWarnLine, mockWindow.Output);
Assert.IsFalse(redirector.HasErrors);
mockWindow.ClearScreen();
redirector.WriteLine("npm ERR! The sky is falling!");
var expectedErrorLine =
NpmReplCommand.NpmReplRedirector.ErrorAnsiColor + "npm ERR!" +
NpmReplCommand.NpmReplRedirector.NormalAnsiColor + " The sky is falling!" +
Environment.NewLine;
Assert.AreEqual(expectedErrorLine, mockWindow.Output);
Assert.IsTrue(redirector.HasErrors);
mockWindow.ClearScreen();
var decodedInfoLine = "\u251C\u2500\u2500 parseurl@1.0.1";
string encodedText = Console.OutputEncoding.GetString(Encoding.UTF8.GetBytes(decodedInfoLine));
redirector.WriteLine(encodedText);
var expectedDecodedInfoLine = NpmReplCommand.NpmReplRedirector.NormalAnsiColor + decodedInfoLine
+ Environment.NewLine;
Assert.AreEqual(expectedDecodedInfoLine, mockWindow.Output);
Assert.IsTrue(redirector.HasErrors, "Errors should remain until end");
}
}
}
}
| |
using Signum.Utilities;
using Signum.Utilities.ExpressionTrees;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Signum.Entities.Dynamic
{
[Serializable, EntityKind(EntityKind.Main, EntityData.Master)]
public class DynamicTypeEntity : Entity
{
public DynamicBaseType BaseType { set; get; }
[UniqueIndex]
[StringLengthValidator(Min = 3, Max = 100), IdentifierValidator(IdentifierType.PascalAscii)]
public string TypeName { get; set; }
[DbType(Size = int.MaxValue)]
string typeDefinition;
[StringLengthValidator(Min = 3)]
public string TypeDefinition
{
get { return this.Get(typeDefinition); }
set
{
if (this.Set(ref typeDefinition, value))
this.definition = null;
}
}
static JsonSerializerOptions settings = new JsonSerializerOptions
{
IncludeFields = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNameCaseInsensitive = true,
Converters=
{
new JsonStringEnumConverter(),
}
};
[Ignore]
DynamicTypeDefinition? definition;
public DynamicTypeDefinition GetDefinition()
{
return definition ?? (definition = JsonSerializer.Deserialize<DynamicTypeDefinition>(this.TypeDefinition, settings))!;
}
public void SetDefinition(DynamicTypeDefinition definition)
{
this.TypeDefinition = JsonSerializer.Serialize(definition, settings);
this.definition = definition;
}
protected override string? PropertyValidation(PropertyInfo pi)
{
if (pi.Name == nameof(TypeDefinition))
{
var def = this.GetDefinition();
return def.Properties
.Where(p => p.Name.HasText() && !IdentifierValidatorAttribute.PascalAscii.IsMatch(p.Name))
.Select(p => ValidationMessage._0DoesNotHaveAValid1IdentifierFormat.NiceToString(p.Name, IdentifierType.PascalAscii))
.ToString("\r\n")
.DefaultToNull();
}
return base.PropertyValidation(pi);
}
[AutoExpressionField]
public override string ToString() => As.Expression(() => TypeName);
}
[AutoInit]
public static class DynamicTypeOperation
{
public static readonly ConstructSymbol<DynamicTypeEntity>.Simple Create;
public static readonly ConstructSymbol<DynamicTypeEntity>.From<DynamicTypeEntity> Clone;
public static readonly ExecuteSymbol<DynamicTypeEntity> Save;
public static readonly DeleteSymbol<DynamicTypeEntity> Delete;
}
public enum DynamicTypeMessage
{
TypeSaved,
[Description("DynamicType '{0}' successfully saved. Go to DynamicPanel now?")]
DynamicType0SucessfullySavedGoToDynamicPanelNow,
[Description("Server restarted with errors in dynamic code. Fix errors and restart again.")]
ServerRestartedWithErrorsInDynamicCodeFixErrorsAndRestartAgain,
[Description("Remove Save Operation?")]
RemoveSaveOperation,
TheEntityShouldBeSynchronizedToApplyMixins,
}
public class DynamicTypePrimaryKeyDefinition
{
public string? Name;
public string? Type;
public bool Identity;
}
public class DynamicTypeTicksDefinition
{
public bool HasTicks;
public string? Name;
public string? Type;
}
public class DynamicTypeBackMListDefinition
{
public string? TableName;
public bool PreserveOrder;
public string? OrderName;
public string? BackReferenceName;
}
public class DynamicTypeDefinition
{
public EntityKind? EntityKind;
public EntityData? EntityData;
public string? TableName;
public DynamicTypePrimaryKeyDefinition? PrimaryKey;
public DynamicTypeTicksDefinition? Ticks;
public List<DynamicProperty> Properties;
public OperationConstruct? OperationCreate;
public OperationExecute? OperationSave;
public OperationDelete? OperationDelete;
public OperationConstructFrom? OperationClone;
public DynamicTypeCustomCode? CustomInheritance;
public DynamicTypeCustomCode? CustomEntityMembers;
public DynamicTypeCustomCode? CustomStartCode;
public DynamicTypeCustomCode? CustomLogicMembers;
public DynamicTypeCustomCode? CustomTypes;
public DynamicTypeCustomCode? CustomBeforeSchema;
public List<string> QueryFields;
public MultiColumnUniqueIndex? MultiColumnUniqueIndex;
public string? ToStringExpression;
}
public class MultiColumnUniqueIndex
{
public List<string> Fields;
public string? Where;
}
public class OperationConstruct
{
public string Construct;
}
public class OperationExecute
{
public string? CanExecute;
public string Execute;
}
public class OperationDelete
{
public string? CanDelete;
public string Delete;
}
public class OperationConstructFrom
{
public string? CanConstruct;
public string Construct;
}
public class DynamicTypeCustomCode
{
public string Code;
}
public enum DynamicBaseType
{
Entity,
MixinEntity,
EmbeddedEntity,
ModelEntity,
}
public class DynamicProperty
{
public string UID;
public string Name;
public string? ColumnName;
public string Type;
public string? ColumnType;
public IsNullable IsNullable;
public UniqueIndex UniqueIndex;
public bool? IsLite;
public DynamicTypeBackMListDefinition IsMList;
public int? Size;
public int? Scale;
public string? Unit;
public string? Format;
public bool? NotifyChanges;
public List<DynamicValidator>? Validators;
public string? CustomFieldAttributes;
public string? CustomPropertyAttributes;
}
public enum IsNullable
{
Yes,
OnlyInMemory,
No,
}
public enum UniqueIndex
{
No,
Yes,
YesAllowNull,
}
class DynamicValidatorConverter : JsonConverter<DynamicValidator>
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(DynamicValidator));
}
public override DynamicValidator? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
using(JsonDocument doc = JsonDocument.ParseValue(ref reader))
{
var typeName = doc.RootElement.GetProperty("type").GetString()!;
var type = DynamicValidator.GetDynamicValidatorType(typeName);
return (DynamicValidator)doc.RootElement.ToObject(type, options);
}
}
public override void Write(Utf8JsonWriter writer, DynamicValidator value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
[JsonConverter(typeof(DynamicValidatorConverter))]
public class DynamicValidator
{
public string Type;
public static Type GetDynamicValidatorType(string type)
{
switch (type)
{
case "NotNull": return typeof(NotNull);
case "StringLength": return typeof(StringLength);
case "Decimals": return typeof(Decimals);
case "NumberIs": return typeof(NumberIs);
case "CountIs": return typeof(CountIs);
case "NumberBetween": return typeof(NumberBetween);
case "DateTimePrecision": return typeof(DateTimePrecision);
case "TimeSpanPrecision": return typeof(TimeSpanPrecision);
case "StringCase": return typeof(StringCase);
default: return typeof(DynamicValidator);
}
}
public virtual string? ExtraArguments()
{
return null;
}
string Value(object obj)
{
if (obj is decimal)
obj = (double)(decimal)obj;
return CSharpRenderer.Value(obj);
}
public class NotNull : DynamicValidator
{
public bool Disabled;
public override string? ExtraArguments()
{
return new string?[]
{
Disabled ? "Disabled=true" : null,
}.NotNull().ToString(", ");
}
}
public class StringLength : DynamicValidator
{
public bool MultiLine;
public int? Min;
public int? Max;
public bool? AllowLeadingSpaces;
public bool? AllowTrailingSpaces;
public override string? ExtraArguments()
{
return new string?[]
{
MultiLine ? "MultiLine=true" : null,
Min.HasValue ? "Min=" + Value(Min.Value) : null,
Max.HasValue ? "Max=" + Value(Max.Value) : null,
AllowLeadingSpaces.HasValue ? "AllowLeadingSpaces=" + Value(AllowLeadingSpaces.Value) : null,
AllowTrailingSpaces.HasValue ? "AllowTrailingSpaces=" + Value(AllowTrailingSpaces.Value) : null,
}.NotNull().ToString(", ");
}
}
public class Decimals : DynamicValidator
{
public int DecimalPlaces;
public override string? ExtraArguments()
{
return Value(DecimalPlaces);
}
}
public class NumberIs : DynamicValidator
{
public ComparisonType ComparisonType;
public decimal Number;
public override string? ExtraArguments()
{
return Value(ComparisonType) + ", " + Value(Number);
}
}
public class CountIs : DynamicValidator
{
public ComparisonType ComparisonType;
public decimal Number;
public override string? ExtraArguments()
{
return Value(ComparisonType) + ", " + Value(Number);
}
}
public class NumberBetween : DynamicValidator
{
public decimal Min;
public decimal Max;
public override string? ExtraArguments()
{
return Value(Min) + ", " + Value(Max);
}
}
public class DateTimePrecision : DynamicValidator
{
public Signum.Utilities.DateTimePrecision Precision;
public override string? ExtraArguments()
{
return Value(Precision);
}
}
public class TimeSpanPrecision : DynamicValidator
{
public Signum.Utilities.DateTimePrecision Precision;
public override string? ExtraArguments()
{
return Value(Precision);
}
}
public class StringCase : DynamicValidator
{
public Signum.Entities.StringCase TextCase;
public override string? ExtraArguments()
{
return Value(TextCase);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Threading;
using System.Threading.Tasks;
using GoCardless.Internals;
using GoCardless.Resources;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace GoCardless.Services
{
/// <summary>
/// Service class for working with mandate resources.
///
/// Mandates represent the Direct Debit mandate with a
/// [customer](#core-endpoints-customers).
///
/// GoCardless will notify you via a [webhook](#appendix-webhooks) whenever
/// the status of a mandate changes.
/// </summary>
public class MandateService
{
private readonly GoCardlessClient _goCardlessClient;
/// <summary>
/// Constructor. Users of this library should not call this. An instance of this
/// class can be accessed through an initialised GoCardlessClient.
/// </summary>
public MandateService(GoCardlessClient goCardlessClient)
{
_goCardlessClient = goCardlessClient;
}
/// <summary>
/// Creates a new mandate object.
/// </summary>
/// <param name="request">An optional `MandateCreateRequest` representing the body for this create request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single mandate resource</returns>
public Task<MandateResponse> CreateAsync(MandateCreateRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new MandateCreateRequest();
var urlParams = new List<KeyValuePair<string, object>>
{};
return _goCardlessClient.ExecuteAsync<MandateResponse>("POST", "/mandates", urlParams, request, id => GetAsync(id, null, customiseRequestMessage), "mandates", customiseRequestMessage);
}
/// <summary>
/// Returns a [cursor-paginated](#api-usage-cursor-pagination) list of
/// your mandates.
/// </summary>
/// <param name="request">An optional `MandateListRequest` representing the query parameters for this list request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A set of mandate resources</returns>
public Task<MandateListResponse> ListAsync(MandateListRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new MandateListRequest();
var urlParams = new List<KeyValuePair<string, object>>
{};
return _goCardlessClient.ExecuteAsync<MandateListResponse>("GET", "/mandates", urlParams, request, null, null, customiseRequestMessage);
}
/// <summary>
/// Get a lazily enumerated list of mandates.
/// This acts like the #list method, but paginates for you automatically.
/// </summary>
public IEnumerable<Mandate> All(MandateListRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new MandateListRequest();
string cursor = null;
do
{
request.After = cursor;
var result = Task.Run(() => ListAsync(request, customiseRequestMessage)).Result;
foreach (var item in result.Mandates)
{
yield return item;
}
cursor = result.Meta?.Cursors?.After;
} while (cursor != null);
}
/// <summary>
/// Get a lazily enumerated list of mandates.
/// This acts like the #list method, but paginates for you automatically.
/// </summary>
public IEnumerable<Task<IReadOnlyList<Mandate>>> AllAsync(MandateListRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new MandateListRequest();
return new TaskEnumerable<IReadOnlyList<Mandate>, string>(async after =>
{
request.After = after;
var list = await this.ListAsync(request, customiseRequestMessage);
return Tuple.Create(list.Mandates, list.Meta?.Cursors?.After);
});
}
/// <summary>
/// Retrieves the details of an existing mandate.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "MD". Note that this prefix may
/// not apply to mandates created before 2016.</param>
/// <param name="request">An optional `MandateGetRequest` representing the query parameters for this get request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single mandate resource</returns>
public Task<MandateResponse> GetAsync(string identity, MandateGetRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new MandateGetRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<MandateResponse>("GET", "/mandates/:identity", urlParams, request, null, null, customiseRequestMessage);
}
/// <summary>
/// Updates a mandate object. This accepts only the metadata parameter.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "MD". Note that this prefix may
/// not apply to mandates created before 2016.</param>
/// <param name="request">An optional `MandateUpdateRequest` representing the body for this update request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single mandate resource</returns>
public Task<MandateResponse> UpdateAsync(string identity, MandateUpdateRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new MandateUpdateRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<MandateResponse>("PUT", "/mandates/:identity", urlParams, request, null, "mandates", customiseRequestMessage);
}
/// <summary>
/// Immediately cancels a mandate and all associated cancellable
/// payments. Any metadata supplied to this endpoint will be stored on
/// the mandate cancellation event it causes.
///
/// This will fail with a `cancellation_failed` error if the mandate is
/// already cancelled.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "MD". Note that this prefix may
/// not apply to mandates created before 2016.</param>
/// <param name="request">An optional `MandateCancelRequest` representing the body for this cancel request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single mandate resource</returns>
public Task<MandateResponse> CancelAsync(string identity, MandateCancelRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new MandateCancelRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<MandateResponse>("POST", "/mandates/:identity/actions/cancel", urlParams, request, null, "data", customiseRequestMessage);
}
/// <summary>
/// <a name="mandate_not_inactive"></a>Reinstates a cancelled or expired
/// mandate to the banks. You will receive a `resubmission_requested`
/// webhook, but after that reinstating the mandate follows the same
/// process as its initial creation, so you will receive a `submitted`
/// webhook, followed by a `reinstated` or `failed` webhook up to two
/// working days later. Any metadata supplied to this endpoint will be
/// stored on the `resubmission_requested` event it causes.
///
/// This will fail with a `mandate_not_inactive` error if the mandate is
/// already being submitted, or is active.
///
/// Mandates can be resubmitted up to 10 times.
/// </summary>
/// <param name="identity">Unique identifier, beginning with "MD". Note that this prefix may
/// not apply to mandates created before 2016.</param>
/// <param name="request">An optional `MandateReinstateRequest` representing the body for this reinstate request.</param>
/// <param name="customiseRequestMessage">An optional `RequestSettings` allowing you to configure the request</param>
/// <returns>A single mandate resource</returns>
public Task<MandateResponse> ReinstateAsync(string identity, MandateReinstateRequest request = null, RequestSettings customiseRequestMessage = null)
{
request = request ?? new MandateReinstateRequest();
if (identity == null) throw new ArgumentException(nameof(identity));
var urlParams = new List<KeyValuePair<string, object>>
{
new KeyValuePair<string, object>("identity", identity),
};
return _goCardlessClient.ExecuteAsync<MandateResponse>("POST", "/mandates/:identity/actions/reinstate", urlParams, request, null, "data", customiseRequestMessage);
}
}
/// <summary>
/// Creates a new mandate object.
/// </summary>
public class MandateCreateRequest : IHasIdempotencyKey
{
/// <summary>
/// Linked resources.
/// </summary>
[JsonProperty("links")]
public MandateLinks Links { get; set; }
/// <summary>
/// Linked resources for a Mandate.
/// </summary>
public class MandateLinks
{
/// <summary>
/// ID of the associated [creditor](#core-endpoints-creditors). Only
/// required if your account manages multiple creditors.
/// </summary>
[JsonProperty("creditor")]
public string Creditor { get; set; }
/// <summary>
/// ID of the associated [customer bank
/// account](#core-endpoints-customer-bank-accounts) which the
/// mandate is created and submits payments against.
/// </summary>
[JsonProperty("customer_bank_account")]
public string CustomerBankAccount { get; set; }
}
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with key
/// names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<String, String> Metadata { get; set; }
/// <summary>
/// For ACH customers only. Required for ACH customers. A string
/// containing the IP address of the payer to whom the mandate belongs
/// (i.e. as a result of their completion of a mandate setup flow in
/// their browser).
/// </summary>
[JsonProperty("payer_ip_address")]
public string PayerIpAddress { get; set; }
/// <summary>
/// Unique reference. Different schemes have different length and
/// [character set](#appendix-character-sets) requirements. GoCardless
/// will generate a unique reference satisfying the different scheme
/// requirements if this field is left blank.
/// </summary>
[JsonProperty("reference")]
public string Reference { get; set; }
/// <summary>
/// <a name="mandates_scheme"></a>Direct Debit scheme to which this
/// mandate and associated payments are submitted. Can be supplied or
/// automatically detected from the customer's bank account.
/// </summary>
[JsonProperty("scheme")]
public string Scheme { get; set; }
/// <summary>
/// A unique key to ensure that this request only succeeds once, allowing you to safely retry request errors such as network failures.
/// Any requests, where supported, to create a resource with a key that has previously been used will not succeed.
/// See: https://developer.gocardless.com/api-reference/#making-requests-idempotency-keys
/// </summary>
[JsonIgnore]
public string IdempotencyKey { get; set; }
}
/// <summary>
/// Returns a [cursor-paginated](#api-usage-cursor-pagination) list of your
/// mandates.
/// </summary>
public class MandateListRequest
{
/// <summary>
/// Cursor pointing to the start of the desired set.
/// </summary>
[JsonProperty("after")]
public string After { get; set; }
/// <summary>
/// Cursor pointing to the end of the desired set.
/// </summary>
[JsonProperty("before")]
public string Before { get; set; }
/// <summary>
/// Limit to records created within certain times.
/// </summary>
[JsonProperty("created_at")]
public CreatedAtParam CreatedAt { get; set; }
/// <summary>
/// Specify filters to limit records by creation time.
/// </summary>
public class CreatedAtParam
{
/// <summary>
/// Limit to records created after the specified date-time.
/// </summary>
[JsonProperty("gt")]
public DateTimeOffset? GreaterThan { get; set; }
/// <summary>
/// Limit to records created on or after the specified date-time.
/// </summary>
[JsonProperty("gte")]
public DateTimeOffset? GreaterThanOrEqual { get; set; }
/// <summary>
/// Limit to records created before the specified date-time.
/// </summary>
[JsonProperty("lt")]
public DateTimeOffset? LessThan { get; set; }
/// <summary>
///Limit to records created on or before the specified date-time.
/// </summary>
[JsonProperty("lte")]
public DateTimeOffset? LessThanOrEqual { get; set; }
}
/// <summary>
/// ID of a [creditor](#core-endpoints-creditors). If specified, this
/// endpoint will return all mandates for the given creditor. Cannot be
/// used in conjunction with `customer` or `customer_bank_account`
/// </summary>
[JsonProperty("creditor")]
public string Creditor { get; set; }
/// <summary>
/// ID of a [customer](#core-endpoints-customers). If specified, this
/// endpoint will return all mandates for the given customer. Cannot be
/// used in conjunction with `customer_bank_account` or `creditor`
/// </summary>
[JsonProperty("customer")]
public string Customer { get; set; }
/// <summary>
/// ID of a [customer bank
/// account](#core-endpoints-customer-bank-accounts). If specified, this
/// endpoint will return all mandates for the given bank account. Cannot
/// be used in conjunction with `customer` or `creditor`
/// </summary>
[JsonProperty("customer_bank_account")]
public string CustomerBankAccount { get; set; }
/// <summary>
/// Number of records to return.
/// </summary>
[JsonProperty("limit")]
public int? Limit { get; set; }
/// <summary>
/// Unique reference. Different schemes have different length and
/// [character set](#appendix-character-sets) requirements. GoCardless
/// will generate a unique reference satisfying the different scheme
/// requirements if this field is left blank.
/// </summary>
[JsonProperty("reference")]
public string Reference { get; set; }
/// <summary>
/// Scheme you'd like to retrieve mandates for
/// </summary>
[JsonProperty("scheme")]
public string[] Scheme { get; set; }
/// <summary>
/// At most four valid status values
/// </summary>
[JsonProperty("status")]
public MandateStatus[] Status { get; set; }
/// <summary>
/// One of:
/// <ul>
/// <li>`pending_customer_approval`: the mandate has not yet been signed
/// by the second customer</li>
/// <li>`pending_submission`: the mandate has not yet been submitted to
/// the customer's bank</li>
/// <li>`submitted`: the mandate has been submitted to the customer's
/// bank but has not been processed yet</li>
/// <li>`active`: the mandate has been successfully set up by the
/// customer's bank</li>
/// <li>`failed`: the mandate could not be created</li>
/// <li>`cancelled`: the mandate has been cancelled</li>
/// <li>`expired`: the mandate has expired due to dormancy</li>
/// <li>`consumed`: the mandate has been consumed and cannot be reused
/// (note that this only applies to schemes that are per-payment
/// authorised)</li>
/// <li>`blocked`: the mandate has been blocked and payments cannot be
/// created</li>
/// </ul>
/// </summary>
[JsonConverter(typeof(StringEnumConverter))]
public enum MandateStatus
{
/// <summary>`status` with a value of "pending_customer_approval"</summary>
[EnumMember(Value = "pending_customer_approval")]
PendingCustomerApproval,
/// <summary>`status` with a value of "pending_submission"</summary>
[EnumMember(Value = "pending_submission")]
PendingSubmission,
/// <summary>`status` with a value of "submitted"</summary>
[EnumMember(Value = "submitted")]
Submitted,
/// <summary>`status` with a value of "active"</summary>
[EnumMember(Value = "active")]
Active,
/// <summary>`status` with a value of "failed"</summary>
[EnumMember(Value = "failed")]
Failed,
/// <summary>`status` with a value of "cancelled"</summary>
[EnumMember(Value = "cancelled")]
Cancelled,
/// <summary>`status` with a value of "expired"</summary>
[EnumMember(Value = "expired")]
Expired,
/// <summary>`status` with a value of "consumed"</summary>
[EnumMember(Value = "consumed")]
Consumed,
/// <summary>`status` with a value of "blocked"</summary>
[EnumMember(Value = "blocked")]
Blocked,
}
}
/// <summary>
/// Retrieves the details of an existing mandate.
/// </summary>
public class MandateGetRequest
{
}
/// <summary>
/// Updates a mandate object. This accepts only the metadata parameter.
/// </summary>
public class MandateUpdateRequest
{
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with key
/// names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<String, String> Metadata { get; set; }
}
/// <summary>
/// Immediately cancels a mandate and all associated cancellable payments.
/// Any metadata supplied to this endpoint will be stored on the mandate
/// cancellation event it causes.
///
/// This will fail with a `cancellation_failed` error if the mandate is
/// already cancelled.
/// </summary>
public class MandateCancelRequest
{
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with key
/// names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<String, String> Metadata { get; set; }
}
/// <summary>
/// <a name="mandate_not_inactive"></a>Reinstates a cancelled or expired
/// mandate to the banks. You will receive a `resubmission_requested`
/// webhook, but after that reinstating the mandate follows the same process
/// as its initial creation, so you will receive a `submitted` webhook,
/// followed by a `reinstated` or `failed` webhook up to two working days
/// later. Any metadata supplied to this endpoint will be stored on the
/// `resubmission_requested` event it causes.
///
/// This will fail with a `mandate_not_inactive` error if the mandate is
/// already being submitted, or is active.
///
/// Mandates can be resubmitted up to 10 times.
/// </summary>
public class MandateReinstateRequest
{
/// <summary>
/// Key-value store of custom data. Up to 3 keys are permitted, with key
/// names up to 50 characters and values up to 500 characters.
/// </summary>
[JsonProperty("metadata")]
public IDictionary<String, String> Metadata { get; set; }
}
/// <summary>
/// An API response for a request returning a single mandate.
/// </summary>
public class MandateResponse : ApiResponse
{
/// <summary>
/// The mandate from the response.
/// </summary>
[JsonProperty("mandates")]
public Mandate Mandate { get; private set; }
}
/// <summary>
/// An API response for a request returning a list of mandates.
/// </summary>
public class MandateListResponse : ApiResponse
{
/// <summary>
/// The list of mandates from the response.
/// </summary>
[JsonProperty("mandates")]
public IReadOnlyList<Mandate> Mandates { get; private set; }
/// <summary>
/// Response metadata (e.g. pagination cursors)
/// </summary>
public Meta Meta { get; private set; }
}
}
| |
/*
* 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 redshift-2012-12-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.Redshift.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.Redshift.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for Snapshot Object
/// </summary>
public class SnapshotUnmarshaller : IUnmarshaller<Snapshot, XmlUnmarshallerContext>, IUnmarshaller<Snapshot, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Snapshot Unmarshall(XmlUnmarshallerContext context)
{
Snapshot unmarshalledObject = new Snapshot();
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("AccountsWithRestoreAccess/AccountWithRestoreAccess", targetDepth))
{
var unmarshaller = AccountWithRestoreAccessUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.AccountsWithRestoreAccess.Add(item);
continue;
}
if (context.TestExpression("ActualIncrementalBackupSizeInMegaBytes", targetDepth))
{
var unmarshaller = DoubleUnmarshaller.Instance;
unmarshalledObject.ActualIncrementalBackupSizeInMegaBytes = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("AvailabilityZone", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.AvailabilityZone = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("BackupProgressInMegaBytes", targetDepth))
{
var unmarshaller = DoubleUnmarshaller.Instance;
unmarshalledObject.BackupProgressInMegaBytes = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterCreateTime", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
unmarshalledObject.ClusterCreateTime = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterIdentifier", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ClusterIdentifier = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ClusterVersion", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.ClusterVersion = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("CurrentBackupRateInMegaBytesPerSecond", targetDepth))
{
var unmarshaller = DoubleUnmarshaller.Instance;
unmarshalledObject.CurrentBackupRateInMegaBytesPerSecond = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("DBName", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.DBName = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ElapsedTimeInSeconds", targetDepth))
{
var unmarshaller = LongUnmarshaller.Instance;
unmarshalledObject.ElapsedTimeInSeconds = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Encrypted", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.Encrypted = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("EncryptedWithHSM", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.EncryptedWithHSM = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("EstimatedSecondsToCompletion", targetDepth))
{
var unmarshaller = LongUnmarshaller.Instance;
unmarshalledObject.EstimatedSecondsToCompletion = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("KmsKeyId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.KmsKeyId = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("MasterUsername", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.MasterUsername = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("NodeType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.NodeType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("NumberOfNodes", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.NumberOfNodes = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("OwnerAccount", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.OwnerAccount = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Port", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.Port = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("RestorableNodeTypes/NodeType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.RestorableNodeTypes.Add(item);
continue;
}
if (context.TestExpression("SnapshotCreateTime", targetDepth))
{
var unmarshaller = DateTimeUnmarshaller.Instance;
unmarshalledObject.SnapshotCreateTime = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("SnapshotIdentifier", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.SnapshotIdentifier = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("SnapshotType", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.SnapshotType = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("SourceRegion", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.SourceRegion = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Status", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Status = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("Tags/Tag", targetDepth))
{
var unmarshaller = TagUnmarshaller.Instance;
var item = unmarshaller.Unmarshall(context);
unmarshalledObject.Tags.Add(item);
continue;
}
if (context.TestExpression("TotalBackupSizeInMegaBytes", targetDepth))
{
var unmarshaller = DoubleUnmarshaller.Instance;
unmarshalledObject.TotalBackupSizeInMegaBytes = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("VpcId", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.VpcId = unmarshaller.Unmarshall(context);
continue;
}
}
else if (context.IsEndElement && context.CurrentDepth < originalDepth)
{
return unmarshalledObject;
}
}
return unmarshalledObject;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public Snapshot Unmarshall(JsonUnmarshallerContext context)
{
return null;
}
private static SnapshotUnmarshaller _instance = new SnapshotUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static SnapshotUnmarshaller Instance
{
get
{
return _instance;
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Firestore.V1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.Grpc;
using Google.Protobuf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedFirestoreClientSnippets
{
/// <summary>Snippet for GetDocument</summary>
public void GetDocumentRequestObject()
{
// Snippet: GetDocument(GetDocumentRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
GetDocumentRequest request = new GetDocumentRequest
{
Name = "",
Mask = new DocumentMask(),
Transaction = ByteString.Empty,
};
// Make the request
Document response = firestoreClient.GetDocument(request);
// End snippet
}
/// <summary>Snippet for GetDocumentAsync</summary>
public async Task GetDocumentRequestObjectAsync()
{
// Snippet: GetDocumentAsync(GetDocumentRequest, CallSettings)
// Additional: GetDocumentAsync(GetDocumentRequest, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
GetDocumentRequest request = new GetDocumentRequest
{
Name = "",
Mask = new DocumentMask(),
Transaction = ByteString.Empty,
};
// Make the request
Document response = await firestoreClient.GetDocumentAsync(request);
// End snippet
}
/// <summary>Snippet for ListDocuments</summary>
public void ListDocumentsRequestObject()
{
// Snippet: ListDocuments(ListDocumentsRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
ListDocumentsRequest request = new ListDocumentsRequest
{
Parent = "",
CollectionId = "",
OrderBy = "",
Mask = new DocumentMask(),
Transaction = ByteString.Empty,
ShowMissing = false,
};
// Make the request
PagedEnumerable<ListDocumentsResponse, Document> response = firestoreClient.ListDocuments(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Document item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListDocumentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Document item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Document> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Document item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListDocumentsAsync</summary>
public async Task ListDocumentsRequestObjectAsync()
{
// Snippet: ListDocumentsAsync(ListDocumentsRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
ListDocumentsRequest request = new ListDocumentsRequest
{
Parent = "",
CollectionId = "",
OrderBy = "",
Mask = new DocumentMask(),
Transaction = ByteString.Empty,
ShowMissing = false,
};
// Make the request
PagedAsyncEnumerable<ListDocumentsResponse, Document> response = firestoreClient.ListDocumentsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Document item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListDocumentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Document item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Document> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Document item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for UpdateDocument</summary>
public void UpdateDocumentRequestObject()
{
// Snippet: UpdateDocument(UpdateDocumentRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
UpdateDocumentRequest request = new UpdateDocumentRequest
{
Document = new Document(),
UpdateMask = new DocumentMask(),
Mask = new DocumentMask(),
CurrentDocument = new Precondition(),
};
// Make the request
Document response = firestoreClient.UpdateDocument(request);
// End snippet
}
/// <summary>Snippet for UpdateDocumentAsync</summary>
public async Task UpdateDocumentRequestObjectAsync()
{
// Snippet: UpdateDocumentAsync(UpdateDocumentRequest, CallSettings)
// Additional: UpdateDocumentAsync(UpdateDocumentRequest, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
UpdateDocumentRequest request = new UpdateDocumentRequest
{
Document = new Document(),
UpdateMask = new DocumentMask(),
Mask = new DocumentMask(),
CurrentDocument = new Precondition(),
};
// Make the request
Document response = await firestoreClient.UpdateDocumentAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateDocument</summary>
public void UpdateDocument()
{
// Snippet: UpdateDocument(Document, DocumentMask, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
Document document = new Document();
DocumentMask updateMask = new DocumentMask();
// Make the request
Document response = firestoreClient.UpdateDocument(document, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateDocumentAsync</summary>
public async Task UpdateDocumentAsync()
{
// Snippet: UpdateDocumentAsync(Document, DocumentMask, CallSettings)
// Additional: UpdateDocumentAsync(Document, DocumentMask, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
Document document = new Document();
DocumentMask updateMask = new DocumentMask();
// Make the request
Document response = await firestoreClient.UpdateDocumentAsync(document, updateMask);
// End snippet
}
/// <summary>Snippet for DeleteDocument</summary>
public void DeleteDocumentRequestObject()
{
// Snippet: DeleteDocument(DeleteDocumentRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
DeleteDocumentRequest request = new DeleteDocumentRequest
{
Name = "",
CurrentDocument = new Precondition(),
};
// Make the request
firestoreClient.DeleteDocument(request);
// End snippet
}
/// <summary>Snippet for DeleteDocumentAsync</summary>
public async Task DeleteDocumentRequestObjectAsync()
{
// Snippet: DeleteDocumentAsync(DeleteDocumentRequest, CallSettings)
// Additional: DeleteDocumentAsync(DeleteDocumentRequest, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
DeleteDocumentRequest request = new DeleteDocumentRequest
{
Name = "",
CurrentDocument = new Precondition(),
};
// Make the request
await firestoreClient.DeleteDocumentAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteDocument</summary>
public void DeleteDocument()
{
// Snippet: DeleteDocument(string, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
firestoreClient.DeleteDocument(name);
// End snippet
}
/// <summary>Snippet for DeleteDocumentAsync</summary>
public async Task DeleteDocumentAsync()
{
// Snippet: DeleteDocumentAsync(string, CallSettings)
// Additional: DeleteDocumentAsync(string, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
await firestoreClient.DeleteDocumentAsync(name);
// End snippet
}
/// <summary>Snippet for BatchGetDocuments</summary>
public async Task BatchGetDocumentsRequestObject()
{
// Snippet: BatchGetDocuments(BatchGetDocumentsRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
BatchGetDocumentsRequest request = new BatchGetDocumentsRequest
{
Database = "",
Documents = { "", },
Mask = new DocumentMask(),
Transaction = ByteString.Empty,
};
// Make the request, returning a streaming response
FirestoreClient.BatchGetDocumentsStream response = firestoreClient.BatchGetDocuments(request);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<BatchGetDocumentsResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
BatchGetDocumentsResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for BeginTransaction</summary>
public void BeginTransactionRequestObject()
{
// Snippet: BeginTransaction(BeginTransactionRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
BeginTransactionRequest request = new BeginTransactionRequest
{
Database = "",
Options = new TransactionOptions(),
};
// Make the request
BeginTransactionResponse response = firestoreClient.BeginTransaction(request);
// End snippet
}
/// <summary>Snippet for BeginTransactionAsync</summary>
public async Task BeginTransactionRequestObjectAsync()
{
// Snippet: BeginTransactionAsync(BeginTransactionRequest, CallSettings)
// Additional: BeginTransactionAsync(BeginTransactionRequest, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
BeginTransactionRequest request = new BeginTransactionRequest
{
Database = "",
Options = new TransactionOptions(),
};
// Make the request
BeginTransactionResponse response = await firestoreClient.BeginTransactionAsync(request);
// End snippet
}
/// <summary>Snippet for BeginTransaction</summary>
public void BeginTransaction()
{
// Snippet: BeginTransaction(string, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
string database = "";
// Make the request
BeginTransactionResponse response = firestoreClient.BeginTransaction(database);
// End snippet
}
/// <summary>Snippet for BeginTransactionAsync</summary>
public async Task BeginTransactionAsync()
{
// Snippet: BeginTransactionAsync(string, CallSettings)
// Additional: BeginTransactionAsync(string, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
string database = "";
// Make the request
BeginTransactionResponse response = await firestoreClient.BeginTransactionAsync(database);
// End snippet
}
/// <summary>Snippet for Commit</summary>
public void CommitRequestObject()
{
// Snippet: Commit(CommitRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
CommitRequest request = new CommitRequest
{
Database = "",
Writes = { new Write(), },
Transaction = ByteString.Empty,
};
// Make the request
CommitResponse response = firestoreClient.Commit(request);
// End snippet
}
/// <summary>Snippet for CommitAsync</summary>
public async Task CommitRequestObjectAsync()
{
// Snippet: CommitAsync(CommitRequest, CallSettings)
// Additional: CommitAsync(CommitRequest, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
CommitRequest request = new CommitRequest
{
Database = "",
Writes = { new Write(), },
Transaction = ByteString.Empty,
};
// Make the request
CommitResponse response = await firestoreClient.CommitAsync(request);
// End snippet
}
/// <summary>Snippet for Commit</summary>
public void Commit()
{
// Snippet: Commit(string, IEnumerable<Write>, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
string database = "";
IEnumerable<Write> writes = new Write[] { new Write(), };
// Make the request
CommitResponse response = firestoreClient.Commit(database, writes);
// End snippet
}
/// <summary>Snippet for CommitAsync</summary>
public async Task CommitAsync()
{
// Snippet: CommitAsync(string, IEnumerable<Write>, CallSettings)
// Additional: CommitAsync(string, IEnumerable<Write>, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
string database = "";
IEnumerable<Write> writes = new Write[] { new Write(), };
// Make the request
CommitResponse response = await firestoreClient.CommitAsync(database, writes);
// End snippet
}
/// <summary>Snippet for Rollback</summary>
public void RollbackRequestObject()
{
// Snippet: Rollback(RollbackRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
RollbackRequest request = new RollbackRequest
{
Database = "",
Transaction = ByteString.Empty,
};
// Make the request
firestoreClient.Rollback(request);
// End snippet
}
/// <summary>Snippet for RollbackAsync</summary>
public async Task RollbackRequestObjectAsync()
{
// Snippet: RollbackAsync(RollbackRequest, CallSettings)
// Additional: RollbackAsync(RollbackRequest, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
RollbackRequest request = new RollbackRequest
{
Database = "",
Transaction = ByteString.Empty,
};
// Make the request
await firestoreClient.RollbackAsync(request);
// End snippet
}
/// <summary>Snippet for Rollback</summary>
public void Rollback()
{
// Snippet: Rollback(string, ByteString, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
string database = "";
ByteString transaction = ByteString.Empty;
// Make the request
firestoreClient.Rollback(database, transaction);
// End snippet
}
/// <summary>Snippet for RollbackAsync</summary>
public async Task RollbackAsync()
{
// Snippet: RollbackAsync(string, ByteString, CallSettings)
// Additional: RollbackAsync(string, ByteString, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
string database = "";
ByteString transaction = ByteString.Empty;
// Make the request
await firestoreClient.RollbackAsync(database, transaction);
// End snippet
}
/// <summary>Snippet for RunQuery</summary>
public async Task RunQueryRequestObject()
{
// Snippet: RunQuery(RunQueryRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
RunQueryRequest request = new RunQueryRequest
{
Parent = "",
StructuredQuery = new StructuredQuery(),
Transaction = ByteString.Empty,
};
// Make the request, returning a streaming response
FirestoreClient.RunQueryStream response = firestoreClient.RunQuery(request);
// Read streaming responses from server until complete
// Note that C# 8 code can use await foreach
AsyncResponseStream<RunQueryResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
RunQueryResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
// End snippet
}
/// <summary>Snippet for PartitionQuery</summary>
public void PartitionQueryRequestObject()
{
// Snippet: PartitionQuery(PartitionQueryRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
PartitionQueryRequest request = new PartitionQueryRequest
{
Parent = "",
StructuredQuery = new StructuredQuery(),
PartitionCount = 0L,
};
// Make the request
PagedEnumerable<PartitionQueryResponse, Cursor> response = firestoreClient.PartitionQuery(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (Cursor item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (PartitionQueryResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Cursor item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Cursor> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Cursor item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for PartitionQueryAsync</summary>
public async Task PartitionQueryRequestObjectAsync()
{
// Snippet: PartitionQueryAsync(PartitionQueryRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
PartitionQueryRequest request = new PartitionQueryRequest
{
Parent = "",
StructuredQuery = new StructuredQuery(),
PartitionCount = 0L,
};
// Make the request
PagedAsyncEnumerable<PartitionQueryResponse, Cursor> response = firestoreClient.PartitionQueryAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((Cursor item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((PartitionQueryResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Cursor item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Cursor> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Cursor item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for Write</summary>
public async Task Write()
{
// Snippet: Write(CallSettings, BidirectionalStreamingSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize streaming call, retrieving the stream object
FirestoreClient.WriteStream response = firestoreClient.Write();
// Sending requests and retrieving responses can be arbitrarily interleaved
// Exact sequence will depend on client/server behavior
// Create task to do something with responses from server
Task responseHandlerTask = Task.Run(async () =>
{
// Note that C# 8 code can use await foreach
AsyncResponseStream<WriteResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
WriteResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
});
// Send requests to the server
bool done = false;
while (!done)
{
// Initialize a request
WriteRequest request = new WriteRequest
{
Database = "",
StreamId = "",
Writes = { new Write(), },
StreamToken = ByteString.Empty,
Labels = { { "", "" }, },
};
// Stream a request to the server
await response.WriteAsync(request);
// Set "done" to true when sending requests is complete
}
// Complete writing requests to the stream
await response.WriteCompleteAsync();
// Await the response handler
// This will complete once all server responses have been processed
await responseHandlerTask;
// End snippet
}
/// <summary>Snippet for Listen</summary>
public async Task Listen()
{
// Snippet: Listen(CallSettings, BidirectionalStreamingSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize streaming call, retrieving the stream object
FirestoreClient.ListenStream response = firestoreClient.Listen();
// Sending requests and retrieving responses can be arbitrarily interleaved
// Exact sequence will depend on client/server behavior
// Create task to do something with responses from server
Task responseHandlerTask = Task.Run(async () =>
{
// Note that C# 8 code can use await foreach
AsyncResponseStream<ListenResponse> responseStream = response.GetResponseStream();
while (await responseStream.MoveNextAsync())
{
ListenResponse responseItem = responseStream.Current;
// Do something with streamed response
}
// The response stream has completed
});
// Send requests to the server
bool done = false;
while (!done)
{
// Initialize a request
ListenRequest request = new ListenRequest
{
Database = "",
AddTarget = new Target(),
Labels = { { "", "" }, },
};
// Stream a request to the server
await response.WriteAsync(request);
// Set "done" to true when sending requests is complete
}
// Complete writing requests to the stream
await response.WriteCompleteAsync();
// Await the response handler
// This will complete once all server responses have been processed
await responseHandlerTask;
// End snippet
}
/// <summary>Snippet for ListCollectionIds</summary>
public void ListCollectionIdsRequestObject()
{
// Snippet: ListCollectionIds(ListCollectionIdsRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
ListCollectionIdsRequest request = new ListCollectionIdsRequest { Parent = "", };
// Make the request
PagedEnumerable<ListCollectionIdsResponse, string> response = firestoreClient.ListCollectionIds(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (string item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListCollectionIdsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (string item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<string> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (string item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCollectionIdsAsync</summary>
public async Task ListCollectionIdsRequestObjectAsync()
{
// Snippet: ListCollectionIdsAsync(ListCollectionIdsRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
ListCollectionIdsRequest request = new ListCollectionIdsRequest { Parent = "", };
// Make the request
PagedAsyncEnumerable<ListCollectionIdsResponse, string> response = firestoreClient.ListCollectionIdsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((string item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListCollectionIdsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (string item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<string> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (string item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCollectionIds</summary>
public void ListCollectionIds()
{
// Snippet: ListCollectionIds(string, string, int?, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedEnumerable<ListCollectionIdsResponse, string> response = firestoreClient.ListCollectionIds(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (string item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListCollectionIdsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (string item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<string> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (string item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListCollectionIdsAsync</summary>
public async Task ListCollectionIdsAsync()
{
// Snippet: ListCollectionIdsAsync(string, string, int?, CallSettings)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedAsyncEnumerable<ListCollectionIdsResponse, string> response = firestoreClient.ListCollectionIdsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((string item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListCollectionIdsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (string item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<string> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (string item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for BatchWrite</summary>
public void BatchWriteRequestObject()
{
// Snippet: BatchWrite(BatchWriteRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
BatchWriteRequest request = new BatchWriteRequest
{
Database = "",
Writes = { new Write(), },
Labels = { { "", "" }, },
};
// Make the request
BatchWriteResponse response = firestoreClient.BatchWrite(request);
// End snippet
}
/// <summary>Snippet for BatchWriteAsync</summary>
public async Task BatchWriteRequestObjectAsync()
{
// Snippet: BatchWriteAsync(BatchWriteRequest, CallSettings)
// Additional: BatchWriteAsync(BatchWriteRequest, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
BatchWriteRequest request = new BatchWriteRequest
{
Database = "",
Writes = { new Write(), },
Labels = { { "", "" }, },
};
// Make the request
BatchWriteResponse response = await firestoreClient.BatchWriteAsync(request);
// End snippet
}
/// <summary>Snippet for CreateDocument</summary>
public void CreateDocumentRequestObject()
{
// Snippet: CreateDocument(CreateDocumentRequest, CallSettings)
// Create client
FirestoreClient firestoreClient = FirestoreClient.Create();
// Initialize request argument(s)
CreateDocumentRequest request = new CreateDocumentRequest
{
Parent = "",
CollectionId = "",
DocumentId = "",
Document = new Document(),
Mask = new DocumentMask(),
};
// Make the request
Document response = firestoreClient.CreateDocument(request);
// End snippet
}
/// <summary>Snippet for CreateDocumentAsync</summary>
public async Task CreateDocumentRequestObjectAsync()
{
// Snippet: CreateDocumentAsync(CreateDocumentRequest, CallSettings)
// Additional: CreateDocumentAsync(CreateDocumentRequest, CancellationToken)
// Create client
FirestoreClient firestoreClient = await FirestoreClient.CreateAsync();
// Initialize request argument(s)
CreateDocumentRequest request = new CreateDocumentRequest
{
Parent = "",
CollectionId = "",
DocumentId = "",
Document = new Document(),
Mask = new DocumentMask(),
};
// Make the request
Document response = await firestoreClient.CreateDocumentAsync(request);
// End snippet
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Indiefreaks.AOP.Profiler;
using Indiefreaks.Xna.Profiler;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
namespace WarZ
{
/// <summary>
/// This is the main type for your game
/// </summary>
public class WarZGame : Microsoft.Xna.Framework.Game
{
private GraphicsDeviceManager graphics;
private GUIManager _GUI;
private Camera _activeCamera; //use ActiveCamera prop
private Camera[] _cameras;
private FPSCamera _fpsCamera;
private TopViewCamera _topViewCamera;
private ChaseCamera _chaseCamera;
private SimpleCamera _aiCamera;
private int cameraNumber;
private Terrain _terrain;
private Axis _3DAxis;
private Skybox _skybox;
private Player _player1;
private AiPlayerManager _aiPlayerManager;
private CollisionSystem _collisionSystem;
private ParticlesManager _particlesManager;
public WarZGame()
{
graphics = new GraphicsDeviceManager(this);
Content.RootDirectory = "Content";
Graphics.SynchronizeWithVerticalRetrace = false;
IsFixedTimeStep = false;
var profilerGameComponent = new ProfilerGameComponent(this, "Fonts/Segoi");
ProfilingManager.Run = false;
Components.Add(profilerGameComponent);
graphics.PreferMultiSampling = true;
}
/// <summary>
/// Allows the game to perform any initialization it needs to before starting to run.
/// This is where it can query for any required services and load any non-graphic
/// related content. Calling base.Initialize will enumerate through any components
/// and initialize them as well.
/// </summary>
protected override void Initialize()
{
Window.Title = "WarZ v" + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
Prepare3DRenderer.Initialize(this);
Song mainTheme = Content.Load<Song>(@"Music/main1");
MediaPlayer.Play(mainTheme);
MediaPlayer.Volume *= 0.7f;
_fpsCamera = new FPSCamera(this, new Vector3(0, 10, 3), Vector3.Zero, Vector3.Up);
_topViewCamera = new TopViewCamera(this, new Vector3(0, 10, 0), Vector3.Zero, Vector3.Forward);
// _chaseCamera = new ChaseCamera(this, new Vector3(0, 10, 3), Vector3.Zero, Vector3.Up);
SimpleCamera simpleCam = new SimpleCamera(this, Vector3.Zero, Vector3.Forward, Vector3.Up);
_aiCamera = new SimpleCamera(this, Vector3.Backward, Vector3.Zero, Vector3.Up);
GodViewCamera godView = new GodViewCamera(this, Vector3.Up * 50, Vector3.Forward * 62.5f + Vector3.Right * 62.5f, Vector3.Up);
_cameras = new Camera[3];
_cameras[0] = _fpsCamera;
_cameras[1] = _topViewCamera;
_cameras[2] = godView;
cameraNumber = 0;
_activeCamera = _fpsCamera;
_3DAxis = new Axis(this, _activeCamera);
_GUI = new GUIManager(this);
_GUI.CrossairVisible = true;
Terrain = new Terrain(this, _activeCamera);
_skybox = new Skybox(this, _activeCamera);
Tank tank = new Tank(this, Content.Load<Model>(@"Models\Tank\DXTank"));
Player1 = new Player(this, _activeCamera, tank, Terrain);
_aiPlayerManager = new AiPlayerManager(this, tank);
_collisionSystem = new CollisionSystem(this, _player1, _aiPlayerManager);
_particlesManager = new ParticlesManager(this);
Components.Add(_skybox);
//Components.Add(_activeCamera);
Components.Add(Player1);
Components.Add(_3DAxis);
Components.Add(Terrain);
Components.Add(_aiPlayerManager);
Components.Add(_collisionSystem);
Components.Add(_particlesManager);
Components.Add(_GUI);
_aiPlayerManager.AddBot(_aiCamera, Vector3.Backward * 10 + Vector3.Right * 20);
_aiPlayerManager.AddBot(_aiCamera, Vector3.Backward * 10 + Vector3.Right * 10);
_aiPlayerManager.AddBot(_aiCamera, Vector3.Backward * 10 + Vector3.Right * 10);
_aiPlayerManager.AddBot(_aiCamera, Vector3.Backward * 10 + Vector3.Right * 10);
_aiPlayerManager.AddBot(_aiCamera, Vector3.Backward * 10 + Vector3.Right * 10);
base.Initialize();
}
/// <summary>
/// LoadContent will be called once per game and is the place to load
/// all of your content.
/// </summary>
protected override void LoadContent()
{
}
/// <summary>
/// UnloadContent will be called once per game and is the place to unload
/// all content.
/// </summary>
protected override void UnloadContent()
{
// TODO: Unload any non ContentManager content here
}
/// <summary>
/// Allows the game to run logic such as updating the world,
/// checking for collisions, gathering input, and playing audio.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Update(GameTime gameTime)
{
// Allows the game to exit
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed ||
Keyboard.GetState(PlayerIndex.One).IsKeyDown(Keys.Escape))
this.Exit();
KeyboardHelper.Update(); //Handles the keyboard input
MouseHelper.Update();
_terrain.LimitsCollisionCheckWithReposition(_player1);
//_activeCamera.ApplySurfaceFollow(_terrain);
//checkLimits();
if (KeyboardHelper.IsKeyPressed(Keys.V))
ChangeCamera();
base.Update(gameTime);
}
private void ChangeCamera()
{
cameraNumber = ++cameraNumber % _cameras.Length;
ActiveCamera = _cameras[cameraNumber];
}
/// <summary>
/// Checks Terrain limits
/// </summary>
private void checkLimits()
{
Vector3 position = _fpsCamera.Position;
if (position.X < 0.1f)
position.X = 0.5f;
if (position.Z > -0.1f)
position.Z = -0.5f;
if (position.Z < -Terrain.Width + 2)
position.Z = -Terrain.Width + 4;
if (position.X > Terrain.Height - 2)
position.X = Terrain.Height - 4;
_fpsCamera.Position = position;
}
/// <summary>
/// This is called when the game should draw itself.
/// </summary>
/// <param name="gameTime">Provides a snapshot of timing values.</param>
protected override void Draw(GameTime gameTime)
{
GraphicsDevice.Clear(Color.Black);
base.Draw(gameTime);
}
public Camera ActiveCamera
{
get { return _activeCamera; }
set
{
_activeCamera = value;
if (_activeCamera is TopViewCamera || _activeCamera is GodViewCamera)
_GUI.CrossairVisible = false;
else
_GUI.CrossairVisible = true;
foreach (var component in Components)
{
IGotCamera gotCameraComponent = component as IGotCamera;
if (gotCameraComponent != null)
gotCameraComponent.Camera = _activeCamera;
}
}
}
public Terrain Terrain
{
get { return _terrain; }
set { _terrain = value; }
}
public Player Player1
{
get { return _player1; }
set { _player1 = value; }
}
public GraphicsDeviceManager Graphics
{
get { return graphics; }
}
public ParticlesManager ParticlesManager
{
get { return _particlesManager; }
set { _particlesManager = value; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Orleans.Configuration;
using Orleans.Runtime.GrainDirectory;
using Orleans.Runtime.Messaging;
using Orleans.Runtime.Placement;
using Orleans.Runtime.Scheduler;
using Orleans.Runtime.Versions;
namespace Orleans.Runtime
{
internal class Dispatcher
{
private readonly MessageCenter messageCenter;
private readonly RuntimeMessagingTrace messagingTrace;
private readonly OrleansTaskScheduler scheduler;
private readonly Catalog catalog;
private readonly ILogger logger;
private readonly SiloMessagingOptions messagingOptions;
private readonly PlacementService placementService;
private readonly MessageFactory messageFactory;
private readonly ActivationDirectory activationDirectory;
private readonly ILocalGrainDirectory localGrainDirectory;
internal Dispatcher(
OrleansTaskScheduler scheduler,
MessageCenter messageCenter,
Catalog catalog,
IOptionsMonitor<SiloMessagingOptions> messagingOptions,
PlacementService placementService,
ILocalGrainDirectory localGrainDirectory,
MessageFactory messageFactory,
ILoggerFactory loggerFactory,
ActivationDirectory activationDirectory,
RuntimeMessagingTrace messagingTrace)
{
this.scheduler = scheduler;
this.catalog = catalog;
this.messageCenter = messageCenter;
this.messagingOptions = messagingOptions.CurrentValue;
this.placementService = placementService;
this.localGrainDirectory = localGrainDirectory;
this.messageFactory = messageFactory;
this.activationDirectory = activationDirectory;
this.messagingTrace = messagingTrace;
this.logger = loggerFactory.CreateLogger<Dispatcher>();
messageCenter.SetDispatcher(this);
}
public InsideRuntimeClient RuntimeClient => this.catalog.RuntimeClient;
public void RejectMessage(
Message message,
Message.RejectionTypes rejectionType,
Exception exc,
string rejectInfo = null)
{
if (message.Direction == Message.Directions.Request
|| (message.Direction == Message.Directions.OneWay && message.HasCacheInvalidationHeader))
{
this.messagingTrace.OnDispatcherRejectMessage(message, rejectionType, rejectInfo, exc);
var str = string.Format("{0} {1}", rejectInfo ?? "", exc == null ? "" : exc.ToString());
var rejection = this.messageFactory.CreateRejectionResponse(message, rejectionType, str, exc);
messageCenter.SendMessage(rejection);
}
else
{
this.messagingTrace.OnDispatcherDiscardedRejection(message, rejectionType, rejectInfo, exc);
}
}
internal void ProcessRequestsToInvalidActivation(
List<Message> messages,
ActivationAddress oldAddress,
ActivationAddress forwardingAddress,
string failedOperation,
Exception exc = null,
bool rejectMessages = false)
{
// IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already.
scheduler.QueueAction(
() =>
{
foreach (var message in messages)
{
if (rejectMessages)
{
RejectMessage(message, Message.RejectionTypes.Transient, exc, failedOperation);
}
else
{
this.messagingTrace.OnDispatcherForwardingMultiple(messages.Count, oldAddress, forwardingAddress, failedOperation, exc);
TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc);
}
}
},
catalog);
}
internal void ProcessRequestToInvalidActivation(
Message message,
ActivationAddress oldAddress,
ActivationAddress forwardingAddress,
string failedOperation,
Exception exc = null,
bool rejectMessages = false)
{
// Just use this opportunity to invalidate local Cache Entry as well.
if (oldAddress != null)
{
this.localGrainDirectory.InvalidateCacheEntry(oldAddress);
}
// IMPORTANT: do not do anything on activation context anymore, since this activation is invalid already.
if (rejectMessages)
{
this.RejectMessage(message, Message.RejectionTypes.Transient, exc, failedOperation);
}
else
{
this.TryForwardRequest(message, oldAddress, forwardingAddress, failedOperation, exc);
}
}
public void ProcessRequestToStuckActivation(
Message message,
ActivationData activationData,
string failedOperation)
{
scheduler.RunOrQueueTask(
async () =>
{
await catalog.DeactivateStuckActivation(activationData);
TryForwardRequest(message, activationData.Address, activationData.ForwardingAddress, failedOperation);
},
catalog)
.Ignore();
}
internal void TryForwardRequest(Message message, ActivationAddress oldAddress, ActivationAddress forwardingAddress, string failedOperation, Exception exc = null)
{
bool forwardingSucceded = false;
try
{
this.messagingTrace.OnDispatcherForwarding(message, oldAddress, forwardingAddress, failedOperation, exc);
if (oldAddress != null)
{
message.AddToCacheInvalidationHeader(oldAddress);
}
forwardingSucceded = this.TryForwardMessage(message, forwardingAddress);
}
catch (Exception exc2)
{
forwardingSucceded = false;
exc = exc2;
}
finally
{
var sentRejection = false;
// If the message was a one-way message, send a cache invalidation response even if the message was successfully forwarded.
if (message.Direction == Message.Directions.OneWay)
{
this.RejectMessage(
message,
Message.RejectionTypes.CacheInvalidation,
exc,
"OneWay message sent to invalid activation");
sentRejection = true;
}
if (!forwardingSucceded)
{
this.messagingTrace.OnDispatcherForwardingFailed(message, oldAddress, forwardingAddress, failedOperation, exc);
if (!sentRejection)
{
var str = $"Forwarding failed: tried to forward message {message} for {message.ForwardCount} times after {failedOperation} to invalid activation. Rejecting now.";
RejectMessage(message, Message.RejectionTypes.Transient, exc, str);
}
}
}
}
/// <summary>
/// Reroute a message coming in through a gateway
/// </summary>
/// <param name="message"></param>
internal void RerouteMessage(Message message)
{
ResendMessageImpl(message);
}
internal bool TryForwardMessage(Message message, ActivationAddress forwardingAddress)
{
if (!MayForward(message, this.messagingOptions)) return false;
message.ForwardCount = message.ForwardCount + 1;
MessagingProcessingStatisticsGroup.OnDispatcherMessageForwared(message);
ResendMessageImpl(message, forwardingAddress);
return true;
}
private void ResendMessageImpl(Message message, ActivationAddress forwardingAddress = null)
{
if (logger.IsEnabled(LogLevel.Debug)) logger.Debug("Resend {0}", message);
message.TargetHistory = message.GetTargetHistory();
if (message.TargetGrain.IsSystemTarget())
{
this.PrepareSystemTargetMessage(message);
this.messageCenter.SendMessage(message);
}
else if (forwardingAddress != null)
{
message.TargetAddress = forwardingAddress;
message.IsNewPlacement = false;
this.messageCenter.SendMessage(message);
}
else
{
message.TargetActivation = default;
message.TargetSilo = null;
message.ClearTargetAddress();
this.SendMessage(message);
}
}
// Forwarding is used by the receiver, usually when it cannot process the message and forwards it to another silo to perform the processing
// (got here due to duplicate activation, outdated cache, silo is shutting down/overloaded, ...).
private static bool MayForward(Message message, SiloMessagingOptions messagingOptions)
{
return message.ForwardCount < messagingOptions.MaxForwardCount
// allow one more forward hop for multi-cluster case
+ (message.IsReturnedFromRemoteCluster ? 1 : 0);
}
/// <summary>
/// Send an outgoing message, may complete synchronously
/// - may buffer for transaction completion / commit if it ends a transaction
/// - choose target placement address, maintaining send order
/// - add ordering info and maintain send order
///
/// </summary>
internal Task SendMessage(Message message, IGrainContext sendingActivation = null)
{
try
{
var messageAddressingTask = AddressMessage(message);
if (messageAddressingTask.Status != TaskStatus.RanToCompletion)
{
return SendMessageAsync(messageAddressingTask, message, sendingActivation);
}
messageCenter.SendMessage(message);
}
catch (Exception ex)
{
OnAddressingFailure(message, sendingActivation, ex);
}
return Task.CompletedTask;
async Task SendMessageAsync(Task addressMessageTask, Message m, IGrainContext activation)
{
try
{
await addressMessageTask;
}
catch (Exception ex)
{
OnAddressingFailure(m, activation, ex);
return;
}
messageCenter.SendMessage(m);
}
void OnAddressingFailure(Message m, IGrainContext activation, Exception ex)
{
this.messagingTrace.OnDispatcherSelectTargetFailed(m, activation, ex);
RejectMessage(m, Message.RejectionTypes.Unrecoverable, ex);
}
}
/// <summary>
/// Resolve target address for a message
/// </summary>
/// <returns>Resolve when message is addressed (modifies message fields)</returns>
private Task AddressMessage(Message message)
{
var targetAddress = message.TargetAddress;
if (targetAddress is null) throw new InvalidOperationException("Cannot address a message with a null TargetAddress");
if (targetAddress.IsComplete) return Task.CompletedTask;
var target = new PlacementTarget(
message.TargetGrain,
message.RequestContextData,
message.InterfaceType,
message.InterfaceVersion);
var placementTask = placementService.GetOrPlaceActivation(target, this.catalog);
if (placementTask.IsCompletedSuccessfully)
{
SetMessageTargetPlacement(message, placementTask.Result, targetAddress);
return Task.CompletedTask;
}
return AddressMessageAsync(placementTask);
async Task AddressMessageAsync(ValueTask<PlacementResult> addressTask)
{
var placementResult = await addressTask;
SetMessageTargetPlacement(message, placementResult, targetAddress);
}
}
private void SetMessageTargetPlacement(Message message, PlacementResult placementResult, ActivationAddress targetAddress)
{
if (placementResult.IsNewPlacement && targetAddress.Grain.IsClient())
{
logger.Error(ErrorCode.Dispatcher_AddressMsg_UnregisteredClient, $"AddressMessage could not find target for client pseudo-grain {message}");
throw new KeyNotFoundException($"Attempting to send a message {message} to an unregistered client pseudo-grain {targetAddress.Grain}");
}
message.SetTargetPlacement(placementResult);
if (placementResult.IsNewPlacement)
{
CounterStatistic.FindOrCreate(StatisticNames.DISPATCHER_NEW_PLACEMENT).Increment();
}
if (logger.IsEnabled(LogLevel.Trace)) logger.Trace(ErrorCode.Dispatcher_AddressMsg_SelectTarget, "AddressMessage Placement SelectTarget {0}", message);
}
internal void SendResponse(Message request, Response response)
{
// create the response
var message = this.messageFactory.CreateResponseMessage(request);
message.BodyObject = response;
if (message.TargetGrain.IsSystemTarget())
{
PrepareSystemTargetMessage(message);
}
messageCenter.SendMessage(message);
}
internal void PrepareSystemTargetMessage(Message message)
{
message.Category = message.TargetGrain.Equals(Constants.MembershipServiceType) ?
Message.Categories.Ping : Message.Categories.System;
if (message.TargetSilo == null)
{
message.TargetSilo = messageCenter.MyAddress;
}
if (message.TargetActivation is null)
{
message.TargetActivation = ActivationId.GetDeterministic(message.TargetGrain);
}
}
public void ReceiveMessage(Message msg)
{
this.messagingTrace.OnIncomingMessageAgentReceiveMessage(msg);
// Find the activation it targets; first check for a system activation, then an app activation
if (msg.TargetGrain.IsSystemTarget())
{
SystemTarget target = this.activationDirectory.FindSystemTarget(msg.TargetActivation);
if (target == null)
{
MessagingStatisticsGroup.OnRejectedMessage(msg);
this.logger.LogWarning(
(int) ErrorCode.MessagingMessageFromUnknownActivation,
"Received a message {Message} for an unknown SystemTarget: {Target}",
msg, msg.TargetAddress);
// Send a rejection only on a request
if (msg.Direction == Message.Directions.Request)
{
var response = this.messageFactory.CreateRejectionResponse(
msg,
Message.RejectionTypes.Unrecoverable,
$"SystemTarget {msg.TargetGrain} not active on this silo. Msg={msg}");
this.messageCenter.SendMessage(response);
}
return;
}
target.ReceiveMessage(msg);
}
else if (messageCenter.TryDeliverToProxy(msg))
{
return;
}
else
{
try
{
var targetActivation = catalog.GetOrCreateActivation(
msg.TargetAddress,
msg.IsNewPlacement,
msg.RequestContextData);
if (targetActivation is null)
{
// Activation does not exists and is not a new placement.
if (msg.Direction == Message.Directions.Response)
{
logger.LogWarning(
(int)ErrorCode.Dispatcher_NoTargetActivation,
"No target activation {Activation} for response message: {Message}",
msg.TargetActivation,
msg);
return;
}
else
{
logger.LogInformation(
(int)ErrorCode.Dispatcher_Intermediate_GetOrCreateActivation,
"Intermediate NonExistentActivation for message {Message}",
msg);
var nonExistentActivation = msg.TargetAddress;
ProcessRequestToInvalidActivation(msg, nonExistentActivation, null, "Non-existent activation");
return;
}
}
targetActivation.ReceiveMessage(msg);
}
catch (Exception ex)
{
MessagingProcessingStatisticsGroup.OnDispatcherMessageProcessedError(msg);
logger.LogError(
(int)ErrorCode.Dispatcher_ErrorCreatingActivation,
ex,
"Error creating activation for grain {TargetGrain} (interface: {InterfaceType}). Message {Message}",
msg.TargetGrain,
msg.InterfaceType,
msg);
this.RejectMessage(msg, Message.RejectionTypes.Transient, ex);
}
}
}
}
}
| |
// 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.AzureStack.Management.InfrastructureInsights.Admin
{
using Microsoft.AzureStack;
using Microsoft.AzureStack.Management;
using Microsoft.AzureStack.Management.InfrastructureInsights;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
/// <summary>
/// InfrastructureInsights Admin Client
/// </summary>
public partial class InfrastructureInsightsAdminClient : ServiceClient<InfrastructureInsightsAdminClient>, IInfrastructureInsightsAdminClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Subscription credentials which uniquely identify Microsoft Azure
/// subscription.The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IAlertsOperations.
/// </summary>
public virtual IAlertsOperations Alerts { get; private set; }
/// <summary>
/// Gets the IRegionHealthsOperations.
/// </summary>
public virtual IRegionHealthsOperations RegionHealths { get; private set; }
/// <summary>
/// Gets the IResourceHealthsOperations.
/// </summary>
public virtual IResourceHealthsOperations ResourceHealths { get; private set; }
/// <summary>
/// Gets the IServiceHealthsOperations.
/// </summary>
public virtual IServiceHealthsOperations ServiceHealths { get; private set; }
/// <summary>
/// Initializes a new instance of the InfrastructureInsightsAdminClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected InfrastructureInsightsAdminClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the InfrastructureInsightsAdminClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected InfrastructureInsightsAdminClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the InfrastructureInsightsAdminClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected InfrastructureInsightsAdminClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the InfrastructureInsightsAdminClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected InfrastructureInsightsAdminClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the InfrastructureInsightsAdminClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public InfrastructureInsightsAdminClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the InfrastructureInsightsAdminClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public InfrastructureInsightsAdminClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the InfrastructureInsightsAdminClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public InfrastructureInsightsAdminClient(System.Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the InfrastructureInsightsAdminClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public InfrastructureInsightsAdminClient(System.Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new System.ArgumentNullException("credentials");
}
BaseUri = baseUri;
Credentials = credentials;
if (Credentials != null)
{
Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
Alerts = new AlertsOperations(this);
RegionHealths = new RegionHealthsOperations(this);
ResourceHealths = new ResourceHealthsOperations(this);
ServiceHealths = new ServiceHealthsOperations(this);
BaseUri = new System.Uri("https://adminmanagement.local.azurestack.external");
ApiVersion = "2016-05-01";
AcceptLanguage = "en-US";
LongRunningOperationRetryTimeout = 30;
GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;
namespace System.IO.Tests
{
public class FileSystemWatcherTests : FileSystemWatcherTest
{
private static void ValidateDefaults(FileSystemWatcher watcher, string path, string filter)
{
Assert.Equal(false, watcher.EnableRaisingEvents);
Assert.Equal(filter, watcher.Filter);
Assert.Equal(false, watcher.IncludeSubdirectories);
Assert.Equal(8192, watcher.InternalBufferSize);
Assert.Equal(NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, watcher.NotifyFilter);
Assert.Equal(path, watcher.Path);
}
[Fact]
public void FileSystemWatcher_NewFileInfoAction_TriggersNothing()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
Action action = () => new FileInfo(file.Path);
ExpectEvent(watcher, 0, action, expectedPath: file.Path);
}
}
[Fact]
public void FileSystemWatcher_FileInfoGetter_TriggersNothing()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
FileAttributes res;
Action action = () => res = new FileInfo(file.Path).Attributes;
ExpectEvent(watcher, 0, action, expectedPath: file.Path);
}
}
[Fact]
public void FileSystemWatcher_EmptyAction_TriggersNothing()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(testDirectory.Path, "file")))
using (var watcher = new FileSystemWatcher(testDirectory.Path, Path.GetFileName(file.Path)))
{
Action action = () => { };
ExpectEvent(watcher, 0, action, expectedPath: file.Path);
}
}
[Fact]
public void FileSystemWatcher_ctor()
{
string path = String.Empty;
string pattern = "*.*";
using (FileSystemWatcher watcher = new FileSystemWatcher())
ValidateDefaults(watcher, path, pattern);
}
[Fact]
public void FileSystemWatcher_ctor_path()
{
string path = @".";
string pattern = "*.*";
using (FileSystemWatcher watcher = new FileSystemWatcher(path))
ValidateDefaults(watcher, path, pattern);
}
[Fact]
public void FileSystemWatcher_ctor_path_pattern()
{
string path = @".";
string pattern = "honey.jar";
using (FileSystemWatcher watcher = new FileSystemWatcher(path, pattern))
ValidateDefaults(watcher, path, pattern);
}
[Fact]
public void FileSystemWatcher_ctor_NullStrings()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
// Null filter
AssertExtensions.Throws<ArgumentNullException>("filter", () => new FileSystemWatcher(testDirectory.Path, null));
// Null path
AssertExtensions.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null));
AssertExtensions.Throws<ArgumentNullException>("path", () => new FileSystemWatcher(null, "*"));
}
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "On Desktop, these exceptions don't have a parameter")]
public void FileSystemWatcher_ctor_InvalidStrings()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
// Empty path
AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(string.Empty));
AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(string.Empty, "*"));
// Invalid directory
AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(GetTestFilePath()));
AssertExtensions.Throws<ArgumentException>("path", () => new FileSystemWatcher(GetTestFilePath(), "*"));
}
}
[Fact]
public void FileSystemWatcher_Changed()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new FileSystemEventHandler((o, e) => { });
// add / remove
watcher.Changed += handler;
watcher.Changed -= handler;
// shouldn't throw
watcher.Changed -= handler;
}
}
[Fact]
public void FileSystemWatcher_Created()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new FileSystemEventHandler((o, e) => { });
// add / remove
watcher.Created += handler;
watcher.Created -= handler;
// shouldn't throw
watcher.Created -= handler;
}
}
[Fact]
public void FileSystemWatcher_Deleted()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new FileSystemEventHandler((o, e) => { });
// add / remove
watcher.Deleted += handler;
watcher.Deleted -= handler;
// shouldn't throw
watcher.Deleted -= handler;
}
}
[Fact]
public void FileSystemWatcher_Disposed()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Dispose();
watcher.Dispose(); // shouldn't throw
Assert.Throws<ObjectDisposedException>(() => watcher.EnableRaisingEvents = true);
}
[Fact]
public void FileSystemWatcher_EnableRaisingEvents()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
{
FileSystemWatcher watcher = new FileSystemWatcher(testDirectory.Path);
Assert.Equal(false, watcher.EnableRaisingEvents);
watcher.EnableRaisingEvents = true;
Assert.Equal(true, watcher.EnableRaisingEvents);
watcher.EnableRaisingEvents = false;
Assert.Equal(false, watcher.EnableRaisingEvents);
}
}
[Fact]
public void FileSystemWatcher_Error()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new ErrorEventHandler((o, e) => { });
// add / remove
watcher.Error += handler;
watcher.Error -= handler;
// shouldn't throw
watcher.Error -= handler;
}
}
[Fact]
public void FileSystemWatcher_Filter()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal("*.*", watcher.Filter);
// Null and empty should be mapped to "*.*"
watcher.Filter = null;
Assert.Equal("*.*", watcher.Filter);
watcher.Filter = String.Empty;
Assert.Equal("*.*", watcher.Filter);
watcher.Filter = " ";
Assert.Equal(" ", watcher.Filter);
watcher.Filter = "\0";
Assert.Equal("\0", watcher.Filter);
watcher.Filter = "\n";
Assert.Equal("\n", watcher.Filter);
watcher.Filter = "abc.dll";
Assert.Equal("abc.dll", watcher.Filter);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || // expect no change for OrdinalIgnoreCase-equal strings
RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
// expect no change for OrdinalIgnoreCase-equal strings
// it's unclear why desktop does this but preserve it for compat
watcher.Filter = "ABC.DLL";
Assert.Equal("abc.dll", watcher.Filter);
}
// We can make this setting by first changing to another value then back.
watcher.Filter = null;
watcher.Filter = "ABC.DLL";
Assert.Equal("ABC.DLL", watcher.Filter);
}
[Fact]
public void FileSystemWatcher_IncludeSubdirectories()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal(false, watcher.IncludeSubdirectories);
watcher.IncludeSubdirectories = true;
Assert.Equal(true, watcher.IncludeSubdirectories);
watcher.IncludeSubdirectories = false;
Assert.Equal(false, watcher.IncludeSubdirectories);
}
[Fact]
public void FileSystemWatcher_InternalBufferSize()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal(8192, watcher.InternalBufferSize);
watcher.InternalBufferSize = 20000;
Assert.Equal(20000, watcher.InternalBufferSize);
watcher.InternalBufferSize = int.MaxValue;
Assert.Equal(int.MaxValue, watcher.InternalBufferSize);
// FSW enforces a minimum value of 4096
watcher.InternalBufferSize = 0;
Assert.Equal(4096, watcher.InternalBufferSize);
watcher.InternalBufferSize = -1;
Assert.Equal(4096, watcher.InternalBufferSize);
watcher.InternalBufferSize = int.MinValue;
Assert.Equal(4096, watcher.InternalBufferSize);
watcher.InternalBufferSize = 4095;
Assert.Equal(4096, watcher.InternalBufferSize);
}
[Fact]
public void FileSystemWatcher_NotifyFilter()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal(NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName, watcher.NotifyFilter);
var notifyFilters = Enum.GetValues(typeof(NotifyFilters)).Cast<NotifyFilters>();
foreach (NotifyFilters filterValue in notifyFilters)
{
watcher.NotifyFilter = filterValue;
Assert.Equal(filterValue, watcher.NotifyFilter);
}
var allFilters = notifyFilters.Aggregate((mask, flag) => mask | flag);
watcher.NotifyFilter = allFilters;
Assert.Equal(allFilters, watcher.NotifyFilter);
// This doesn't make sense, but it is permitted.
watcher.NotifyFilter = 0;
Assert.Equal((NotifyFilters)0, watcher.NotifyFilter);
// These throw InvalidEnumException on desktop, but ArgumentException on K
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)(-1));
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)int.MinValue);
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = (NotifyFilters)int.MaxValue);
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = allFilters + 1);
// Simulate a bit added to the flags
Assert.ThrowsAny<ArgumentException>(() => watcher.NotifyFilter = allFilters | (NotifyFilters)((int)notifyFilters.Max() << 1));
}
[Fact]
public void FileSystemWatcher_OnChanged()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Changed, "directory", "file");
watcher.Changed += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnChanged(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
public void FileSystemWatcher_OnCreated()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Created, "directory", "file");
watcher.Created += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnCreated(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.OSX | TestPlatforms.Windows)] // Casing matters on Linux
public void FileSystemWatcher_OnCreatedWithMismatchedCasingGivesExpectedFullPath()
{
using (var dir = new TempDirectory(GetTestFilePath()))
using (var fsw = new FileSystemWatcher(dir.Path))
{
AutoResetEvent are = new AutoResetEvent(false);
string fullPath = Path.Combine(dir.Path.ToUpper(), "Foo.txt");
fsw.Created += (o, e) =>
{
Assert.True(fullPath.Equals(e.FullPath, StringComparison.OrdinalIgnoreCase));
are.Set();
};
fsw.EnableRaisingEvents = true;
using (var file = new TempFile(fullPath))
{
ExpectEvent(are, "created");
}
}
}
[Fact]
public void FileSystemWatcher_OnDeleted()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
FileSystemEventArgs actualArgs = null, expectedArgs = new FileSystemEventArgs(WatcherChangeTypes.Deleted, "directory", "file");
watcher.Deleted += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnDeleted(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
public void FileSystemWatcher_OnError()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
ErrorEventArgs actualArgs = null, expectedArgs = new ErrorEventArgs(new Exception());
watcher.Error += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnError(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
public void FileSystemWatcher_OnRenamed()
{
using (TestFileSystemWatcher watcher = new TestFileSystemWatcher())
{
bool eventOccurred = false;
object obj = null;
RenamedEventArgs actualArgs = null, expectedArgs = new RenamedEventArgs(WatcherChangeTypes.Renamed, "directory", "file", "oldFile");
watcher.Renamed += (o, e) =>
{
eventOccurred = true;
obj = o;
actualArgs = e;
};
watcher.CallOnRenamed(expectedArgs);
Assert.True(eventOccurred, "Event should be invoked");
Assert.Equal(watcher, obj);
Assert.Equal(expectedArgs, actualArgs);
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)] // Unix FSW don't trigger on a file rename.
public void FileSystemWatcher_Windows_OnRenameGivesExpectedFullPath()
{
using (var dir = new TempDirectory(GetTestFilePath()))
using (var file = new TempFile(Path.Combine(dir.Path, "file")))
using (var fsw = new FileSystemWatcher(dir.Path))
{
AutoResetEvent eventOccurred = WatchRenamed(fsw);
string newPath = Path.Combine(dir.Path, "newPath");
fsw.Renamed += (o, e) =>
{
Assert.Equal(e.OldFullPath, file.Path);
Assert.Equal(e.FullPath, newPath);
};
fsw.EnableRaisingEvents = true;
File.Move(file.Path, newPath);
ExpectEvent(eventOccurred, "renamed");
}
}
[Fact]
public void FileSystemWatcher_Path()
{
FileSystemWatcher watcher = new FileSystemWatcher();
Assert.Equal(String.Empty, watcher.Path);
watcher.Path = null;
Assert.Equal(String.Empty, watcher.Path);
watcher.Path = ".";
Assert.Equal(".", watcher.Path);
if (!PlatformDetection.IsInAppContainer)
{
watcher.Path = "..";
Assert.Equal("..", watcher.Path);
}
string currentDir = Path.GetFullPath(".").TrimEnd('.', Path.DirectorySeparatorChar);
watcher.Path = currentDir;
Assert.Equal(currentDir, watcher.Path);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || // expect no change for OrdinalIgnoreCase-equal strings
RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
watcher.Path = currentDir.ToUpperInvariant();
Assert.Equal(currentDir, watcher.Path);
watcher.Path = currentDir.ToLowerInvariant();
Assert.Equal(currentDir, watcher.Path);
}
// expect a change for same "full-path" but different string path, FSW does not normalize
string currentDirRelative = currentDir +
Path.DirectorySeparatorChar + "." +
Path.DirectorySeparatorChar + "." +
Path.DirectorySeparatorChar + "." +
Path.DirectorySeparatorChar + ".";
watcher.Path = currentDirRelative;
Assert.Equal(currentDirRelative, watcher.Path);
// FSW starts with String.Empty and will ignore setting this if it is already set,
// but if you set it after some other valid string has been set it will throw.
Assert.Throws<ArgumentException>(() => watcher.Path = String.Empty);
// Non-existent path
Assert.Throws<ArgumentException>(() => watcher.Path = GetTestFilePath());
// Web path
Assert.Throws<ArgumentException>(() => watcher.Path = "http://localhost");
// File protocol
Assert.Throws<ArgumentException>(() => watcher.Path = "file:///" + currentDir.Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
}
[Fact]
public void FileSystemWatcher_Renamed()
{
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
var handler = new RenamedEventHandler((o, e) => { });
// add / remove
watcher.Renamed += handler;
watcher.Renamed -= handler;
// shouldn't throw
watcher.Renamed -= handler;
}
}
[Fact]
[PlatformSpecific(TestPlatforms.Linux)] // Reads MaxUsersWatches from Linux OS files
[OuterLoop("This test has high system resource demands and may cause failures in other concurrent tests")]
public void FileSystemWatcher_CreateManyConcurrentWatches()
{
int maxUserWatches = int.Parse(File.ReadAllText("/proc/sys/fs/inotify/max_user_watches"));
using (var dir = new TempDirectory(GetTestFilePath()))
using (var watcher = new FileSystemWatcher(dir.Path) { IncludeSubdirectories = true, NotifyFilter = NotifyFilters.FileName })
{
Action action = () =>
{
// Create enough directories to exceed the number of allowed watches
for (int i = 0; i <= maxUserWatches; i++)
{
Directory.CreateDirectory(Path.Combine(dir.Path, i.ToString()));
}
};
Action cleanup = () =>
{
for (int i = 0; i <= maxUserWatches; i++)
{
Directory.Delete(Path.Combine(dir.Path, i.ToString()));
}
};
ExpectError(watcher, action, cleanup);
// Make sure existing watches still work even after we've had one or more failures
Action createAction = () => File.WriteAllText(Path.Combine(dir.Path, Path.GetRandomFileName()), "text");
Action createCleanup = () => File.Delete(Path.Combine(dir.Path, Path.GetRandomFileName()));
ExpectEvent(watcher, WatcherChangeTypes.Created, createAction, createCleanup);
}
}
[Fact]
public void FileSystemWatcher_StopCalledOnBackgroundThreadDoesNotDeadlock()
{
// Check the case where Stop or Dispose (they do the same thing) is called from
// a FSW event callback and make sure we don't Thread.Join to deadlock
using (var dir = new TempDirectory(GetTestFilePath()))
{
string filePath = Path.Combine(dir.Path, "testfile.txt");
File.Create(filePath).Dispose();
AutoResetEvent are = new AutoResetEvent(false);
FileSystemWatcher watcher = new FileSystemWatcher(Path.GetFullPath(dir.Path), "*");
FileSystemEventHandler callback = (sender, arg) =>
{
watcher.Dispose();
are.Set();
};
watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
watcher.Changed += callback;
watcher.EnableRaisingEvents = true;
File.SetLastWriteTime(filePath, File.GetLastWriteTime(filePath).AddDays(1));
Assert.True(are.WaitOne(10000));
Assert.Throws<ObjectDisposedException>(() => watcher.EnableRaisingEvents = true);
}
}
[Fact]
public void FileSystemWatcher_WatchingAliasedFolderResolvesToRealPathWhenWatching()
{
using (var testDirectory = new TempDirectory(GetTestFilePath()))
using (var dir = new TempDirectory(Path.Combine(testDirectory.Path, "dir")))
using (var fsw = new FileSystemWatcher(dir.Path))
{
AutoResetEvent are = WatchCreated(fsw);
fsw.Filter = "*";
fsw.EnableRaisingEvents = true;
using (var temp = new TempDirectory(Path.Combine(dir.Path, "foo")))
{
ExpectEvent(are, "created");
}
}
}
}
}
| |
using System;
using System.ComponentModel;
using Csla.Rules;
using ProjectTracker.Library;
using Wisej.Web;
namespace PTWisej
{
public partial class ProjectEdit : WinPart
{
#region Properties
public ProjectTracker.Library.ProjectEdit Project { get; private set; }
protected internal override object GetIdValue()
{
return Project;
}
public override string ToString()
{
return Project.Name;
}
#endregion
#region Change event handlers
private void ProjectEdit_CurrentPrincipalChanged(object sender, EventArgs e)
{
ApplyAuthorizationRules();
}
private void Project_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsDirty")
{
this.ProjectBindingSource.ResetBindings(true);
this.ResourcesBindingSource.ResetBindings(true);
}
}
#endregion
#region Constructors
private ProjectEdit()
{
// force to use parametrized constructor
}
public ProjectEdit(ProjectTracker.Library.ProjectEdit project)
{
InitializeComponent();
// store object reference
Project = project;
}
#endregion
#region Plumbing...
private void ProjectEdit_Load(object sender, EventArgs e)
{
this.CurrentPrincipalChanged += new EventHandler(ProjectEdit_CurrentPrincipalChanged);
Project.PropertyChanged += new PropertyChangedEventHandler(Project_PropertyChanged);
Setup();
}
private void Setup()
{
// set up binding
this.RoleListBindingSource.DataSource = ProjectTracker.Library.RoleList.GetCachedList();
BindUI();
// check authorization
ApplyAuthorizationRules();
}
private void ApplyAuthorizationRules()
{
bool canEdit = Csla.Rules.BusinessRules.HasPermission(Csla.Rules.AuthorizationActions.EditObject,
typeof(ProjectTracker.Library.ProjectEdit));
if (!canEdit)
RebindUI(false, true);
// have the controls enable/disable/etc
this.ReadWriteAuthorization1.ResetControlAuthorization();
// enable/disable appropriate buttons
this.OKButton.Enabled = canEdit;
this.ApplyButton.Enabled = canEdit;
this.Cancel_Button.Enabled = canEdit;
this.AssignButton.Enabled = canEdit;
this.UnassignButton.Enabled = canEdit;
// enable/disable role column in grid
this.ResourcesDataGridView.Columns[2].ReadOnly = !canEdit;
}
private void BindUI()
{
Project.BeginEdit();
this.ProjectBindingSource.DataSource = Project;
}
private bool RebindUI(bool saveObject, bool rebind)
{
// disable events
this.ProjectBindingSource.RaiseListChangedEvents = false;
this.ResourcesBindingSource.RaiseListChangedEvents = false;
try
{
// unbind the UI
UnbindBindingSource(this.ResourcesBindingSource, saveObject, false);
UnbindBindingSource(this.ProjectBindingSource, saveObject, true);
this.ResourcesBindingSource.DataSource = this.ProjectBindingSource;
// save or cancel changes
if (saveObject)
{
Project.ApplyEdit();
try
{
Project = Project.Save();
}
catch (Csla.DataPortalException ex)
{
MessageBox.Show(ex.BusinessException.ToString(),
"Error saving", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(),
"Error Saving", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
else
Project.CancelEdit();
return true;
}
finally
{
// rebind UI if requested
if (rebind)
BindUI();
// restore events
this.ProjectBindingSource.RaiseListChangedEvents = true;
this.ResourcesBindingSource.RaiseListChangedEvents = true;
if (rebind)
{
// refresh the UI if rebinding
this.ProjectBindingSource.ResetBindings(false);
this.ResourcesBindingSource.ResetBindings(false);
}
}
}
#endregion
#region Button event handlers
private void OKButton_Click(object sender, EventArgs e)
{
if (IsSavable())
{
using (StatusBusy busy = new StatusBusy("Saving..."))
{
if (RebindUI(true, false))
{
this.Close();
}
}
}
}
private void ApplyButton_Click(object sender, EventArgs e)
{
if (IsSavable())
{
using (StatusBusy busy = new StatusBusy("Saving..."))
{
RebindUI(true, true);
}
}
}
private bool IsSavable()
{
if (Project.IsSavable)
return true;
if (!Project.IsValid)
{
MessageBox.Show(GetErrorMessage(), "Saving Project", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
private string GetErrorMessage()
{
var message = "Project is invalid and cannot be saved." + Environment.NewLine + Environment.NewLine;
foreach (var rule in Project.BrokenRulesCollection)
{
if (rule.Severity == RuleSeverity.Error)
message += "- " + rule.Description + Environment.NewLine;
}
return message;
}
private void Cancel_Button_Click(object sender, EventArgs e)
{
RebindUI(false, true);
}
private void CloseButton_Click(object sender, EventArgs e)
{
RebindUI(false, false);
this.Close();
}
private void RefreshButton_Click(object sender, EventArgs e)
{
if (CanRefresh())
{
using (StatusBusy busy = new StatusBusy("Refreshing..."))
{
if (RebindUI(false, false))
{
Project = ProjectTracker.Library.ProjectEdit.GetProject(Project.Id);
RoleList.InvalidateCache();
RoleList.CacheList();
Setup();
}
}
}
}
private bool CanRefresh()
{
if (!Project.IsDirty)
return true;
var dlg = MessageBox.Show("Project is not saved and all changes will be lost.\r\n\r\nDo you want to refresh?.",
"Refreshing Project",
MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
return dlg == DialogResult.OK;
}
private void AssignButton_Click(object sender, EventArgs e)
{
using (ResourceSelect dlg = new ResourceSelect())
{
if (dlg.ShowDialog() == DialogResult.OK)
{
try
{
Project.Resources.Assign(dlg.ResourceId);
}
catch (InvalidOperationException ex)
{
MessageBox.Show(ex.Message,
"Error Assigning", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(),
"Error Assigning", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void UnassignButton_Click(object sender, EventArgs e)
{
if (this.ResourcesDataGridView.SelectedRows.Count > 0)
{
int resourceId = int.Parse(this.ResourcesDataGridView.SelectedRows[0].Cells[0].Value.ToString());
Project.Resources.Remove(resourceId);
}
}
private void ResourcesDataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1 && e.RowIndex > -1)
{
int resourceId = int.Parse(this.ResourcesDataGridView.Rows[e.RowIndex].Cells[0].Value.ToString());
MainPage.Instance.ShowEditResource(resourceId);
}
}
#endregion
}
}
| |
/*
* Copyright (2011) Intel Corporation and Sandia Corporation. Under the
* terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the
* U.S. Government retains certain rights in this software.
*
* 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 Intel Corporation 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 INTEL OR ITS
* 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 NUnit.Framework;
using OpenMetaverse;
using OpenSim.Tests.Common;
using WaterWars.Models;
namespace WaterWars.Models.Tests
{
[TestFixture]
public class GameAssetTests
{
[Test]
public void TestWaterAllocationToFullOnlyAsset()
{
TestHelpers.InMethod();
Houses h1
= new Houses("houses1", UUID.Parse("00000000-0000-0000-0000-000000001001"), Vector3.Zero)
{ StepsToBuilds = new int[] { 0, 1 }, StepsBuilt = 1 };
h1.WaterUsages = new int[] { 0, 4 };
h1.Level = 1;
Assert.That(h1.WaterAllocated, Is.EqualTo(0));
h1.WaterAllocated = 4;
Assert.That(h1.WaterAllocated, Is.EqualTo(4));
h1.WaterAllocated = 0;
Assert.That(h1.WaterAllocated, Is.EqualTo(0));
bool gotNegativeException = false;
try
{
h1.WaterAllocated = -1;
}
catch (WaterWarsGameLogicException)
{
gotNegativeException = true;
}
Assert.That(gotNegativeException, Is.True);
Assert.That(h1.WaterAllocated, Is.EqualTo(0));
// Over allocation should fail
Houses h2 = new Houses("houses2", UUID.Parse("00000000-0000-0000-0000-000000001002"), Vector3.Zero)
{ StepsToBuilds = new int[] { 0, 1 }, StepsBuilt = 1 };
h2.WaterUsages = new int[] { 0, 4 };
h2.Level = 1;
bool gotOverException = false;
try
{
h2.WaterAllocated = 5;
}
catch (WaterWarsGameLogicException)
{
gotOverException = true;
}
Assert.That(gotOverException, Is.True);
Assert.That(h2.WaterAllocated, Is.EqualTo(0));
// Partial allocation should fail
Houses h3 = new Houses("houses3", UUID.Parse("00000000-0000-0000-0000-000000001003"), Vector3.Zero)
{ StepsToBuilds = new int[] { 0, 1 }, StepsBuilt = 1 };
h3.WaterUsages = new int[] { 0, 4 };
h3.Level = 1;
bool gotPartialException = false;
try
{
h3.WaterAllocated = 2;
}
catch (WaterWarsGameLogicException)
{
gotPartialException = true;
}
Assert.That(gotPartialException, Is.True);
Assert.That(h3.WaterAllocated, Is.EqualTo(0));
}
[Test]
public void TestWaterAllocationToPartialOkayAsset()
{
TestHelpers.InMethod();
Factory f1
= new Factory("factory1", UUID.Parse("00000000-0000-0000-0000-000000001001"), Vector3.Zero)
{ StepsToBuilds = new int[] { 0, 1 }, StepsBuilt = 1 };
f1.WaterUsages = new int[] { 0, 4 };
f1.Level = 1;
Assert.That(f1.WaterAllocated, Is.EqualTo(0));
f1.WaterAllocated = 4;
Assert.That(f1.WaterAllocated, Is.EqualTo(4));
f1.WaterAllocated = 2;
Assert.That(f1.WaterAllocated, Is.EqualTo(2));
// Over allocation should fail
bool gotOverException = false;
try
{
f1.WaterAllocated = 5;
}
catch (WaterWarsGameLogicException)
{
gotOverException = true;
}
Assert.That(gotOverException, Is.True);
Assert.That(f1.WaterAllocated, Is.EqualTo(2));
f1.WaterAllocated = 0;
Assert.That(f1.WaterAllocated, Is.EqualTo(0));
bool gotNegativeException = false;
try
{
f1.WaterAllocated = -1;
}
catch (WaterWarsGameLogicException)
{
gotNegativeException = true;
}
Assert.That(gotNegativeException, Is.True);
Assert.That(f1.WaterAllocated, Is.EqualTo(0));
}
/// <summary>
/// Check that the null asset behaves as expected.
/// </summary>
///
/// When the game starts up, the player selection will be for the null asset, so we need it to behave properly
[Test]
public void TestNoneAsset()
{
AbstractGameAsset ga = AbstractGameAsset.None;
Assert.That(ga.BuyPointUuid, Is.EqualTo(UUID.Zero));
Assert.That(ga.CanBeAllocatedWater, Is.False);
Assert.That(ga.CanBeSoldToEconomy, Is.False);
Assert.That(ga.CanUpgrade, Is.False);
Assert.That(ga.CanUpgradeInPrinciple, Is.False);
Assert.That(ga.ConstructionCost, Is.EqualTo(0));
Assert.That(ga.ConstructionCostPerBuildStep, Is.EqualTo(0));
Assert.That(ga.ConstructionCosts, Is.EqualTo(new int[] { 0 }));
Assert.That(ga.ConstructionCostsPerBuildStep, Is.EqualTo(new int[] { 0 }));
Assert.That(ga.Field, Is.Null);
Assert.That(ga.Game, Is.EqualTo(Game.None));
Assert.That(ga.InitialNames, Is.Null);
Assert.That(ga.IsBuilt, Is.False);
Assert.That(ga.Level, Is.EqualTo(0));
Assert.That(ga.MaintenanceCost, Is.EqualTo(0));
Assert.That(ga.MaintenanceCosts, Is.EqualTo(new int[] { 0 }));
Assert.That(ga.MaxLevel, Is.EqualTo(0));
Assert.That(ga.MinLevel, Is.EqualTo(0));
Assert.That(ga.Name, Is.EqualTo("NONE"));
Assert.That(ga.OwnerName, Is.EqualTo("UNKNOWN"));
Assert.That(ga.OwnerUuid, Is.EqualTo(UUID.Zero));
Assert.That(ga.Position, Is.EqualTo(Vector3.Zero));
Assert.That(ga.NormalRevenue, Is.EqualTo(0));
Assert.That(ga.NormalRevenues, Is.EqualTo(new int[] { 0 }));
Assert.That(ga.TimeToLive, Is.EqualTo(AbstractGameAsset.INFINITE_TIME_TO_LIVE));
Assert.That(ga.StepsBuilt, Is.EqualTo(0));
Assert.That(ga.StepsToBuild, Is.EqualTo(0));
Assert.That(ga.StepsToBuilds, Is.EqualTo(new int[] { 0 }));
Assert.That(ga.Type, Is.EqualTo(AbstractGameAssetType.None));
Assert.That(ga.UpgradeCosts, Is.EqualTo(new int[] { 0 }));
Assert.That(ga.Uuid, Is.EqualTo(UUID.Zero));
Assert.That(ga.WaterAllocated, Is.EqualTo(0));
Assert.That(ga.WaterUsage, Is.EqualTo(0));
Assert.That(ga.WaterUsages, Is.EqualTo(new int[] { 0 }));
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using HttpServer.Rendering.Haml.Nodes;
using HttpServer.Rendering.Haml.Rules;
namespace HttpServer.Rendering.Haml
{
/// <summary>
/// Generates C#/HTML from HAML code.
/// </summary>
/// <remarks>HAML documentation: http://haml.hamptoncatlin.com/docs/rdoc/classes/Haml.html</remarks>
public class HamlGenerator : ITemplateGenerator
{
private LineInfo _currentLine;
private int _lineNo = -1;
private LineInfo _mother;
private Node _parentNode;
private LineInfo _prevLine;
private TextReader _reader;
private readonly List<Rule> _rules = new List<Rule>();
private readonly ILogWriter _log;
/// <summary>
/// Initializes a new instance of the <see cref="HamlGenerator"/> class.
/// </summary>
public HamlGenerator()
{
_rules.Add(new NewLineRule());
_rules.Add(new AttributesRule());
_log = NullLogWriter.Instance;
}
/// <summary>
/// Initializes a new instance of the <see cref="HamlGenerator"/> class.
/// </summary>
/// <param name="logWriter">The log writer.</param>
public HamlGenerator(ILogWriter logWriter)
{
_rules.Add(new NewLineRule());
_rules.Add(new AttributesRule());
_log = logWriter ?? NullLogWriter.Instance;
}
/// <summary>
/// Property to retrieve the root node for the latest parsed document
/// </summary>
public Node RootNode
{
get { return _parentNode; }
}
/// <summary>
/// Check and validate indentation
/// </summary>
/// <param name="line">line to check</param>
/// <param name="ws">number of white spaces</param>
/// <param name="intendation">number of indentations (2 white spaces = 1 intend, 1 tab = 1 intend)</param>
protected static void CheckIntendation(LineInfo line, out int ws, out int intendation)
{
intendation = 0;
ws = -1;
char prevUnusedCh = line.UnparsedData[0];
if (prevUnusedCh == '\t')
{
++intendation;
prevUnusedCh = char.MinValue;
}
else if (prevUnusedCh != ' ')
{
ws = 0;
return;
}
for (int i = 1; i < line.UnparsedData.Length; ++i)
{
char ch = line.UnparsedData[i];
if (ch == ' ')
{
if (prevUnusedCh == '\t')
{
++intendation;
prevUnusedCh = ' ';
continue;
}
if (prevUnusedCh == ' ')
{
prevUnusedCh = char.MinValue;
++intendation;
continue;
}
prevUnusedCh = ' ';
}
else if (ch == '\t')
{
if (prevUnusedCh == ' ')
throw new CodeGeneratorException(line.LineNumber, line.Data,
"Invalid intendation sequence: One space + one tab. Should either be one tab or two spaces.");
if (prevUnusedCh == char.MinValue)
{
++intendation;
prevUnusedCh = char.MinValue;
continue;
}
}
else
{
if (prevUnusedCh != char.MinValue)
throw new CodeGeneratorException(line.LineNumber, line.Data,
"Invalid intendation at char " + i + ", expected a space.");
if (i == 1 && !char.IsWhiteSpace(line.UnparsedData[0]))
ws = 0;
else
ws = i;
return;
}
}
}
/// <summary>
/// Check indentation
/// </summary>
/// <param name="line">fills line with intend info</param>
protected static void CheckIntendation(LineInfo line)
{
int ws, intendation;
CheckIntendation(line, out ws, out intendation);
if (ws == -1)
throw new CodeGeneratorException(line.LineNumber, line.Data,
"Failed to find indentation on line #" + line.LineNumber);
line.Set(ws, intendation);
}
/// <summary>
/// check if current line is a multi line
/// </summary>
/// <param name="prevLine">previous line</param>
/// <param name="line">current line</param>
protected void CheckMultiLine(LineInfo prevLine, LineInfo line)
{
if (prevLine != null && prevLine.UnfinishedRule != null)
{
if (prevLine.UnfinishedRule.IsMultiLine(line, true))
{
_log.Write(this, LogPrio.Trace, line.LineNumber + ": " + prevLine.UnfinishedRule.GetType().Name +
" says that the next line should be appended.");
line.AppendNextLine = true;
return;
}
}
foreach (Rule rule in _rules)
{
if (rule.IsMultiLine(line, false))
{
_log.Write(this, LogPrio.Trace, line.LineNumber + ": " + rule.GetType().Name +
" says that the next line should be appended.");
line.AppendNextLine = true;
continue;
}
}
}
/// <summary>
/// Generate HTML code from the template.
/// Code is encapsulated in <% and <%=
/// </summary>
/// <param name="writer">A <see cref="TextWriter"/> that the generated code will be written to.</param>
/// <exception cref="InvalidOperationException">If the template have not been parsed first.</exception>
/// <exception cref="CodeGeneratorException">If template is incorrect</exception>
public void GenerateHtml(TextWriter writer)
{
foreach (Node child in _parentNode.Children)
writer.Write(child.ToHtml());
}
/// <summary>
/// Get the first word (letters and digits only) from the specified offset.
/// </summary>
/// <param name="data"></param>
/// <param name="offset"></param>
/// <returns></returns>
public static string GetWord(string data, int offset)
{
for (int i = offset; i < data.Length; ++i)
{
if (!char.IsLetterOrDigit(data[i]) && data[i] != '!')
return data.Substring(offset, i - offset + 1);
}
return data;
}
/// <summary>
/// Check indentation / node placement
/// </summary>
protected void HandlePlacement()
{
// Check intendation so that we know where to place the line
// Larger intendation = child
if (_currentLine.Intendation > _prevLine.Intendation)
{
if (_currentLine.Intendation != _prevLine.Intendation + 1)
throw new CodeGeneratorException(_currentLine.LineNumber,
"Too large indentation, " + (_currentLine.Intendation -
_prevLine.Intendation) +
" steps instead of 1.");
_currentLine.Parent = _prevLine;
}
// same intendation = same parent.
else if (_currentLine.Intendation == _prevLine.Intendation)
_currentLine.Parent = _prevLine.Parent;
// Node should be placed on a node up the chain.
else
{
// go back until we find someone at the same level
LineInfo sameLevelNode = _prevLine;
while (sameLevelNode != null && sameLevelNode.Intendation > _currentLine.Intendation)
sameLevelNode = sameLevelNode.Parent;
if (sameLevelNode == null)
{
if (_currentLine.Intendation > 0)
throw new CodeGeneratorException(_currentLine.LineNumber, "Failed to find parent.");
_currentLine.Parent = _mother;
}
else
_currentLine.Parent = sameLevelNode.Parent;
}
}
/// <summary>
/// Parse a node
/// todo: improve doc
/// </summary>
/// <param name="theLine"></param>
/// <param name="prototypes"></param>
/// <param name="parent"></param>
/// <param name="textNode"></param>
protected static void ParseNode(LineInfo theLine, NodeList prototypes, Node parent, TextNode textNode)
{
Node curNode = null;
int offset = 0;
// parse each part of a line
while (offset <= theLine.Data.Length - 1)
{
Node node = prototypes.GetPrototype(GetWord(theLine.Data, offset), curNode == null) ?? textNode;
node = node.Parse(prototypes, curNode, theLine, ref offset);
// first node on line, set it as current
if (curNode == null)
{
curNode = node;
curNode.LineInfo = theLine;
parent.Children.AddLast(node);
}
else
curNode.AddModifier(node); // append attributes etc.
}
foreach (LineInfo child in theLine.Children)
ParseNode(child, prototypes, curNode, textNode);
}
/// <summary>
/// PreParse goes through the text add handles indentation
/// and all multi line cases.
/// </summary>
/// <param name="reader">Reader containing the text</param>
protected void PreParse(TextReader reader)
{
if (reader == null)
throw new ArgumentNullException("reader");
// Read first line to be able to assign it to the mother.
if (!ReadLine())
throw new CodeGeneratorException(1, "No data.");
if (_currentLine.Intendation != 0)
throw new CodeGeneratorException(1, "Invalid indentation, should be 0.");
_currentLine.Parent = _mother;
CheckIntendation(_currentLine);
CheckMultiLine(_prevLine, _currentLine);
while (ReadLine())
{
if (_currentLine.UnparsedData.Length == 0)
continue;
CheckIntendation(_currentLine);
CheckMultiLine(_prevLine, _currentLine);
if (_prevLine.AppendNextLine)
{
_prevLine.Append(_currentLine);
if(_currentLine.AppendNextLine)
_prevLine.AppendNextLine = true;
_currentLine = _prevLine;
continue;
}
HandlePlacement();
}
}
/// <summary>
/// print the entire document
/// </summary>
public void PrintDocument()
{
PrintNode(_mother);
}
/// <summary>
/// Print line information to the console
/// </summary>
/// <param name="line"></param>
public void PrintNode(LineInfo line)
{
_log.Write(this, LogPrio.Debug, Spaces(line.Intendation) + line.Data);
foreach (LineInfo info in line.Children)
PrintNode(info);
}
/// <summary>
/// Read next line from file
/// </summary>
/// <returns>true if line could be read; false if EOF.</returns>
protected bool ReadLine()
{
string line = _reader.ReadLine();
string trimmedLine = (line != null) ? line.Trim(new char[] {' ', '\t'}) : string.Empty;
while (line != null && (trimmedLine == string.Empty
|| (trimmedLine.Length > 0 && trimmedLine[0] == '-' && trimmedLine[1] == '/')
))
{
++_lineNo;
line = _reader.ReadLine();
trimmedLine = (line != null) ? line.Trim(new char[] {' ', '\t'}) : string.Empty;
}
if (line == null)
return false;
++_lineNo;
_prevLine = _currentLine;
_currentLine = new LineInfo(_lineNo, line);
return true;
}
/// <summary>
/// Generates a string with spaces.
/// </summary>
/// <param name="count">number of spaces.</param>
/// <returns>string of spaces.</returns>
public string Spaces(int count)
{
return "".PadLeft(count);
}
#region ITemplateGenerator Members
/// <summary>
/// Parse a file and convert into to our own template object code.
/// </summary>
/// <param name="fullPath">Path and filename to a template</param>
/// <exception cref="CodeGeneratorException">If something is incorrect in the template.</exception>
/// <exception cref="FileNotFoundException"></exception>
/// <exception cref="DirectoryNotFoundException"></exception>
/// <exception cref="UnauthorizedAccessException"></exception>
/// <exception cref="PathTooLongException"></exception>
/// <exception cref="NotSupportedException"></exception>
/// <exception cref="ArgumentException"></exception>
public void Parse(string fullPath)
{
if (string.IsNullOrEmpty(fullPath))
throw new ArgumentException("Path must be specified.", "fullPath");
Stream stream = null;
try
{
stream = File.OpenRead(fullPath);
TextReader reader = new StreamReader(stream);
Parse(reader);
reader.Close();
reader.Dispose();
stream.Dispose();
}
finally
{
if (stream != null)
stream.Close();
}
}
/// <summary>
/// Parse a file and convert into to our own template object code.
/// </summary>
/// <param name="reader">A <see cref="TextReader"/> containing our template</param>
/// <exception cref="CodeGeneratorException">If something is incorrect in the template.</exception>
public void Parse(TextReader reader)
{
_lineNo = -1;
_reader = reader;
_mother = new LineInfo(-1, string.Empty);
_prevLine = null;
_currentLine = null;
PreParse(reader);
NodeList prototypes = new NodeList();
prototypes.Add(new AttributeNode(null));
prototypes.Add(new TagNode(null));
prototypes.Add(new IdNode(null));
prototypes.Add(new SilentCodeNode(null));
prototypes.Add(new ClassNode(null));
prototypes.Add(new DisplayCodeNode(null));
prototypes.Add(new DocTypeTag(null, null));
prototypes.Add(new PartialNode(null));
TextNode textNode = new TextNode(null, "prototype");
_parentNode = new TextNode(null, string.Empty);
foreach (LineInfo info in _mother.Children)
ParseNode(info, prototypes, _parentNode, textNode);
}
/// <summary>
/// Generate C# code from the template.
/// </summary>
/// <param name="writer">A <see cref="TextWriter"/> that the generated code will be written to.</param>
/// <exception cref="InvalidOperationException">If the template have not been parsed first.</exception>
/// <exception cref="CodeGeneratorException">If template is incorrect</exception>
public void GenerateCode(TextWriter writer)
{
writer.Write("sb.Append(@\"");
bool inString = true;
foreach (Node child in _parentNode.Children)
writer.Write(child.ToCode(ref inString));
if (inString)
writer.Write("\");");
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.Linq;
using GitVersion.Core.Tests.Helpers;
using GitVersion.Extensions;
using GitVersion.Model.Configuration;
using GitVersion.VersionCalculation;
using NSubstitute;
using NUnit.Framework;
using Shouldly;
namespace GitVersion.Core.Tests.VersionCalculation.Strategies
{
[TestFixture]
public class MergeMessageBaseVersionStrategyTests : TestBase
{
[Test]
public void ShouldNotAllowIncrementOfVersion()
{
// When a branch is merged in you want to start building stable packages of that version
// So we shouldn't bump the version
var mockCommit = GitToolsTestingExtensions.CreateMockCommit();
mockCommit.Message.Returns("Merge branch 'release-0.1.5'");
mockCommit.Parents.Returns(GetParents(true));
var mockBranch = GitToolsTestingExtensions.CreateMockBranch(MainBranch, mockCommit);
var branches = Substitute.For<IBranchCollection>();
branches.GetEnumerator().Returns(_ => ((IEnumerable<IBranch>)new[] { mockBranch }).GetEnumerator());
var mockRepository = Substitute.For<IGitRepository>();
mockRepository.Head.Returns(mockBranch);
mockRepository.Branches.Returns(branches);
mockRepository.Commits.Returns(mockBranch.Commits);
var contextBuilder = new GitVersionContextBuilder().WithRepository(mockRepository);
contextBuilder.Build();
var strategy = contextBuilder.ServicesProvider.GetServiceForType<IVersionStrategy, MergeMessageVersionStrategy>();
var baseVersion = strategy.GetVersions().Single();
baseVersion.ShouldIncrement.ShouldBe(false);
}
[TestCase("Merge branch 'release-10.10.50'", true, "10.10.50")]
[TestCase("Merge branch 'release-0.2.0'", true, "0.2.0")]
[TestCase("Merge branch 'Release-0.2.0'", true, "0.2.0")]
[TestCase("Merge branch 'Release/0.2.0'", true, "0.2.0")]
[TestCase("Merge branch 'releases-0.2.0'", true, "0.2.0")]
[TestCase("Merge branch 'Releases-0.2.0'", true, "0.2.0")]
[TestCase("Merge branch 'Releases/0.2.0'", true, "0.2.0")]
[TestCase("Merge branch 'release-4.6.6' into support-4.6", true, "4.6.6")]
[TestCase("Merge branch 'release-0.1.5'\n\nRelates to: TicketId", true, "0.1.5")]
[TestCase("Finish Release-0.12.0", true, "0.12.0")] //Support Syntevo SmartGit/Hg's Gitflow merge commit messages for finishing a 'Release' branch
[TestCase("Merge branch 'Release-v0.2.0'", true, "0.2.0")]
[TestCase("Merge branch 'Release-v2.2'", true, "2.2.0")]
[TestCase("Merge remote-tracking branch 'origin/release/0.8.0' into develop/" + MainBranch, true, "0.8.0")]
[TestCase("Merge remote-tracking branch 'refs/remotes/origin/release/2.0.0'", true, "2.0.0")]
public void TakesVersionFromMergeOfReleaseBranch(string message, bool isMergeCommit, string expectedVersion)
{
var parents = GetParents(isMergeCommit);
AssertMergeMessage(message, expectedVersion, parents);
AssertMergeMessage(message + " ", expectedVersion, parents);
AssertMergeMessage(message + "\r ", expectedVersion, parents);
AssertMergeMessage(message + "\r", expectedVersion, parents);
AssertMergeMessage(message + "\r\n", expectedVersion, parents);
AssertMergeMessage(message + "\r\n ", expectedVersion, parents);
AssertMergeMessage(message + "\n", expectedVersion, parents);
AssertMergeMessage(message + "\n ", expectedVersion, parents);
}
[TestCase("Merge branch 'hotfix-0.1.5'", false)]
[TestCase("Merge branch 'develop' of github.com:Particular/NServiceBus into develop", true)]
[TestCase("Merge branch '4.0.3'", true)]
[TestCase("Merge branch 's'", true)]
[TestCase("Merge tag '10.10.50'", true)]
[TestCase("Merge branch 'hotfix-4.6.6' into support-4.6", true)]
[TestCase("Merge branch 'hotfix-10.10.50'", true)]
[TestCase("Merge branch 'Hotfix-10.10.50'", true)]
[TestCase("Merge branch 'Hotfix/10.10.50'", true)]
[TestCase("Merge branch 'hotfix-0.1.5'", true)]
[TestCase("Merge branch 'hotfix-4.2.2' into support-4.2", true)]
[TestCase("Merge branch 'somebranch' into release-3.0.0", true)]
[TestCase("Merge branch 'hotfix-0.1.5'\n\nRelates to: TicketId", true)]
[TestCase("Merge branch 'alpha-0.1.5'", true)]
[TestCase("Merge pull request #95 from Particular/issue-94", false)]
[TestCase("Merge pull request #95 in Particular/issue-94", true)]
[TestCase("Merge pull request #95 in Particular/issue-94", false)]
[TestCase("Merge pull request #64 from arledesma/feature-VS2013_3rd_party_test_framework_support", true)]
[TestCase("Merge pull request #500 in FOO/bar from Particular/release-1.0.0 to develop)", true)]
[TestCase("Merge pull request #500 in FOO/bar from feature/new-service to develop)", true)]
[TestCase("Finish 0.14.1", true)] // Don't support Syntevo SmartGit/Hg's Gitflow merge commit messages for finishing a 'Hotfix' branch
public void ShouldNotTakeVersionFromMergeOfNonReleaseBranch(string message, bool isMergeCommit)
{
var parents = GetParents(isMergeCommit);
AssertMergeMessage(message, null, parents);
AssertMergeMessage(message + " ", null, parents);
AssertMergeMessage(message + "\r ", null, parents);
AssertMergeMessage(message + "\r", null, parents);
AssertMergeMessage(message + "\r\n", null, parents);
AssertMergeMessage(message + "\r\n ", null, parents);
AssertMergeMessage(message + "\n", null, parents);
AssertMergeMessage(message + "\n ", null, parents);
}
[TestCase("Merge pull request #165 from Particular/release-1.0.0", true)]
[TestCase("Merge pull request #165 in Particular/release-1.0.0", true)]
[TestCase("Merge pull request #500 in FOO/bar from Particular/release-1.0.0 to develop)", true)]
public void ShouldNotTakeVersionFromMergeOfReleaseBranchWithRemoteOtherThanOrigin(string message, bool isMergeCommit)
{
var parents = GetParents(isMergeCommit);
AssertMergeMessage(message, null, parents);
AssertMergeMessage(message + " ", null, parents);
AssertMergeMessage(message + "\r ", null, parents);
AssertMergeMessage(message + "\r", null, parents);
AssertMergeMessage(message + "\r\n", null, parents);
AssertMergeMessage(message + "\r\n ", null, parents);
AssertMergeMessage(message + "\n", null, parents);
AssertMergeMessage(message + "\n ", null, parents);
}
[TestCase(@"Merge pull request #1 in FOO/bar from feature/ISSUE-1 to develop
* commit '38560a7eed06e8d3f3f1aaf091befcdf8bf50fea':
Updated jQuery to v2.1.3")]
[TestCase(@"Merge pull request #45 in BRIKKS/brikks from feature/NOX-68 to develop
* commit '38560a7eed06e8d3f3f1aaf091befcdf8bf50fea':
Another commit message
Commit message including a IP-number https://10.50.1.1
A commit message")]
[TestCase(@"Merge branch 'release/Sprint_2.0_Holdings_Computed_Balances'")]
[TestCase(@"Merge branch 'develop' of http://10.0.6.3/gitblit/r/... into develop")]
[TestCase(@"Merge branch " + MainBranch + @" of http://172.16.3.10:8082/r/asu_tk/p_sd")]
[TestCase(@"Merge branch " + MainBranch + @" of http://212.248.89.56:8082/r/asu_tk/p_sd")]
[TestCase(@"Merge branch 'DEMO' of http://10.10.10.121/gitlab/mtolland/orcid into DEMO")]
public void ShouldNotTakeVersionFromUnrelatedMerge(string commitMessage)
{
var parents = GetParents(true);
AssertMergeMessage(commitMessage, null, parents);
}
[TestCase("Merge branch 'support/0.2.0'", "support", "0.2.0")]
[TestCase("Merge branch 'support/0.2.0'", null, null)]
[TestCase("Merge branch 'release/2.0.0'", null, "2.0.0")]
public void TakesVersionFromMergeOfConfiguredReleaseBranch(string message, string releaseBranch, string expectedVersion)
{
var config = new Config();
if (releaseBranch != null) config.Branches[releaseBranch] = new BranchConfig { IsReleaseBranch = true };
var parents = GetParents(true);
AssertMergeMessage(message, expectedVersion, parents, config);
}
private static void AssertMergeMessage(string message, string expectedVersion, IEnumerable<ICommit> parents, Config config = null)
{
var commit = GitToolsTestingExtensions.CreateMockCommit();
commit.Message.Returns(message);
commit.Parents.Returns(parents);
var mockBranch = GitToolsTestingExtensions.CreateMockBranch(MainBranch, commit, GitToolsTestingExtensions.CreateMockCommit());
var mockRepository = Substitute.For<IGitRepository>();
mockRepository.Head.Returns(mockBranch);
mockRepository.Commits.Returns(mockBranch.Commits);
var contextBuilder = new GitVersionContextBuilder()
.WithConfig(config ?? new Config())
.WithRepository(mockRepository);
contextBuilder.Build();
var strategy = contextBuilder.ServicesProvider.GetServiceForType<IVersionStrategy, MergeMessageVersionStrategy>();
var baseVersion = strategy.GetVersions().SingleOrDefault();
if (expectedVersion == null)
{
baseVersion.ShouldBe(null);
}
else
{
baseVersion.ShouldNotBeNull();
baseVersion.SemanticVersion.ToString().ShouldBe(expectedVersion);
}
}
private static List<ICommit> GetParents(bool isMergeCommit)
{
if (isMergeCommit)
{
return new List<ICommit>
{
null,
null
};
}
return new List<ICommit>
{
null
};
}
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace System.ServiceModel.MsmqIntegration
{
using System.IO;
using System.Runtime;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Diagnostics;
using System.ServiceModel.Security.Tokens;
sealed class MsmqIntegrationOutputChannel : TransportOutputChannel
{
MsmqQueue msmqQueue;
MsmqTransactionMode transactionMode;
MsmqIntegrationChannelFactory factory;
SecurityTokenProviderContainer certificateTokenProvider;
public MsmqIntegrationOutputChannel(MsmqIntegrationChannelFactory factory, EndpointAddress to, Uri via, bool manualAddressing)
: base(factory, to, via, manualAddressing, factory.MessageVersion)
{
this.factory = factory;
if (factory.IsMsmqX509SecurityConfigured)
{
this.certificateTokenProvider = factory.CreateX509TokenProvider(to, via);
}
}
void CloseQueue()
{
if (null != this.msmqQueue)
this.msmqQueue.Dispose();
this.msmqQueue = null;
}
void OnCloseCore(bool isAborting, TimeSpan timeout)
{
this.CloseQueue();
if (this.certificateTokenProvider != null)
{
if (isAborting)
this.certificateTokenProvider.Abort();
else
this.certificateTokenProvider.Close(timeout);
}
}
protected override void OnAbort()
{
this.OnCloseCore(true, TimeSpan.Zero);
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
this.OnCloseCore(false, timeout);
return new CompletedAsyncResult(callback, state);
}
protected override void OnEndClose(IAsyncResult result)
{
CompletedAsyncResult.End(result);
}
protected override void OnClose(TimeSpan timeout)
{
this.OnCloseCore(false, timeout);
}
void OpenQueue()
{
try
{
this.msmqQueue = new MsmqQueue(this.factory.AddressTranslator.UriToFormatName(this.RemoteAddress.Uri), UnsafeNativeMethods.MQ_SEND_ACCESS);
}
catch (MsmqException ex)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex.Normalized);
}
if (this.factory.ExactlyOnce)
{
this.transactionMode = MsmqTransactionMode.CurrentOrSingle;
}
else
{
this.transactionMode = MsmqTransactionMode.None;
}
}
void OnOpenCore(TimeSpan timeout)
{
OpenQueue();
if (this.certificateTokenProvider != null)
{
this.certificateTokenProvider.Open(timeout);
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
OnOpenCore(timeout);
return new CompletedAsyncResult(callback, state);
}
protected override void OnEndOpen(IAsyncResult result)
{
CompletedAsyncResult.End(result);
}
protected override void OnOpen(TimeSpan timeout)
{
OnOpenCore(timeout);
}
protected override IAsyncResult OnBeginSend(Message message, TimeSpan timeout, AsyncCallback callback, object state)
{
OnSend(message, timeout);
return new CompletedAsyncResult(callback, state);
}
protected override void OnEndSend(IAsyncResult result)
{
CompletedAsyncResult.End(result);
}
protected override void OnSend(Message message, TimeSpan timeout)
{
MessageProperties properties = message.Properties;
Stream stream = null;
MsmqIntegrationMessageProperty property = MsmqIntegrationMessageProperty.Get(message);
if (null == property)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new CommunicationException(SR.GetString(SR.MsmqMessageDoesntHaveIntegrationProperty)));
if (null != property.Body)
stream = this.factory.Serialize(property);
int size;
if (stream == null)
{
size = 0;
}
else
{
if (stream.Length > int.MaxValue)
{
throw TraceUtility.ThrowHelperError(new ProtocolException(SR.GetString(SR.MessageSizeMustBeInIntegerRange)), message);
}
size = (int)stream.Length;
}
using (MsmqIntegrationOutputMessage msmqMessage = new MsmqIntegrationOutputMessage(this.factory, size, this.RemoteAddress, property))
{
msmqMessage.ApplyCertificateIfNeeded(this.certificateTokenProvider, this.factory.MsmqTransportSecurity.MsmqAuthenticationMode, timeout);
if (stream != null)
{
stream.Position = 0;
for (int bytesRemaining = size; bytesRemaining > 0; )
{
int bytesRead = stream.Read(msmqMessage.Body.Buffer, 0, bytesRemaining);
bytesRemaining -= bytesRead;
}
}
bool lockHeld = false;
try
{
Msmq.EnterXPSendLock(out lockHeld, this.factory.MsmqTransportSecurity.MsmqProtectionLevel);
this.msmqQueue.Send(msmqMessage, this.transactionMode);
MsmqDiagnostics.DatagramSent(msmqMessage.MessageId, message);
property.Id = MsmqMessageId.ToString(msmqMessage.MessageId.Buffer);
}
catch (MsmqException ex)
{
if (ex.FaultSender)
this.Fault();
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ex.Normalized);
}
finally
{
if (lockHeld)
{
Msmq.LeaveXPSendLock();
}
}
}
}
class MsmqIntegrationOutputMessage : MsmqOutputMessage<IOutputChannel>
{
ByteProperty acknowledge;
StringProperty adminQueue;
IntProperty appSpecific;
BufferProperty correlationId;
BufferProperty extension;
StringProperty label;
ByteProperty priority;
StringProperty responseQueue;
public MsmqIntegrationOutputMessage(
MsmqChannelFactoryBase<IOutputChannel> factory,
int bodySize,
EndpointAddress remoteAddress,
MsmqIntegrationMessageProperty property)
: base(factory, bodySize, remoteAddress, 8)
{
if (null == property)
{
Fx.Assert("MsmqIntegrationMessageProperty expected");
}
if (property.AcknowledgeType.HasValue)
EnsureAcknowledgeProperty((byte)property.AcknowledgeType.Value);
if (null != property.AdministrationQueue)
EnsureAdminQueueProperty(property.AdministrationQueue, false);
if (property.AppSpecific.HasValue)
this.appSpecific = new IntProperty(this, UnsafeNativeMethods.PROPID_M_APPSPECIFIC, property.AppSpecific.Value);
if (property.BodyType.HasValue)
EnsureBodyTypeProperty(property.BodyType.Value);
if (null != property.CorrelationId)
this.correlationId = new BufferProperty(this, UnsafeNativeMethods.PROPID_M_CORRELATIONID, MsmqMessageId.FromString(property.CorrelationId));
if (null != property.Extension)
this.extension = new BufferProperty(this, UnsafeNativeMethods.PROPID_M_EXTENSION, property.Extension);
if (null != property.Label)
this.label = new StringProperty(this, UnsafeNativeMethods.PROPID_M_LABEL, property.Label);
if (property.Priority.HasValue)
this.priority = new ByteProperty(this, UnsafeNativeMethods.PROPID_M_PRIORITY, (byte)property.Priority.Value);
if (null != property.ResponseQueue)
EnsureResponseQueueProperty(property.ResponseQueue);
if (property.TimeToReachQueue.HasValue)
EnsureTimeToReachQueueProperty(MsmqDuration.FromTimeSpan(property.TimeToReachQueue.Value));
}
void EnsureAcknowledgeProperty(byte value)
{
if (this.acknowledge == null)
{
this.acknowledge = new ByteProperty(this, UnsafeNativeMethods.PROPID_M_ACKNOWLEDGE);
}
this.acknowledge.Value = value;
}
void EnsureAdminQueueProperty(Uri value, bool useNetMsmqTranslator)
{
if (null != value)
{
string queueName = useNetMsmqTranslator ?
MsmqUri.NetMsmqAddressTranslator.UriToFormatName(value) :
MsmqUri.FormatNameAddressTranslator.UriToFormatName(value);
if (this.adminQueue == null)
{
this.adminQueue = new StringProperty(this, UnsafeNativeMethods.PROPID_M_ADMIN_QUEUE, queueName);
}
else
{
this.adminQueue.SetValue(queueName);
}
}
}
void EnsureResponseQueueProperty(Uri value)
{
if (null != value)
{
string queueName = MsmqUri.FormatNameAddressTranslator.UriToFormatName(value);
if (this.responseQueue == null)
{
this.responseQueue = new StringProperty(this, UnsafeNativeMethods.PROPID_M_RESP_FORMAT_NAME, queueName);
}
else
{
this.responseQueue.SetValue(queueName);
}
}
}
}
}
}
| |
using BefunGen.AST.CodeGen;
using BefunGen.AST.Exceptions;
using System.Linq;
using System;
using BefunGen.AST.CodeGen.NumberCode;
using BefunGen.MathExtensions;
using BefunGen.AST.CodeGen.Tags;
using System.Collections.Generic;
namespace BefunGen.AST
{
#region Parents
public abstract class BType : ASTObject
{
protected const int PRIORITY_VOID = 0;
protected const int PRIORITY_BOOL = 1;
protected const int PRIORITY_DIGIT = 2;
protected const int PRIORITY_CHAR = 3;
protected const int PRIORITY_INT = 4;
protected const int PRIORITY_UNION = 99;
public BType(SourceCodePosition pos)
: base(pos)
{
//--
}
public abstract int GetCodeSize();
public override bool Equals(System.Object obj)
{
if (obj == null)
return false;
return this.Equals(obj as BType);
}
public virtual bool Equals(BType p)
{
if ((object)p == null)
return false;
return GetType() == p.GetType();
}
public static bool operator ==(BType a, BType b)
{
return (object)a != null && a.Equals(b);
}
public static bool operator !=(BType a, BType b)
{
return !(a == b);
}
public override int GetHashCode()
{
return -GetPriority();
}
public override string ToString()
{
return GetDebugString();
}
public abstract Literal GetDefaultValue();
public abstract bool IsImplicitCastableTo(BType other);
public abstract int GetPriority();
public abstract CodePiece GenerateCodeAssignment(CodeGenEnvironment env, SourceCodePosition pos, Expression source, ExpressionValuePointer target, bool reversed);
public abstract CodePiece GenerateCodePopValueFromStack(CodeGenEnvironment env, SourceCodePosition pos, bool reversed);
public abstract CodePiece GenerateCodeWriteFromStackToGrid(CodeGenEnvironment env, SourceCodePosition pos, VarDeclarationPosition gridPos, bool reversed);
public abstract CodePiece GenerateCodeReadFromGridToStack(CodeGenEnvironment env, SourceCodePosition pos, VarDeclarationPosition gridPos, bool reversed);
public abstract CodePiece GenerateCodeReturnFromMethodCall(CodeGenEnvironment env, SourceCodePosition pos, Expression value, bool reversed);
}
public abstract class BTypeValue : BType
{
public BTypeValue(SourceCodePosition pos)
: base(pos)
{
//--
}
public override int GetCodeSize()
{
return 1;
}
public override CodePiece GenerateCodeAssignment(CodeGenEnvironment env, SourceCodePosition pos, Expression source, ExpressionValuePointer target, bool reversed)
{
CodePiece p = new CodePiece();
if (reversed)
{
p.AppendLeft(source.GenerateCode(env, reversed));
p.AppendLeft(target.GenerateCodeSingle(env, reversed));
p.AppendLeft(BCHelper.ReflectSet);
p.NormalizeX();
}
else
{
p.AppendRight(source.GenerateCode(env, reversed));
p.AppendRight(target.GenerateCodeSingle(env, reversed));
p.AppendRight(BCHelper.ReflectSet);
p.NormalizeX();
}
return p;
}
public override CodePiece GenerateCodePopValueFromStack(CodeGenEnvironment env, SourceCodePosition pos, bool reversed)
{
return new CodePiece(BCHelper.StackPop);
}
public override CodePiece GenerateCodeWriteFromStackToGrid(CodeGenEnvironment env, SourceCodePosition pos, VarDeclarationPosition gridPos, bool reversed)
{
CodePiece p = new CodePiece();
if (reversed)
{
p.AppendLeft(NumberCodeHelper.GenerateCode(gridPos.X, reversed));
p.AppendLeft(NumberCodeHelper.GenerateCode(gridPos.Y, reversed));
p.AppendLeft(BCHelper.ReflectSet);
}
else
{
p.AppendRight(NumberCodeHelper.GenerateCode(gridPos.X, reversed));
p.AppendRight(NumberCodeHelper.GenerateCode(gridPos.Y, reversed));
p.AppendRight(BCHelper.ReflectSet);
}
return p;
}
public override CodePiece GenerateCodeReadFromGridToStack(CodeGenEnvironment env, SourceCodePosition pos, VarDeclarationPosition gridPos, bool reversed)
{
CodePiece p = new CodePiece();
if (reversed)
{
p.AppendLeft(NumberCodeHelper.GenerateCode(gridPos.X, reversed));
p.AppendLeft(NumberCodeHelper.GenerateCode(gridPos.Y, reversed));
p.AppendLeft(BCHelper.ReflectGet);
}
else
{
p.AppendRight(NumberCodeHelper.GenerateCode(gridPos.X, reversed));
p.AppendRight(NumberCodeHelper.GenerateCode(gridPos.Y, reversed));
p.AppendRight(BCHelper.ReflectGet);
}
return p;
}
public override CodePiece GenerateCodeReturnFromMethodCall(CodeGenEnvironment env, SourceCodePosition pos, Expression value, bool reversed)
{
CodePiece p = new CodePiece();
if (reversed)
{
#region Reversed
p.AppendRight(BCHelper.PC_Up_tagged(new MethodCallVerticalExitTag()));
p.AppendRight(BCHelper.Digit0); // Right Lane
p.AppendRight(BCHelper.StackSwap); // Swap BackjumpAddr back to Stack-Front
p.AppendRight(value.GenerateCode(env, reversed));
#endregion
}
else
{
#region Normal
p.AppendRight(value.GenerateCode(env, reversed));
p.AppendRight(BCHelper.StackSwap); // Swap BackjumpAddr back to Stack-Front
p.AppendRight(BCHelper.Digit0); // Right Lane
p.AppendRight(BCHelper.PC_Up_tagged(new MethodCallVerticalExitTag()));
#endregion
}
p.NormalizeX();
return p;
}
}
public abstract class BTypeArray : BType
{
public BTypeValue InternalType { get { return GetInternType(); } }
public readonly int ArraySize;
public BTypeArray(SourceCodePosition pos, int sz)
: base(pos)
{
ArraySize = sz;
}
public override int GetCodeSize()
{
return ArraySize;
}
public override bool Equals(BType p)
{
if ((object)p == null)
return false;
return this.GetType() == p.GetType() && (p as BTypeArray).ArraySize == ArraySize;
}
public override int GetHashCode()
{
return 10000 + GetPriority() * (ArraySize + 1);
}
protected abstract BTypeValue GetInternType();
public override CodePiece GenerateCodeAssignment(CodeGenEnvironment env, SourceCodePosition pos, Expression source, ExpressionValuePointer target, bool reversed)
{
CodePiece p = new CodePiece();
BTypeArray type = target.GetResultType() as BTypeArray;
ExpressionDirectValuePointer vPointer = target as ExpressionDirectValuePointer;
if (reversed)
{
p.AppendLeft(source.GenerateCode(env, reversed));
p.AppendLeft(CodePieceStore.WriteArrayFromStack(env, vPointer.Target.CodeDeclarationPos, reversed));
p.NormalizeX();
}
else
{
p.AppendRight(source.GenerateCode(env, reversed));
p.AppendRight(CodePieceStore.WriteArrayFromStack(env, vPointer.Target.CodeDeclarationPos, reversed));
p.NormalizeX();
}
return p;
}
public override CodePiece GenerateCodePopValueFromStack(CodeGenEnvironment env, SourceCodePosition pos, bool reversed)
{
return CodePieceStore.PopMultipleStackValues(ArraySize, reversed);
}
public override CodePiece GenerateCodeWriteFromStackToGrid(CodeGenEnvironment env, SourceCodePosition pos, VarDeclarationPosition gridPos, bool reversed)
{
return CodePieceStore.WriteArrayFromStack(env, gridPos, reversed);
}
public override CodePiece GenerateCodeReadFromGridToStack(CodeGenEnvironment env, SourceCodePosition pos, VarDeclarationPosition gridPos, bool reversed)
{
return CodePieceStore.ReadArrayToStack(env, gridPos, reversed);
}
public override CodePiece GenerateCodeReturnFromMethodCall(CodeGenEnvironment env, SourceCodePosition pos, Expression value, bool reversed)
{
CodePiece p = new CodePiece();
if (reversed)
{
#region Reversed
p.AppendLeft(value.GenerateCode(env, reversed));
// Switch ReturnValue (Array) and BackJumpAddr
p.AppendLeft(CodePieceStore.WriteArrayFromStack(env, env.TMP_ARRFIELD_RETURNVAL, reversed));
p.AppendLeft(CodePieceStore.WriteValueToField(env.TMP_FIELD_JMP_ADDR, reversed));
p.AppendLeft(CodePieceStore.ReadArrayToStack(env, env.TMP_ARRFIELD_RETURNVAL, reversed));
p.AppendLeft(CodePieceStore.ReadValueFromField(env.TMP_FIELD_JMP_ADDR, reversed));
p.AppendLeft(BCHelper.Digit0); // Right Lane
p.AppendLeft(BCHelper.PC_Up_tagged(new MethodCallVerticalExitTag()));
#endregion
}
else
{
#region Normal
p.AppendRight(value.GenerateCode(env, reversed));
// Switch ReturnValue (Array) and BackJumpAddr
p.AppendRight(CodePieceStore.WriteArrayFromStack(env, env.TMP_ARRFIELD_RETURNVAL, reversed));
p.AppendRight(CodePieceStore.WriteValueToField(env.TMP_FIELD_JMP_ADDR, reversed));
p.AppendRight(CodePieceStore.ReadArrayToStack(env, env.TMP_ARRFIELD_RETURNVAL, reversed));
p.AppendRight(CodePieceStore.ReadValueFromField(env.TMP_FIELD_JMP_ADDR, reversed));
p.AppendRight(BCHelper.Digit0); // Right Lane
p.AppendRight(BCHelper.PC_Up_tagged(new MethodCallVerticalExitTag()));
#endregion
}
p.NormalizeX();
return p;
}
}
public class BTypeVoid : BType // neither Array nor Value ...
{
public BTypeVoid(SourceCodePosition pos)
: base(pos)
{
//--
}
public override int GetCodeSize()
{
return 1;
}
public override string GetDebugString()
{
return "void";
}
public override Literal GetDefaultValue()
{
throw new VoidObjectCallException(Position);
}
public override bool IsImplicitCastableTo(BType other)
{
return false;
}
public override int GetPriority()
{
return PRIORITY_VOID;
}
public override CodePiece GenerateCodeAssignment(CodeGenEnvironment env, SourceCodePosition pos, Expression source, ExpressionValuePointer target, bool reversed)
{
throw new InvalidAstStateException(pos);
}
public override CodePiece GenerateCodePopValueFromStack(CodeGenEnvironment env, SourceCodePosition pos, bool reversed)
{
return new CodePiece(BCHelper.StackPop);
}
public override CodePiece GenerateCodeWriteFromStackToGrid(CodeGenEnvironment env, SourceCodePosition pos, VarDeclarationPosition gridPos, bool reversed)
{
return new CodePiece(BCHelper.StackPop); // Nobody cares about the result ...
}
public override CodePiece GenerateCodeReadFromGridToStack(CodeGenEnvironment env, SourceCodePosition pos, VarDeclarationPosition gridPos, bool reversed)
{
return CodePiece.Empty; // Do nothing
}
public override CodePiece GenerateCodeReturnFromMethodCall(CodeGenEnvironment env, SourceCodePosition pos, Expression value, bool reversed)
{
CodePiece p = CodePiece.ParseFromLine(@"0\0");
p.AppendRight(BCHelper.PC_Up_tagged(new MethodCallVerticalExitTag()));
if (reversed) p.ReverseX(false);
return p;
}
}
public class BTypeUnion : BType // Only for internal cast - is castable to everything
{
public BTypeUnion(SourceCodePosition pos)
: base(pos)
{
//--
}
public override int GetCodeSize()
{
throw new InvalidAstStateException(Position);
}
public override string GetDebugString()
{
return "union";
}
public override Literal GetDefaultValue()
{
return new LiteralInt(new SourceCodePosition(), 0);
}
public override bool IsImplicitCastableTo(BType other)
{
return true;
}
public override int GetPriority()
{
return PRIORITY_UNION;
}
public override CodePiece GenerateCodeAssignment(CodeGenEnvironment env, SourceCodePosition pos, Expression source, ExpressionValuePointer target, bool reversed)
{
throw new InvalidAstStateException(pos);
}
public override CodePiece GenerateCodePopValueFromStack(CodeGenEnvironment env, SourceCodePosition pos, bool reversed)
{
throw new InvalidAstStateException(pos);
}
public override CodePiece GenerateCodeWriteFromStackToGrid(CodeGenEnvironment env, SourceCodePosition pos, VarDeclarationPosition gridPos, bool reversed)
{
throw new InvalidAstStateException(pos);
}
public override CodePiece GenerateCodeReadFromGridToStack(CodeGenEnvironment env, SourceCodePosition pos, VarDeclarationPosition gridPos, bool reversed)
{
throw new InvalidAstStateException(pos);
}
public override CodePiece GenerateCodeReturnFromMethodCall(CodeGenEnvironment env, SourceCodePosition pos, Expression value, bool reversed)
{
throw new InvalidAstStateException(pos);
}
}
public abstract class BTypeStack : BType
{
public BTypeValue InternalType { get { return GetInternType(); } }
public readonly int StackSize;
public BTypeStack(SourceCodePosition pos, int sz)
: base(pos)
{
StackSize = sz;
}
public override int GetCodeSize()
{
return StackSize + 1;
}
public override bool Equals(BType p)
{
if ((object)p == null)
return false;
return this.GetType() == p.GetType() && (p as BTypeStack).StackSize == StackSize;
}
public override int GetHashCode()
{
return 20000 + GetPriority() * (StackSize + 1);
}
protected abstract BTypeValue GetInternType();
public override CodePiece GenerateCodeAssignment(CodeGenEnvironment env, SourceCodePosition pos, Expression source, ExpressionValuePointer target, bool reversed)
{
CodePiece p = new CodePiece();
BTypeArray type = target.GetResultType() as BTypeArray;
ExpressionDirectValuePointer vPointer = target as ExpressionDirectValuePointer;
if (reversed)
{
p.AppendLeft(source.GenerateCode(env, reversed));
p.AppendLeft(CodePieceStore.WriteArrayFromStack(env, vPointer.Target.CodeDeclarationPos, reversed));
p.NormalizeX();
}
else
{
p.AppendRight(source.GenerateCode(env, reversed));
p.AppendRight(CodePieceStore.WriteArrayFromStack(env, vPointer.Target.CodeDeclarationPos, reversed));
p.NormalizeX();
}
return p;
}
public override CodePiece GenerateCodePopValueFromStack(CodeGenEnvironment env, SourceCodePosition pos, bool reversed)
{
return CodePieceStore.PopMultipleStackValues(StackSize + 1, reversed);
}
public override CodePiece GenerateCodeWriteFromStackToGrid(CodeGenEnvironment env, SourceCodePosition pos, VarDeclarationPosition gridPos, bool reversed)
{
return CodePieceStore.WriteArrayFromStack(env, gridPos, reversed);
}
public override CodePiece GenerateCodeReadFromGridToStack(CodeGenEnvironment env, SourceCodePosition pos, VarDeclarationPosition gridPos, bool reversed)
{
return CodePieceStore.ReadArrayToStack(env, gridPos, reversed);
}
public override CodePiece GenerateCodeReturnFromMethodCall(CodeGenEnvironment env, SourceCodePosition pos, Expression value, bool reversed)
{
CodePiece p = new CodePiece();
if (reversed)
{
#region Reversed
p.AppendLeft(value.GenerateCode(env, reversed));
// Switch ReturnValue (Array) and BackJumpAddr
p.AppendLeft(CodePieceStore.WriteArrayFromStack(env, env.TMP_ARRFIELD_RETURNVAL, reversed));
p.AppendLeft(CodePieceStore.WriteValueToField(env.TMP_FIELD_JMP_ADDR, reversed));
p.AppendLeft(CodePieceStore.ReadArrayToStack(env, env.TMP_ARRFIELD_RETURNVAL, reversed));
p.AppendLeft(CodePieceStore.ReadValueFromField(env.TMP_FIELD_JMP_ADDR, reversed));
p.AppendLeft(BCHelper.Digit0); // Right Lane
p.AppendLeft(BCHelper.PC_Up_tagged(new MethodCallVerticalExitTag()));
#endregion
}
else
{
#region Normal
p.AppendRight(value.GenerateCode(env, reversed));
// Switch ReturnValue (Array) and BackJumpAddr
p.AppendRight(CodePieceStore.WriteArrayFromStack(env, env.TMP_ARRFIELD_RETURNVAL, reversed));
p.AppendRight(CodePieceStore.WriteValueToField(env.TMP_FIELD_JMP_ADDR, reversed));
p.AppendRight(CodePieceStore.ReadArrayToStack(env, env.TMP_ARRFIELD_RETURNVAL, reversed));
p.AppendRight(CodePieceStore.ReadValueFromField(env.TMP_FIELD_JMP_ADDR, reversed));
p.AppendRight(BCHelper.Digit0); // Right Lane
p.AppendRight(BCHelper.PC_Up_tagged(new MethodCallVerticalExitTag()));
#endregion
}
p.NormalizeX();
return p;
}
}
#endregion
#region Value Types
public class BTypeInt : BTypeValue
{
public BTypeInt(SourceCodePosition pos)
: base(pos)
{
//--
}
public override string GetDebugString()
{
return "int";
}
public override Literal GetDefaultValue()
{
return new LiteralInt(new SourceCodePosition(), CGO.DefaultNumeralValue);
}
public override bool IsImplicitCastableTo(BType other)
{
return (other is BTypeInt);
}
public override int GetPriority()
{
return PRIORITY_INT;
}
}
public class BTypeDigit : BTypeValue
{
public BTypeDigit(SourceCodePosition pos)
: base(pos)
{
//--
}
public override string GetDebugString()
{
return "digit";
}
public override Literal GetDefaultValue()
{
return new LiteralDigit(new SourceCodePosition(), CGO.DefaultNumeralValue);
}
public override bool IsImplicitCastableTo(BType other)
{
return (other is BTypeDigit || other is BTypeInt);
}
public override int GetPriority()
{
return PRIORITY_DIGIT;
}
}
public class BTypeChar : BTypeValue
{
public BTypeChar(SourceCodePosition pos)
: base(pos)
{
//--
}
public override string GetDebugString()
{
return "char";
}
public override Literal GetDefaultValue()
{
return new LiteralChar(new SourceCodePosition(), CGO.DefaultCharacterValue);
}
public override bool IsImplicitCastableTo(BType other)
{
return (other is BTypeChar);
}
public override int GetPriority()
{
return PRIORITY_CHAR;
}
}
public class BTypeBool : BTypeValue
{
public BTypeBool(SourceCodePosition pos)
: base(pos)
{
//--
}
public override string GetDebugString()
{
return "bool";
}
public override Literal GetDefaultValue()
{
return new LiteralBool(new SourceCodePosition(), CGO.DefaultBooleanValue);
}
public override bool IsImplicitCastableTo(BType other)
{
return (other is BTypeBool);
}
public override int GetPriority()
{
return PRIORITY_BOOL;
}
}
#endregion Value Types
#region Array Types
public class BTypeIntArr : BTypeArray
{
public BTypeIntArr(SourceCodePosition pos, int sz)
: base(pos, sz)
{
}
public override string GetDebugString()
{
return string.Format("int[{0}]", ArraySize);
}
public override Literal GetDefaultValue()
{
return new LiteralIntArr(new SourceCodePosition(), Enumerable.Repeat((long)CGO.DefaultNumeralValue, ArraySize).ToList());
}
public override bool IsImplicitCastableTo(BType other)
{
return (other is BTypeArray && (other as BTypeArray).ArraySize == ArraySize && (other is BTypeIntArr));
}
public override int GetPriority()
{
return PRIORITY_INT;
}
protected override BTypeValue GetInternType()
{
return new BTypeInt(Position);
}
}
public class BTypeCharArr : BTypeArray
{
public BTypeCharArr(SourceCodePosition pos, int sz)
: base(pos, sz)
{
}
public override string GetDebugString()
{
return string.Format("char[{0}]", ArraySize);
}
public override Literal GetDefaultValue()
{
return new LiteralCharArr(new SourceCodePosition(), Enumerable.Repeat(CGO.DefaultCharacterValue, ArraySize).ToList());
}
public override bool IsImplicitCastableTo(BType other)
{
return (other is BTypeArray && (other as BTypeArray).ArraySize == ArraySize && (other is BTypeCharArr));
}
public override int GetPriority()
{
return PRIORITY_CHAR;
}
protected override BTypeValue GetInternType()
{
return new BTypeChar(Position);
}
}
public class BTypeDigitArr : BTypeArray
{
public BTypeDigitArr(SourceCodePosition pos, int sz)
: base(pos, sz)
{
}
public override string GetDebugString()
{
return string.Format("digit[{0}]", ArraySize);
}
public override Literal GetDefaultValue()
{
return new LiteralDigitArr(new SourceCodePosition(), Enumerable.Repeat(CGO.DefaultNumeralValue, ArraySize).ToList());
}
public override bool IsImplicitCastableTo(BType other)
{
return (other is BTypeArray && (other as BTypeArray).ArraySize == ArraySize && (other is BTypeDigitArr || other is BTypeIntArr));
}
public override int GetPriority()
{
return PRIORITY_DIGIT;
}
protected override BTypeValue GetInternType()
{
return new BTypeDigit(Position);
}
}
public class BTypeBoolArr : BTypeArray
{
public BTypeBoolArr(SourceCodePosition pos, int sz)
: base(pos, sz)
{
}
public override string GetDebugString()
{
return string.Format("bool[{0}]", ArraySize);
}
public override Literal GetDefaultValue()
{
return new LiteralBoolArr(new SourceCodePosition(), Enumerable.Repeat(CGO.DefaultBooleanValue, ArraySize).ToList());
}
public override bool IsImplicitCastableTo(BType other)
{
return (other is BTypeArray && (other as BTypeArray).ArraySize == ArraySize && (other is BTypeBoolArr));
}
public override int GetPriority()
{
return PRIORITY_BOOL;
}
protected override BTypeValue GetInternType()
{
return new BTypeBool(Position);
}
}
#endregion Array Types
#region Stack Types
public class BTypeIntStack : BTypeStack
{
public BTypeIntStack(SourceCodePosition pos, int sz)
: base(pos, sz)
{
}
public override string GetDebugString()
{
return string.Format("int_stack<{0}>", StackSize);
}
public override Literal GetDefaultValue()
{
return new LiteralIntStack(new SourceCodePosition(), new List<long>(), StackSize);
}
public override bool IsImplicitCastableTo(BType other)
{
return (other is BTypeStack && (other as BTypeStack).StackSize == StackSize && (other is BTypeIntStack));
}
public override int GetPriority()
{
return PRIORITY_INT;
}
protected override BTypeValue GetInternType()
{
return new BTypeInt(Position);
}
}
public class BTypeCharStack : BTypeStack
{
public BTypeCharStack(SourceCodePosition pos, int sz)
: base(pos, sz)
{
}
public override string GetDebugString()
{
return string.Format("char_stack<{0}>", StackSize);
}
public override Literal GetDefaultValue()
{
return new LiteralCharStack(new SourceCodePosition(), new List<char>(), StackSize);
}
public override bool IsImplicitCastableTo(BType other)
{
return (other is BTypeStack && (other as BTypeStack).StackSize == StackSize && (other is BTypeCharStack));
}
public override int GetPriority()
{
return PRIORITY_CHAR;
}
protected override BTypeValue GetInternType()
{
return new BTypeChar(Position);
}
}
public class BTypeDigitStack : BTypeStack
{
public BTypeDigitStack(SourceCodePosition pos, int sz)
: base(pos, sz)
{
}
public override string GetDebugString()
{
return string.Format("digit_stack<{0}>", StackSize);
}
public override Literal GetDefaultValue()
{
return new LiteralDigitStack(new SourceCodePosition(), new List<byte>(), StackSize);
}
public override bool IsImplicitCastableTo(BType other)
{
return (other is BTypeStack && (other as BTypeStack).StackSize == StackSize && (other is BTypeDigitStack));
}
public override int GetPriority()
{
return PRIORITY_DIGIT;
}
protected override BTypeValue GetInternType()
{
return new BTypeDigit(Position);
}
}
public class BTypeBoolStack : BTypeStack
{
public BTypeBoolStack(SourceCodePosition pos, int sz)
: base(pos, sz)
{
}
public override string GetDebugString()
{
return string.Format("bool_stack<{0}>", StackSize);
}
public override Literal GetDefaultValue()
{
return new LiteralBoolStack(new SourceCodePosition(), new List<bool>(), StackSize);
}
public override bool IsImplicitCastableTo(BType other)
{
return (other is BTypeStack && (other as BTypeStack).StackSize == StackSize && (other is BTypeBoolStack));
}
public override int GetPriority()
{
return PRIORITY_BOOL;
}
protected override BTypeValue GetInternType()
{
return new BTypeBool(Position);
}
}
#endregion
}
| |
using System;
using Csla;
using Invoices.DataAccess;
namespace Invoices.Business
{
/// <summary>
/// InvoiceInfo (read only object).<br/>
/// This is a generated <see cref="InvoiceInfo"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="InvoiceList"/> collection.
/// </remarks>
[Serializable]
public partial class InvoiceInfo : ReadOnlyBase<InvoiceInfo>
{
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="InvoiceId"/> property.
/// </summary>
public static readonly PropertyInfo<Guid> InvoiceIdProperty = RegisterProperty<Guid>(p => p.InvoiceId, "Invoice Id", Guid.NewGuid());
/// <summary>
/// The invoice internal identification
/// </summary>
/// <value>The Invoice Id.</value>
public Guid InvoiceId
{
get { return GetProperty(InvoiceIdProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="InvoiceNumber"/> property.
/// </summary>
public static readonly PropertyInfo<string> InvoiceNumberProperty = RegisterProperty<string>(p => p.InvoiceNumber, "Invoice Number");
/// <summary>
/// The public invoice number
/// </summary>
/// <value>The Invoice Number.</value>
public string InvoiceNumber
{
get { return GetProperty(InvoiceNumberProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CustomerId"/> property.
/// </summary>
public static readonly PropertyInfo<string> CustomerIdProperty = RegisterProperty<string>(p => p.CustomerId, "Customer Id");
/// <summary>
/// Gets the Customer Id.
/// </summary>
/// <value>The Customer Id.</value>
public string CustomerId
{
get { return GetProperty(CustomerIdProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="InvoiceDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> InvoiceDateProperty = RegisterProperty<SmartDate>(p => p.InvoiceDate, "Invoice Date");
/// <summary>
/// Gets the Invoice Date.
/// </summary>
/// <value>The Invoice Date.</value>
public string InvoiceDate
{
get { return GetPropertyConvert<SmartDate, string>(InvoiceDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="TotalAmount"/> property.
/// </summary>
public static readonly PropertyInfo<decimal> TotalAmountProperty = RegisterProperty<decimal>(p => p.TotalAmount, "Total Amount");
/// <summary>
/// Computed invoice total amount
/// </summary>
/// <value>The Total Amount.</value>
public decimal TotalAmount
{
get { return GetProperty(TotalAmountProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="IsActive"/> property.
/// </summary>
public static readonly PropertyInfo<bool> IsActiveProperty = RegisterProperty<bool>(p => p.IsActive, "Is Active");
/// <summary>
/// Gets the Is Active.
/// </summary>
/// <value><c>true</c> if Is Active; otherwise, <c>false</c>.</value>
public bool IsActive
{
get { return GetProperty(IsActiveProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> CreateDateProperty = RegisterProperty<SmartDate>(p => p.CreateDate, "Create Date", new SmartDate(DateTime.Now));
/// <summary>
/// Gets the Create Date.
/// </summary>
/// <value>The Create Date.</value>
public SmartDate CreateDate
{
get { return GetProperty(CreateDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="CreateUser"/> property.
/// </summary>
public static readonly PropertyInfo<int> CreateUserProperty = RegisterProperty<int>(p => p.CreateUser, "Create User", Security.UserInformation.UserId);
/// <summary>
/// Gets the Create User.
/// </summary>
/// <value>The Create User.</value>
public int CreateUser
{
get { return GetProperty(CreateUserProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeDate"/> property.
/// </summary>
public static readonly PropertyInfo<SmartDate> ChangeDateProperty = RegisterProperty<SmartDate>(p => p.ChangeDate, "Change Date");
/// <summary>
/// Gets the Change Date.
/// </summary>
/// <value>The Change Date.</value>
public SmartDate ChangeDate
{
get { return GetProperty(ChangeDateProperty); }
}
/// <summary>
/// Maintains metadata about <see cref="ChangeUser"/> property.
/// </summary>
public static readonly PropertyInfo<int> ChangeUserProperty = RegisterProperty<int>(p => p.ChangeUser, "Change User");
/// <summary>
/// Gets the Change User.
/// </summary>
/// <value>The Change User.</value>
public int ChangeUser
{
get { return GetProperty(ChangeUserProperty); }
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="InvoiceInfo"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public InvoiceInfo()
{
// Use factory methods and do not use direct creation.
}
#endregion
#region Data Access
/// <summary>
/// Loads a <see cref="InvoiceInfo"/> object from the given <see cref="InvoiceInfoDto"/>.
/// </summary>
/// <param name="data">The InvoiceInfoDto to use.</param>
private void Child_Fetch(InvoiceInfoDto data)
{
// Value properties
LoadProperty(InvoiceIdProperty, data.InvoiceId);
LoadProperty(InvoiceNumberProperty, data.InvoiceNumber);
LoadProperty(CustomerIdProperty, data.CustomerId);
LoadProperty(InvoiceDateProperty, data.InvoiceDate);
LoadProperty(IsActiveProperty, data.IsActive);
LoadProperty(CreateDateProperty, data.CreateDate);
LoadProperty(CreateUserProperty, data.CreateUser);
LoadProperty(ChangeDateProperty, data.ChangeDate);
LoadProperty(ChangeUserProperty, data.ChangeUser);
var args = new DataPortalHookArgs(data);
OnFetchRead(args);
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.Linq;
using NuGet.VisualStudio.Resources;
using System.Globalization;
namespace NuGet.VisualStudio
{
[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(IVsPackageSourceProvider))]
[Export(typeof(IPackageSourceProvider))]
public class VsPackageSourceProvider : IVsPackageSourceProvider
{
private static readonly string NuGetOfficialFeedNameV3 = VsResources.NuGetOfficialPreviewSourceName;
private static readonly string NuGetLegacyOfficialFeedName = VsResources.NuGetLegacyOfficialSourceName;
private static readonly string NuGetOfficialFeedName = VsResources.NuGetOfficialSourceName;
private static readonly PackageSource NuGetDefaultSource = new PackageSource(NuGetConstants.DefaultFeedUrl, NuGetOfficialFeedName);
private static readonly PackageSource NuGetV3Source = new PackageSource(
NuGetConstants.V3FeedUrl,
NuGetOfficialFeedNameV3,
isEnabled: true,
isOfficial: true,
isPersistable: false);
private static readonly PackageSource Windows8Source = new PackageSource(
NuGetConstants.VSExpressForWindows8FeedUrl,
VsResources.VisualStudioExpressForWindows8SourceName,
isEnabled: true,
isOfficial: true,
isPersistable: false);
private static readonly Dictionary<PackageSource, PackageSource> _feedsToMigrate = new Dictionary<PackageSource, PackageSource>
{
{ new PackageSource(NuGetConstants.V1FeedUrl, NuGetLegacyOfficialFeedName), NuGetDefaultSource },
{ new PackageSource(NuGetConstants.V2LegacyFeedUrl, NuGetLegacyOfficialFeedName), NuGetDefaultSource },
{ new PackageSource(NuGetConstants.V2LegacyOfficialPackageSourceUrl, NuGetLegacyOfficialFeedName), NuGetDefaultSource },
};
internal const string ActivePackageSourceSectionName = "activePackageSource";
private readonly IPackageSourceProvider _packageSourceProvider;
private readonly IVsShellInfo _vsShellInfo;
private readonly ISettings _settings;
private readonly ISolutionManager _solutionManager;
private bool _initialized;
private List<PackageSource> _packageSources;
private PackageSource _activePackageSource;
[ImportingConstructor]
public VsPackageSourceProvider(
ISettings settings,
IVsShellInfo vsShellInfo,
ISolutionManager solutionManager) :
this(settings, new PackageSourceProvider(settings, new[] { NuGetV3Source, NuGetDefaultSource }, _feedsToMigrate), vsShellInfo, solutionManager)
{
}
internal VsPackageSourceProvider(
ISettings settings,
IPackageSourceProvider packageSourceProvider,
IVsShellInfo vsShellInfo)
:this(settings, packageSourceProvider, vsShellInfo, null)
{
}
private VsPackageSourceProvider(
ISettings settings,
IPackageSourceProvider packageSourceProvider,
IVsShellInfo vsShellInfo,
ISolutionManager solutionManager)
{
if (settings == null)
{
throw new ArgumentNullException("settings");
}
if (packageSourceProvider == null)
{
throw new ArgumentNullException("packageSourceProvider");
}
if (vsShellInfo == null)
{
throw new ArgumentNullException("vsShellInfo");
}
_packageSourceProvider = packageSourceProvider;
_solutionManager = solutionManager;
_settings = settings;
_vsShellInfo = vsShellInfo;
_packageSources = new List<PackageSource>();
if (null != _solutionManager)
{
_solutionManager.SolutionClosed += OnSolutionOpenedOrClosed;
_solutionManager.SolutionOpened += OnSolutionOpenedOrClosed;
}
}
private void OnSolutionOpenedOrClosed(object sender, EventArgs e)
{
_initialized = false;
}
public PackageSource ActivePackageSource
{
get
{
EnsureInitialized();
return _activePackageSource;
}
set
{
EnsureInitialized();
if (value != null &&
!_packageSources.Contains(value) &&
!value.Name.Equals(NuGetOfficialFeedName, StringComparison.CurrentCultureIgnoreCase))
{
throw new ArgumentException(VsResources.PackageSource_Invalid, "value");
}
_activePackageSource = value;
PersistActivePackageSource(_settings, _activePackageSource);
}
}
internal static IEnumerable<PackageSource> DefaultSources
{
get { return new[] { NuGetDefaultSource }; }
}
internal static Dictionary<PackageSource, PackageSource> FeedsToMigrate
{
get { return _feedsToMigrate; }
}
public IEnumerable<PackageSource> LoadPackageSources()
{
EnsureInitialized();
// assert that we are not returning aggregate source
Debug.Assert(_packageSources == null || !_packageSources.Any(IsAggregateSource));
return _packageSources;
}
public void SavePackageSources(IEnumerable<PackageSource> sources)
{
if (sources == null)
{
throw new ArgumentNullException("sources");
}
// reload the sources
_initialized = false;
EnsureInitialized();
var newSources = sources.ToList();
Debug.Assert(!newSources.Any(IsAggregateSource));
if (PackageSourcesEqual(_packageSources, newSources))
{
return;
}
ActivePackageSource = null;
_packageSources.Clear();
_packageSources.AddRange(newSources);
PersistPackageSources(_packageSourceProvider, _vsShellInfo, _packageSources);
if (PackageSourcesSaved != null)
{
PackageSourcesSaved(this, EventArgs.Empty);
}
}
// We only need to check properties that can be changed by user through UI.
internal static bool PackageSourcesEqual(List<PackageSource> a, List<PackageSource> b)
{
if (a.Count != b.Count)
{
return false;
}
for (int i = 0; i < a.Count; ++i)
{
var s1 = a[i];
var s2 = b[i];
if (!StringComparer.CurrentCultureIgnoreCase.Equals(s1.Name, s2.Name))
{
return false;
}
if (!StringComparer.OrdinalIgnoreCase.Equals(s1.Source, s2.Source))
{
return false;
}
if (s1.IsEnabled != s2.IsEnabled)
{
return false;
}
}
return true;
}
public void DisablePackageSource(PackageSource source)
{
// There's no scenario for this method to get called, so do nothing here.
Debug.Fail("This method shouldn't get called.");
}
public bool IsPackageSourceEnabled(PackageSource source)
{
EnsureInitialized();
var sourceInUse = _packageSources.FirstOrDefault(ps => ps.Equals(source));
return sourceInUse != null && sourceInUse.IsEnabled;
}
private void EnsureInitialized()
{
if (_initialized)
{
return;
}
lock (this)
{
if (_initialized)
{
return;
}
_packageSources = _packageSourceProvider.LoadPackageSources().ToList();
// When running Visual Studio Express for Windows 8, we insert the curated feed at the top
if (_vsShellInfo.IsVisualStudioExpressForWindows8)
{
bool windows8SourceIsEnabled = _packageSourceProvider.IsPackageSourceEnabled(Windows8Source);
// defensive coding: make sure we don't add duplicated win8 source
_packageSources.RemoveAll(p => p.Equals(Windows8Source));
// Windows8Source is a static object which is meant for doing comparison only.
// To add it to the list of package sources, we make a clone of it first.
var windows8SourceClone = Windows8Source.Clone();
windows8SourceClone.IsEnabled = windows8SourceIsEnabled;
_packageSources.Insert(0, windows8SourceClone);
}
InitializeActivePackageSource();
_initialized = true;
}
}
private void InitializeActivePackageSource()
{
_activePackageSource = DeserializeActivePackageSource(_settings, _vsShellInfo);
bool activeSourceChanged = false;
// Don't allow the aggregate source as the active source any more!
if (IsAggregateSource(_activePackageSource))
{
activeSourceChanged = true;
_activePackageSource = _packageSources.FirstOrDefault(p => p.IsEnabled);
}
PackageSource migratedActiveSource;
if (_activePackageSource == null)
{
// If there are no sources, pick the first source that's enabled.
activeSourceChanged = true;
_activePackageSource = _packageSources.FirstOrDefault(p => p.IsEnabled);
}
else if (_feedsToMigrate.TryGetValue(_activePackageSource, out migratedActiveSource))
{
// Check if we need to migrate the active source.
activeSourceChanged = true;
_activePackageSource = migratedActiveSource;
}
if (activeSourceChanged)
{
PersistActivePackageSource(_settings, _activePackageSource);
}
}
private static void PersistActivePackageSource(ISettings settings, PackageSource activePackageSource)
{
settings.DeleteSection(ActivePackageSourceSectionName);
if (activePackageSource != null)
{
settings.SetValue(ActivePackageSourceSectionName, activePackageSource.Name, activePackageSource.Source);
}
}
private PackageSource DeserializeActivePackageSource(
ISettings settings,
IVsShellInfo vsShellInfo)
{
// NOTE: Even though the aggregate source is being disabled, this method can still return it because
// it could be reading a v2.x active source setting. The caller of this method will migrate the active source
// to the first enabled feed.
var enabledSources = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase);
foreach (var source in _packageSources.Where(p => p.IsEnabled))
{
enabledSources.Add(source.Name);
}
// The special aggregate source, i.e. "All", is always enabled.
enabledSources.Add(Resources.VsResources.AggregateSourceName);
var settingValues = settings.GetValues(ActivePackageSourceSectionName);
if (settingValues != null)
{
settingValues = settingValues.Where(s => enabledSources.Contains(s.Key)).ToList();
}
PackageSource packageSource = null;
if (settingValues != null && settingValues.Any())
{
KeyValuePair<string, string> setting = settingValues.First();
if (IsAggregateSource(setting.Key, setting.Value))
{
packageSource = AggregatePackageSource.Instance;
}
else
{
packageSource = new PackageSource(setting.Value, setting.Key);
}
}
if (packageSource != null)
{
// guard against corrupted data if the active package source is not enabled
packageSource.IsEnabled = true;
}
return packageSource;
}
private static void PersistPackageSources(IPackageSourceProvider packageSourceProvider, IVsShellInfo vsShellInfo, List<PackageSource> packageSources)
{
// Starting from version 1.3, we persist the package sources to the nuget.config file instead of VS registry.
// assert that we are not saving aggregate source
Debug.Assert(!packageSources.Any(p => IsAggregateSource(p.Name, p.Source)));
packageSourceProvider.SavePackageSources(packageSources);
}
private static bool IsAggregateSource(string name, string source)
{
PackageSource aggregate = AggregatePackageSource.Instance;
return aggregate.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase) ||
aggregate.Source.Equals(source, StringComparison.InvariantCultureIgnoreCase);
}
private static bool IsAggregateSource(PackageSource packageSource)
{
return packageSource != null &&
IsAggregateSource(packageSource.Name, packageSource.Source);
}
public event EventHandler PackageSourcesSaved;
}
}
| |
namespace OpenLibrary.Mvc.Helper
{
/// <summary>
/// Routing type
/// </summary>
public enum RoutingType
{
/// <summary>
/// Area route name
/// </summary>
Area,
/// <summary>
/// Controller route name
/// </summary>
Controller,
/// <summary>
/// Action route name
/// </summary>
Action
}
/// <summary>
/// Helper for controller
/// </summary>
public static class ControllerHelper
{
// ReSharper disable EmptyGeneralCatchClause
// ReSharper disable InconsistentNaming
/// <summary>
/// Get current routing value
/// </summary>
/// <param name="helper"></param>
/// <param name="type">Requested routing type</param>
/// <returns>string</returns>
public static string Routing(this System.Web.Mvc.HtmlHelper helper, RoutingType type)
{
return Routing(helper.ViewContext.RouteData, type);
}
/// <summary>
/// Get current routing value
/// </summary>
/// <param name="controller"></param>
/// <param name="type">Requested routing type</param>
/// <returns>string</returns>
public static string Routing(this System.Web.Mvc.Controller controller, RoutingType type)
{
return Routing(controller.RouteData, type);
}
/// <summary>
/// Get current routing value
/// </summary>
/// <param name="controller"></param>
/// <param name="type">Requested routing type</param>
/// <returns>string</returns>
public static string Routing(this System.Web.Mvc.ControllerBase controller, RoutingType type)
{
return Routing(controller.ControllerContext.RouteData, type);
}
/// <summary>
/// Get current routing value
/// </summary>
/// <param name="routeData"></param>
/// <param name="type">Requested routing type</param>
/// <returns>string</returns>
public static string Routing(this System.Web.Routing.RouteData routeData, RoutingType type)
{
try
{
return type == RoutingType.Area
? routeData.DataTokens[type.ToString().ToLower()].ToString()
: routeData.Values[type.ToString().ToLower()].ToString();
}
catch (System.NullReferenceException)
{
return string.Empty;
}
}
/// <summary>
/// Absolute site URL
/// </summary>
/// <param name="controller"></param>
/// <returns></returns>
public static string GetApplicationUrl(this System.Web.Mvc.Controller controller)
{
return controller.GetHostUrl() + controller.Url.Content("~/");
}
/// <summary>
/// Absolute site URL without base path
/// </summary>
/// <param name="controller"></param>
/// <returns></returns>
public static string GetHostUrl(this System.Web.Mvc.Controller controller)
{
return controller.Request.Url != null
? controller.Request.Url.Scheme + "://" + controller.Request.ServerVariables["HTTP_HOST"]
: string.Empty;
}
/// <summary>
/// Get remote client IP
/// </summary>
/// <param name="controller"></param>
/// <returns>Client IP</returns>
[System.Obsolete("Use Controller.Request.IpAddress() instead")]
public static string GetClientIpAddress(this System.Web.Mvc.Controller controller)
{
return controller.Request.IpAddress();
}
/// <summary>
/// Get remote client IP
/// </summary>
/// <param name="request"></param>
/// <returns>Client IP</returns>
public static string IpAddress(this System.Web.HttpRequestBase request)
{
string ip = request.UserHostAddress ?? string.Empty;
try
{
var temp = System.Net.Dns.GetHostAddresses(ip);
foreach (var ipAddress in temp)
{
if (ipAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
return ipAddress.ToString().Trim();
}
foreach (var ipAddress in temp)
{
if (ipAddress.AddressFamily != System.Net.Sockets.AddressFamily.InterNetworkV6)
continue;
var ipEntry = System.Net.Dns.GetHostEntry(ipAddress);
foreach (var _ipEntry in ipEntry.AddressList)
{
if (_ipEntry.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
return _ipEntry.ToString().Trim();
}
}
if (temp.Length > 0)
ip = temp[0].MapToIPv4().ToString();
}
catch (System.Exception) { }
return ip;
}
/// <summary>
/// Get remote hostname
/// </summary>
/// <param name="controller"></param>
/// <param name="ip">IP address</param>
/// <returns></returns>
[System.Obsolete("Use Controller.Request.Hostname() instead")]
public static string GetClientHostname(this System.Web.Mvc.Controller controller, string ip = "")
{
return controller.Request.Hostname(ip);
}
/// <summary>
/// Get remote hostname
/// </summary>
/// <param name="request"></param>
/// <param name="ip">IP address</param>
/// <returns></returns>
public static string Hostname(this System.Web.HttpRequestBase request, string ip = "")
{
try
{
if (string.IsNullOrEmpty(ip))
ip = request.IpAddress();
return System.Net.Dns.GetHostEntry(ip).HostName;
}
catch (System.Exception) { }
return string.Empty;
}
/// <summary>
/// Get raw request
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public static string Raw(this System.Web.HttpRequestBase request)
{
return new System.IO.StreamReader(request.InputStream).ReadToEnd();
}
#if NET40
/// <summary>
/// Implement missing extension of MapToIPv4
/// </summary>
/// <param name="ipAddress"></param>
/// <returns></returns>
public static System.Net.IPAddress MapToIPv4(this System.Net.IPAddress ipAddress)
{
//TODO: implement MapToIPv4
return new System.Net.IPAddress(0);
}
#endif
}
}
| |
using System;
using System.Collections;
using Server.Network;
using Server.Mobiles;
using Server.Items;
using Server.Gumps;
namespace Server.Items.Crops
{
public class CabbageSeed : BaseCrop
{
// return true to allow planting on Dirt Item (ItemID 0x32C9)
// See CropHelper.cs for other overriddable types
public override bool CanGrowGarden { get { return true; } }
[Constructable]
public CabbageSeed()
: this(1)
{
}
[Constructable]
public CabbageSeed(int amount)
: base(0xF27)
{
Stackable = true;
Weight = .5;
Hue = 0x5E2;
Movable = true;
Amount = amount;
Name = AgriTxt.Seed + " de Chou";
}
public override void OnDoubleClick(Mobile from)
{
if (from.Mounted && !CropHelper.CanWorkMounted)
{
from.SendMessage(AgriTxt.CannotWorkMounted);
return;
}
Point3D m_pnt = from.Location;
Map m_map = from.Map;
if (!IsChildOf(from.Backpack))
{
from.SendLocalizedMessage(1042010); //You must have the object in your backpack to use it.
return;
}
else if (!CropHelper.CheckCanGrow(this, m_map, m_pnt.X, m_pnt.Y))
{
from.SendMessage(AgriTxt.CannotGrowHere);
return;
}
//check for BaseCrop on this tile
ArrayList cropshere = CropHelper.CheckCrop(m_pnt, m_map, 0);
if (cropshere.Count > 0)
{
from.SendMessage(AgriTxt.AlreadyCrop);
return;
}
//check for over planting prohibt if 6 maybe 5 neighboring crops
ArrayList cropsnear = CropHelper.CheckCrop(m_pnt, m_map, 1);
if ((cropsnear.Count > 5) || ((cropsnear.Count == 5) && Utility.RandomBool()))
{
from.SendMessage(AgriTxt.TooMuchCrops);
return;
}
if (this.BumpZ) ++m_pnt.Z;
if (!from.Mounted)
from.Animate(32, 5, 1, true, false, 0); // Bow
from.SendMessage(AgriTxt.CropPlanted);
this.Consume();
Item item = new CabbageSeedling(from);
item.Location = m_pnt;
item.Map = m_map;
}
public CabbageSeed(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
public class CabbageSeedling : BaseCrop
{
private static Mobile m_sower;
public Timer thisTimer;
[CommandProperty(AccessLevel.GameMaster)]
public Mobile Sower { get { return m_sower; } set { m_sower = value; } }
[Constructable]
public CabbageSeedling(Mobile sower)
: base(0xCB5)
{
Movable = false;
Name = AgriTxt.Seedling + " de Chou";
m_sower = sower;
init(this);
}
public static void init(CabbageSeedling plant)
{
plant.thisTimer = new CropHelper.GrowTimer(plant, typeof(CabbageCrop), plant.Sower);
plant.thisTimer.Start();
}
public override void OnDoubleClick(Mobile from)
{
if (from.Mounted && !CropHelper.CanWorkMounted)
{
from.SendMessage(AgriTxt.CannotWorkMounted);
return;
}
if ((Utility.RandomDouble() <= .25) && !(m_sower.AccessLevel > AccessLevel.Counselor))
{ //25% Chance
from.SendMessage(AgriTxt.PickCrop);
thisTimer.Stop();
this.Delete();
}
else from.SendMessage(AgriTxt.TooYoungCrop);
}
public CabbageSeedling(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0);
writer.Write(m_sower);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
m_sower = reader.ReadMobile();
init(this);
}
}
public class CabbageCrop : BaseCrop
{
private const int max = 1;
private int fullGraphic;
private int pickedGraphic;
private DateTime lastpicked;
private Mobile m_sower;
private int m_yield;
public Timer regrowTimer;
private DateTime m_lastvisit;
[CommandProperty(AccessLevel.GameMaster)]
public DateTime LastSowerVisit { get { return m_lastvisit; } }
[CommandProperty(AccessLevel.GameMaster)] // debuging
public bool Growing { get { return regrowTimer.Running; } }
[CommandProperty(AccessLevel.GameMaster)]
public Mobile Sower { get { return m_sower; } set { m_sower = value; } }
[CommandProperty(AccessLevel.GameMaster)]
public int Yield { get { return m_yield; } set { m_yield = value; } }
public int Capacity { get { return max; } }
public int FullGraphic { get { return fullGraphic; } set { fullGraphic = value; } }
public int PickGraphic { get { return pickedGraphic; } set { pickedGraphic = value; } }
public DateTime LastPick { get { return lastpicked; } set { lastpicked = value; } }
[Constructable]
public CabbageCrop(Mobile sower)
: base(0xC61)
{
Movable = false;
Name = "Chou";
m_sower = sower;
m_lastvisit = DateTime.Now;
init(this, false);
}
public static void init(CabbageCrop plant, bool full)
{
plant.PickGraphic = (0xC61);
plant.FullGraphic = (0xC7C);
plant.LastPick = DateTime.Now;
plant.regrowTimer = new CropTimer(plant);
if (full)
{
plant.Yield = plant.Capacity;
((Item)plant).ItemID = plant.FullGraphic;
}
else
{
plant.Yield = 0;
((Item)plant).ItemID = plant.PickGraphic;
plant.regrowTimer.Start();
}
}
public void UpRoot(Mobile from)
{
from.SendMessage(AgriTxt.WitherCrop);
if (regrowTimer.Running)
regrowTimer.Stop();
this.Delete();
}
public override void OnDoubleClick(Mobile from)
{
if (m_sower == null || m_sower.Deleted)
m_sower = from;
if (from.Mounted && !CropHelper.CanWorkMounted)
{
from.SendMessage(AgriTxt.CannotWorkMounted);
return;
}
if (DateTime.Now > lastpicked.AddSeconds(3)) // 3 seconds between picking
{
lastpicked = DateTime.Now;
int lumberValue = (int)from.Skills[SkillName.Lumberjacking].Value / 5;
if (lumberValue == 0)
{
from.SendMessage(AgriTxt.DunnoHowTo);
return;
}
if (from.InRange(this.GetWorldLocation(), 2))
{
if (m_yield < 1)
{
from.SendMessage(AgriTxt.NoCrop);
if (PlayerCanDestroy && !(m_sower.AccessLevel > AccessLevel.Counselor))
{
UpRootGump g = new UpRootGump(from, this);
from.SendGump(g);
}
}
else //check skill and sower
{
from.Direction = from.GetDirectionTo(this);
from.Animate(from.Mounted ? 29 : 32, 5, 1, true, false, 0);
if (from == m_sower)
{
lumberValue *= 2;
m_lastvisit = DateTime.Now;
}
if (lumberValue > m_yield)
lumberValue = m_yield + 1;
int pick = Utility.Random(lumberValue);
if (pick == 0)
{
from.SendMessage(AgriTxt.ZeroPicked);
return;
}
m_yield -= pick;
from.SendMessage(AgriTxt.YouPick + " {0} chou{1}!", pick, (pick == 1 ? "" : "x"));
//PublicOverheadMessage( MessageType.Regular, 0x3BD, false, string.Format( "{0}", m_yield ));
((Item)this).ItemID = pickedGraphic;
Cabbage crop = new Cabbage(pick);
from.AddToBackpack(crop);
if (SowerPickTime != TimeSpan.Zero && m_lastvisit + SowerPickTime < DateTime.Now && !(m_sower.AccessLevel > AccessLevel.Counselor))
{
this.UpRoot(from);
return;
}
if (!regrowTimer.Running)
{
//regrowTimer = new CropTimer( this );
regrowTimer.Start();
}
}
}
else
{
from.SendMessage(AgriTxt.TooFar);
}
}
}
private class CropTimer : Timer
{
private CabbageCrop i_plant;
public CropTimer(CabbageCrop plant)
: base(TimeSpan.FromSeconds(450), TimeSpan.FromSeconds(15))
{
Priority = TimerPriority.OneSecond;
i_plant = plant;
}
protected override void OnTick()
{
if (Utility.RandomBool())
{
if ((i_plant != null) && (!i_plant.Deleted))
{
int current = i_plant.Yield;
if (++current >= i_plant.Capacity)
{
current = i_plant.Capacity;
((Item)i_plant).ItemID = i_plant.FullGraphic;
Stop();
}
else if (current <= 0)
current = 1;
i_plant.Yield = current;
//i_plant.PublicOverheadMessage( MessageType.Regular, 0x22, false, string.Format( "{0}", current ));
}
else Stop();
}
}
}
public CabbageCrop(Serial serial)
: base(serial)
{
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)1);
writer.Write(m_lastvisit);
writer.Write(m_sower);
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
switch (version)
{
case 1:
{
m_lastvisit = reader.ReadDateTime();
goto case 0;
}
case 0:
{
m_sower = reader.ReadMobile();
break;
}
}
if (version == 0)
m_lastvisit = DateTime.Now;
init(this, true);
}
}
}
| |
#region License
/*
* HttpListenerRequest.cs
*
* This code is derived from HttpListenerRequest.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2018 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.IO;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace WebSocketSharp.Net
{
/// <summary>
/// Represents an incoming request to a <see cref="HttpListener"/> instance.
/// </summary>
/// <remarks>
/// This class cannot be inherited.
/// </remarks>
public sealed class HttpListenerRequest
{
#region Private Fields
private static readonly byte[] _100continue;
private string[] _acceptTypes;
private bool _chunked;
private HttpConnection _connection;
private Encoding _contentEncoding;
private long _contentLength;
private HttpListenerContext _context;
private CookieCollection _cookies;
private WebHeaderCollection _headers;
private string _httpMethod;
private Stream _inputStream;
private Version _protocolVersion;
private NameValueCollection _queryString;
private string _rawUrl;
private Guid _requestTraceIdentifier;
private Uri _url;
private Uri _urlReferrer;
private bool _urlSet;
private string _userHostName;
private string[] _userLanguages;
#endregion
#region Static Constructor
static HttpListenerRequest ()
{
_100continue = Encoding.ASCII.GetBytes ("HTTP/1.1 100 Continue\r\n\r\n");
}
#endregion
#region Internal Constructors
internal HttpListenerRequest (HttpListenerContext context)
{
_context = context;
_connection = context.Connection;
_contentLength = -1;
_headers = new WebHeaderCollection ();
_requestTraceIdentifier = Guid.NewGuid ();
}
#endregion
#region Public Properties
/// <summary>
/// Gets the media types that are acceptable for the client.
/// </summary>
/// <value>
/// <para>
/// An array of <see cref="string"/> that contains the names of the media
/// types specified in the value of the Accept header.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string[] AcceptTypes {
get {
var val = _headers["Accept"];
if (val == null)
return null;
if (_acceptTypes == null) {
_acceptTypes = val
.SplitHeaderValue (',')
.Trim ()
.ToList ()
.ToArray ();
}
return _acceptTypes;
}
}
/// <summary>
/// Gets an error code that identifies a problem with the certificate
/// provided by the client.
/// </summary>
/// <value>
/// An <see cref="int"/> that represents an error code.
/// </value>
/// <exception cref="NotSupportedException">
/// This property is not supported.
/// </exception>
public int ClientCertificateError {
get {
throw new NotSupportedException ();
}
}
/// <summary>
/// Gets the encoding for the entity body data included in the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Encoding"/> converted from the charset value of the
/// Content-Type header.
/// </para>
/// <para>
/// <see cref="Encoding.UTF8"/> if the charset value is not available.
/// </para>
/// </value>
public Encoding ContentEncoding {
get {
if (_contentEncoding == null)
_contentEncoding = getContentEncoding () ?? Encoding.UTF8;
return _contentEncoding;
}
}
/// <summary>
/// Gets the length in bytes of the entity body data included in the
/// request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="long"/> converted from the value of the Content-Length
/// header.
/// </para>
/// <para>
/// -1 if the header is not present.
/// </para>
/// </value>
public long ContentLength64 {
get {
return _contentLength;
}
}
/// <summary>
/// Gets the media type of the entity body data included in the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the value of the Content-Type
/// header.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string ContentType {
get {
return _headers["Content-Type"];
}
}
/// <summary>
/// Gets the cookies included in the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="CookieCollection"/> that contains the cookies.
/// </para>
/// <para>
/// An empty collection if not included.
/// </para>
/// </value>
public CookieCollection Cookies {
get {
if (_cookies == null)
_cookies = _headers.GetCookies (false);
return _cookies;
}
}
/// <summary>
/// Gets a value indicating whether the request has the entity body data.
/// </summary>
/// <value>
/// <c>true</c> if the request has the entity body data; otherwise,
/// <c>false</c>.
/// </value>
public bool HasEntityBody {
get {
return _contentLength > 0 || _chunked;
}
}
/// <summary>
/// Gets the headers included in the request.
/// </summary>
/// <value>
/// A <see cref="NameValueCollection"/> that contains the headers.
/// </value>
public NameValueCollection Headers {
get {
return _headers;
}
}
/// <summary>
/// Gets the HTTP method specified by the client.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the HTTP method specified in
/// the request line.
/// </value>
public string HttpMethod {
get {
return _httpMethod;
}
}
/// <summary>
/// Gets a stream that contains the entity body data included in
/// the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Stream"/> that contains the entity body data.
/// </para>
/// <para>
/// <see cref="Stream.Null"/> if the entity body data is not available.
/// </para>
/// </value>
public Stream InputStream {
get {
if (_inputStream == null)
_inputStream = getInputStream () ?? Stream.Null;
return _inputStream;
}
}
/// <summary>
/// Gets a value indicating whether the client is authenticated.
/// </summary>
/// <value>
/// <c>true</c> if the client is authenticated; otherwise, <c>false</c>.
/// </value>
public bool IsAuthenticated {
get {
return _context.User != null;
}
}
/// <summary>
/// Gets a value indicating whether the request is sent from the local
/// computer.
/// </summary>
/// <value>
/// <c>true</c> if the request is sent from the same computer as the server;
/// otherwise, <c>false</c>.
/// </value>
public bool IsLocal {
get {
return _connection.IsLocal;
}
}
/// <summary>
/// Gets a value indicating whether a secure connection is used to send
/// the request.
/// </summary>
/// <value>
/// <c>true</c> if the connection is secure; otherwise, <c>false</c>.
/// </value>
public bool IsSecureConnection {
get {
return _connection.IsSecure;
}
}
/// <summary>
/// Gets a value indicating whether the request is a WebSocket handshake
/// request.
/// </summary>
/// <value>
/// <c>true</c> if the request is a WebSocket handshake request; otherwise,
/// <c>false</c>.
/// </value>
public bool IsWebSocketRequest {
get {
return _httpMethod == "GET"
&& _protocolVersion > HttpVersion.Version10
&& _headers.Upgrades ("websocket");
}
}
/// <summary>
/// Gets a value indicating whether a persistent connection is requested.
/// </summary>
/// <value>
/// <c>true</c> if the request specifies that the connection is kept open;
/// otherwise, <c>false</c>.
/// </value>
public bool KeepAlive {
get {
return _headers.KeepsAlive (_protocolVersion);
}
}
/// <summary>
/// Gets the endpoint to which the request is sent.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the server IP
/// address and port number.
/// </value>
public System.Net.IPEndPoint LocalEndPoint {
get {
return _connection.LocalEndPoint;
}
}
/// <summary>
/// Gets the HTTP version specified by the client.
/// </summary>
/// <value>
/// A <see cref="Version"/> that represents the HTTP version specified in
/// the request line.
/// </value>
public Version ProtocolVersion {
get {
return _protocolVersion;
}
}
/// <summary>
/// Gets the query string included in the request.
/// </summary>
/// <value>
/// <para>
/// A <see cref="NameValueCollection"/> that contains the query
/// parameters.
/// </para>
/// <para>
/// An empty collection if not included.
/// </para>
/// </value>
public NameValueCollection QueryString {
get {
if (_queryString == null) {
var url = Url;
_queryString = HttpUtility.InternalParseQueryString (
url != null ? url.Query : null,
Encoding.UTF8
);
}
return _queryString;
}
}
/// <summary>
/// Gets the raw URL specified by the client.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the request target specified in
/// the request line.
/// </value>
public string RawUrl {
get {
return _rawUrl;
}
}
/// <summary>
/// Gets the endpoint from which the request is sent.
/// </summary>
/// <value>
/// A <see cref="System.Net.IPEndPoint"/> that represents the client IP
/// address and port number.
/// </value>
public System.Net.IPEndPoint RemoteEndPoint {
get {
return _connection.RemoteEndPoint;
}
}
/// <summary>
/// Gets the trace identifier of the request.
/// </summary>
/// <value>
/// A <see cref="Guid"/> that represents the trace identifier.
/// </value>
public Guid RequestTraceIdentifier {
get {
return _requestTraceIdentifier;
}
}
/// <summary>
/// Gets the URL requested by the client.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Uri"/> that represents the URL parsed from the request.
/// </para>
/// <para>
/// <see langword="null"/> if the URL cannot be parsed.
/// </para>
/// </value>
public Uri Url {
get {
if (!_urlSet) {
_url = HttpUtility.CreateRequestUrl (
_rawUrl,
_userHostName ?? UserHostAddress,
IsWebSocketRequest,
IsSecureConnection
);
_urlSet = true;
}
return _url;
}
}
/// <summary>
/// Gets the URI of the resource from which the requested URL was obtained.
/// </summary>
/// <value>
/// <para>
/// A <see cref="Uri"/> converted from the value of the Referer header.
/// </para>
/// <para>
/// <see langword="null"/> if the header value is not available.
/// </para>
/// </value>
public Uri UrlReferrer {
get {
var val = _headers["Referer"];
if (val == null)
return null;
if (_urlReferrer == null)
_urlReferrer = val.ToUri ();
return _urlReferrer;
}
}
/// <summary>
/// Gets the user agent from which the request is originated.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the value of the User-Agent
/// header.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string UserAgent {
get {
return _headers["User-Agent"];
}
}
/// <summary>
/// Gets the IP address and port number to which the request is sent.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the server IP address and port
/// number.
/// </value>
public string UserHostAddress {
get {
return _connection.LocalEndPoint.ToString ();
}
}
/// <summary>
/// Gets the server host name requested by the client.
/// </summary>
/// <value>
/// <para>
/// A <see cref="string"/> that represents the value of the Host header.
/// </para>
/// <para>
/// It includes the port number if provided.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string UserHostName {
get {
return _userHostName;
}
}
/// <summary>
/// Gets the natural languages that are acceptable for the client.
/// </summary>
/// <value>
/// <para>
/// An array of <see cref="string"/> that contains the names of the
/// natural languages specified in the value of the Accept-Language
/// header.
/// </para>
/// <para>
/// <see langword="null"/> if the header is not present.
/// </para>
/// </value>
public string[] UserLanguages {
get {
var val = _headers["Accept-Language"];
if (val == null)
return null;
if (_userLanguages == null)
_userLanguages = val.Split (',').Trim ().ToList ().ToArray ();
return _userLanguages;
}
}
#endregion
#region Private Methods
private void finishInitialization10 ()
{
var transferEnc = _headers["Transfer-Encoding"];
if (transferEnc != null) {
_context.ErrorMessage = "Invalid Transfer-Encoding header";
return;
}
if (_httpMethod == "POST") {
if (_contentLength == -1) {
_context.ErrorMessage = "Content-Length header required";
return;
}
if (_contentLength == 0) {
_context.ErrorMessage = "Invalid Content-Length header";
return;
}
}
}
private Encoding getContentEncoding ()
{
var val = _headers["Content-Type"];
if (val == null)
return null;
Encoding ret;
HttpUtility.TryGetEncoding (val, out ret);
return ret;
}
private RequestStream getInputStream ()
{
return _contentLength > 0 || _chunked
? _connection.GetRequestStream (_contentLength, _chunked)
: null;
}
#endregion
#region Internal Methods
internal void AddHeader (string headerField)
{
var start = headerField[0];
if (start == ' ' || start == '\t') {
_context.ErrorMessage = "Invalid header field";
return;
}
var colon = headerField.IndexOf (':');
if (colon < 1) {
_context.ErrorMessage = "Invalid header field";
return;
}
var name = headerField.Substring (0, colon).Trim ();
if (name.Length == 0 || !name.IsToken ()) {
_context.ErrorMessage = "Invalid header name";
return;
}
var val = colon < headerField.Length - 1
? headerField.Substring (colon + 1).Trim ()
: String.Empty;
_headers.InternalSet (name, val, false);
var lower = name.ToLower (CultureInfo.InvariantCulture);
if (lower == "host") {
if (_userHostName != null) {
_context.ErrorMessage = "Invalid Host header";
return;
}
if (val.Length == 0) {
_context.ErrorMessage = "Invalid Host header";
return;
}
_userHostName = val;
return;
}
if (lower == "content-length") {
if (_contentLength > -1) {
_context.ErrorMessage = "Invalid Content-Length header";
return;
}
long len;
if (!Int64.TryParse (val, out len)) {
_context.ErrorMessage = "Invalid Content-Length header";
return;
}
if (len < 0) {
_context.ErrorMessage = "Invalid Content-Length header";
return;
}
_contentLength = len;
return;
}
}
internal void FinishInitialization ()
{
if (_protocolVersion == HttpVersion.Version10) {
finishInitialization10 ();
return;
}
if (_userHostName == null) {
_context.ErrorMessage = "Host header required";
return;
}
var transferEnc = _headers["Transfer-Encoding"];
if (transferEnc != null) {
var comparison = StringComparison.OrdinalIgnoreCase;
if (!transferEnc.Equals ("chunked", comparison)) {
_context.ErrorMessage = String.Empty;
_context.ErrorStatus = 501;
return;
}
_chunked = true;
}
if (_httpMethod == "POST" || _httpMethod == "PUT") {
if (_contentLength <= 0 && !_chunked) {
_context.ErrorMessage = String.Empty;
_context.ErrorStatus = 411;
return;
}
}
var expect = _headers["Expect"];
if (expect != null) {
var comparison = StringComparison.OrdinalIgnoreCase;
if (!expect.Equals ("100-continue", comparison)) {
_context.ErrorMessage = "Invalid Expect header";
return;
}
var output = _connection.GetResponseStream ();
output.InternalWrite (_100continue, 0, _100continue.Length);
}
}
internal bool FlushInput ()
{
var input = InputStream;
if (input == Stream.Null)
return true;
var len = 2048;
if (_contentLength > 0 && _contentLength < len)
len = (int) _contentLength;
var buff = new byte[len];
while (true) {
try {
var ares = input.BeginRead (buff, 0, len, null, null);
if (!ares.IsCompleted) {
var timeout = 100;
if (!ares.AsyncWaitHandle.WaitOne (timeout))
return false;
}
if (input.EndRead (ares) <= 0)
return true;
}
catch {
return false;
}
}
}
internal bool IsUpgradeRequest (string protocol)
{
return _headers.Upgrades (protocol);
}
internal void SetRequestLine (string requestLine)
{
var parts = requestLine.Split (new[] { ' ' }, 3);
if (parts.Length < 3) {
_context.ErrorMessage = "Invalid request line (parts)";
return;
}
var method = parts[0];
if (method.Length == 0) {
_context.ErrorMessage = "Invalid request line (method)";
return;
}
var target = parts[1];
if (target.Length == 0) {
_context.ErrorMessage = "Invalid request line (target)";
return;
}
var rawVer = parts[2];
if (rawVer.Length != 8) {
_context.ErrorMessage = "Invalid request line (version)";
return;
}
if (rawVer.IndexOf ("HTTP/") != 0) {
_context.ErrorMessage = "Invalid request line (version)";
return;
}
Version ver;
if (!rawVer.Substring (5).TryCreateVersion (out ver)) {
_context.ErrorMessage = "Invalid request line (version)";
return;
}
if (ver.Major < 1) {
_context.ErrorMessage = "Invalid request line (version)";
return;
}
if (!method.IsHttpMethod (ver)) {
_context.ErrorMessage = "Invalid request line (method)";
return;
}
_httpMethod = method;
_rawUrl = target;
_protocolVersion = ver;
}
#endregion
#region Public Methods
/// <summary>
/// Begins getting the certificate provided by the client asynchronously.
/// </summary>
/// <returns>
/// An <see cref="IAsyncResult"/> instance that indicates the status of the
/// operation.
/// </returns>
/// <param name="requestCallback">
/// An <see cref="AsyncCallback"/> delegate that invokes the method called
/// when the operation is complete.
/// </param>
/// <param name="state">
/// An <see cref="object"/> that represents a user defined object to pass to
/// the callback delegate.
/// </param>
/// <exception cref="NotSupportedException">
/// This method is not supported.
/// </exception>
public IAsyncResult BeginGetClientCertificate (
AsyncCallback requestCallback, object state
)
{
throw new NotSupportedException ();
}
/// <summary>
/// Ends an asynchronous operation to get the certificate provided by the
/// client.
/// </summary>
/// <returns>
/// A <see cref="X509Certificate2"/> that represents an X.509 certificate
/// provided by the client.
/// </returns>
/// <param name="asyncResult">
/// An <see cref="IAsyncResult"/> instance returned when the operation
/// started.
/// </param>
/// <exception cref="NotSupportedException">
/// This method is not supported.
/// </exception>
public X509Certificate2 EndGetClientCertificate (IAsyncResult asyncResult)
{
throw new NotSupportedException ();
}
/// <summary>
/// Gets the certificate provided by the client.
/// </summary>
/// <returns>
/// A <see cref="X509Certificate2"/> that represents an X.509 certificate
/// provided by the client.
/// </returns>
/// <exception cref="NotSupportedException">
/// This method is not supported.
/// </exception>
public X509Certificate2 GetClientCertificate ()
{
throw new NotSupportedException ();
}
/// <summary>
/// Returns a string that represents the current instance.
/// </summary>
/// <returns>
/// A <see cref="string"/> that contains the request line and headers
/// included in the request.
/// </returns>
public override string ToString ()
{
var buff = new StringBuilder (64);
buff
.AppendFormat (
"{0} {1} HTTP/{2}\r\n", _httpMethod, _rawUrl, _protocolVersion
)
.Append (_headers.ToString ());
return buff.ToString ();
}
#endregion
}
}
| |
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Fairweather.Service
{
public class Multi_Writer : TextWriter
{
public Multi_Writer(IEnumerable<TextWriter> writers) {
this.Writers = writers.lst();
}
public Multi_Writer(bool parallel, IEnumerable<TextWriter> writers) {
this.Writers = writers.lst();
this.Parallel = parallel;
}
public Multi_Writer(params TextWriter[] writers) {
this.Writers = writers.lst();
}
public Multi_Writer(bool serial, params TextWriter[] writers) {
this.Writers = writers.lst();
this.Parallel = serial;
}
public bool Parallel {
get;
set;
}
public List<TextWriter> Writers {
get;
set;
}
public override void Flush() {
foreach (var writer in Writers)
writer.Flush();
}
public override void Close() {
foreach (var writer in Writers)
writer.Close();
}
public override string NewLine {
get {
return base.NewLine;
}
set {
base.NewLine = value;
foreach (var writer in Writers)
writer.NewLine = value;
}
}
protected override void Dispose(bool disposing) {
if (disposing)
foreach (var writer in Writers)
writer.Dispose();
}
public override Encoding Encoding {
get { return null; }
}
public override void Write(char value) {
foreach (var writer in Writers)
writer.Write(value);
}
// ****************************
public override void Write(bool value) {
if (Parallel) { base.Write(value); return; } foreach (var writer in this.Writers) writer.Write(value);
}
public override void Write(char[] buffer) {
if (Parallel) { base.Write(buffer); return; } foreach (var writer in this.Writers) writer.Write(buffer);
}
public override void Write(double value) {
if (Parallel) { base.Write(value); return; } foreach (var writer in this.Writers) writer.Write(value);
}
public override void Write(int value) {
if (Parallel) { base.Write(value); return; } foreach (var writer in this.Writers) writer.Write(value);
}
public override void Write(long value) {
if (Parallel) { base.Write(value); return; } foreach (var writer in this.Writers) writer.Write(value);
}
public override void Write(float value) {
if (Parallel) { base.Write(value); return; } foreach (var writer in this.Writers) writer.Write(value);
}
public override void Write(object value) {
if (Parallel) { base.Write(value); return; } foreach (var writer in this.Writers) writer.Write(value);
}
public override void Write(string s) {
if (Parallel) { base.Write(s); return; } foreach (var writer in this.Writers) writer.Write(s);
}
public override void Write(string format, object arg0) {
if (Parallel) { base.Write(format, arg0); return; } foreach (var writer in this.Writers) writer.Write(format, arg0);
}
public override void Write(string format, params object[] arg) {
if (Parallel) { base.Write(format, arg); return; } foreach (var writer in this.Writers) writer.Write(format, arg);
}
public override void Write(string format, object arg0, object arg1) {
if (Parallel) { base.Write(format, arg0, arg1); return; } foreach (var writer in this.Writers) writer.Write(format, arg0, arg1);
}
public override void Write(char[] buffer, int index, int count) {
if (Parallel) { base.Write(buffer, index, count); return; } foreach (var writer in this.Writers) writer.Write(buffer, index, count);
}
public override void WriteLine() {
if (Parallel) { base.WriteLine(); return; } foreach (var writer in this.Writers) writer.WriteLine();
}
public override void WriteLine(bool value) {
if (Parallel) { base.WriteLine(value); return; } foreach (var writer in this.Writers) writer.WriteLine(value);
}
public override void WriteLine(char value) {
if (Parallel) { base.WriteLine(value); return; } foreach (var writer in this.Writers) writer.WriteLine(value);
}
public override void WriteLine(double value) {
if (Parallel) { base.WriteLine(value); return; } foreach (var writer in this.Writers) writer.WriteLine(value);
}
public override void WriteLine(char[] buffer) {
if (Parallel) { base.WriteLine(buffer); return; } foreach (var writer in this.Writers) writer.WriteLine(buffer);
}
public override void WriteLine(int value) {
if (Parallel) { base.WriteLine(value); return; } foreach (var writer in this.Writers) writer.WriteLine(value);
}
public override void WriteLine(long value) {
if (Parallel) { base.WriteLine(value); return; } foreach (var writer in this.Writers) writer.WriteLine(value);
}
public override void WriteLine(float value) {
if (Parallel) { base.WriteLine(value); return; } foreach (var writer in this.Writers) writer.WriteLine(value);
}
// [CLSCompliant(false)]
public override void WriteLine(uint value) {
if (Parallel) { base.WriteLine(value); return; } foreach (var writer in this.Writers) writer.WriteLine(value);
}
public override void WriteLine(object value) {
if (Parallel) { base.WriteLine(value); return; } foreach (var writer in this.Writers) writer.WriteLine(value);
}
public override void WriteLine(string s) {
if (Parallel) { base.WriteLine(s); return; } foreach (var writer in this.Writers) writer.WriteLine(s);
}
public override void WriteLine(string format, object arg0) {
if (Parallel) { base.WriteLine(format, arg0); return; } foreach (var writer in this.Writers) writer.WriteLine(format, arg0);
}
public override void WriteLine(string format, params object[] arg) {
if (Parallel) { base.WriteLine(format, arg); return; } foreach (var writer in this.Writers) writer.WriteLine(format, arg);
}
public override void WriteLine(string format, object arg0, object arg1) {
if (Parallel) { base.WriteLine(format, arg0, arg1); return; } foreach (var writer in this.Writers) writer.WriteLine(format, arg0, arg1);
}
public override void WriteLine(char[] buffer, int index, int count) {
if (Parallel) { base.WriteLine(buffer, index, count); return; } foreach (var writer in this.Writers) writer.WriteLine(buffer, index, count);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Cors.Infrastructure
{
/// <summary>
/// A middleware for handling CORS.
/// </summary>
public class CorsMiddleware
{
// Property key is used by other systems, e.g. MVC, to check if CORS middleware has run
private const string CorsMiddlewareWithEndpointInvokedKey = "__CorsMiddlewareWithEndpointInvoked";
private static readonly object CorsMiddlewareWithEndpointInvokedValue = new object();
private readonly Func<object, Task> OnResponseStartingDelegate = OnResponseStarting;
private readonly RequestDelegate _next;
private readonly CorsPolicy? _policy;
private readonly string? _corsPolicyName;
/// <summary>
/// Instantiates a new <see cref="CorsMiddleware"/>.
/// </summary>
/// <param name="next">The next middleware in the pipeline.</param>
/// <param name="corsService">An instance of <see cref="ICorsService"/>.</param>
/// <param name="loggerFactory">An instance of <see cref="ILoggerFactory"/>.</param>
public CorsMiddleware(
RequestDelegate next,
ICorsService corsService,
ILoggerFactory loggerFactory)
: this(next, corsService, loggerFactory, policyName: null)
{
}
/// <summary>
/// Instantiates a new <see cref="CorsMiddleware"/>.
/// </summary>
/// <param name="next">The next middleware in the pipeline.</param>
/// <param name="corsService">An instance of <see cref="ICorsService"/>.</param>
/// <param name="loggerFactory">An instance of <see cref="ILoggerFactory"/>.</param>
/// <param name="policyName">An optional name of the policy to be fetched.</param>
public CorsMiddleware(
RequestDelegate next,
ICorsService corsService,
ILoggerFactory loggerFactory,
string? policyName)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (corsService == null)
{
throw new ArgumentNullException(nameof(corsService));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
_next = next;
CorsService = corsService;
_corsPolicyName = policyName;
Logger = loggerFactory.CreateLogger<CorsMiddleware>();
}
/// <summary>
/// Instantiates a new <see cref="CorsMiddleware"/>.
/// </summary>
/// <param name="next">The next middleware in the pipeline.</param>
/// <param name="corsService">An instance of <see cref="ICorsService"/>.</param>
/// <param name="policy">An instance of the <see cref="CorsPolicy"/> which can be applied.</param>
/// <param name="loggerFactory">An instance of <see cref="ILoggerFactory"/>.</param>
public CorsMiddleware(
RequestDelegate next,
ICorsService corsService,
CorsPolicy policy,
ILoggerFactory loggerFactory)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (corsService == null)
{
throw new ArgumentNullException(nameof(corsService));
}
if (policy == null)
{
throw new ArgumentNullException(nameof(policy));
}
if (loggerFactory == null)
{
throw new ArgumentNullException(nameof(loggerFactory));
}
_next = next;
CorsService = corsService;
_policy = policy;
Logger = loggerFactory.CreateLogger<CorsMiddleware>();
}
private ICorsService CorsService { get; }
private ILogger Logger { get; }
/// <inheritdoc />
public Task Invoke(HttpContext context, ICorsPolicyProvider corsPolicyProvider)
{
// CORS policy resolution rules:
//
// 1. If there is an endpoint with IDisableCorsAttribute then CORS is not run
// 2. If there is an endpoint with ICorsPolicyMetadata then use its policy or if
// there is an endpoint with IEnableCorsAttribute that has a policy name then
// fetch policy by name, prioritizing it above policy on middleware
// 3. If there is no policy on middleware then use name on middleware
var endpoint = context.GetEndpoint();
if (endpoint != null)
{
// EndpointRoutingMiddleware uses this flag to check if the CORS middleware processed CORS metadata on the endpoint.
// The CORS middleware can only make this claim if it observes an actual endpoint.
context.Items[CorsMiddlewareWithEndpointInvokedKey] = CorsMiddlewareWithEndpointInvokedValue;
}
if (!context.Request.Headers.ContainsKey(CorsConstants.Origin))
{
return _next(context);
}
// Get the most significant CORS metadata for the endpoint
// For backwards compatibility reasons this is then downcast to Enable/Disable metadata
var corsMetadata = endpoint?.Metadata.GetMetadata<ICorsMetadata>();
if (corsMetadata is IDisableCorsAttribute)
{
var isOptionsRequest = HttpMethods.IsOptions(context.Request.Method);
var isCorsPreflightRequest = isOptionsRequest && context.Request.Headers.ContainsKey(CorsConstants.AccessControlRequestMethod);
if (isCorsPreflightRequest)
{
// If this is a preflight request, and we disallow CORS, complete the request
context.Response.StatusCode = StatusCodes.Status204NoContent;
return Task.CompletedTask;
}
return _next(context);
}
var corsPolicy = _policy;
var policyName = _corsPolicyName;
if (corsMetadata is ICorsPolicyMetadata corsPolicyMetadata)
{
policyName = null;
corsPolicy = corsPolicyMetadata.Policy;
}
else if (corsMetadata is IEnableCorsAttribute enableCorsAttribute &&
enableCorsAttribute.PolicyName != null)
{
// If a policy name has been provided on the endpoint metadata then prioritizing it above the static middleware policy
policyName = enableCorsAttribute.PolicyName;
corsPolicy = null;
}
if (corsPolicy == null)
{
// Resolve policy by name if the local policy is not being used
var policyTask = corsPolicyProvider.GetPolicyAsync(context, policyName);
if (!policyTask.IsCompletedSuccessfully)
{
return InvokeCoreAwaited(context, policyTask);
}
corsPolicy = policyTask.Result;
}
return EvaluateAndApplyPolicy(context, corsPolicy);
async Task InvokeCoreAwaited(HttpContext context, Task<CorsPolicy?> policyTask)
{
var corsPolicy = await policyTask;
await EvaluateAndApplyPolicy(context, corsPolicy);
}
}
private Task EvaluateAndApplyPolicy(HttpContext context, CorsPolicy? corsPolicy)
{
if (corsPolicy == null)
{
Logger.NoCorsPolicyFound();
return _next(context);
}
var corsResult = CorsService.EvaluatePolicy(context, corsPolicy);
if (corsResult.IsPreflightRequest)
{
CorsService.ApplyResult(corsResult, context.Response);
// Since there is a policy which was identified,
// always respond to preflight requests.
context.Response.StatusCode = StatusCodes.Status204NoContent;
return Task.CompletedTask;
}
else
{
context.Response.OnStarting(OnResponseStartingDelegate, Tuple.Create(this, context, corsResult));
return _next(context);
}
}
private static Task OnResponseStarting(object state)
{
var (middleware, context, result) = (Tuple<CorsMiddleware, HttpContext, CorsResult>)state;
try
{
middleware.CorsService.ApplyResult(result, context.Response);
}
catch (Exception exception)
{
middleware.Logger.FailedToSetCorsHeaders(exception);
}
return Task.CompletedTask;
}
}
}
| |
using System;
using UIKit;
using RepositoryStumble.Core.ViewModels.Repositories;
using ReactiveUI;
using Xamarin.Utilities.DialogElements;
using System.Reactive.Linq;
using RepositoryStumble.Views;
using CoreGraphics;
using Foundation;
using Newtonsoft.Json;
namespace RepositoryStumble.ViewControllers.Repositories
{
public abstract class BaseRepositoryViewController<TViewModel> : ViewModelViewController<TViewModel> where TViewModel : BaseRepositoryViewModel
{
private UIWebView _web;
private UIActionSheet _actionSheet;
protected readonly UIBarButtonItem DislikeButton;
protected readonly UIBarButtonItem LikeButton;
private SlideUpTitleView _slideUpTitle;
public override string Title
{
get
{
return base.Title;
}
set
{
if (_slideUpTitle != null) _slideUpTitle.Text = value;
base.Title = value;
}
}
protected BaseRepositoryViewController()
{
DislikeButton = new UIBarButtonItem(Images.ThumbDown, UIBarButtonItemStyle.Plain, (s, e) => ViewModel.DislikeCommand.ExecuteIfCan());
DislikeButton.TintColor = UITabBar.Appearance.TintColor;
LikeButton = new UIBarButtonItem(Images.ThumbUp, UIBarButtonItemStyle.Plain, (s, e) => ViewModel.LikeCommand.ExecuteIfCan());
LikeButton.TintColor = UITabBar.Appearance.TintColor;
}
private bool _loaded;
private bool IsWebLoaded
{
get { return _loaded; }
set { this.RaiseAndSetIfChanged(ref _loaded, value); }
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
NavigationItem.TitleView = _slideUpTitle = new SlideUpTitleView(NavigationController.NavigationBar.Bounds.Height) { Text = Title };
_slideUpTitle.Offset = 100f;
_web = new UIWebView(new CGRect(0, 0, View.Frame.Width, View.Frame.Height));
_web.BackgroundColor = UIColor.White;
_web.Opaque = false;
_web.AutoresizingMask = UIViewAutoresizing.All;
_web.LoadFinished += (sender, e) => IsWebLoaded = true;
_web.ShouldStartLoad = (w, r, x) =>
{
if (x == UIWebViewNavigationType.LinkClicked && r.Url.Scheme.StartsWith("http", StringComparison.OrdinalIgnoreCase))
{
ViewModel.GoToUrlCommand.ExecuteIfCan(r.Url.AbsoluteString);
return false;
}
return true;
};
_web.ScrollView.Scrolled += WebScrolled;
Add(_web);
_web.ScrollView.CreateTopBackground(UIColor.FromRGB(0x4e, 0x4b, 0xbe));
NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Action, (s, e) => ShowMore());
NavigationItem.RightBarButtonItem.EnableIfExecutable(this.WhenAnyValue(x => x.ViewModel)
.Where(x => x != null)
.Select(x => x.WhenAnyValue(y => y.Repository))
.Switch().Select(x => x != null));
this.WhenAnyObservable(x => x.ViewModel.LoadCommand.IsExecuting)
.Where(x => x)
.Subscribe(_ => IsWebLoaded = false);
this.WhenAnyValue(x => x.ViewModel.Repository)
.Where(x => x != null)
.Subscribe(x =>
{
_web.LoadHtmlString(new ReadmeRazorView().GenerateString(), new NSUrl(x.HtmlUrl + "/raw/" + x.DefaultBranch + "/"));
Title = x.Name;
});
this.WhenAnyValue(x => x.ViewModel)
.Where(x => x != null)
.Select(x => x.WhenAnyValue(y => y.Liked))
.Switch()
.Subscribe(x =>
{
if (x == null)
{
DislikeButton.Image = Images.ThumbDown;
LikeButton.Image = Images.ThumbUp;
}
else if (x.Value)
{
DislikeButton.Image = Images.ThumbDown;
LikeButton.Image = Images.ThumbUpFilled;
}
else
{
DislikeButton.Image = Images.ThumbDownFilled;
LikeButton.Image = Images.ThumbUp;
}
});
this.WhenAnyValue(y => y.ViewModel.Repository, y => y.IsWebLoaded)
.Where(y => y.Item1 != null && y.Item2)
.Subscribe(x =>
{
var s = JsonConvert.SerializeObject(x.Item1);
_web.EvaluateJavascript("setRepository(" + s + ")");
});
this.WhenAnyValue(y => y.ViewModel.ContributorCount, y => y.IsWebLoaded)
.Where(y => y.Item1 != null && y.Item2)
.Subscribe(x =>
{
_web.EvaluateJavascript("setContrib(" + x.Item1.Value + ")");
});
this.WhenAnyValue(y => y.ViewModel.Readme, y => y.IsWebLoaded)
.Where(y => y.Item2 && y.Item1 != null)
.Subscribe(x =>
{
var s = JsonConvert.SerializeObject(x.Item1);
_web.EvaluateJavascript("setBody(" + s + ")");
});
ToolbarItems = new []
{
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
DislikeButton,
new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace) { Width = 80 },
LikeButton,
new UIBarButtonItem(UIBarButtonSystemItem.FlexibleSpace),
};
}
void WebScrolled (object sender, EventArgs e)
{
if (NavigationController == null)
return;
var x = _web.ScrollView.ContentOffset;
if (x.Y > 0)
NavigationController.NavigationBar.ShadowImage = null;
if (x.Y <= 0 && NavigationController.NavigationBar.ShadowImage == null)
NavigationController.NavigationBar.ShadowImage = new UIImage();
_slideUpTitle.Offset = 108 + 28f - x.Y;
}
private void ShowMore()
{
_actionSheet = new UIActionSheet();
var showCodeHub = _actionSheet.AddButton("Open in CodeHub");
var show = _actionSheet.AddButton("Show in GitHub");
var showSafari = _actionSheet.AddButton("Show in Safari");
var share = _actionSheet.AddButton("Share");
_actionSheet.CancelButtonIndex = _actionSheet.AddButton("Cancel");
_actionSheet.Clicked += (sender, e) =>
{
if (e.ButtonIndex == show)
{
ViewModel.GoToGitHubCommand.ExecuteIfCan();
}
else if (e.ButtonIndex == showCodeHub)
{
var url = new NSUrl("codehub://github.com/" + ViewModel.RepositoryIdentifier.Owner + "/" + ViewModel.RepositoryIdentifier.Name);
if (UIApplication.SharedApplication.CanOpenUrl(url))
{
UIApplication.SharedApplication.OpenUrl(url);
}
else
{
// Go to the CodeHub iTunes page
UIApplication.SharedApplication.OpenUrl(new NSUrl("https://itunes.apple.com/us/app/codehub-github-for-ios/id707173885?mt=8"));
}
}
else if (e.ButtonIndex == showSafari)
{
UIApplication.SharedApplication.OpenUrl(new NSUrl(ViewModel.Repository.HtmlUrl));
}
else if (e.ButtonIndex == share)
{
var item = NSObject.FromObject(ViewModel.Repository.HtmlUrl);
var activityItems = new [] { item };
UIActivity[] applicationActivities = null;
var activityController = new UIActivityViewController(activityItems, applicationActivities);
PresentViewController(activityController, true, null);
}
_actionSheet = null;
};
_actionSheet.ShowFrom(NavigationItem.RightBarButtonItem, true);
}
private class LoadingView : UIView
{
private readonly UIActivityIndicatorView _activity;
public LoadingView()
: base(new CGRect(0, 0, 320f, 44f))
{
BackgroundColor = UIColor.Clear;
_activity = new UIActivityIndicatorView();
_activity.Color = UINavigationBar.Appearance.BackgroundColor;
_activity.Center = new CGPoint(Bounds.Width / 2, Bounds.Height / 2);
_activity.AutoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin |
UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin;
_activity.StartAnimating();
Add(_activity);
}
}
public override void ViewWillAppear(bool animated)
{
if (ToolbarItems != null)
NavigationController.SetToolbarHidden(false, animated);
base.ViewWillAppear(animated);
NavigationController.NavigationBar.ShadowImage = new UIImage();
_web.Frame = new CGRect(0, 0, View.Frame.Width, View.Frame.Height);
}
public override void ViewWillDisappear(bool animated)
{
base.ViewWillDisappear(animated);
NavigationController.NavigationBar.ShadowImage = null;
if (ToolbarItems != null)
NavigationController.SetToolbarHidden(true, animated);
}
}
}
| |
// 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 GCVariant {
using System;
internal class GCVariant
{
internal static object [] G_Vart;
public static int Main(String [] Args)
{
int iRep = 0;
int iObj = 0;
int iNum = 0;
Console.WriteLine("Test should return with ExitCode 100 ...");
switch( Args.Length )
{
case 1:
if (!Int32.TryParse( Args[0], out iRep ))
{
iRep = 5;
}
iObj = 100;
iNum = 10;
break;
case 2:
if (!Int32.TryParse( Args[0], out iRep ))
{
iRep = 5;
}
if (!Int32.TryParse( Args[1], out iObj ))
{
iObj = 100;
}
iNum = 10;
break;
case 3:
if (!Int32.TryParse( Args[0], out iRep ))
{
iRep = 5;
}
if (!Int32.TryParse( Args[1], out iObj ))
{
iObj = 100;
}
if (!Int32.TryParse( Args[2], out iNum ))
{
iNum = 10;
}
break;
default:
iRep = 5;
iObj = 100;
iNum = 10;
break;
}
Console.Write("iRep= ");
Console.Write(iRep);
Console.Write(" iObj= ");
Console.Write(iObj);
Console.Write(" iNum= ");
Console.WriteLine(iNum);
GCVariant Mv_Obj = new GCVariant();
if(Mv_Obj.runTest(iRep, iObj, iNum ))
{
Console.WriteLine("Test Passed");
return 100;
}
Console.WriteLine("Test Failed");
return 1;
}
public bool runTest(int iRep, int iObj, int iNum)
{
DoubLink L_Node1 = new DoubLink(iNum);
DLinkNode L_Node2 = new DLinkNode(iNum, null, null);
for(int i= 0; i< iRep; i++)
{
G_Vart = new Object[iObj];
for(int j=0; j< iObj; j++)
{
if(j%2 == 1)
G_Vart[j] = (L_Node1);
else
G_Vart[j] = (L_Node2);
}
MakeLeak(iRep, iObj, iNum);
}
return true;
}
public void MakeLeak(int iRep, int iObj, int iNum)
{
DoubLink L_Node1 = new DoubLink(iNum);
DLinkNode L_Node2 = new DLinkNode(iNum, null, null);
Object [] L_Vart1 = new Object[iObj];
Object [] L_Vart2;
for(int i= 0; i< iRep; i++)
{
L_Vart2 = new Object[iObj];
for(int j=0; j< iObj; j++)
{
if(j%2 == 1)
{
L_Vart1[j] = (j);
L_Vart2[j] = ((double)j);
}
else
{
L_Vart2[j] = (L_Node2);
L_Vart1[j] = (L_Node1);
}
}
}
}
}
public class DoubLink
{
internal DLinkNode[] Mv_DLink;
public DoubLink(int Num)
: this(Num, false)
{
}
public DoubLink(int Num, bool large)
{
Mv_DLink = new DLinkNode[Num];
if (Num == 0)
{
return;
}
if (Num == 1)
{
// only one element
Mv_DLink[0] = new DLinkNode((large ? 256 : 1), Mv_DLink[0], Mv_DLink[0]);
return;
}
// first element
Mv_DLink[0] = new DLinkNode((large ? 256 : 1), Mv_DLink[Num - 1], Mv_DLink[1]);
// all elements in between
for (int i = 1; i < Num - 1; i++)
{
Mv_DLink[i] = new DLinkNode((large ? 256 : i + 1), Mv_DLink[i - 1], Mv_DLink[i + 1]);
}
// last element
Mv_DLink[Num - 1] = new DLinkNode((large ? 256 : Num), Mv_DLink[Num - 2], Mv_DLink[0]);
}
public int NodeNum
{
get
{
return Mv_DLink.Length;
}
}
}
public class DLinkNode
{
// disabling unused variable warning
#pragma warning disable 0414
internal DLinkNode Last;
internal DLinkNode Next;
#pragma warning restore 0414
internal int[] Size;
public DLinkNode(int SizeNum, DLinkNode LastObject, DLinkNode NextObject)
{
Last = LastObject;
Next = NextObject;
Size = new int[SizeNum * 1024];
Size[0] = 1;
Size[SizeNum * 1024 - 1] = 2;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*============================================================
**
**
**
**
**
** Purpose: Abstract base class for all Streams. Provides
** default implementations of asynchronous reads & writes, in
** terms of the synchronous reads & writes (and vice versa).
**
**
===========================================================*/
using System.Buffers;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
public abstract partial class Stream : MarshalByRefObject, IDisposable, IAsyncDisposable
{
public static readonly Stream Null = new NullStream();
// We pick a value that is the largest multiple of 4096 that is still smaller than the large object heap threshold (85K).
// The CopyTo/CopyToAsync buffer is short-lived and is likely to be collected at Gen0, and it offers a significant
// improvement in Copy performance.
private const int DefaultCopyBufferSize = 81920;
// To implement Async IO operations on streams that don't support async IO
private ReadWriteTask _activeReadWriteTask;
private SemaphoreSlim _asyncActiveSemaphore;
internal SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized()
{
// Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's
// WaitHandle, we don't need to worry about Disposing it.
return LazyInitializer.EnsureInitialized(ref _asyncActiveSemaphore, () => new SemaphoreSlim(1, 1));
}
public abstract bool CanRead
{
get;
}
// If CanSeek is false, Position, Seek, Length, and SetLength should throw.
public abstract bool CanSeek
{
get;
}
public virtual bool CanTimeout
{
get
{
return false;
}
}
public abstract bool CanWrite
{
get;
}
public abstract long Length
{
get;
}
public abstract long Position
{
get;
set;
}
public virtual int ReadTimeout
{
get
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
public virtual int WriteTimeout
{
get
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
set
{
throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported);
}
}
public Task CopyToAsync(Stream destination)
{
int bufferSize = GetCopyBufferSize();
return CopyToAsync(destination, bufferSize);
}
public Task CopyToAsync(Stream destination, int bufferSize)
{
return CopyToAsync(destination, bufferSize, CancellationToken.None);
}
public Task CopyToAsync(Stream destination, CancellationToken cancellationToken)
{
int bufferSize = GetCopyBufferSize();
return CopyToAsync(destination, bufferSize, cancellationToken);
}
public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return CopyToAsyncInternal(destination, bufferSize, cancellationToken);
}
private async Task CopyToAsyncInternal(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
while (true)
{
int bytesRead = await ReadAsync(new Memory<byte>(buffer), cancellationToken).ConfigureAwait(false);
if (bytesRead == 0) break;
await destination.WriteAsync(new ReadOnlyMemory<byte>(buffer, 0, bytesRead), cancellationToken).ConfigureAwait(false);
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
// Reads the bytes from the current stream and writes the bytes to
// the destination stream until all bytes are read, starting at
// the current position.
public void CopyTo(Stream destination)
{
int bufferSize = GetCopyBufferSize();
CopyTo(destination, bufferSize);
}
public virtual void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
int read;
while ((read = Read(buffer, 0, buffer.Length)) != 0)
{
destination.Write(buffer, 0, read);
}
}
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
private int GetCopyBufferSize()
{
int bufferSize = DefaultCopyBufferSize;
if (CanSeek)
{
long length = Length;
long position = Position;
if (length <= position) // Handles negative overflows
{
// There are no bytes left in the stream to copy.
// However, because CopyTo{Async} is virtual, we need to
// ensure that any override is still invoked to provide its
// own validation, so we use the smallest legal buffer size here.
bufferSize = 1;
}
else
{
long remaining = length - position;
if (remaining > 0)
{
// In the case of a positive overflow, stick to the default size
bufferSize = (int)Math.Min(bufferSize, remaining);
}
}
}
return bufferSize;
}
// Stream used to require that all cleanup logic went into Close(),
// which was thought up before we invented IDisposable. However, we
// need to follow the IDisposable pattern so that users can write
// sensible subclasses without needing to inspect all their base
// classes, and without worrying about version brittleness, from a
// base class switching to the Dispose pattern. We're moving
// Stream to the Dispose(bool) pattern - that's where all subclasses
// should put their cleanup now.
public virtual void Close()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public void Dispose()
{
Close();
}
protected virtual void Dispose(bool disposing)
{
// Note: Never change this to call other virtual methods on Stream
// like Write, since the state on subclasses has already been
// torn down. This is the last code to run on cleanup for a stream.
}
public virtual ValueTask DisposeAsync()
{
try
{
Dispose();
return default;
}
catch (Exception exc)
{
return new ValueTask(Task.FromException(exc));
}
}
public abstract void Flush();
public Task FlushAsync()
{
return FlushAsync(CancellationToken.None);
}
public virtual Task FlushAsync(CancellationToken cancellationToken)
{
return Task.Factory.StartNew(state => ((Stream)state).Flush(), this,
cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
}
[Obsolete("CreateWaitHandle will be removed eventually. Please use \"new ManualResetEvent(false)\" instead.")]
protected virtual WaitHandle CreateWaitHandle()
{
return new ManualResetEvent(false);
}
public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
internal IAsyncResult BeginReadInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, object state,
bool serializeAsynchronously, bool apm)
{
if (!CanRead) throw Error.GetReadNotSupported();
// To avoid a race with a stream's position pointer & generating race conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
var semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync();
}
else
{
semaphore.Wait();
}
// Create the task to asynchronously do a Read. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(true /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Read.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
// Do the Read and return the number of bytes read
return thisTask._stream.Read(thisTask._buffer, thisTask._offset, thisTask._count);
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
public virtual int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
var readTask = _activeReadWriteTask;
if (readTask == null)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
else if (readTask != asyncResult)
{
throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
else if (!readTask._isRead)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndReadCalledMultiple);
}
try
{
return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception
}
finally
{
FinishTrackingAsyncOperation();
}
}
public Task<int> ReadAsync(byte[] buffer, int offset, int count)
{
return ReadAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled<int>(cancellationToken)
: BeginEndReadAsync(buffer, offset, count);
}
public virtual ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> array))
{
return new ValueTask<int>(ReadAsync(array.Array, array.Offset, array.Count, cancellationToken));
}
else
{
byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
return FinishReadAsync(ReadAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer, buffer);
async ValueTask<int> FinishReadAsync(Task<int> readTask, byte[] localBuffer, Memory<byte> localDestination)
{
try
{
int result = await readTask.ConfigureAwait(false);
new Span<byte>(localBuffer, 0, result).CopyTo(localDestination.Span);
return result;
}
finally
{
ArrayPool<byte>.Shared.Return(localBuffer);
}
}
}
}
private Task<int> BeginEndReadAsync(byte[] buffer, int offset, int count)
{
if (!HasOverriddenBeginEndRead())
{
// If the Stream does not override Begin/EndRead, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task<int>)BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<int>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
(stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler
}
private struct ReadWriteParameters // struct for arguments to Read and Write calls
{
internal byte[] Buffer;
internal int Offset;
internal int Count;
}
public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
return BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true);
}
internal IAsyncResult BeginWriteInternal(
byte[] buffer, int offset, int count, AsyncCallback callback, object state,
bool serializeAsynchronously, bool apm)
{
if (!CanWrite) throw Error.GetWriteNotSupported();
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread if it does a second IO request until the first one completes.
var semaphore = EnsureAsyncActiveSemaphoreInitialized();
Task semaphoreTask = null;
if (serializeAsynchronously)
{
semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block
}
else
{
semaphore.Wait(); // synchronously wait here
}
// Create the task to asynchronously do a Write. This task serves both
// as the asynchronous work item and as the IAsyncResult returned to the user.
var asyncResult = new ReadWriteTask(false /*isRead*/, apm, delegate
{
// The ReadWriteTask stores all of the parameters to pass to Write.
// As we're currently inside of it, we can get the current task
// and grab the parameters from it.
var thisTask = Task.InternalCurrent as ReadWriteTask;
Debug.Assert(thisTask != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask");
try
{
// Do the Write
thisTask._stream.Write(thisTask._buffer, thisTask._offset, thisTask._count);
return 0; // not used, but signature requires a value be returned
}
finally
{
// If this implementation is part of Begin/EndXx, then the EndXx method will handle
// finishing the async operation. However, if this is part of XxAsync, then there won't
// be an end method, and this task is responsible for cleaning up.
if (!thisTask._apm)
{
thisTask._stream.FinishTrackingAsyncOperation();
}
thisTask.ClearBeginState(); // just to help alleviate some memory pressure
}
}, state, this, buffer, offset, count, callback);
// Schedule it
if (semaphoreTask != null)
RunReadWriteTaskWhenReady(semaphoreTask, asyncResult);
else
RunReadWriteTask(asyncResult);
return asyncResult; // return it
}
private void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask)
{
Debug.Assert(readWriteTask != null);
Debug.Assert(asyncWaiter != null);
// If the wait has already completed, run the task.
if (asyncWaiter.IsCompleted)
{
Debug.Assert(asyncWaiter.IsCompletedSuccessfully, "The semaphore wait should always complete successfully.");
RunReadWriteTask(readWriteTask);
}
else // Otherwise, wait for our turn, and then run the task.
{
asyncWaiter.ContinueWith((t, state) =>
{
Debug.Assert(t.IsCompletedSuccessfully, "The semaphore wait should always complete successfully.");
var rwt = (ReadWriteTask)state;
rwt._stream.RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask);
}, readWriteTask, default, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);
}
}
private void RunReadWriteTask(ReadWriteTask readWriteTask)
{
Debug.Assert(readWriteTask != null);
Debug.Assert(_activeReadWriteTask == null, "Expected no other readers or writers");
// Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race.
// Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding
// two interlocked operations. However, if ReadWriteTask is ever changed to use
// a cancellation token, this should be changed to use Start.
_activeReadWriteTask = readWriteTask; // store the task so that EndXx can validate it's given the right one
readWriteTask.m_taskScheduler = TaskScheduler.Default;
readWriteTask.ScheduleAndStart(needsProtection: false);
}
private void FinishTrackingAsyncOperation()
{
_activeReadWriteTask = null;
Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here.");
_asyncActiveSemaphore.Release();
}
public virtual void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
var writeTask = _activeReadWriteTask;
if (writeTask == null)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask != asyncResult)
{
throw new InvalidOperationException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
else if (writeTask._isRead)
{
throw new ArgumentException(SR.InvalidOperation_WrongAsyncResultOrEndWriteCalledMultiple);
}
try
{
writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions
Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion);
}
finally
{
FinishTrackingAsyncOperation();
}
}
// Task used by BeginRead / BeginWrite to do Read / Write asynchronously.
// A single instance of this task serves four purposes:
// 1. The work item scheduled to run the Read / Write operation
// 2. The state holding the arguments to be passed to Read / Write
// 3. The IAsyncResult returned from BeginRead / BeginWrite
// 4. The completion action that runs to invoke the user-provided callback.
// This last item is a bit tricky. Before the AsyncCallback is invoked, the
// IAsyncResult must have completed, so we can't just invoke the handler
// from within the task, since it is the IAsyncResult, and thus it's not
// yet completed. Instead, we use AddCompletionAction to install this
// task as its own completion handler. That saves the need to allocate
// a separate completion handler, it guarantees that the task will
// have completed by the time the handler is invoked, and it allows
// the handler to be invoked synchronously upon the completion of the
// task. This all enables BeginRead / BeginWrite to be implemented
// with a single allocation.
private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction
{
internal readonly bool _isRead;
internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync
internal Stream _stream;
internal byte[] _buffer;
internal readonly int _offset;
internal readonly int _count;
private AsyncCallback _callback;
private ExecutionContext _context;
internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC
{
_stream = null;
_buffer = null;
}
public ReadWriteTask(
bool isRead,
bool apm,
Func<object, int> function, object state,
Stream stream, byte[] buffer, int offset, int count, AsyncCallback callback) :
base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach)
{
Debug.Assert(function != null);
Debug.Assert(stream != null);
Debug.Assert(buffer != null);
// Store the arguments
_isRead = isRead;
_apm = apm;
_stream = stream;
_buffer = buffer;
_offset = offset;
_count = count;
// If a callback was provided, we need to:
// - Store the user-provided handler
// - Capture an ExecutionContext under which to invoke the handler
// - Add this task as its own completion handler so that the Invoke method
// will run the callback when this task completes.
if (callback != null)
{
_callback = callback;
_context = ExecutionContext.Capture();
base.AddCompletionAction(this);
}
}
private static void InvokeAsyncCallback(object completedTask)
{
var rwc = (ReadWriteTask)completedTask;
var callback = rwc._callback;
rwc._callback = null;
callback(rwc);
}
private static ContextCallback s_invokeAsyncCallback;
void ITaskCompletionAction.Invoke(Task completingTask)
{
// Get the ExecutionContext. If there is none, just run the callback
// directly, passing in the completed task as the IAsyncResult.
// If there is one, process it with ExecutionContext.Run.
var context = _context;
if (context == null)
{
var callback = _callback;
_callback = null;
callback(completingTask);
}
else
{
_context = null;
var invokeAsyncCallback = s_invokeAsyncCallback;
if (invokeAsyncCallback == null) s_invokeAsyncCallback = invokeAsyncCallback = InvokeAsyncCallback; // benign race condition
ExecutionContext.RunInternal(context, invokeAsyncCallback, this);
}
}
bool ITaskCompletionAction.InvokeMayRunArbitraryCode { get { return true; } }
}
public Task WriteAsync(byte[] buffer, int offset, int count)
{
return WriteAsync(buffer, offset, count, CancellationToken.None);
}
public virtual Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
// If cancellation was requested, bail early with an already completed task.
// Otherwise, return a task that represents the Begin/End methods.
return cancellationToken.IsCancellationRequested
? Task.FromCanceled(cancellationToken)
: BeginEndWriteAsync(buffer, offset, count);
}
public virtual ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> array))
{
return new ValueTask(WriteAsync(array.Array, array.Offset, array.Count, cancellationToken));
}
else
{
byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
buffer.Span.CopyTo(sharedBuffer);
return new ValueTask(FinishWriteAsync(WriteAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer));
}
}
private async Task FinishWriteAsync(Task writeTask, byte[] localBuffer)
{
try
{
await writeTask.ConfigureAwait(false);
}
finally
{
ArrayPool<byte>.Shared.Return(localBuffer);
}
}
private Task BeginEndWriteAsync(byte[] buffer, int offset, int count)
{
if (!HasOverriddenBeginEndWrite())
{
// If the Stream does not override Begin/EndWrite, then we can take an optimized path
// that skips an extra layer of tasks / IAsyncResults.
return (Task)BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false);
}
// Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality.
return TaskFactory<VoidTaskResult>.FromAsyncTrim(
this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count },
(stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler
(stream, asyncResult) => // cached by compiler
{
stream.EndWrite(asyncResult);
return default;
});
}
public abstract long Seek(long offset, SeekOrigin origin);
public abstract void SetLength(long value);
public abstract int Read(byte[] buffer, int offset, int count);
public virtual int Read(Span<byte> buffer)
{
byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
try
{
int numRead = Read(sharedBuffer, 0, buffer.Length);
if ((uint)numRead > (uint)buffer.Length)
{
throw new IOException(SR.IO_StreamTooLong);
}
new Span<byte>(sharedBuffer, 0, numRead).CopyTo(buffer);
return numRead;
}
finally { ArrayPool<byte>.Shared.Return(sharedBuffer); }
}
// Reads one byte from the stream by calling Read(byte[], int, int).
// Will return an unsigned byte cast to an int or -1 on end of stream.
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are reading one byte at a time.
public virtual int ReadByte()
{
byte[] oneByteArray = new byte[1];
int r = Read(oneByteArray, 0, 1);
if (r == 0)
return -1;
return oneByteArray[0];
}
public abstract void Write(byte[] buffer, int offset, int count);
public virtual void Write(ReadOnlySpan<byte> buffer)
{
byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length);
try
{
buffer.CopyTo(sharedBuffer);
Write(sharedBuffer, 0, buffer.Length);
}
finally { ArrayPool<byte>.Shared.Return(sharedBuffer); }
}
// Writes one byte from the stream by calling Write(byte[], int, int).
// This implementation does not perform well because it allocates a new
// byte[] each time you call it, and should be overridden by any
// subclass that maintains an internal buffer. Then, it can help perf
// significantly for people who are writing one byte at a time.
public virtual void WriteByte(byte value)
{
byte[] oneByteArray = new byte[1];
oneByteArray[0] = value;
Write(oneByteArray, 0, 1);
}
public static Stream Synchronized(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
if (stream is SyncStream)
return stream;
return new SyncStream(stream);
}
[Obsolete("Do not call or override this method.")]
protected virtual void ObjectInvariant()
{
}
internal IAsyncResult BlockingBeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
// To avoid a race with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try
{
int numRead = Read(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(numRead, state);
}
catch (IOException ex)
{
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: false);
}
if (callback != null)
{
callback(asyncResult);
}
return asyncResult;
}
internal static int BlockingEndRead(IAsyncResult asyncResult)
{
return SynchronousAsyncResult.EndRead(asyncResult);
}
internal IAsyncResult BlockingBeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
// To avoid a race condition with a stream's position pointer & generating conditions
// with internal buffer indexes in our own streams that
// don't natively support async IO operations when there are multiple
// async requests outstanding, we will block the application's main
// thread and do the IO synchronously.
// This can't perform well - use a different approach.
SynchronousAsyncResult asyncResult;
try
{
Write(buffer, offset, count);
asyncResult = new SynchronousAsyncResult(state);
}
catch (IOException ex)
{
asyncResult = new SynchronousAsyncResult(ex, state, isWrite: true);
}
if (callback != null)
{
callback(asyncResult);
}
return asyncResult;
}
internal static void BlockingEndWrite(IAsyncResult asyncResult)
{
SynchronousAsyncResult.EndWrite(asyncResult);
}
private sealed class NullStream : Stream
{
private static readonly Task<int> s_zeroTask = Task.FromResult(0);
internal NullStream() { }
public override bool CanRead => true;
public override bool CanWrite => true;
public override bool CanSeek => true;
public override long Length => 0;
public override long Position
{
get { return 0; }
set { }
}
public override void CopyTo(Stream destination, int bufferSize)
{
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// After we validate arguments this is a nop.
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// Validate arguments here for compat, since previously this method
// was inherited from Stream (which did check its arguments).
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
protected override void Dispose(bool disposing)
{
// Do nothing - we don't want NullStream singleton (static) to be closable
}
public override void Flush()
{
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (!CanRead) throw Error.GetReadNotSupported();
return BlockingBeginRead(buffer, offset, count, callback, state);
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
return BlockingEndRead(asyncResult);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (!CanWrite) throw Error.GetWriteNotSupported();
return BlockingBeginWrite(buffer, offset, count, callback, state);
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
BlockingEndWrite(asyncResult);
}
public override int Read(byte[] buffer, int offset, int count)
{
return 0;
}
public override int Read(Span<byte> buffer)
{
return 0;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return s_zeroTask;
}
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
return new ValueTask<int>(0);
}
public override int ReadByte()
{
return -1;
}
public override void Write(byte[] buffer, int offset, int count)
{
}
public override void Write(ReadOnlySpan<byte> buffer)
{
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return cancellationToken.IsCancellationRequested ?
Task.FromCanceled(cancellationToken) :
Task.CompletedTask;
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
return cancellationToken.IsCancellationRequested ?
new ValueTask(Task.FromCanceled(cancellationToken)) :
default;
}
public override void WriteByte(byte value)
{
}
public override long Seek(long offset, SeekOrigin origin)
{
return 0;
}
public override void SetLength(long length)
{
}
}
/// <summary>Used as the IAsyncResult object when using asynchronous IO methods on the base Stream class.</summary>
private sealed class SynchronousAsyncResult : IAsyncResult
{
private readonly object _stateObject;
private readonly bool _isWrite;
private ManualResetEvent _waitHandle;
private ExceptionDispatchInfo _exceptionInfo;
private bool _endXxxCalled;
private int _bytesRead;
internal SynchronousAsyncResult(int bytesRead, object asyncStateObject)
{
_bytesRead = bytesRead;
_stateObject = asyncStateObject;
//_isWrite = false;
}
internal SynchronousAsyncResult(object asyncStateObject)
{
_stateObject = asyncStateObject;
_isWrite = true;
}
internal SynchronousAsyncResult(Exception ex, object asyncStateObject, bool isWrite)
{
_exceptionInfo = ExceptionDispatchInfo.Capture(ex);
_stateObject = asyncStateObject;
_isWrite = isWrite;
}
public bool IsCompleted
{
// We never hand out objects of this type to the user before the synchronous IO completed:
get { return true; }
}
public WaitHandle AsyncWaitHandle
{
get
{
return LazyInitializer.EnsureInitialized(ref _waitHandle, () => new ManualResetEvent(true));
}
}
public object AsyncState
{
get { return _stateObject; }
}
public bool CompletedSynchronously
{
get { return true; }
}
internal void ThrowIfError()
{
if (_exceptionInfo != null)
_exceptionInfo.Throw();
}
internal static int EndRead(IAsyncResult asyncResult)
{
if (!(asyncResult is SynchronousAsyncResult ar) || ar._isWrite)
throw new ArgumentException(SR.Arg_WrongAsyncResult);
if (ar._endXxxCalled)
throw new ArgumentException(SR.InvalidOperation_EndReadCalledMultiple);
ar._endXxxCalled = true;
ar.ThrowIfError();
return ar._bytesRead;
}
internal static void EndWrite(IAsyncResult asyncResult)
{
if (!(asyncResult is SynchronousAsyncResult ar) || !ar._isWrite)
throw new ArgumentException(SR.Arg_WrongAsyncResult);
if (ar._endXxxCalled)
throw new ArgumentException(SR.InvalidOperation_EndWriteCalledMultiple);
ar._endXxxCalled = true;
ar.ThrowIfError();
}
} // class SynchronousAsyncResult
// SyncStream is a wrapper around a stream that takes
// a lock for every operation making it thread safe.
private sealed class SyncStream : Stream, IDisposable
{
private Stream _stream;
internal SyncStream(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream));
_stream = stream;
}
public override bool CanRead => _stream.CanRead;
public override bool CanWrite => _stream.CanWrite;
public override bool CanSeek => _stream.CanSeek;
public override bool CanTimeout => _stream.CanTimeout;
public override long Length
{
get
{
lock (_stream)
{
return _stream.Length;
}
}
}
public override long Position
{
get
{
lock (_stream)
{
return _stream.Position;
}
}
set
{
lock (_stream)
{
_stream.Position = value;
}
}
}
public override int ReadTimeout
{
get
{
return _stream.ReadTimeout;
}
set
{
_stream.ReadTimeout = value;
}
}
public override int WriteTimeout
{
get
{
return _stream.WriteTimeout;
}
set
{
_stream.WriteTimeout = value;
}
}
// In the off chance that some wrapped stream has different
// semantics for Close vs. Dispose, let's preserve that.
public override void Close()
{
lock (_stream)
{
try
{
_stream.Close();
}
finally
{
base.Dispose(true);
}
}
}
protected override void Dispose(bool disposing)
{
lock (_stream)
{
try
{
// Explicitly pick up a potentially methodimpl'ed Dispose
if (disposing)
((IDisposable)_stream).Dispose();
}
finally
{
base.Dispose(disposing);
}
}
}
public override ValueTask DisposeAsync()
{
lock (_stream)
return _stream.DisposeAsync();
}
public override void Flush()
{
lock (_stream)
_stream.Flush();
}
public override int Read(byte[] bytes, int offset, int count)
{
lock (_stream)
return _stream.Read(bytes, offset, count);
}
public override int Read(Span<byte> buffer)
{
lock (_stream)
return _stream.Read(buffer);
}
public override int ReadByte()
{
lock (_stream)
return _stream.ReadByte();
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
#if CORERT
throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251
#else
bool overridesBeginRead = _stream.HasOverriddenBeginEndRead();
lock (_stream)
{
// If the Stream does have its own BeginRead implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginRead ?
_stream.BeginRead(buffer, offset, count, callback, state) :
_stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
#endif
}
public override int EndRead(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
lock (_stream)
return _stream.EndRead(asyncResult);
}
public override long Seek(long offset, SeekOrigin origin)
{
lock (_stream)
return _stream.Seek(offset, origin);
}
public override void SetLength(long length)
{
lock (_stream)
_stream.SetLength(length);
}
public override void Write(byte[] bytes, int offset, int count)
{
lock (_stream)
_stream.Write(bytes, offset, count);
}
public override void Write(ReadOnlySpan<byte> buffer)
{
lock (_stream)
_stream.Write(buffer);
}
public override void WriteByte(byte b)
{
lock (_stream)
_stream.WriteByte(b);
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
#if CORERT
throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251
#else
bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite();
lock (_stream)
{
// If the Stream does have its own BeginWrite implementation, then we must use that override.
// If it doesn't, then we'll use the base implementation, but we'll make sure that the logic
// which ensures only one asynchronous operation does so with an asynchronous wait rather
// than a synchronous wait. A synchronous wait will result in a deadlock condition, because
// the EndXx method for the outstanding async operation won't be able to acquire the lock on
// _stream due to this call blocked while holding the lock.
return overridesBeginWrite ?
_stream.BeginWrite(buffer, offset, count, callback, state) :
_stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true);
}
#endif
}
public override void EndWrite(IAsyncResult asyncResult)
{
if (asyncResult == null)
throw new ArgumentNullException(nameof(asyncResult));
lock (_stream)
_stream.EndWrite(asyncResult);
}
}
}
}
| |
using Microsoft.DirectX.Direct3D;
using System;
using System.Drawing;
using TGC.Core.Direct3D;
using TGC.Core.Mathematica;
using TGC.Core.SceneLoader;
using TGC.Core.Shaders;
namespace TGC.Examples.ShadersExamples
{
public class F1Circuit
{
public float ancho_guarray = 3;
public float ancho_ruta = 200;
public TgcMesh[] arbol = new TgcMesh[10];
public int cant_arboles;
public int cant_carteles;
public int cant_ptos_ruta;
public float dh = 3; // alto de la pared
public bool en_ruta;
public float Hpiso; // Altura del piso en la Pos
public float M_PI = 3.14151f;
public int pos_carteles;
public int pos_en_ruta;
public TGCVector3[] pt_ruta = new TGCVector3[500];
public float scaleXZ = 20;
public float scaleY = 15;
public Texture textura_cartel;
public Texture textura_guardrail;
public Texture textura_piso;
public int totalVertices;
private VertexBuffer vb;
public F1Circuit(string mediaDir)
{
CrearRuta(mediaDir);
var loader = new TgcSceneLoader();
arbol[cant_arboles] =
loader.loadSceneFromFile(mediaDir +
"MeshCreator\\Meshes\\Vegetacion\\ArbolSelvatico\\ArbolSelvatico-TgcScene.xml")
.Meshes[0];
cant_arboles++;
arbol[cant_arboles] =
loader.loadSceneFromFile(mediaDir + "MeshCreator\\Meshes\\Vegetacion\\Palmera3\\Palmera3-TgcScene.xml")
.Meshes[0];
arbol[cant_arboles].Scale = new TGCVector3(2, 2, 2);
++cant_arboles;
arbol[cant_arboles] =
loader.loadSceneFromFile(mediaDir + "MeshCreator\\Meshes\\Vegetacion\\Palmera2\\Palmera2-TgcScene.xml")
.Meshes[0];
arbol[cant_arboles].Scale = TGCVector3.One;
++cant_arboles;
arbol[cant_arboles] =
loader.loadSceneFromFile(mediaDir + "MeshCreator\\Meshes\\Vegetacion\\Pino\\Pino-TgcScene.xml").Meshes[0
];
arbol[cant_arboles].Scale = new TGCVector3(4, 4, 4);
++cant_arboles;
}
// Carga los ptos de la ruta
public int load_pt_ruta()
{
// Genero el path de la ruta
double dt = M_PI / 64;
double t = 0;
double hasta = 2 * M_PI;
var cant = 0;
//float dw = 10000;
while (t < hasta + 0.1)
{
pt_ruta[cant].X = (float)(8 * (8 * Math.Cos(t) + Math.Cos(5 * t) * Math.Cos(t))) * scaleXZ;
pt_ruta[cant].Z = (float)(8 * (8 * Math.Sin(t) + Math.Cos(4 * t) * Math.Sin(t))) * scaleXZ;
pt_ruta[cant].Y = (float)Math.Max(0, 3 + 2 * Math.Cos(3 + t * 5)) * scaleY;
t += dt;
++cant;
}
--cant; // me aseguro que siempre exista el i+1
return cant;
}
public void CrearRuta(string mediaDir)
{
//Dispose de VertexBuffer anterior, si habia
if (vb != null && !vb.Disposed)
{
vb.Dispose();
}
var Kr = 0.5f;
var dr = ancho_ruta / 2;
// Cargo la ruta
cant_ptos_ruta = load_pt_ruta();
cant_carteles = 6;
var dc = cant_ptos_ruta / cant_carteles;
//Crear vertexBuffer
totalVertices = cant_ptos_ruta * 6 + cant_carteles * 4;
vb = new VertexBuffer(typeof(CustomVertex.PositionTextured), totalVertices, D3DDevice.Instance.Device,
Usage.Dynamic | Usage.WriteOnly, CustomVertex.PositionTextured.Format, Pool.Default);
//Cargar vertices
var dataIdx = 0;
var data = new CustomVertex.PositionTextured[totalVertices];
// piso
for (var i = 0; i < cant_ptos_ruta; ++i)
{
var dir = pt_ruta[i + 1] - pt_ruta[i];
dir.Normalize();
var n = TGCVector3.Cross(dir, TGCVector3.Up);
var p0 = pt_ruta[i] - n * dr;
var p1 = pt_ruta[i] + n * dr;
data[dataIdx++] = new CustomVertex.PositionTextured(p0, 1, i * Kr);
data[dataIdx++] = new CustomVertex.PositionTextured(p1, 0, i * Kr);
}
// pared izquierda
for (var i = 0; i < cant_ptos_ruta; ++i)
{
var dir = pt_ruta[i + 1] - pt_ruta[i];
dir.Normalize();
var n = TGCVector3.Cross(dir, TGCVector3.Up);
var u = TGCVector3.Cross(n, dir);
var p0 = pt_ruta[i] - n * (dr + ancho_guarray);
var p1 = pt_ruta[i] - n * dr;
p0.Y -= 25;
p1.Y += 25;
data[dataIdx++] = new CustomVertex.PositionTextured(p0, i * Kr, 1);
data[dataIdx++] = new CustomVertex.PositionTextured(p1, i * Kr, 0);
}
// pared derecha
for (var i = 0; i < cant_ptos_ruta; ++i)
{
var dir = pt_ruta[i + 1] - pt_ruta[i];
dir.Normalize();
var n = TGCVector3.Cross(dir, TGCVector3.Up);
var u = TGCVector3.Cross(n, dir);
var p0 = pt_ruta[i] + n * (dr + ancho_guarray);
var p1 = pt_ruta[i] + n * dr;
p0.Y -= 25;
p1.Y += 25;
data[dataIdx++] = new CustomVertex.PositionTextured(p0, i * Kr, 1);
data[dataIdx++] = new CustomVertex.PositionTextured(p1, i * Kr, 0);
}
// Carteles
pos_carteles = dataIdx;
for (var t = 0; t < cant_carteles; ++t)
{
var i = t * dc;
var dir = pt_ruta[i + 1] - pt_ruta[i];
dir.Normalize();
var up = TGCVector3.Up;
var n = TGCVector3.Cross(dir, up);
var p0 = pt_ruta[i] - n * (dr + 50) + up * 0;
var p1 = pt_ruta[i] - n * (dr + 50) + up * 170;
var p2 = pt_ruta[i] + n * (dr + 50) + up * 170;
var p3 = pt_ruta[i] + n * (dr + 50) + up * 0;
data[dataIdx++] = new CustomVertex.PositionTextured(p0, 1, 1);
data[dataIdx++] = new CustomVertex.PositionTextured(p3, 0, 1);
data[dataIdx++] = new CustomVertex.PositionTextured(p1, 1, 0);
data[dataIdx++] = new CustomVertex.PositionTextured(p2, 0, 0);
}
vb.SetData(data, 0, LockFlags.None);
// Cargo la textura del piso
loadTextures(mediaDir);
}
/// <summary>
/// Carga la textura del terreno
/// </summary>
public void loadTextures(string mediaDir)
{
//Dispose textura anterior, si habia
if (textura_piso != null && !textura_piso.Disposed)
{
textura_piso.Dispose();
}
var d3dDevice = D3DDevice.Instance.Device;
var MyMediaDir = mediaDir + "Texturas\\f1\\";
textura_piso = Texture.FromBitmap(d3dDevice, (Bitmap)Image.FromFile(MyMediaDir + "f1piso2.png"), Usage.None,
Pool.Managed);
textura_guardrail = Texture.FromBitmap(d3dDevice, (Bitmap)Image.FromFile(MyMediaDir + "guardrail.png"),
Usage.None, Pool.Managed);
textura_cartel = Texture.FromBitmap(d3dDevice, (Bitmap)Image.FromFile(MyMediaDir + "cartel1.png"),
Usage.None, Pool.Managed);
}
public void render(Effect effect)
{
var device = D3DDevice.Instance.Device;
TGCShaders.Instance.SetShaderMatrixIdentity(effect);
device.VertexFormat = CustomVertex.PositionTextured.Format;
device.SetStreamSource(0, vb, 0);
// primero dibujo los objetos opacos:
// piso de la ruta
effect.SetValue("texDiffuseMap", textura_piso);
device.RenderState.AlphaBlendEnable = false;
var numPasses = effect.Begin(0);
for (var n = 0; n < numPasses; n++)
{
effect.BeginPass(n);
device.DrawPrimitives(PrimitiveType.TriangleStrip, 0, 2 * (cant_ptos_ruta - 1));
effect.EndPass();
}
effect.End();
// vegetacion
if (pos_en_ruta != -1)
{
var K = new float[10];
for (var i = 0; i < cant_arboles; ++i)
{
K[i] = 1;
arbol[i].Effect = effect;
arbol[i].Technique = "DefaultTechnique";
}
var P = new int[10];
P[0] = 11;
P[1] = 7;
P[2] = 13;
P[3] = 5;
var dr = ancho_ruta / 2;
for (var i = 0; i < cant_ptos_ruta; ++i)
{
var dir = pt_ruta[i + 1] - pt_ruta[i];
dir.Normalize();
var n = TGCVector3.Cross(dir, TGCVector3.Up);
var p0 = pt_ruta[i] - n * dr;
var p1 = pt_ruta[i] + n * dr;
for (var j = 0; j < cant_arboles; ++j)
{
if (i % P[j] == 0)
{
var pos = pt_ruta[i] - n * 300 * K[j];
pos.Y = 0;
arbol[j].Position = pos;
arbol[j].UpdateMeshTransform();
arbol[j].Render();
K[j] *= -1;
}
}
}
}
// Ahora los objetos transparentes (el guarda rail, y los carteles)
// guarda rail
device.RenderState.AlphaBlendEnable = true;
TGCShaders.Instance.SetShaderMatrixIdentity(effect);
device.VertexFormat = CustomVertex.PositionTextured.Format;
device.SetStreamSource(0, vb, 0);
effect.SetValue("texDiffuseMap", textura_guardrail);
numPasses = effect.Begin(0);
for (var n = 0; n < numPasses; n++)
{
effect.BeginPass(n);
device.DrawPrimitives(PrimitiveType.TriangleStrip, 2 * cant_ptos_ruta, 2 * (cant_ptos_ruta - 1));
device.DrawPrimitives(PrimitiveType.TriangleStrip, 4 * cant_ptos_ruta, 2 * (cant_ptos_ruta - 1));
effect.EndPass();
}
effect.End();
// carteles
effect.SetValue("texDiffuseMap", textura_cartel);
numPasses = effect.Begin(0);
for (var n = 0; n < numPasses; n++)
{
effect.BeginPass(n);
for (var i = 0; i < cant_carteles; ++i)
device.DrawPrimitives(PrimitiveType.TriangleStrip, pos_carteles + 4 * i, 2);
effect.EndPass();
}
effect.End();
}
public float updatePos(float x, float z)
{
// Verifico si el pto x,z esta cerca de la ruta
// busco todos los puntos de la ruta cercanos a Pos
var mdist = ancho_ruta / 2 + ancho_guarray;
var aux_tramo = -1;
en_ruta = false;
var cant_p = 0;
var ndx = new int[700];
for (var i = 0; i < cant_ptos_ruta - 1; ++i)
if (Math.Abs(x - pt_ruta[i].X) < mdist + 5 && Math.Abs(z - pt_ruta[i].Z) < mdist + 5)
// es un pto posible
ndx[cant_p++] = i;
if (cant_p == 0)
return 0; // nivel del suelo
var dr = ancho_ruta / 2;
float H = 0;
var p = new TGCVector2(x, z);
for (var t = 0; t < cant_p; ++t)
{
var i = ndx[t];
var r0 = new TGCVector2(pt_ruta[i].X, pt_ruta[i].Z);
var r1 = new TGCVector2(pt_ruta[i + 1].X, pt_ruta[i + 1].Z);
var r = r1 - r0;
var rm = r.Length();
r.Normalize();
var d = TGCVector2.Dot(p - r0, r);
// d ==0 , rm
if (d >= -0.5 && d <= rm + 0.5)
{
var rc = r0 + r * d;
var dist = (rc - p).Length();
if (dist < mdist)
{
aux_tramo = i;
mdist = dist;
// interpolo la altura de la ruta
var k = d / rm;
if (k < 0)
k = 0;
else if (k > 1)
k = 1;
var Hruta = pt_ruta[i].Y * (1 - k) + pt_ruta[i + 1].Y * k;
if (dist <= dr)
{
// esta en la ruta
en_ruta = true;
H = Hruta;
}
else
{
// esta en el guarray
en_ruta = false;
H = (1 - (dist - dr) / ancho_guarray) * Hruta;
}
}
}
}
// Actualizo el status
Hpiso = H;
pos_en_ruta = aux_tramo;
return H;
}
// se fue de la ruta, devuelve que posicion mas cercana en el centro de la ruta
public TGCVector3 que_pos_buena(float x, float z)
{
var mdist = 10000000000f;
var aux_tramo = -1;
var dr = ancho_ruta / 2;
//float H = 0;
var p = new TGCVector2(x, z);
for (var i = 0; i < cant_ptos_ruta; ++i)
{
var r0 = new TGCVector2(pt_ruta[i].X, pt_ruta[i].Z);
var r1 = new TGCVector2(pt_ruta[i + 1].X, pt_ruta[i + 1].Z);
var r = r1 - r0;
var rm = r.Length();
r.Normalize();
var d = TGCVector2.Dot(p - r0, r);
// d ==0 , rm
if (d >= -0.5 && d <= rm + 0.5)
{
var rc = r0 + r * d;
var dist = (rc - p).Length();
if (dist < mdist)
{
aux_tramo = i;
mdist = dist;
}
}
}
if (aux_tramo != -1)
{
x = pt_ruta[aux_tramo].X;
z = pt_ruta[aux_tramo].Z;
}
return new TGCVector3(x, updatePos(x, z), z);
}
public void dispose()
{
if (vb != null)
{
vb.Dispose();
}
if (textura_piso != null)
{
textura_piso.Dispose();
}
if (textura_guardrail != null)
{
textura_guardrail.Dispose();
}
if (textura_cartel != null)
{
textura_cartel.Dispose();
}
for (var i = 0; i < cant_arboles; ++i)
arbol[i].Dispose();
}
}
}
| |
using Microsoft.CodeAnalysis;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Collections.Generic;
using System.Collections.Immutable;
using System;
namespace ZeroFormatter.Analyzer
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ZeroFormatterAnalyzer : DiagnosticAnalyzer
{
const string DiagnosticIdBase = "ZeroFormatterAnalyzer";
internal const string Title = "Lint of ZeroFormattable Type.";
internal const string Category = "Usage";
internal const string ZeroFormattableAttributeShortName = "ZeroFormattableAttribute";
internal const string IndexAttributeShortName = "IndexAttribute";
internal const string IgnoreShortName = "IgnoreFormatAttribute";
internal const string UnionAttributeShortName = "UnionAttribute";
internal const string DynamicUnionAttributeShortName = "DynamicUnionAttribute";
internal const string UnionKeyAttributeShortName = "UnionKeyAttribute";
internal static readonly DiagnosticDescriptor TypeMustBeZeroFormattable = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(TypeMustBeZeroFormattable), title: Title, category: Category,
messageFormat: "Type must be marked with ZeroFormattableAttribute. {0}.", // type.Name
description: "Type must be marked with ZeroFormattableAttribute.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor PublicPropertyNeedsIndex = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(PublicPropertyNeedsIndex), title: Title, category: Category,
messageFormat: "Public property must be marked with IndexAttribute or IgnoreFormatAttribute. {0}.{1}.", // type.Name + "." + item.Name
description: "Public property must be marked with IndexAttribute or IgnoreFormatAttribute.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor PublicPropertyNeedsGetAndSetAccessor = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(PublicPropertyNeedsGetAndSetAccessor), title: Title, category: Category,
messageFormat: "Public property must needs both public/protected get and set accessor. {0}.{1}.", // type.Name + "." + item.Name
description: "Public property must needs both public/protected get and set accessor.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor PublicPropertyMustBeVirtual = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(PublicPropertyMustBeVirtual), title: Title, category: Category,
messageFormat: "Public property's accessor must be virtual. {0}.{1}.", // type.Name + "." + item.Name
description: "Public property's accessor must be virtual.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor ClassNotSupportPublicField = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(ClassNotSupportPublicField), title: Title, category: Category,
messageFormat: "Class's public field is not supported. {0}.{1}.", // type.Name + "." + item.Name
description: "Class's public field is not supported.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor IndexAttributeDuplicate = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(IndexAttributeDuplicate), title: Title, category: Category,
messageFormat: "IndexAttribute is not allow duplicate number. {0}.{1}, Index:{2}", // type.Name, item.Name index.Index
description: "IndexAttribute is not allow duplicate number.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor IndexIsTooLarge = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(IndexIsTooLarge), title: Title, category: Category,
messageFormat: "MaxIndex is {0}, it is large. Index is size of binary, recommended to small. {1}", // index, type.Name
description: "MaxIndex is large. Index is size of binary, recommended to small.",
defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor TypeMustNeedsParameterlessConstructor = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(TypeMustNeedsParameterlessConstructor), title: Title, category: Category,
messageFormat: "Type must needs parameterless constructor. {0}", // type.Name
description: "Type must needs parameterless constructor.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor StructIndexMustBeStartedWithZeroAndSequential = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(StructIndexMustBeStartedWithZeroAndSequential), title: Title, category: Category,
messageFormat: "Struct index must be started with 0 and be sequential. Type: {0}, InvalidIndex: {1}", // type.Name, index
description: "Struct index must be started with 0 and be sequential.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor StructMustNeedsSameConstructorWithIndexes = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(StructIndexMustBeStartedWithZeroAndSequential), title: Title, category: Category,
messageFormat: "Struct needs full parameter constructor of index property types. Type: {0}", // type.Name
description: "Struct needs full parameter constructor of index property types.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor UnionTypeRequiresUnionKey = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(UnionTypeRequiresUnionKey), title: Title, category: Category,
messageFormat: "Union class requires abstract [UnionKey]property. Type: {0}", // type.Name
description: "Union class requires abstract [UnionKey]property.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor UnionKeyDoesNotAllowMultipleKey = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(UnionKeyDoesNotAllowMultipleKey), title: Title, category: Category,
messageFormat: "[UnionKey]property does not allow multiple key. Type: {0}", // type.Name
description: "[UnionKey]property does not allow multiple key.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
internal static readonly DiagnosticDescriptor AllUnionSubTypesMustBeInheritedType = new DiagnosticDescriptor(
id: DiagnosticIdBase + "_" + nameof(UnionKeyDoesNotAllowMultipleKey), title: Title, category: Category,
messageFormat: "All Union subTypes must be inherited type. Type: {0}, SubType: {1}", // type.Name subType.Name
description: "All Union subTypes must be inherited type.",
defaultSeverity: DiagnosticSeverity.Error, isEnabledByDefault: true);
static readonly ImmutableArray<DiagnosticDescriptor> supportedDiagnostics = ImmutableArray.Create(
TypeMustBeZeroFormattable,
PublicPropertyNeedsIndex,
PublicPropertyNeedsGetAndSetAccessor,
PublicPropertyMustBeVirtual,
ClassNotSupportPublicField,
IndexAttributeDuplicate,
IndexIsTooLarge,
TypeMustNeedsParameterlessConstructor,
StructIndexMustBeStartedWithZeroAndSequential,
StructMustNeedsSameConstructorWithIndexes,
UnionTypeRequiresUnionKey,
UnionKeyDoesNotAllowMultipleKey,
AllUnionSubTypesMustBeInheritedType
);
static readonly HashSet<string> AllowTypes = new HashSet<string>
{
"short",
"int",
"long",
"ushort",
"uint",
"ulong",
"float",
"double",
"bool",
"byte",
"sbyte",
"decimal",
"char",
"string",
"System.Guid",
"System.TimeSpan",
"System.DateTime",
"System.DateTimeOffset"
};
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return supportedDiagnostics;
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration, SyntaxKind.InterfaceDeclaration);
}
static void Analyze(SyntaxNodeAnalysisContext context)
{
var model = context.SemanticModel;
var typeDeclaration = context.Node as TypeDeclarationSyntax;
if (typeDeclaration == null) return;
var declaredSymbol = model.GetDeclaredSymbol(typeDeclaration);
if (declaredSymbol == null) return;
var isUnion = declaredSymbol.GetAttributes().FindAttributeShortName(UnionAttributeShortName) != null;
var isZeroFormattable = declaredSymbol.GetAttributes().FindAttributeShortName(ZeroFormattableAttributeShortName) != null;
if (!isUnion && !isZeroFormattable)
{
return;
}
var reportContext = new DiagnosticsReportContext(context);
if (isUnion)
{
VerifyUnion(reportContext, typeDeclaration.GetLocation(), declaredSymbol);
}
if (isZeroFormattable)
{
VerifyType(reportContext, typeDeclaration.GetLocation(), declaredSymbol, new HashSet<ITypeSymbol>(), null);
}
reportContext.ReportAll();
}
static void VerifyType(DiagnosticsReportContext context, Location callerLocation, ITypeSymbol type, HashSet<ITypeSymbol> alreadyAnalyzed, ISymbol callFromProperty)
{
if (!alreadyAnalyzed.Add(type))
{
return;
}
var displayString = type.ToDisplayString();
if (AllowTypes.Contains(displayString))
{
return; // it is primitive...
}
else if (context.AdditionalAllowTypes.Contains(displayString))
{
return;
}
if (type.GetAttributes().FindAttributeShortName(UnionAttributeShortName) != null)
{
return;
}
if (type.GetAttributes().FindAttributeShortName(DynamicUnionAttributeShortName) != null)
{
return;
}
if (type.TypeKind == TypeKind.Enum)
{
return;
}
if (type.TypeKind == TypeKind.Array)
{
var array = type as IArrayTypeSymbol;
var t = array.ElementType;
VerifyType(context, callerLocation, t, alreadyAnalyzed, callFromProperty);
return;
}
var namedType = type as INamedTypeSymbol;
if (namedType != null && namedType.IsGenericType && callFromProperty != null)
{
var genericType = namedType.ConstructUnboundGenericType();
var genericTypeString = genericType.ToDisplayString();
if (genericTypeString == "T?")
{
VerifyType(context, callerLocation, namedType.TypeArguments[0], alreadyAnalyzed, callFromProperty);
return;
}
else if (genericTypeString == "System.Collections.Generic.IList<>"
|| genericTypeString == "System.Collections.Generic.IDictionary<,>"
|| genericTypeString == "System.Collections.Generic.Dictionary<,>"
|| genericTypeString == "ZeroFormatter.ILazyDictionary<,>"
|| genericTypeString == "System.Collections.Generic.IReadOnlyList<>"
|| genericTypeString == "System.Collections.Generic.IReadOnlyCollection<>"
|| genericTypeString == "System.Collections.Generic.IReadOnlyDictionary<,>"
|| genericTypeString == "System.Collections.Generic.ICollection<>"
|| genericTypeString == "System.Collections.Generic.IEnumerable<>"
|| genericTypeString == "System.Collections.Generic.ISet<>"
|| genericTypeString == "System.Collections.ObjectModel.ReadOnlyCollection<>"
|| genericTypeString == "System.Collections.ObjectModel.ReadOnlyDictionary<,>"
|| genericTypeString == "ZeroFormatter.ILazyReadOnlyDictionary<,>"
|| genericTypeString == "System.Linq.ILookup<,>"
|| genericTypeString == "ZeroFormatter.ILazyLookup<,>"
|| genericTypeString.StartsWith("System.Collections.Generic.KeyValuePair")
|| genericTypeString.StartsWith("System.Tuple")
|| genericTypeString.StartsWith("ZeroFormatter.KeyTuple")
|| context.AdditionalAllowTypes.Contains(genericTypeString)
)
{
foreach (var t in namedType.TypeArguments)
{
VerifyType(context, callerLocation, t, alreadyAnalyzed, callFromProperty);
}
return;
}
else
{
if (namedType.AllInterfaces.Any(x => (x.IsGenericType ? x.ConstructUnboundGenericType().ToDisplayString() : "") == "System.Collections.Generic.ICollection<>"))
{
foreach (var t in namedType.TypeArguments)
{
VerifyType(context, callerLocation, t, alreadyAnalyzed, callFromProperty);
}
return;
}
}
}
if (type.GetAttributes().FindAttributeShortName(ZeroFormattableAttributeShortName) == null)
{
context.Add(Diagnostic.Create(TypeMustBeZeroFormattable, callerLocation, type.Locations, type.Name));
return;
}
if (namedType != null && !namedType.IsValueType)
{
if (!namedType.Constructors.Any(x => x.Parameters.Length == 0))
{
context.Add(Diagnostic.Create(TypeMustNeedsParameterlessConstructor, callerLocation, type.Locations, type.Name));
return;
}
}
// If in another project, we can not report so stop analyze.
if (callFromProperty == null)
{
var definedIndexes = new HashSet<int>();
foreach (var member in type.GetAllMembers().OfType<IPropertySymbol>())
{
VerifyProperty(context, member, alreadyAnalyzed, definedIndexes);
}
foreach (var member in type.GetAllMembers().OfType<IFieldSymbol>())
{
VerifyField(context, member, alreadyAnalyzed, definedIndexes);
}
if (type.IsValueType && context.Diagnostics.Count == 0)
{
var indexes = new List<Tuple<int, ITypeSymbol>>();
foreach (var item in type.GetMembers())
{
var propSymbol = item as IPropertySymbol;
var fieldSymbol = item as IFieldSymbol;
if ((propSymbol == null && fieldSymbol == null))
{
continue;
}
var indexAttr = item.GetAttributes().FindAttributeShortName(IndexAttributeShortName);
if (indexAttr != null)
{
var index = (int)indexAttr.ConstructorArguments[0].Value;
indexes.Add(Tuple.Create(index, (propSymbol != null) ? propSymbol.Type : fieldSymbol.Type));
}
}
indexes = indexes.OrderBy(x => x.Item1).ToList();
var expected = 0;
foreach (var item in indexes)
{
if (item.Item1 != expected)
{
context.Add(Diagnostic.Create(StructIndexMustBeStartedWithZeroAndSequential, callerLocation, type.Locations, type.Name, item.Item1));
return;
}
expected++;
}
var foundConstructor = false;
var ctors = (type as INamedTypeSymbol)?.Constructors;
foreach (var ctor in ctors)
{
var isMatch = indexes.Select(x => x.Item2.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat))
.SequenceEqual(ctor.Parameters.Select(x => x.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)));
if (isMatch)
{
foundConstructor = true;
}
}
if (!foundConstructor && indexes.Count != 0)
{
context.Add(Diagnostic.Create(StructMustNeedsSameConstructorWithIndexes, callerLocation, type.Locations, type.Name));
return;
}
return;
}
}
}
static void VerifyProperty(DiagnosticsReportContext context, IPropertySymbol property, HashSet<ITypeSymbol> alreadyAnalyzed, HashSet<int> definedIndexes)
{
if (property.IsStatic)
{
return;
}
if (property.DeclaredAccessibility != Accessibility.Public)
{
return;
}
var attributes = property.GetAttributes();
if (attributes.FindAttributeShortName(IgnoreShortName) != null)
{
return;
}
if (property.FindAttributeIncludeBasePropertyShortName(UnionKeyAttributeShortName) != null)
{
return;
}
if (!property.IsVirtual && !property.ContainingType.IsValueType)
{
if (property.IsOverride && !property.IsSealed)
{
// ok, base type's override property.
}
else
{
context.Add(Diagnostic.Create(PublicPropertyMustBeVirtual, property.Locations[0], property.ContainingType?.Name, property.Name));
return;
}
}
var indexAttr = attributes.FindAttributeShortName(IndexAttributeShortName);
if (indexAttr == null || indexAttr.ConstructorArguments.Length == 0)
{
context.Add(Diagnostic.Create(PublicPropertyNeedsIndex, property.Locations[0], property.ContainingType?.Name, property.Name));
return;
}
var index = indexAttr.ConstructorArguments[0];
if (index.IsNull)
{
return; // null is normal compiler error.
}
if (!definedIndexes.Add((int)index.Value))
{
context.Add(Diagnostic.Create(IndexAttributeDuplicate, property.Locations[0], property.ContainingType?.Name, property.Name, index.Value));
return;
}
if ((int)index.Value >= 100)
{
context.Add(Diagnostic.Create(IndexIsTooLarge, property.Locations[0], index.Value, property.Name));
}
if (!property.ContainingType.IsValueType)
{
if (property.GetMethod == null || property.SetMethod == null
|| property.GetMethod.DeclaredAccessibility == Accessibility.Private
|| property.SetMethod.DeclaredAccessibility == Accessibility.Private)
{
context.Add(Diagnostic.Create(PublicPropertyNeedsGetAndSetAccessor, property.Locations[0], property.ContainingType?.Name, property.Name));
return;
}
}
var namedType = property.Type as INamedTypeSymbol;
if (namedType != null) // if <T> is unnamed type, it can't analyze.
{
VerifyType(context, property.Locations[0], property.Type, alreadyAnalyzed, property);
return;
}
if (property.Type.TypeKind == TypeKind.Array)
{
var array = property.Type as IArrayTypeSymbol;
var t = array.ElementType;
VerifyType(context, property.Locations[0], property.Type, alreadyAnalyzed, property);
return;
}
}
static void VerifyField(DiagnosticsReportContext context, IFieldSymbol field, HashSet<ITypeSymbol> alreadyAnalyzed, HashSet<int> definedIndexes)
{
if (field.IsStatic)
{
return;
}
if (field.DeclaredAccessibility != Accessibility.Public)
{
return;
}
var attributes = field.GetAttributes();
if (attributes.FindAttributeShortName(IgnoreShortName) != null)
{
return;
}
if (!field.ContainingType.IsValueType)
{
context.Add(Diagnostic.Create(ClassNotSupportPublicField, field.Locations[0], field.ContainingType?.Name, field.Name));
return;
}
var indexAttr = attributes.FindAttributeShortName(IndexAttributeShortName);
if (indexAttr == null || indexAttr.ConstructorArguments.Length == 0)
{
context.Add(Diagnostic.Create(PublicPropertyNeedsIndex, field.Locations[0], field.ContainingType?.Name, field.Name));
return;
}
var index = indexAttr.ConstructorArguments[0];
if (index.IsNull)
{
return; // null is normal compiler error.
}
if (!definedIndexes.Add((int)index.Value))
{
context.Add(Diagnostic.Create(IndexAttributeDuplicate, field.Locations[0], field.ContainingType?.Name, field.Name, index.Value));
return;
}
if ((int)index.Value >= 100)
{
context.Add(Diagnostic.Create(IndexIsTooLarge, field.Locations[0], index.Value, field.Name));
}
var namedType = field.Type as INamedTypeSymbol;
if (namedType != null) // if <T> is unnamed type, it can't analyze.
{
VerifyType(context, field.Locations[0], field.Type, alreadyAnalyzed, field);
}
}
static void VerifyUnion(DiagnosticsReportContext context, Location callerLocation, ITypeSymbol type)
{
var unionKeys = type.GetMembers().OfType<IPropertySymbol>().Where(x => x.GetAttributes().FindAttributeShortName(UnionKeyAttributeShortName) != null).ToArray();
if (unionKeys.Length == 0)
{
context.Add(Diagnostic.Create(UnionTypeRequiresUnionKey, callerLocation, type.Locations, type.Name));
return;
}
else if (unionKeys.Length != 1)
{
context.Add(Diagnostic.Create(UnionKeyDoesNotAllowMultipleKey, callerLocation, type.Locations, type.Name));
return;
}
var unionKeyProperty = unionKeys[0];
if (type.TypeKind != TypeKind.Interface && !unionKeyProperty.GetMethod.IsAbstract)
{
context.Add(Diagnostic.Create(UnionTypeRequiresUnionKey, callerLocation, type.Locations, type.Name));
return;
}
var ctorArguments = type.GetAttributes().FindAttributeShortName(UnionAttributeShortName)?.ConstructorArguments;
var firstArguments = ctorArguments?.FirstOrDefault();
if (firstArguments == null) return;
TypedConstant fallbackType = default(TypedConstant);
if (ctorArguments.Value.Length == 2)
{
fallbackType = ctorArguments.Value[1];
}
if (type.TypeKind != TypeKind.Interface)
{
foreach (var item in firstArguments.Value.Values.Concat(new[] { fallbackType }).Where(x => !x.IsNull).Select(x => x.Value).OfType<ITypeSymbol>())
{
var found = item.FindBaseTargetType(type.ToDisplayString());
if (found == null)
{
context.Add(Diagnostic.Create(AllUnionSubTypesMustBeInheritedType, callerLocation, type.Locations, type.Name, item.Name));
return;
}
}
}
else
{
foreach (var item in firstArguments.Value.Values.Concat(new[] { fallbackType }).Where(x => !x.IsNull).Select(x => x.Value).OfType<ITypeSymbol>())
{
var typeString = type.ToDisplayString();
if (!(item as INamedTypeSymbol).AllInterfaces.Any(x => x.OriginalDefinition?.ToDisplayString() == typeString))
{
context.Add(Diagnostic.Create(AllUnionSubTypesMustBeInheritedType, callerLocation, type.Locations, type.Name, item.Name));
return;
}
}
}
}
}
}
| |
// Copyright (c) 2021 Alachisoft
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License
using System;
using System.Text;
using System.Data;
using System.Collections;
using Alachisoft.NCache.Runtime.Exceptions;
namespace Alachisoft.NCache.Config
{
/// <summary>
/// Utility class to help parse properties from a property string and convert it into
/// a HashMap of properties, which is later used by various classes for configurations.
/// </summary>
public class PropsConfigReader : ConfigReader
{
/// <summary>
/// Class that helps parse the property string.
/// </summary>
class Tokenizer
{
/// <summary> original text to be tokenized. </summary>
private string _text;
/// <summary> current token value. </summary>
private string _token;
/// <summary> indexer used in parsing. </summary>
private int _index = 0;
public const int EOF = -1;
public const int ASSIGN = 0;
public const int NEST = 1;
public const int UNNEST = 2;
public const int CONTINUE = 3;
public const int ID = 4;
/// <summary>
/// Constructor
/// </summary>
/// <param name="text">text to be tokenized</param>
public Tokenizer(string text)
{
_text = text;
}
/// <summary>
/// Current token value.
/// </summary>
public string TokenValue
{
get { return _token; }
}
/// <summary>
/// returns an identifier token value.
/// </summary>
/// <returns></returns>
private string getIdentifier()
{
const string offendingStr = "=();";
StringBuilder returnVal = new StringBuilder();
if(_text[_index] == '\'')
{
_index++;
while(_index < _text.Length)
{
if(_text[_index] == '\'')
{
_index ++;
return returnVal.ToString();
}
if(_text[_index] == '\r' || _text[_index] == '\n' || _text[_index] == '\t')
{
_index++;
continue;
}
returnVal.Append(_text[_index++]);
}
return null;
}
while(_index < _text.Length)
{
if(_text[_index] == '\r' || _text[_index] == '\n' || _text[_index] == '\t')
{
_index++;
continue;
}
if(offendingStr.IndexOf(_text[_index]) != -1)
{
return returnVal.ToString();
}
returnVal.Append(_text[_index++]);
}
return null;
}
/// <summary>
/// parses and returns the next token in the string.
/// </summary>
/// <returns>next token in the string.</returns>
public int getNextToken()
{
string trimStr = "=();";
while(_index < _text.Length)
{
if(trimStr.IndexOf(_text[_index]) != -1)
{
_token = _text[_index].ToString();
return trimStr.IndexOf(_text[_index++]);
}
if(_text[_index] == '\r' || _text[_index] == '\n' || _text[_index] == '\t' || _text[_index] == ' ')
{
_index++;
continue;
}
_token = getIdentifier();
if(_token != null) return ID;
}
return EOF;
}
}
/// <summary> Property string specified. </summary>
private string _propString;
/// <summary>
/// Constructor.
/// </summary>
/// <param name="propString">property string</param>
public PropsConfigReader(string propString)
{
_propString = propString;
}
/// <summary>
/// property string.
/// </summary>
public string PropertyString
{
get { return _propString; }
}
/// <summary>
/// returns the properties collection
/// </summary>
override public Hashtable Properties
{
get { return GetProperties(_propString); }
}
/// <summary>
/// Returns an xml config from the current properties string.
/// </summary>
/// <returns>xml configuration string.</returns>
public string ToPropertiesXml()
{
return ConfigReader.ToPropertiesXml(Properties);
}
/// <summary>
/// enumeration used to maintain the state of the parser.
/// </summary>
enum State
{
/// <summary> Expecting a keyword </summary>
keyNeeded,
/// <summary> Expecting a value for the keyword </summary>
valNeeded
}
/// <summary>
/// Responsible for parsing the specified property string and returning a
/// HashMap representation of the properties specified in it.
/// </summary>
private Hashtable GetProperties(string propString)
{
bool uppercaseFlag = false;
Hashtable properties = new Hashtable();
Tokenizer tokenizer = new Tokenizer(propString);
string key = "";
int nestingLevel = 0;
State state = State.keyNeeded;
Stack stack = new Stack();
try
{
do
{
int token = tokenizer.getNextToken();
switch (token)
{
case Tokenizer.EOF:
if (state != State.keyNeeded)
{
throw new ConfigurationException("Invalid EOF");
}
if (nestingLevel > 0)
{
throw new ConfigurationException("Invalid property string, un-matched paranthesis");
}
return properties;
case Tokenizer.UNNEST:
if (state != State.keyNeeded)
{
throw new ConfigurationException("Invalid property string, ) misplaced");
}
if (nestingLevel < 1)
throw new ConfigurationException("Invalid property string, ) unexpected");
if (uppercaseFlag)
uppercaseFlag = false;
properties = stack.Pop() as Hashtable;
nestingLevel--;
break;
case Tokenizer.ID:
switch (state)
{
case State.keyNeeded:
if (key == "parameters")
uppercaseFlag = true;
key = tokenizer.TokenValue;
token = tokenizer.getNextToken();
if (token == Tokenizer.CONTINUE ||
token == Tokenizer.UNNEST ||
token == Tokenizer.ID ||
token == Tokenizer.EOF)
{
throw new ConfigurationException("Invalid property string, key following a bad token");
}
if (token == Tokenizer.ASSIGN)
{
state = State.valNeeded;
}
else if (token == Tokenizer.NEST)
{
stack.Push(properties);
properties[key.ToLower()] = new Hashtable();
properties = properties[key.ToLower()] as Hashtable;
state = State.keyNeeded;
nestingLevel++;
}
break;
case State.valNeeded:
string val = tokenizer.TokenValue;
token = tokenizer.getNextToken();
state = State.keyNeeded;
if (token == Tokenizer.ASSIGN || token == Tokenizer.ID || token == Tokenizer.EOF)
{
throw new ConfigurationException("Invalid property string, value following a bad token");
}
if (uppercaseFlag)
properties[key] = val;
else
properties[key.ToLower()] = val;
if (token == Tokenizer.NEST)
{
stack.Push(properties);
properties[key.ToLower()] = new Hashtable();
properties = properties[key.ToLower()] as Hashtable;
properties.Add("id", key);
properties.Add("type", val);
state = State.keyNeeded;
nestingLevel++;
}
else if (token == Tokenizer.UNNEST)
{
if (nestingLevel < 1)
throw new ConfigurationException("Invalid property string, ) unexpected");
if (uppercaseFlag)
uppercaseFlag = false;
properties = stack.Pop() as Hashtable;
nestingLevel--;
state = State.keyNeeded;
}
break;
}
break;
default:
throw new ConfigurationException("Invalid property string");
}
}
while (true);
}
catch (Exception e)
{
throw;
}
return properties;
}
}
}
| |
// Copyright (c) Alex Ghiondea. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using SmugMug.v2.Authentication;
namespace SmugMug.v2.Types
{
public partial class AlbumTemplateEntity : SmugMugEntity
{
private bool _allowDownloads;
private string _backprinting;
private BoutiquePackagingEnum _boutiquePackaging;
private bool _canRank;
private bool _clean;
private bool _comments;
private string _communityUri;
private bool _eXIF;
private bool _external;
private bool _familyEdit;
private bool _filenames;
private bool _friendEdit;
private bool _geography;
private HeaderEnum _header;
private bool _hideOwner;
private InterceptShippingEnum _interceptShipping;
private LargestSizeEnum _largestSize;
private string _name;
private bool _packagingBranding;
private string _password;
private string _passwordHint;
private bool _printable;
private string _printmarkUri;
private long _proofDays;
private bool _protected;
private bool _public;
private bool _share;
private SmugSearchableEnum _smugSearchable;
private SortDirectionEnum _sortDirection;
private SortMethodEnum _sortMethod;
private bool _squareThumbs;
private string _templateUri;
private bool _watermark;
private string _watermarkUri;
private bool _worldSearchable;
public bool AllowDownloads {
get {
return _allowDownloads;
}
set {
if (_allowDownloads != value)
{
NotifyPropertyValueChanged("AllowDownloads", oldValue:_allowDownloads, newValue: value);
_allowDownloads = value;
}
}
}
public string Backprinting {
get {
return _backprinting;
}
set {
if (_backprinting != value)
{
NotifyPropertyValueChanged("Backprinting", oldValue:_backprinting, newValue: value);
_backprinting = value;
}
}
}
public BoutiquePackagingEnum BoutiquePackaging {
get {
return _boutiquePackaging;
}
set {
if (_boutiquePackaging != value)
{
NotifyPropertyValueChanged("BoutiquePackaging", oldValue:_boutiquePackaging, newValue: value);
_boutiquePackaging = value;
}
}
}
public bool CanRank {
get {
return _canRank;
}
set {
if (_canRank != value)
{
NotifyPropertyValueChanged("CanRank", oldValue:_canRank, newValue: value);
_canRank = value;
}
}
}
public bool Clean {
get {
return _clean;
}
set {
if (_clean != value)
{
NotifyPropertyValueChanged("Clean", oldValue:_clean, newValue: value);
_clean = value;
}
}
}
public bool Comments {
get {
return _comments;
}
set {
if (_comments != value)
{
NotifyPropertyValueChanged("Comments", oldValue:_comments, newValue: value);
_comments = value;
}
}
}
public string CommunityUri {
get {
return _communityUri;
}
set {
if (_communityUri != value)
{
NotifyPropertyValueChanged("CommunityUri", oldValue:_communityUri, newValue: value);
_communityUri = value;
}
}
}
public bool EXIF {
get {
return _eXIF;
}
set {
if (_eXIF != value)
{
NotifyPropertyValueChanged("EXIF", oldValue:_eXIF, newValue: value);
_eXIF = value;
}
}
}
public bool External {
get {
return _external;
}
set {
if (_external != value)
{
NotifyPropertyValueChanged("External", oldValue:_external, newValue: value);
_external = value;
}
}
}
public bool FamilyEdit {
get {
return _familyEdit;
}
set {
if (_familyEdit != value)
{
NotifyPropertyValueChanged("FamilyEdit", oldValue:_familyEdit, newValue: value);
_familyEdit = value;
}
}
}
public bool Filenames {
get {
return _filenames;
}
set {
if (_filenames != value)
{
NotifyPropertyValueChanged("Filenames", oldValue:_filenames, newValue: value);
_filenames = value;
}
}
}
public bool FriendEdit {
get {
return _friendEdit;
}
set {
if (_friendEdit != value)
{
NotifyPropertyValueChanged("FriendEdit", oldValue:_friendEdit, newValue: value);
_friendEdit = value;
}
}
}
public bool Geography {
get {
return _geography;
}
set {
if (_geography != value)
{
NotifyPropertyValueChanged("Geography", oldValue:_geography, newValue: value);
_geography = value;
}
}
}
public HeaderEnum Header {
get {
return _header;
}
set {
if (_header != value)
{
NotifyPropertyValueChanged("Header", oldValue:_header, newValue: value);
_header = value;
}
}
}
public bool HideOwner {
get {
return _hideOwner;
}
set {
if (_hideOwner != value)
{
NotifyPropertyValueChanged("HideOwner", oldValue:_hideOwner, newValue: value);
_hideOwner = value;
}
}
}
public InterceptShippingEnum InterceptShipping {
get {
return _interceptShipping;
}
set {
if (_interceptShipping != value)
{
NotifyPropertyValueChanged("InterceptShipping", oldValue:_interceptShipping, newValue: value);
_interceptShipping = value;
}
}
}
public LargestSizeEnum LargestSize {
get {
return _largestSize;
}
set {
if (_largestSize != value)
{
NotifyPropertyValueChanged("LargestSize", oldValue:_largestSize, newValue: value);
_largestSize = value;
}
}
}
public string Name {
get {
return _name;
}
set {
if (_name != value)
{
NotifyPropertyValueChanged("Name", oldValue:_name, newValue: value);
_name = value;
}
}
}
public bool PackagingBranding {
get {
return _packagingBranding;
}
set {
if (_packagingBranding != value)
{
NotifyPropertyValueChanged("PackagingBranding", oldValue:_packagingBranding, newValue: value);
_packagingBranding = value;
}
}
}
public string Password {
get {
return _password;
}
set {
if (_password != value)
{
NotifyPropertyValueChanged("Password", oldValue:_password, newValue: value);
_password = value;
}
}
}
public string PasswordHint {
get {
return _passwordHint;
}
set {
if (_passwordHint != value)
{
NotifyPropertyValueChanged("PasswordHint", oldValue:_passwordHint, newValue: value);
_passwordHint = value;
}
}
}
public bool Printable {
get {
return _printable;
}
set {
if (_printable != value)
{
NotifyPropertyValueChanged("Printable", oldValue:_printable, newValue: value);
_printable = value;
}
}
}
public string PrintmarkUri {
get {
return _printmarkUri;
}
set {
if (_printmarkUri != value)
{
NotifyPropertyValueChanged("PrintmarkUri", oldValue:_printmarkUri, newValue: value);
_printmarkUri = value;
}
}
}
public long ProofDays {
get {
return _proofDays;
}
set {
if (_proofDays != value)
{
NotifyPropertyValueChanged("ProofDays", oldValue:_proofDays, newValue: value);
_proofDays = value;
}
}
}
public bool Protected {
get {
return _protected;
}
set {
if (_protected != value)
{
NotifyPropertyValueChanged("Protected", oldValue:_protected, newValue: value);
_protected = value;
}
}
}
public bool Public {
get {
return _public;
}
set {
if (_public != value)
{
NotifyPropertyValueChanged("Public", oldValue:_public, newValue: value);
_public = value;
}
}
}
public bool Share {
get {
return _share;
}
set {
if (_share != value)
{
NotifyPropertyValueChanged("Share", oldValue:_share, newValue: value);
_share = value;
}
}
}
public SmugSearchableEnum SmugSearchable {
get {
return _smugSearchable;
}
set {
if (_smugSearchable != value)
{
NotifyPropertyValueChanged("SmugSearchable", oldValue:_smugSearchable, newValue: value);
_smugSearchable = value;
}
}
}
public SortDirectionEnum SortDirection {
get {
return _sortDirection;
}
set {
if (_sortDirection != value)
{
NotifyPropertyValueChanged("SortDirection", oldValue:_sortDirection, newValue: value);
_sortDirection = value;
}
}
}
public SortMethodEnum SortMethod {
get {
return _sortMethod;
}
set {
if (_sortMethod != value)
{
NotifyPropertyValueChanged("SortMethod", oldValue:_sortMethod, newValue: value);
_sortMethod = value;
}
}
}
public bool SquareThumbs {
get {
return _squareThumbs;
}
set {
if (_squareThumbs != value)
{
NotifyPropertyValueChanged("SquareThumbs", oldValue:_squareThumbs, newValue: value);
_squareThumbs = value;
}
}
}
public string TemplateUri {
get {
return _templateUri;
}
set {
if (_templateUri != value)
{
NotifyPropertyValueChanged("TemplateUri", oldValue:_templateUri, newValue: value);
_templateUri = value;
}
}
}
public bool Watermark {
get {
return _watermark;
}
set {
if (_watermark != value)
{
NotifyPropertyValueChanged("Watermark", oldValue:_watermark, newValue: value);
_watermark = value;
}
}
}
public string WatermarkUri {
get {
return _watermarkUri;
}
set {
if (_watermarkUri != value)
{
NotifyPropertyValueChanged("WatermarkUri", oldValue:_watermarkUri, newValue: value);
_watermarkUri = value;
}
}
}
public bool WorldSearchable {
get {
return _worldSearchable;
}
set {
if (_worldSearchable != value)
{
NotifyPropertyValueChanged("WorldSearchable", oldValue:_worldSearchable, newValue: value);
_worldSearchable = value;
}
}
}
}
}
| |
//
// Copyright (c) 2007 Microsoft Corporation. All rights reserved.
//
using System;
using System.Management.Automation;
using System.Globalization;
using System.Reflection;
using System.Diagnostics.Eventing;
using System.Diagnostics.Eventing.Reader;
using System.Resources;
using System.Diagnostics.CodeAnalysis;
using System.Collections.Generic;
using System.Xml;
using System.IO;
namespace Microsoft.PowerShell.Commands
{
///
/// Class that implements the New-WinEvent cmdlet.
/// This cmdlet writes a new Etw event using the provider specified in parameter.
///
[Cmdlet(VerbsCommon.New, "WinEvent", HelpUri = "http://go.microsoft.com/fwlink/?LinkID=217469")]
public sealed class NewWinEventCommand : PSCmdlet
{
private ProviderMetadata _providerMetadata;
private EventDescriptor? _eventDescriptor;
private const string TemplateTag = "template";
private const string DataTag = "data";
private ResourceManager _resourceMgr = Microsoft.PowerShell.Commands.Diagnostics.Common.CommonUtilities.GetResourceManager();
/// <summary>
/// ProviderName
/// </summary>
[Parameter(
Position = 0,
Mandatory = true,
ParameterSetName = ParameterAttribute.AllParameterSets)]
public string ProviderName
{
get
{
return _providerName;
}
set
{
_providerName = value;
}
}
private string _providerName;
/// <summary>
/// Id (EventId defined in manifest file)
/// </summary>
[Parameter(
Position = 1,
Mandatory = true,
ParameterSetName = ParameterAttribute.AllParameterSets)]
public int Id
{
get
{
return _id;
}
set
{
_id = value;
_idSpecified = true;
}
}
private int _id;
private bool _idSpecified = false;
/// <summary>
/// Version (event version)
/// </summary>
[Parameter(
Mandatory = false,
ParameterSetName = ParameterAttribute.AllParameterSets)]
public byte Version
{
get
{
return _version;
}
set
{
_version = value;
_versionSpecified = true;
}
}
private byte _version;
private bool _versionSpecified = false;
/// <summary>
/// Event Payload
/// </summary>
[Parameter(
Position = 2,
Mandatory = false,
ParameterSetName = ParameterAttribute.AllParameterSets),
AllowEmptyCollection,
SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays",
Target = "Microsoft.PowerShell.Commands",
Justification = "A string[] is required here because that is the type Powershell supports")]
public object[] Payload
{
get
{
return _payload;
}
set
{
_payload = value;
}
}
private object[] _payload;
/// <summary>
/// BeginProcessing
/// </summary>
protected override void BeginProcessing()
{
LoadProvider();
LoadEventDescriptor();
base.BeginProcessing();
}
private void LoadProvider()
{
if (string.IsNullOrEmpty(_providerName))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderNotSpecified")), "ProviderName");
}
using (EventLogSession session = new EventLogSession())
{
foreach (string providerName in session.GetProviderNames())
{
if (string.Equals(providerName, _providerName, StringComparison.OrdinalIgnoreCase))
{
try
{
_providerMetadata = new ProviderMetadata(providerName);
}
catch (EventLogException exc)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("ProviderMetadataUnavailable"), providerName, exc.Message);
throw new Exception(msg, exc);
}
break;
}
}
}
if (_providerMetadata == null)
{
string msg = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("NoProviderFound"), _providerName);
throw new ArgumentException(msg);
}
}
private void LoadEventDescriptor()
{
if (_idSpecified)
{
List<EventMetadata> matchedEvents = new List<EventMetadata>();
foreach (EventMetadata emd in _providerMetadata.Events)
{
if (emd.Id == _id)
{
matchedEvents.Add(emd);
}
}
if (matchedEvents.Count == 0)
{
string msg = string.Format(CultureInfo.InvariantCulture,
_resourceMgr.GetString("IncorrectEventId"),
_id,
_providerName);
throw new EventWriteException(msg);
}
EventMetadata matchedEvent = null;
if (!_versionSpecified && matchedEvents.Count == 1)
{
matchedEvent = matchedEvents[0];
}
else
{
if (_versionSpecified)
{
foreach (EventMetadata emd in matchedEvents)
{
if (emd.Version == _version)
{
matchedEvent = emd;
break;
}
}
if (matchedEvent == null)
{
string msg = string.Format(CultureInfo.InvariantCulture,
_resourceMgr.GetString("IncorrectEventVersion"),
_version,
_id,
_providerName);
throw new EventWriteException(msg);
}
}
else
{
string msg = string.Format(CultureInfo.InvariantCulture,
_resourceMgr.GetString("VersionNotSpecified"),
_id,
_providerName);
throw new EventWriteException(msg);
}
}
VerifyTemplate(matchedEvent);
_eventDescriptor = CreateEventDescriptor(_providerMetadata, matchedEvent);
}
else
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("EventIdNotSpecified")), "Id");
}
}
private bool VerifyTemplate(EventMetadata emd)
{
if (emd.Template != null)
{
XmlReaderSettings readerSettings = new XmlReaderSettings
{
CheckCharacters = false,
IgnoreComments = true,
IgnoreProcessingInstructions = true,
MaxCharactersInDocument = 0, // no limit
ConformanceLevel = ConformanceLevel.Fragment,
#if !CORECLR
XmlResolver = null,
#endif
};
int definedParameterCount = 0;
using (XmlReader reader = XmlReader.Create(new StringReader(emd.Template), readerSettings))
{
if (reader.ReadToFollowing(TemplateTag))
{
bool found = reader.ReadToDescendant(DataTag);
while (found)
{
definedParameterCount++;
found = reader.ReadToFollowing(DataTag);
}
}
}
if ((_payload == null && definedParameterCount != 0)
|| ((_payload != null) && _payload.Length != definedParameterCount))
{
string warning = string.Format(CultureInfo.InvariantCulture, _resourceMgr.GetString("PayloadMismatch"), _id, emd.Template);
WriteWarning(warning);
return false;
}
}
return true;
}
private static EventDescriptor CreateEventDescriptor(ProviderMetadata providerMetaData, EventMetadata emd)
{
long keywords = 0;
foreach (EventKeyword keyword in emd.Keywords)
{
keywords |= keyword.Value;
}
byte channel = 0;
foreach (EventLogLink logLink in providerMetaData.LogLinks)
{
if (string.Equals(logLink.LogName, emd.LogLink.LogName, StringComparison.OrdinalIgnoreCase))
break;
channel++;
}
return new EventDescriptor(
(int)emd.Id,
emd.Version,
channel,
(byte)emd.Level.Value,
(byte)emd.Opcode.Value,
emd.Task.Value,
keywords);
}
/// <summary>
/// ProcessRecord
/// </summary>
protected override void ProcessRecord()
{
using (EventProvider provider = new EventProvider(_providerMetadata.Id))
{
EventDescriptor ed = _eventDescriptor.Value;
if (_payload != null && _payload.Length > 0)
{
for (int i = 0; i < _payload.Length; i++)
{
if (_payload[i] == null)
{
_payload[i] = string.Empty;
}
}
provider.WriteEvent(ref ed, _payload);
}
else
{
provider.WriteEvent(ref ed);
}
}
base.ProcessRecord();
}
/// <summary>
/// EndProcessing
/// </summary>
protected override void EndProcessing()
{
if (_providerMetadata != null)
_providerMetadata.Dispose();
base.EndProcessing();
}
}
internal class EventWriteException : Exception
{
internal EventWriteException(string msg, Exception innerException)
: base(msg, innerException)
{ }
internal EventWriteException(string msg)
: base(msg)
{ }
}
}
| |
/* Copyright 2019 Sannel Software, L.L.C.
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 Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Sannel.House.Client
{
public abstract class ClientBase
{
protected readonly IHttpClientFactory factory=null;
protected readonly ILogger logger;
protected readonly HttpClient client = null;
protected readonly string baseUri = "/";
/// <summary>
/// Initializes a new instance of the <see cref="DevicesClient" /> class.
/// </summary>
/// <param name="factory">The HttpClientFactory.</param>
/// <param name="baseUri">The base path i.e. http://host/v1/ or http://host/</param>
/// <param name="logger">The logger.</param>
/// <exception cref="ArgumentNullException">factory
/// or
/// logger</exception>
protected ClientBase(IHttpClientFactory factory, string baseUri, ILogger logger)
{
if(!Uri.IsWellFormedUriString(baseUri ?? throw new ArgumentNullException(nameof(baseUri))
, UriKind.Absolute))
{
throw new ArgumentException("Invalid Uri format", nameof(baseUri));
}
this.baseUri = baseUri;
this.factory = factory ?? throw new ArgumentNullException(nameof(factory));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
/// <summary>
/// Initializes a new instance of the <see cref="ClientBase" /> class.
/// </summary>
/// <param name="client">The client.</param>
/// <param name="baseUri">The base path i.e. http://host/v1/ or http://host/</param>
/// <param name="logger">The logger.</param>
/// <exception cref="ArgumentNullException">client
/// or
/// logger</exception>
protected ClientBase(HttpClient client, string baseUri, ILogger logger)
{
if(!Uri.IsWellFormedUriString(baseUri ?? throw new ArgumentNullException(nameof(baseUri))
, UriKind.Absolute))
{
throw new ArgumentException("Invalid Uri format", nameof(baseUri));
}
this.baseUri = baseUri;
this.client = client ?? throw new ArgumentNullException(nameof(client));
this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
}
/// <summary>
/// Gets or sets the bearer authentication token.
/// </summary>
/// <value>
/// The authentication token.
/// </value>
public virtual string AuthToken
{
get;
set;
}
/// <summary>
/// Deserializes if supported code asynchronous.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="message">The message.</param>
/// <returns></returns>
protected virtual async Task<T> DeserializeIfSupportedCodeAsync<T>(HttpResponseMessage message)
where T : IResults, new()
{
switch (message.StatusCode)
{
case System.Net.HttpStatusCode.OK:
case System.Net.HttpStatusCode.NotFound:
case System.Net.HttpStatusCode.BadRequest:
var data = await message.Content.ReadAsStringAsync();
var obj = await Task.Run(() => JsonConvert.DeserializeObject<T>(data));
obj.Success = message.StatusCode == System.Net.HttpStatusCode.OK;
return obj;
default:
var err = new T
{
Success = false,
Status = (int)message.StatusCode,
};
if (message.Content != null && message.Content.Headers.ContentLength > 0)
{
err.Title = await message.Content.ReadAsStringAsync();
}
return err;
};
}
/// <summary>
/// Adds the authorization header.
/// </summary>
/// <param name="message">The message.</param>
protected virtual void AddAuthorizationHeader(HttpRequestMessage message)
=> message.Headers.Authorization
= new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", AuthToken);
/// <summary>
/// Gets the HttpClient from the factory.
/// </summary>
/// <returns></returns>
protected abstract HttpClient GetClient();
/// <summary>
/// Prepares the path.
/// </summary>
/// <param name="path">The path.</param>
/// <returns></returns>
/// <exception cref="ArgumentNullException">path</exception>
protected virtual Uri PreparePath(string path)
{
if(path == null)
{
throw new ArgumentNullException(nameof(path));
}
var builder = new UriBuilder(baseUri);
if(path.StartsWith("/"))
{
builder.Path = path;
}
else
{
builder.Path += path;
}
return builder.Uri;
}
/// <summary>
/// Does a get call to the provided url
/// </summary>
/// <param name="url">The URL.</param>
/// <returns></returns>
protected virtual async Task<T> GetAsync<T>(string url)
where T : IResults, new()
{
var client = GetClient();
try
{
using (var message = new HttpRequestMessage(HttpMethod.Get, PreparePath(url)))
{
AddAuthorizationHeader(message);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("RequestUri: {0}", message.RequestUri);
logger.LogDebug("AuthHeader: {0}", message.Headers.Authorization);
}
var response = await client.SendAsync(message);
return await DeserializeIfSupportedCodeAsync<T>(response);
}
}
catch (Exception ex) when (ex is HttpRequestException || ex is JsonException)
{
return new T()
{
Status = 444,
Title = "Exception",
Success = false,
Exception = ex
};
}
}
/// <summary>
/// Posts the object asynchronous.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url">The URL.</param>
/// <param name="obj">The object.</param>
/// <returns></returns>
protected virtual async Task<T> PostAsync<T>(string url, object obj)
where T : IResults, new()
{
var client = GetClient();
try
{
using (var message = new HttpRequestMessage(HttpMethod.Post, PreparePath(url)))
{
AddAuthorizationHeader(message);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("RequestUri: {0}", message.RequestUri);
logger.LogDebug("AuthHeader: {0}", message.Headers.Authorization);
}
message.Content = new StringContent(
await Task.Run(() => JsonConvert.SerializeObject(obj)),
System.Text.Encoding.UTF8,
"application/json");
var response = await client.SendAsync(message);
return await DeserializeIfSupportedCodeAsync<T>(response);
}
}
catch (Exception ex) when (ex is HttpRequestException || ex is JsonException)
{
return new T()
{
Status = 444,
Title = "Exception",
Success = false,
Exception = ex
};
}
}
/// <summary>
/// Puts the object asynchronous.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url">The URL.</param>
/// <param name="obj">The object.</param>
/// <returns></returns>
protected virtual async Task<T> PutAsync<T>(string url, object obj)
where T : IResults, new()
{
var client = GetClient();
try
{
using (var message = new HttpRequestMessage(HttpMethod.Put, PreparePath(url)))
{
AddAuthorizationHeader(message);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("RequestUri: {0}", message.RequestUri);
logger.LogDebug("AuthHeader: {0}", message.Headers.Authorization);
}
message.Content = new StringContent(
await Task.Run(() => JsonConvert.SerializeObject(obj)),
System.Text.Encoding.UTF8,
"application/json");
var response = await client.SendAsync(message);
return await DeserializeIfSupportedCodeAsync<T>(response);
}
}
catch (Exception ex) when (ex is HttpRequestException || ex is JsonException)
{
return new T()
{
Status = 444,
Title = "Exception",
Success = false,
Exception = ex
};
}
}
/// <summary>
/// Deletes the asynchronous.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="url">The URL.</param>
/// <returns></returns>
protected virtual async Task<T> DeleteAsync<T>(string url)
where T : IResults, new()
{
var client = GetClient();
try
{
using (var message = new HttpRequestMessage(HttpMethod.Delete, PreparePath(url)))
{
AddAuthorizationHeader(message);
if (logger.IsEnabled(LogLevel.Debug))
{
logger.LogDebug("RequestUri: {0}", message.RequestUri);
logger.LogDebug("AuthHeader: {0}", message.Headers.Authorization);
}
var response = await client.SendAsync(message);
return await DeserializeIfSupportedCodeAsync<T>(response);
}
}
catch (Exception ex) when (ex is HttpRequestException || ex is JsonException)
{
return new T()
{
Status = 444,
Title = "Exception",
Success = false,
Exception = ex
};
}
}
}
}
| |
// *********************************
// Message from Original Author:
//
// 2008 Jose Menendez Poo
// Please give me credit if you use this code. It's all I ask.
// Contact me for more info: menendezpoo@gmail.com
// *********************************
//
// Original project from http://ribbon.codeplex.com/
// Continue to support and maintain by http://officeribbon.codeplex.com/
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.ComponentModel;
using System.Windows.Forms.VisualStyles;
using System.Diagnostics;
namespace System.Windows.Forms
{
public class RibbonCheckBox
: RibbonItem
{
public enum CheckBoxOrientationEnum
{
Left = 0,
Right = 1
}
public enum CheckBoxStyle
{
CheckBox,
RadioButton
}
#region Fields
private const int spacing = 3;
private bool _labelVisible = true;
private Rectangle _labelBounds;
private Rectangle _checkboxBounds;
private int _labelWidth;
private int _checkboxSize;
private CheckBoxOrientationEnum _CheckBoxOrientation;
private CheckBoxStyle _style;
#endregion
#region Events
/// <summary>
/// Raised when the <see cref="CheckBox Checked"/> property value has changed
/// </summary>
public event EventHandler CheckBoxCheckChanged;
/// <summary>
/// Raised when the <see cref="CheckBox Checked"/> property value is changing
/// </summary>
public event CancelEventHandler CheckBoxCheckChanging;
#endregion
#region Ctor
public RibbonCheckBox()
{
_checkboxSize = 16;
}
#endregion
#region Props
/// <summary>
/// Gets or sets the style of the checkbox item
/// </summary>
[DefaultValue(CheckBoxStyle.CheckBox)]
public CheckBoxStyle Style
{
get { return _style; }
set { _style = value; NotifyOwnerRegionsChanged(); }
}
/// <summary>
/// Gets or sets the width of the Label
/// </summary>
[DefaultValue(CheckBoxOrientationEnum.Left)]
public CheckBoxOrientationEnum CheckBoxOrientation
{
get { return _CheckBoxOrientation; }
set { _CheckBoxOrientation = value; NotifyOwnerRegionsChanged(); }
}
/// <summary>
/// Gets the bounds of the label that is shown next to the textbox
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual Rectangle LabelBounds
{
get { return _labelBounds; }
}
/// <summary>
/// Gets a value indicating if the label is currently visible
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool LabelVisible
{
get { return _labelVisible; }
}
/// <summary>
/// Gets the bounds of the text
/// </summary>
[Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public virtual Rectangle CheckBoxBounds
{
get
{
return _checkboxBounds;
}
}
/// <summary>
/// Gets or sets the width of the Label
/// </summary>
[DefaultValue(0)]
public int LabelWidth
{
get { return _labelWidth; }
set { _labelWidth = value; NotifyOwnerRegionsChanged(); }
}
#endregion
#region Methods
/// <summary>
/// Measures the suposed height of the boxbox
/// </summary>
/// <returns></returns>
protected virtual int MeasureHeight()
{
return _checkboxSize + Owner.ItemMargin.Vertical;
}
public override void OnPaint(object sender, RibbonElementPaintEventArgs e)
{
if (Owner != null)
{
Owner.Renderer.OnRenderRibbonItem(new RibbonItemRenderEventArgs(Owner, e.Graphics, Bounds, this));
if (Style == CheckBoxStyle.CheckBox)
{
CheckBoxState CheckState = Checked == true ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal;
if (Selected)
CheckState += 1;
if (this.CheckBoxOrientation == CheckBoxOrientationEnum.Left)
CheckBoxRenderer.DrawCheckBox(e.Graphics, new Point(_checkboxBounds.Left, _checkboxBounds.Top), CheckState);
else
CheckBoxRenderer.DrawCheckBox(e.Graphics, new Point(_checkboxBounds.Left + spacing, _checkboxBounds.Top), CheckState);
}
else
{
RadioButtonState RadioState = Checked == true ? RadioButtonState.CheckedNormal : RadioButtonState.UncheckedNormal;
if (Selected)
RadioState += 1;
if (this.CheckBoxOrientation == CheckBoxOrientationEnum.Left)
RadioButtonRenderer.DrawRadioButton(e.Graphics, new Point(_checkboxBounds.Left, _checkboxBounds.Top), RadioState);
else
RadioButtonRenderer.DrawRadioButton(e.Graphics, new Point(_checkboxBounds.Left + spacing, _checkboxBounds.Top), RadioState);
}
if (LabelVisible)
{
StringFormat f = new StringFormat();
if (_CheckBoxOrientation == CheckBoxOrientationEnum.Left)
f.Alignment = StringAlignment.Near;
else
f.Alignment = StringAlignment.Far;
f.LineAlignment = StringAlignment.Far; //Top
f.Trimming = StringTrimming.None;
f.FormatFlags |= StringFormatFlags.NoWrap;
Owner.Renderer.OnRenderRibbonItemText(new RibbonTextEventArgs(Owner, e.Graphics, _labelBounds, this, LabelBounds, Text, f));
}
}
}
public override void SetBounds(System.Drawing.Rectangle bounds)
{
base.SetBounds(bounds);
if (CheckBoxOrientation == CheckBoxOrientationEnum.Left)
{
_checkboxBounds = new Rectangle(
bounds.Left + Owner.ItemMargin.Left,
bounds.Top + Owner.ItemMargin.Top + ((bounds.Height - _checkboxSize) / 2),
_checkboxSize,
_checkboxSize);
_labelBounds = Rectangle.FromLTRB(
_checkboxBounds.Right,
bounds.Top + Owner.ItemMargin.Top,
bounds.Right - Owner.ItemMargin.Right,
bounds.Bottom - Owner.ItemMargin.Bottom);
}
else
{
_checkboxBounds = new Rectangle(
bounds.Right - Owner.ItemMargin.Right - _checkboxSize,
bounds.Top + Owner.ItemMargin.Top + ((bounds.Height - _checkboxSize) / 2),
_checkboxSize,
_checkboxSize);
_labelBounds = Rectangle.FromLTRB(
bounds.Left + Owner.ItemMargin.Left,
bounds.Top + Owner.ItemMargin.Top,
_checkboxBounds.Left,
bounds.Bottom - Owner.ItemMargin.Bottom);
}
if (SizeMode == RibbonElementSizeMode.Large)
{
_labelVisible = true;
}
else if (SizeMode == RibbonElementSizeMode.Medium)
{
_labelVisible = true;
_labelBounds = Rectangle.Empty;
}
else if (SizeMode == RibbonElementSizeMode.Compact)
{
_labelBounds = Rectangle.Empty;
_labelVisible = false;
}
}
private bool checkedGlyphSize = false;
public override Size MeasureSize(object sender, RibbonElementMeasureSizeEventArgs e)
{
if (!checkedGlyphSize)
{
try
{
if (Style == CheckBoxStyle.CheckBox)
_checkboxSize = CheckBoxRenderer.GetGlyphSize(e.Graphics, Checked == true ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal).Height + spacing;
else
_checkboxSize = CheckBoxRenderer.GetGlyphSize(e.Graphics, Checked == true ? CheckBoxState.CheckedNormal : CheckBoxState.UncheckedNormal).Height + spacing;
}
catch { /* I don't mind at all */ }
checkedGlyphSize = true;
}
if (!Visible && !Owner.IsDesignMode())
{
SetLastMeasuredSize(new Size(0, 0));
return LastMeasuredSize;
}
Size size = Size.Empty;
int w = Owner.ItemMargin.Horizontal;
int iwidth = Image != null ? Image.Width + spacing : 0;
int lwidth = string.IsNullOrEmpty(Text) ? 0 : _labelWidth > 0 ? _labelWidth : e.Graphics.MeasureString(Text, Owner.Font).ToSize().Width;
w += _checkboxSize;
switch (e.SizeMode)
{
case RibbonElementSizeMode.Large:
w += iwidth + lwidth;
break;
case RibbonElementSizeMode.Medium:
w += iwidth;
break;
}
SetLastMeasuredSize(new Size(w, MeasureHeight()));
return LastMeasuredSize;
}
public override void OnMouseEnter(MouseEventArgs e)
{
if (!Enabled) return;
base.OnMouseEnter(e);
//Canvas.Cursor = Cursors.Default;
//SetSelected(true);
}
public override void OnMouseLeave(MouseEventArgs e)
{
if (!Enabled) return;
base.OnMouseLeave(e);
//Canvas.Cursor = Cursors.Default;
//SetSelected(false);
}
public override void OnMouseDown(MouseEventArgs e)
{
if (!Enabled) return;
base.OnMouseDown(e);
if (CheckBoxBounds.Contains(e.X, e.Y))
{
CancelEventArgs cev = new CancelEventArgs();
OnCheckChanging(cev);
if (!cev.Cancel)
{
Checked = !Checked;
OnCheckChanged(e);
}
}
}
public override void OnMouseMove(MouseEventArgs e)
{
if (!Enabled) return;
base.OnMouseMove(e);
if (CheckBoxBounds.Contains(e.X, e.Y))
{
Debug.WriteLine("Owner.Cursor = Cursors.Hand e.X=" +e.X + " e.Y=" + e.Y + " CheckBoxBounds (" + CheckBoxBounds.ToString() + ")");
Owner.Cursor = Cursors.Hand;
if (!Selected)
SetSelected(true);
}
else
{
Debug.WriteLine("Owner.Cursor = Cursors.Default e.X=" + e.X + " e.Y=" + e.Y + " CheckBoxBounds (" + CheckBoxBounds.ToString() + ")");
Owner.Cursor = Cursors.Default;
if (Selected)
SetSelected(false);
}
}
/// <summary>
/// Raises the <see cref="CheckBox Check Changed"/> event
/// </summary>
/// <param name="e"></param>
public void OnCheckChanged(EventArgs e)
{
if (!Enabled) return;
NotifyOwnerRegionsChanged();
if (CheckBoxCheckChanged != null)
{
CheckBoxCheckChanged(this, e);
}
}
/// <summary>
/// Raises the <see cref="CheckBox Check Changing"/> event
/// </summary>
/// <param name="e"></param>
public void OnCheckChanging(CancelEventArgs e)
{
if (!Enabled) return;
if (CheckBoxCheckChanging != null)
{
CheckBoxCheckChanging(this, e);
}
}
#endregion
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
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
*/
#endregion
using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using Axiom.Collections;
using Axiom.Core;
using Axiom.Graphics;
using Axiom.Media;
using Tao.OpenGl;
namespace Axiom.RenderSystems.OpenGL {
/// <summary>
/// OpenGL specialization of texture handling.
/// </summary>
public class GLTexture : Texture {
#region Member variable
/// <summary>
/// OpenGL texture ID.
/// </summary>
private int glTextureID;
#endregion
#region Constructors
/// <summary>
/// Constructor, called from GLTextureManager.
/// </summary>
/// <param name="name"></param>
public GLTexture(string name, TextureType type) {
this.name = name;
this.textureType = type;
Enable32Bit(false);
}
/// <summary>
/// Constructor used when creating a manual texture.
/// </summary>
/// <param name="name"></param>
/// <param name="type"></param>
/// <param name="width"></param>
/// <param name="height"></param>
/// <param name="numMipMaps"></param>
/// <param name="format"></param>
/// <param name="usage"></param>
public GLTexture(string name, TextureType type, int width, int height, int numMipMaps, PixelFormat format, TextureUsage usage) {
this.name = name;
this.textureType = type;
this.srcWidth = width;
this.srcHeight = height;
this.width = srcWidth;
this.height = srcHeight;
this.depth = 1;
this.numMipMaps = numMipMaps;
this.usage = usage;
this.format = format;
this.srcBpp = Image.GetNumElemBits(format);
Enable32Bit(false);
}
#endregion
#region Properties
/// <summary>
/// OpenGL texture ID.
/// </summary>
public int TextureID {
get {
return glTextureID;
}
}
/// <summary>
/// OpenGL texture format enum value.
/// </summary>
public int GLFormat {
get {
switch(format) {
case PixelFormat.L8:
return Gl.GL_LUMINANCE;
case PixelFormat.R8G8B8:
return Gl.GL_RGB;
case PixelFormat.B8G8R8:
return Gl.GL_BGR;
case PixelFormat.B8G8R8A8:
return Gl.GL_BGRA;
case PixelFormat.A8R8G8B8:
return Gl.GL_RGBA;
case PixelFormat.DXT1:
return Gl.GL_COMPRESSED_RGBA_S3TC_DXT1_EXT;
case PixelFormat.DXT3:
return Gl.GL_COMPRESSED_RGBA_S3TC_DXT3_EXT;
case PixelFormat.DXT5:
return Gl.GL_COMPRESSED_RGBA_S3TC_DXT5_EXT;
}
// make the compiler happy
return 0;
}
}
/// <summary>
/// Type of texture this represents, i.e. 2d, cube, etc.
/// </summary>
public int GLTextureType {
get {
switch(textureType) {
case TextureType.OneD:
return Gl.GL_TEXTURE_1D;
case TextureType.TwoD:
return Gl.GL_TEXTURE_2D;
case TextureType.ThreeD:
return Gl.GL_TEXTURE_3D;
case TextureType.CubeMap:
return Gl.GL_TEXTURE_CUBE_MAP;
}
return 0;
}
}
#endregion
#region Methods
/// <summary>
///
/// </summary>
/// <param name="image"></param>
public override void LoadImage(Image image) {
// create a list with one texture to pass it in to the common loading method
ImageList images = new ImageList();
images.Add(image);
// load this image
LoadImages(images);
// clear the temp list of images
images.Clear();
}
/// <summary>
///
/// </summary>
/// <param name="images"></param>
public void LoadImages(ImageList images) {
bool useSoftwareMipMaps = true;
if(isLoaded) {
LogManager.Instance.Write("Unloading image '{0}'...", name);
Unload();
}
// generate the texture
Gl.glGenTextures(1, out glTextureID);
// bind the texture
Gl.glBindTexture(this.GLTextureType, glTextureID);
// log a quick message
LogManager.Instance.Write("GLTexture: Loading {0} with {1} mipmaps from an Image.", name, numMipMaps);
if(numMipMaps > 0 && Root.Instance.RenderSystem.Caps.CheckCap(Capabilities.HardwareMipMaps)) {
Gl.glTexParameteri(this.GLTextureType, Gl.GL_GENERATE_MIPMAP, Gl.GL_TRUE);
useSoftwareMipMaps = false;
}
for(int i = 0; i < images.Count; i++) {
Image image = (Image)images[i];
// get the images pixel format
format = image.Format;
srcBpp = Image.GetNumElemBits(format);
hasAlpha = image.HasAlpha;
// get dimensions
srcWidth = image.Width;
srcHeight = image.Height;
// same destination dimensions for GL
width = srcWidth;
height = srcHeight;
depth = image.Depth;
// only oiverride global mipmap setting if the image itself has at least 1 already
if(image.NumMipMaps > 0) {
numMipMaps = image.NumMipMaps;
}
// set the max number of mipmap levels
Gl.glTexParameteri(this.GLTextureType, Gl.GL_TEXTURE_MAX_LEVEL, numMipMaps);
// Rescale to Power of 2 (also applies gamma correction)
byte[] data = RescaleNPower2(image);
GenerateMipMaps(data, useSoftwareMipMaps, image.HasFlag(ImageFlags.Compressed), i);
}
// update the size
int bytesPerPixel = finalBpp >> 3;
if(!hasAlpha && finalBpp == 32)
bytesPerPixel--;
size = (long)(width * height * bytesPerPixel);
isLoaded = true;
}
public override void Preload() {
throw new Exception("The method or operation is not implemented.");
}
public override void Load() {
if(isLoaded)
return;
if(usage == TextureUsage.RenderTarget) {
CreateRenderTexture();
isLoaded = true;
}
else {
if(textureType == TextureType.TwoD
|| textureType == TextureType.OneD
|| textureType == TextureType.ThreeD) {
Image image = Image.FromFile(name);
if(name.EndsWith(".dds") && image.HasFlag(ImageFlags.CubeMap)) {
ImageList images = new ImageList();
// all 6 images are in a single data buffer, so we will pull out all 6 pieces
int imageSize = image.Size / 6;
textureType = TextureType.CubeMap;
for(int i = 0, offset = 0; i < 6; i++, offset += imageSize) {
byte[] tempBuffer = new byte[imageSize];
Array.Copy(image.Data, offset, tempBuffer, 0, imageSize);
// load the raw data for this portion of the image data
Image cubeImage = Image.FromRawStream(
new MemoryStream(tempBuffer),
image.Width,
image.Height,
image.Format);
// add to the list of images to load
images.Add(cubeImage);
} // for
LoadImages(images);
}
else {
// if this is a dds volumetric texture, set the flag accordingly
if(name.EndsWith(".dds") && image.Depth > 1) {
textureType = TextureType.ThreeD;
}
// just load the 1 texture
LoadImage(image);
}
}
else if(textureType == TextureType.CubeMap) {
string baseName, ext;
ImageList images = new ImageList();
string[] postfixes = {"_rt", "_lf", "_up", "_dn", "_fr", "_bk"};
int pos = name.LastIndexOf(".");
baseName = name.Substring(0, pos);
ext = name.Substring(pos);
for(int i = 0; i < 6; i++) {
string fullName = baseName + postfixes[i] + ext;
// load the image
Image image = Image.FromFile(fullName);
images.Add(image);
} // for
// load all 6 images
LoadImages(images);
} // else
else {
throw new NotImplementedException("Unknown texture type.");
}
} // if
}
/// <summary>
/// Deletes the texture memory.
/// </summary>
public override void Unload() {
if(isLoaded) {
Gl.glDeleteTextures(1, ref glTextureID);
isLoaded = false;
}
}
protected void GenerateMipMaps(byte[] data, bool useSoftware, bool isCompressed, int faceNum) {
// use regular type, unless cubemap, then specify which face of the cubemap we
// are dealing with here
int type = (textureType == TextureType.CubeMap) ? Gl.GL_TEXTURE_CUBE_MAP_POSITIVE_X + faceNum : this.GLTextureType;
if(useSoftware && numMipMaps > 0) {
if(textureType == TextureType.OneD) {
Glu.gluBuild1DMipmaps(
type,
hasAlpha ? Gl.GL_RGBA8 : Gl.GL_RGB8,
width,
this.GLFormat,
Gl.GL_UNSIGNED_BYTE,
data);
}
else if(textureType == TextureType.ThreeD) {
// TODO: Tao needs glTexImage3D
Gl.glTexImage3DEXT(
type,
0,
hasAlpha ? Gl.GL_RGBA8 : Gl.GL_RGB8,
srcWidth, srcHeight, depth, 0, this.GLFormat,
Gl.GL_UNSIGNED_BYTE,
data);
}
else {
// build the mipmaps
Glu.gluBuild2DMipmaps(
type,
hasAlpha ? Gl.GL_RGBA8 : Gl.GL_RGB8,
width, height,
this.GLFormat,
Gl.GL_UNSIGNED_BYTE,
data);
}
}
else {
if(textureType == TextureType.OneD) {
Gl.glTexImage1D(
type,
0,
hasAlpha ? Gl.GL_RGBA8 : Gl.GL_RGB8,
width,
0,
this.GLFormat,
Gl.GL_UNSIGNED_BYTE,
data);
}
else if(textureType == TextureType.ThreeD) {
// TODO: Tao needs glTexImage3D
Gl.glTexImage3DEXT(
type,
0,
hasAlpha ? Gl.GL_RGBA8 : Gl.GL_RGB8,
srcWidth, srcHeight, depth, 0, this.GLFormat,
Gl.GL_UNSIGNED_BYTE,
data);
}
else {
if(isCompressed && Root.Instance.RenderSystem.Caps.CheckCap(Capabilities.TextureCompressionDXT)) {
int blockSize = (format == PixelFormat.DXT1) ? 8 : 16;
int size = ((width + 3) / 4)*((height + 3) / 4) * blockSize;
// load compressed image data
Gl.glCompressedTexImage2DARB(
type,
0,
this.GLFormat,
srcWidth,
srcHeight,
0,
size,
data);
}
else {
Gl.glTexImage2D(
type,
0,
hasAlpha ? Gl.GL_RGBA8 : Gl.GL_RGB8,
width, height, 0,
this.GLFormat, Gl.GL_UNSIGNED_BYTE,
data);
}
}
}
}
/// <summary>
/// Used to generate a texture capable of serving as a rendering target.
/// </summary>
private void CreateRenderTexture() {
if(this.TextureType != TextureType.TwoD) {
throw new NotImplementedException("Can only create render textures for 2D textures.");
}
// create and bind the texture
Gl.glGenTextures(1, out glTextureID);
Gl.glBindTexture(this.GLTextureType, glTextureID);
// generate an image without data by default to use for rendering to
// Note: null is casted to byte[] in order to remove compiler confusion over ambiguous overloads
Gl.glTexImage2D(
this.GLTextureType,
0,
this.GLFormat,
width,
height,
0,
this.GLFormat,
Gl.GL_UNSIGNED_BYTE,
(byte[])null);
// This needs to be set otherwise the texture doesn't get rendered
Gl.glTexParameteri(this.GLTextureType, Gl.GL_TEXTURE_MAX_LEVEL, numMipMaps);
}
private byte[] RescaleNPower2(Image src) {
// Scale image to n^2 dimensions
int newWidth = (1 << MostSignificantBitSet(srcWidth));
if (newWidth != srcWidth) {
newWidth <<= 1;
}
int newHeight = (1 << MostSignificantBitSet(srcHeight));
if (newHeight != srcHeight) {
newHeight <<= 1;
}
byte[] tempData;
if(newWidth != srcWidth || newHeight != srcHeight) {
int newImageSize = newWidth * newHeight * (hasAlpha ? 4 : 3);
tempData = new byte[newImageSize];
if(Glu.gluScaleImage(this.GLFormat, srcWidth, srcHeight,
Gl.GL_UNSIGNED_BYTE, src.Data, newWidth, newHeight,
Gl.GL_UNSIGNED_BYTE, tempData) != 0) {
throw new AxiomException("Error while rescaling image!");
}
Image.ApplyGamma(tempData, gamma, newImageSize, srcBpp);
srcWidth = width = newWidth;
srcHeight = height = newHeight;
}
else {
tempData = new byte[src.Size];
Array.Copy(src.Data, tempData, src.Size);
Image.ApplyGamma(tempData, gamma, src.Size, srcBpp);
}
return tempData;
}
/// <summary>
/// Helper method for getting the next highest power of 2 value from the specified value.
/// </summary>
/// <remarks>Example: Input: 3 Result: 4, Input: 96 Output: 128</remarks>
/// <param name="val">Integer value.</param>
/// <returns></returns>
private int MostSignificantBitSet(int val) {
int result = 0;
while(val != 0) {
result++;
val >>= 1;
}
return result - 1;
}
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Razor.Infrastructure;
using Microsoft.AspNetCore.Mvc.Razor.TagHelpers;
using Microsoft.AspNetCore.Mvc.Routing;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.AspNetCore.Mvc.TagHelpers
{
/// <summary>
/// <see cref="ITagHelper"/> implementation targeting <link> elements that supports fallback href paths.
/// </summary>
/// <remarks>
/// The tag helper won't process for cases with just the 'href' attribute.
/// </remarks>
[HtmlTargetElement("link", Attributes = HrefIncludeAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = HrefExcludeAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = FallbackHrefAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = FallbackHrefIncludeAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = FallbackHrefExcludeAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = FallbackTestClassAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = FallbackTestPropertyAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = FallbackTestValueAttributeName, TagStructure = TagStructure.WithoutEndTag)]
[HtmlTargetElement("link", Attributes = AppendVersionAttributeName, TagStructure = TagStructure.WithoutEndTag)]
public class LinkTagHelper : UrlResolutionTagHelper
{
private static readonly string FallbackJavaScriptResourceName =
typeof(LinkTagHelper).Namespace + ".compiler.resources.LinkTagHelper_FallbackJavaScript.js";
private const string HrefIncludeAttributeName = "asp-href-include";
private const string HrefExcludeAttributeName = "asp-href-exclude";
private const string FallbackHrefAttributeName = "asp-fallback-href";
private const string SuppressFallbackIntegrityAttributeName = "asp-suppress-fallback-integrity";
private const string FallbackHrefIncludeAttributeName = "asp-fallback-href-include";
private const string FallbackHrefExcludeAttributeName = "asp-fallback-href-exclude";
private const string FallbackTestClassAttributeName = "asp-fallback-test-class";
private const string FallbackTestPropertyAttributeName = "asp-fallback-test-property";
private const string FallbackTestValueAttributeName = "asp-fallback-test-value";
private const string AppendVersionAttributeName = "asp-append-version";
private const string HrefAttributeName = "href";
private const string RelAttributeName = "rel";
private const string IntegrityAttributeName = "integrity";
private static readonly Func<Mode, Mode, int> Compare = (a, b) => a - b;
private static readonly ModeAttributes<Mode>[] ModeDetails = new[] {
// Regular src with file version alone
new ModeAttributes<Mode>(Mode.AppendVersion, new[] { AppendVersionAttributeName }),
// Globbed Href (include only) no static href
new ModeAttributes<Mode>(Mode.GlobbedHref, new [] { HrefIncludeAttributeName }),
// Globbed Href (include & exclude), no static href
new ModeAttributes<Mode>(Mode.GlobbedHref, new [] { HrefIncludeAttributeName, HrefExcludeAttributeName }),
// Fallback with static href
new ModeAttributes<Mode>(
Mode.Fallback,
new[]
{
FallbackHrefAttributeName,
FallbackTestClassAttributeName,
FallbackTestPropertyAttributeName,
FallbackTestValueAttributeName
}),
// Fallback with globbed href (include only)
new ModeAttributes<Mode>(
Mode.Fallback,
new[]
{
FallbackHrefIncludeAttributeName,
FallbackTestClassAttributeName,
FallbackTestPropertyAttributeName,
FallbackTestValueAttributeName
}),
// Fallback with globbed href (include & exclude)
new ModeAttributes<Mode>(
Mode.Fallback,
new[]
{
FallbackHrefIncludeAttributeName,
FallbackHrefExcludeAttributeName,
FallbackTestClassAttributeName,
FallbackTestPropertyAttributeName,
FallbackTestValueAttributeName
}),
};
private StringWriter _stringWriter;
/// <summary>
/// Creates a new <see cref="LinkTagHelper"/>.
/// </summary>
/// <param name="hostingEnvironment">The <see cref="IHostingEnvironment"/>.</param>
/// <param name="cacheProvider"></param>
/// <param name="fileVersionProvider">The <see cref="IFileVersionProvider"/>.</param>
/// <param name="htmlEncoder">The <see cref="HtmlEncoder"/>.</param>
/// <param name="javaScriptEncoder">The <see cref="JavaScriptEncoder"/>.</param>
/// <param name="urlHelperFactory">The <see cref="IUrlHelperFactory"/>.</param>
// Decorated with ActivatorUtilitiesConstructor since we want to influence tag helper activation
// to use this constructor in the default case.
public LinkTagHelper(
IWebHostEnvironment hostingEnvironment,
TagHelperMemoryCacheProvider cacheProvider,
IFileVersionProvider fileVersionProvider,
HtmlEncoder htmlEncoder,
JavaScriptEncoder javaScriptEncoder,
IUrlHelperFactory urlHelperFactory)
: base(urlHelperFactory, htmlEncoder)
{
HostingEnvironment = hostingEnvironment;
JavaScriptEncoder = javaScriptEncoder;
Cache = cacheProvider.Cache;
FileVersionProvider = fileVersionProvider;
}
/// <inheritdoc />
public override int Order => -1000;
/// <summary>
/// Address of the linked resource.
/// </summary>
/// <remarks>
/// Passed through to the generated HTML in all cases.
/// </remarks>
[HtmlAttributeName(HrefAttributeName)]
public string Href { get; set; }
/// <summary>
/// A comma separated list of globbed file patterns of CSS stylesheets to load.
/// The glob patterns are assessed relative to the application's 'webroot' setting.
/// </summary>
[HtmlAttributeName(HrefIncludeAttributeName)]
public string HrefInclude { get; set; }
/// <summary>
/// A comma separated list of globbed file patterns of CSS stylesheets to exclude from loading.
/// The glob patterns are assessed relative to the application's 'webroot' setting.
/// Must be used in conjunction with <see cref="HrefInclude"/>.
/// </summary>
[HtmlAttributeName(HrefExcludeAttributeName)]
public string HrefExclude { get; set; }
/// <summary>
/// The URL of a CSS stylesheet to fallback to in the case the primary one fails.
/// </summary>
[HtmlAttributeName(FallbackHrefAttributeName)]
public string FallbackHref { get; set; }
/// <summary>
/// Boolean value that determines if an integrity hash will be compared with <see cref="FallbackHref"/> value.
/// </summary>
[HtmlAttributeName(SuppressFallbackIntegrityAttributeName)]
public bool SuppressFallbackIntegrity { get; set; }
/// <summary>
/// Value indicating if file version should be appended to the href urls.
/// </summary>
/// <remarks>
/// If <c>true</c> then a query string "v" with the encoded content of the file is added.
/// </remarks>
[HtmlAttributeName(AppendVersionAttributeName)]
public bool? AppendVersion { get; set; }
/// <summary>
/// A comma separated list of globbed file patterns of CSS stylesheets to fallback to in the case the primary
/// one fails.
/// The glob patterns are assessed relative to the application's 'webroot' setting.
/// </summary>
[HtmlAttributeName(FallbackHrefIncludeAttributeName)]
public string FallbackHrefInclude { get; set; }
/// <summary>
/// A comma separated list of globbed file patterns of CSS stylesheets to exclude from the fallback list, in
/// the case the primary one fails.
/// The glob patterns are assessed relative to the application's 'webroot' setting.
/// Must be used in conjunction with <see cref="FallbackHrefInclude"/>.
/// </summary>
[HtmlAttributeName(FallbackHrefExcludeAttributeName)]
public string FallbackHrefExclude { get; set; }
/// <summary>
/// The class name defined in the stylesheet to use for the fallback test.
/// Must be used in conjunction with <see cref="FallbackTestProperty"/> and <see cref="FallbackTestValue"/>,
/// and either <see cref="FallbackHref"/> or <see cref="FallbackHrefInclude"/>.
/// </summary>
[HtmlAttributeName(FallbackTestClassAttributeName)]
public string FallbackTestClass { get; set; }
/// <summary>
/// The CSS property name to use for the fallback test.
/// Must be used in conjunction with <see cref="FallbackTestClass"/> and <see cref="FallbackTestValue"/>,
/// and either <see cref="FallbackHref"/> or <see cref="FallbackHrefInclude"/>.
/// </summary>
[HtmlAttributeName(FallbackTestPropertyAttributeName)]
public string FallbackTestProperty { get; set; }
/// <summary>
/// The CSS property value to use for the fallback test.
/// Must be used in conjunction with <see cref="FallbackTestClass"/> and <see cref="FallbackTestProperty"/>,
/// and either <see cref="FallbackHref"/> or <see cref="FallbackHrefInclude"/>.
/// </summary>
[HtmlAttributeName(FallbackTestValueAttributeName)]
public string FallbackTestValue { get; set; }
/// <summary>
/// Gets the <see cref="IWebHostEnvironment"/> for the application.
/// </summary>
protected internal IWebHostEnvironment HostingEnvironment { get; }
/// <summary>
/// Gets the <see cref="IMemoryCache"/> used to store globbed urls.
/// </summary>
protected internal IMemoryCache Cache { get; }
/// <summary>
/// Gets the <see cref="System.Text.Encodings.Web.JavaScriptEncoder"/> used to encode fallback information.
/// </summary>
protected JavaScriptEncoder JavaScriptEncoder { get; }
/// <summary>
/// Gets the <see cref="GlobbingUrlBuilder"/> used to populate included and excluded urls.
/// </summary>
// Internal for ease of use when testing.
protected internal GlobbingUrlBuilder GlobbingUrlBuilder { get; set; }
internal IFileVersionProvider FileVersionProvider { get; private set; }
// Shared writer for determining the string content of a TagHelperAttribute's Value.
private StringWriter StringWriter
{
get
{
if (_stringWriter == null)
{
_stringWriter = new StringWriter();
}
return _stringWriter;
}
}
/// <inheritdoc />
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (output == null)
{
throw new ArgumentNullException(nameof(output));
}
// Pass through attribute that is also a well-known HTML attribute.
if (Href != null)
{
output.CopyHtmlAttribute(HrefAttributeName, context);
}
// If there's no "href" attribute in output.Attributes this will noop.
ProcessUrlAttribute(HrefAttributeName, output);
// Retrieve the TagHelperOutput variation of the "href" attribute in case other TagHelpers in the
// pipeline have touched the value. If the value is already encoded this LinkTagHelper may
// not function properly.
Href = output.Attributes[HrefAttributeName]?.Value as string;
if (!AttributeMatcher.TryDetermineMode(context, ModeDetails, Compare, out var mode))
{
// No attributes matched so we have nothing to do
return;
}
if (AppendVersion == true)
{
EnsureFileVersionProvider();
if (Href != null)
{
var index = output.Attributes.IndexOfName(HrefAttributeName);
var existingAttribute = output.Attributes[index];
output.Attributes[index] = new TagHelperAttribute(
existingAttribute.Name,
FileVersionProvider.AddFileVersionToPath(ViewContext.HttpContext.Request.PathBase, Href),
existingAttribute.ValueStyle);
}
}
var builder = output.PostElement;
builder.Clear();
if (mode == Mode.GlobbedHref || mode == Mode.Fallback && !string.IsNullOrEmpty(HrefInclude))
{
BuildGlobbedLinkTags(output.Attributes, builder);
if (string.IsNullOrEmpty(Href))
{
// Only HrefInclude is specified. Don't render the original tag.
output.TagName = null;
output.Content.SetHtmlContent(HtmlString.Empty);
}
}
if (mode == Mode.Fallback && HasStyleSheetLinkType(output.Attributes))
{
if (TryResolveUrl(FallbackHref, resolvedUrl: out string resolvedUrl))
{
FallbackHref = resolvedUrl;
}
BuildFallbackBlock(output.Attributes, builder);
}
}
private void BuildGlobbedLinkTags(TagHelperAttributeList attributes, TagHelperContent builder)
{
EnsureGlobbingUrlBuilder();
// Build a <link /> tag for each matched href.
var urls = GlobbingUrlBuilder.BuildUrlList(null, HrefInclude, HrefExclude);
for (var i = 0; i < urls.Count; i++)
{
var url = urls[i];
// "url" values come from bound attributes and globbing. Must always be non-null.
Debug.Assert(url != null);
if (string.Equals(Href, url, StringComparison.OrdinalIgnoreCase))
{
// Don't build duplicate link tag for the original href url.
continue;
}
BuildLinkTag(url, attributes, builder);
}
}
private void BuildFallbackBlock(TagHelperAttributeList attributes, TagHelperContent builder)
{
EnsureGlobbingUrlBuilder();
var fallbackHrefs = GlobbingUrlBuilder.BuildUrlList(
FallbackHref,
FallbackHrefInclude,
FallbackHrefExclude);
if (fallbackHrefs.Count == 0)
{
return;
}
builder.AppendHtml(HtmlString.NewLine);
// Build the <meta /> tag that's used to test for the presence of the stylesheet
builder
.AppendHtml("<meta name=\"x-stylesheet-fallback-test\" content=\"\" class=\"")
.Append(FallbackTestClass)
.AppendHtml("\" />");
// Build the <script /> tag that checks the effective style of <meta /> tag above and renders the extra
// <link /> tag to load the fallback stylesheet if the test CSS property value is found to be false,
// indicating that the primary stylesheet failed to load.
// GetEmbeddedJavaScript returns JavaScript to which we add '"{0}","{1}",{2});'
builder
.AppendHtml("<script>")
.AppendHtml(JavaScriptResources.GetEmbeddedJavaScript(FallbackJavaScriptResourceName))
.AppendHtml("\"")
.AppendHtml(JavaScriptEncoder.Encode(FallbackTestProperty))
.AppendHtml("\",\"")
.AppendHtml(JavaScriptEncoder.Encode(FallbackTestValue))
.AppendHtml("\",");
AppendFallbackHrefs(builder, fallbackHrefs);
builder.AppendHtml(", \"");
// Perf: Avoid allocating enumerator and read interface .Count once rather than per iteration
var attributesCount = attributes.Count;
for (var i = 0; i < attributesCount; i++)
{
var attribute = attributes[i];
if (string.Equals(attribute.Name, HrefAttributeName, StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (SuppressFallbackIntegrity && string.Equals(attribute.Name, IntegrityAttributeName, StringComparison.OrdinalIgnoreCase))
{
continue;
}
attribute.WriteTo(StringWriter, HtmlEncoder);
StringWriter.Write(' ');
}
var stringBuilder = StringWriter.GetStringBuilder();
var scriptTags = stringBuilder.ToString();
stringBuilder.Clear();
var encodedScriptTags = JavaScriptEncoder.Encode(scriptTags);
builder.AppendHtml(encodedScriptTags);
builder.AppendHtml("\");</script>");
}
private bool HasStyleSheetLinkType(TagHelperAttributeList attributes)
{
if (!attributes.TryGetAttribute(RelAttributeName, out var relAttribute) ||
relAttribute.Value == null)
{
return false;
}
var attributeValue = relAttribute.Value;
var stringValue = attributeValue as string;
if (attributeValue is IHtmlContent contentValue)
{
contentValue.WriteTo(StringWriter, HtmlEncoder);
stringValue = StringWriter.ToString();
// Reset writer
StringWriter.GetStringBuilder().Clear();
}
else if (stringValue == null)
{
stringValue = Convert.ToString(attributeValue, CultureInfo.InvariantCulture);
}
var hasRelStylesheet = string.Equals("stylesheet", stringValue, StringComparison.Ordinal);
return hasRelStylesheet;
}
private void AppendFallbackHrefs(TagHelperContent builder, IReadOnlyList<string> fallbackHrefs)
{
builder.AppendHtml("[");
var firstAdded = false;
// Perf: Avoid allocating enumerator and read interface .Count once rather than per iteration
var fallbackHrefsCount = fallbackHrefs.Count;
for (var i = 0; i < fallbackHrefsCount; i++)
{
if (firstAdded)
{
builder.AppendHtml(",\"");
}
else
{
builder.AppendHtml("\"");
firstAdded = true;
}
// fallbackHrefs come from bound attributes (a C# context) and globbing. Must always be non-null.
Debug.Assert(fallbackHrefs[i] != null);
var valueToWrite = fallbackHrefs[i];
if (AppendVersion == true)
{
valueToWrite = FileVersionProvider.AddFileVersionToPath(ViewContext.HttpContext.Request.PathBase, fallbackHrefs[i]);
}
// Must HTML-encode the href attribute value to ensure the written <link/> element is valid. Must also
// JavaScript-encode that value to ensure the doc.write() statement is valid.
valueToWrite = HtmlEncoder.Encode(valueToWrite);
valueToWrite = JavaScriptEncoder.Encode(valueToWrite);
builder.AppendHtml(valueToWrite);
builder.AppendHtml("\"");
}
builder.AppendHtml("]");
}
private void EnsureGlobbingUrlBuilder()
{
if (GlobbingUrlBuilder == null)
{
GlobbingUrlBuilder = new GlobbingUrlBuilder(
HostingEnvironment.WebRootFileProvider,
Cache,
ViewContext.HttpContext.Request.PathBase);
}
}
private void EnsureFileVersionProvider()
{
if (FileVersionProvider == null)
{
FileVersionProvider = ViewContext.HttpContext.RequestServices.GetRequiredService<IFileVersionProvider>();
}
}
private void BuildLinkTag(string href, TagHelperAttributeList attributes, TagHelperContent builder)
{
builder.AppendHtml("<link ");
var addHref = true;
// Perf: Avoid allocating enumerator and read interface .Count once rather than per iteration
var attributesCount = attributes.Count;
for (var i = 0; i < attributesCount; i++)
{
var attribute = attributes[i];
if (string.Equals(attribute.Name, HrefAttributeName, StringComparison.OrdinalIgnoreCase))
{
addHref = false;
AppendVersionedHref(attribute.Name, href, builder);
}
else
{
attribute.CopyTo(builder);
builder.AppendHtml(" ");
}
}
if (addHref)
{
AppendVersionedHref(HrefAttributeName, href, builder);
}
builder.AppendHtml("/>");
}
private void AppendVersionedHref(string hrefName, string hrefValue, TagHelperContent builder)
{
if (AppendVersion == true)
{
hrefValue = FileVersionProvider.AddFileVersionToPath(ViewContext.HttpContext.Request.PathBase, hrefValue);
}
builder
.AppendHtml(hrefName)
.AppendHtml("=\"")
.Append(hrefValue)
.AppendHtml("\" ");
}
private enum Mode
{
/// <summary>
/// Just adding a file version for the generated urls.
/// </summary>
AppendVersion = 0,
/// <summary>
/// Just performing file globbing search for the href, rendering a separate <link> for each match.
/// </summary>
GlobbedHref = 1,
/// <summary>
/// Rendering a fallback block if primary stylesheet fails to load. Will also do globbing for both the
/// primary and fallback hrefs if the appropriate properties are set.
/// </summary>
Fallback = 2,
}
}
}
| |
/*
* 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;
using System.IO;
using System.Reflection;
using System.Net;
using System.Text;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Nini.Config;
using log4net;
namespace OpenSim.Server.Handlers.Simulation
{
public class ObjectHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private ISimulationService m_SimulationService;
public ObjectHandler() { }
public ObjectHandler(ISimulationService sim)
{
m_SimulationService = sim;
}
public Hashtable Handler(Hashtable request)
{
//m_log.Debug("[CONNECTION DEBUGGING]: ObjectHandler Called");
//m_log.Debug("---------------------------");
//m_log.Debug(" >> uri=" + request["uri"]);
//m_log.Debug(" >> content-type=" + request["content-type"]);
//m_log.Debug(" >> http-method=" + request["http-method"]);
//m_log.Debug("---------------------------\n");
Hashtable responsedata = new Hashtable();
responsedata["content_type"] = "text/html";
UUID objectID;
UUID regionID;
string action;
if (!Utils.GetParams((string)request["uri"], out objectID, out regionID, out action))
{
m_log.InfoFormat("[OBJECT HANDLER]: Invalid parameters for object message {0}", request["uri"]);
responsedata["int_response_code"] = 404;
responsedata["str_response_string"] = "false";
return responsedata;
}
try
{
// Next, let's parse the verb
string method = (string)request["http-method"];
if (method.Equals("POST"))
{
DoObjectPost(request, responsedata, regionID);
return responsedata;
}
//else if (method.Equals("DELETE"))
//{
// DoObjectDelete(request, responsedata, agentID, action, regionHandle);
// return responsedata;
//}
else
{
m_log.InfoFormat("[OBJECT HANDLER]: method {0} not supported in object message", method);
responsedata["int_response_code"] = HttpStatusCode.MethodNotAllowed;
responsedata["str_response_string"] = "Method not allowed";
return responsedata;
}
}
catch (Exception e)
{
m_log.WarnFormat("[OBJECT HANDLER]: Caught exception {0}", e.StackTrace);
responsedata["int_response_code"] = HttpStatusCode.InternalServerError;
responsedata["str_response_string"] = "Internal server error";
return responsedata;
}
}
protected void DoObjectPost(Hashtable request, Hashtable responsedata, UUID regionID)
{
OSDMap args = Utils.GetOSDMap((string)request["body"]);
if (args == null)
{
responsedata["int_response_code"] = 400;
responsedata["str_response_string"] = "false";
return;
}
// retrieve the input arguments
int x = 0, y = 0;
UUID uuid = UUID.Zero;
string regionname = string.Empty;
Vector3 newPosition = Vector3.Zero;
if (args.ContainsKey("destination_x") && args["destination_x"] != null)
Int32.TryParse(args["destination_x"].AsString(), out x);
if (args.ContainsKey("destination_y") && args["destination_y"] != null)
Int32.TryParse(args["destination_y"].AsString(), out y);
if (args.ContainsKey("destination_uuid") && args["destination_uuid"] != null)
UUID.TryParse(args["destination_uuid"].AsString(), out uuid);
if (args.ContainsKey("destination_name") && args["destination_name"] != null)
regionname = args["destination_name"].ToString();
if (args.ContainsKey("new_position") && args["new_position"] != null)
Vector3.TryParse(args["new_position"], out newPosition);
GridRegion destination = new GridRegion();
destination.RegionID = uuid;
destination.RegionLocX = x;
destination.RegionLocY = y;
destination.RegionName = regionname;
string sogXmlStr = "", extraStr = "", stateXmlStr = "";
if (args.ContainsKey("sog") && args["sog"] != null)
sogXmlStr = args["sog"].AsString();
if (args.ContainsKey("extra") && args["extra"] != null)
extraStr = args["extra"].AsString();
IScene s = m_SimulationService.GetScene(destination.RegionID);
ISceneObject sog = null;
try
{
//m_log.DebugFormat("[OBJECT HANDLER]: received {0}", sogXmlStr);
sog = s.DeserializeObject(sogXmlStr);
sog.ExtraFromXmlString(extraStr);
}
catch (Exception ex)
{
m_log.InfoFormat("[OBJECT HANDLER]: exception on deserializing scene object {0}", ex.Message);
responsedata["int_response_code"] = HttpStatusCode.BadRequest;
responsedata["str_response_string"] = "Bad request";
return;
}
if (args.ContainsKey("modified"))
sog.HasGroupChanged = args["modified"].AsBoolean();
else
sog.HasGroupChanged = false;
if ((args["state"] != null) && s.AllowScriptCrossings)
{
stateXmlStr = args["state"].AsString();
if (stateXmlStr != "")
{
try
{
sog.SetState(stateXmlStr, s);
}
catch (Exception ex)
{
m_log.InfoFormat("[OBJECT HANDLER]: exception on setting state for scene object {0}", ex.Message);
// ignore and continue
}
}
}
bool result = false;
try
{
// This is the meaning of POST object
result = CreateObject(destination, newPosition, sog);
}
catch (Exception e)
{
m_log.DebugFormat("[OBJECT HANDLER]: Exception in CreateObject: {0}", e.StackTrace);
}
responsedata["int_response_code"] = HttpStatusCode.OK;
responsedata["str_response_string"] = result.ToString();
}
// subclasses can override this
protected virtual bool CreateObject(GridRegion destination, Vector3 newPosition, ISceneObject sog)
{
return m_SimulationService.CreateObject(destination, newPosition, sog, 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.
using Microsoft.Win32;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using System.Threading;
using System;
#if !ES_BUILD_AGAINST_DOTNET_V35
using Contract = System.Diagnostics.Contracts.Contract;
#else
using Contract = Microsoft.Diagnostics.Contracts.Internal.Contract;
#endif
#if ES_BUILD_STANDALONE
using Environment = Microsoft.Diagnostics.Tracing.Internal.Environment;
using EventDescriptor = Microsoft.Diagnostics.Tracing.EventDescriptor;
#endif
#if ES_BUILD_AGAINST_DOTNET_V35
using Microsoft.Internal; // for Tuple (can't define alias for open generic types so we "use" the whole namespace)
#endif
#if ES_BUILD_STANDALONE
namespace Microsoft.Diagnostics.Tracing
#else
namespace System.Diagnostics.Tracing
#endif
{
// New in CLR4.0
internal enum ControllerCommand
{
// Strictly Positive numbers are for provider-specific commands, negative number are for 'shared' commands. 256
// The first 256 negative numbers are reserved for the framework.
Update = 0, // Not used by EventPrividerBase.
SendManifest = -1,
Enable = -2,
Disable = -3,
};
/// <summary>
/// Only here because System.Diagnostics.EventProvider needs one more extensibility hook (when it gets a
/// controller callback)
/// </summary>
[System.Security.Permissions.HostProtection(MayLeakOnAbort = true)]
internal partial class EventProvider : IDisposable
{
// This is the windows EVENT_DATA_DESCRIPTOR structure. We expose it because this is what
// subclasses of EventProvider use when creating efficient (but unsafe) version of
// EventWrite. We do make it a nested type because we really don't expect anyone to use
// it except subclasses (and then only rarely).
public struct EventData
{
internal unsafe ulong Ptr;
internal uint Size;
internal uint Reserved;
}
/// <summary>
/// A struct characterizing ETW sessions (identified by the etwSessionId) as
/// activity-tracing-aware or legacy. A session that's activity-tracing-aware
/// has specified one non-zero bit in the reserved range 44-47 in the
/// 'allKeywords' value it passed in for a specific EventProvider.
/// </summary>
public struct SessionInfo
{
internal int sessionIdBit; // the index of the bit used for tracing in the "reserved" field of AllKeywords
internal int etwSessionId; // the machine-wide ETW session ID
internal SessionInfo(int sessionIdBit_, int etwSessionId_)
{ sessionIdBit = sessionIdBit_; etwSessionId = etwSessionId_; }
}
private static bool m_setInformationMissing;
[SecurityCritical]
UnsafeNativeMethods.ManifestEtw.EtwEnableCallback m_etwCallback; // Trace Callback function
private long m_regHandle; // Trace Registration Handle
private byte m_level; // Tracing Level
private long m_anyKeywordMask; // Trace Enable Flags
private long m_allKeywordMask; // Match all keyword
#if ES_SESSION_INFO || FEATURE_ACTIVITYSAMPLING
private List<SessionInfo> m_liveSessions; // current live sessions (Tuple<sessionIdBit, etwSessionId>)
#endif
private bool m_enabled; // Enabled flag from Trace callback
private Guid m_providerId; // Control Guid
internal bool m_disposed; // when true provider has unregistered
[ThreadStatic]
private static WriteEventErrorCode s_returnCode; // The last return code
private const int s_basicTypeAllocationBufferSize = 16;
private const int s_etwMaxNumberArguments = 32;
private const int s_etwAPIMaxRefObjCount = 8;
private const int s_maxEventDataDescriptors = 128;
private const int s_traceEventMaximumSize = 65482;
private const int s_traceEventMaximumStringSize = 32724;
[SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")]
public enum WriteEventErrorCode : int
{
//check mapping to runtime codes
NoError = 0,
NoFreeBuffers = 1,
EventTooBig = 2,
NullInput = 3,
TooManyArgs = 4,
Other = 5,
};
// Because callbacks happen on registration, and we need the callbacks for those setup
// we can't call Register in the constructor.
//
// Note that EventProvider should ONLY be used by EventSource. In particular because
// it registers a callback from native code you MUST dispose it BEFORE shutdown, otherwise
// you may get native callbacks during shutdown when we have destroyed the delegate.
// EventSource has special logic to do this, no one else should be calling EventProvider.
internal EventProvider()
{
}
/// <summary>
/// This method registers the controlGuid of this class with ETW. We need to be running on
/// Vista or above. If not a PlatformNotSupported exception will be thrown. If for some
/// reason the ETW Register call failed a NotSupported exception will be thrown.
/// </summary>
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventRegister(System.Guid&,Microsoft.Win32.UnsafeNativeMethods.ManifestEtw+EtwEnableCallback,System.Void*,System.Int64&):System.UInt32" />
// <SatisfiesLinkDemand Name="Win32Exception..ctor(System.Int32)" />
// <ReferencesCritical Name="Method: EtwEnableCallBack(Guid&, Int32, Byte, Int64, Int64, Void*, Void*):Void" Ring="1" />
// </SecurityKernel>
[System.Security.SecurityCritical]
internal unsafe void Register(Guid providerGuid)
{
m_providerId = providerGuid;
uint status;
m_etwCallback = new UnsafeNativeMethods.ManifestEtw.EtwEnableCallback(EtwEnableCallBack);
status = EventRegister(ref m_providerId, m_etwCallback);
if (status != 0)
{
throw new ArgumentException(Win32Native.GetMessage(unchecked((int)status)));
}
}
//
// implement Dispose Pattern to early deregister from ETW insted of waiting for
// the finalizer to call deregistration.
// Once the user is done with the provider it needs to call Close() or Dispose()
// If neither are called the finalizer will unregister the provider anyway
//
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// <SecurityKernel Critical="True" TreatAsSafe="Does not expose critical resource" Ring="1">
// <ReferencesCritical Name="Method: Deregister():Void" Ring="1" />
// </SecurityKernel>
[System.Security.SecuritySafeCritical]
protected virtual void Dispose(bool disposing)
{
//
// explicit cleanup is done by calling Dispose with true from
// Dispose() or Close(). The disposing arguement is ignored because there
// are no unmanaged resources.
// The finalizer calls Dispose with false.
//
//
// check if the object has been allready disposed
//
if (m_disposed) return;
// Disable the provider.
m_enabled = false;
// Do most of the work under a lock to avoid shutdown race.
lock (EventListener.EventListenersLock)
{
// Double check
if (m_disposed)
return;
Deregister();
m_disposed = true;
}
}
/// <summary>
/// This method deregisters the controlGuid of this class with ETW.
///
/// </summary>
public virtual void Close()
{
Dispose();
}
~EventProvider()
{
Dispose(false);
}
/// <summary>
/// This method un-registers from ETW.
/// </summary>
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64):System.Int32" />
// </SecurityKernel>
// TODO Check return code from UnsafeNativeMethods.ManifestEtw.EventUnregister
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1806:DoNotIgnoreMethodResults", MessageId = "Microsoft.Win32.UnsafeNativeMethods.ManifestEtw.EventUnregister(System.Int64)"), System.Security.SecurityCritical]
private unsafe void Deregister()
{
//
// Unregister from ETW using the RegHandle saved from
// the register call.
//
if (m_regHandle != 0)
{
EventUnregister();
m_regHandle = 0;
}
}
[System.Security.SecurityCritical]
unsafe void EtwEnableCallBack(
ref System.Guid sourceId,
int controlCode,
byte setLevel,
long anyKeyword,
long allKeyword,
UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData,
void* callbackContext
)
{
// This is an optional callback API. We will therefore ignore any failures that happen as a
// result of turning on this provider as to not crash the app.
// EventSource has code to validate whether initialization it expected to occur actually occurred
try
{
ControllerCommand command = ControllerCommand.Update;
IDictionary<string, string> args = null;
bool skipFinalOnControllerCommand = false;
if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_ENABLE_PROVIDER)
{
m_enabled = true;
m_level = setLevel;
m_anyKeywordMask = anyKeyword;
m_allKeywordMask = allKeyword;
// ES_SESSION_INFO is a marker for additional places we #ifdeffed out to remove
// references to EnumerateTraceGuidsEx. This symbol is actually not used because
// today we use FEATURE_ACTIVITYSAMPLING to determine if this code is there or not.
// However we put it in the #if so that we don't lose the fact that this feature
// switch is at least partially independent of FEATURE_ACTIVITYSAMPLING
#if ES_SESSION_INFO || FEATURE_ACTIVITYSAMPLING
List<Tuple<SessionInfo, bool>> sessionsChanged = GetSessions();
foreach (var session in sessionsChanged)
{
int sessionChanged = session.Item1.sessionIdBit;
int etwSessionId = session.Item1.etwSessionId;
bool bEnabling = session.Item2;
skipFinalOnControllerCommand = true;
args = null; // reinitialize args for every session...
// if we get more than one session changed we have no way
// of knowing which one "filterData" belongs to
if (sessionsChanged.Count > 1)
filterData = null;
// read filter data only when a session is being *added*
byte[] data;
int keyIndex;
if (bEnabling &&
GetDataFromController(etwSessionId, filterData, out command, out data, out keyIndex))
{
args = new Dictionary<string, string>(4);
while (keyIndex < data.Length)
{
int keyEnd = FindNull(data, keyIndex);
int valueIdx = keyEnd + 1;
int valueEnd = FindNull(data, valueIdx);
if (valueEnd < data.Length)
{
string key = System.Text.Encoding.UTF8.GetString(data, keyIndex, keyEnd - keyIndex);
string value = System.Text.Encoding.UTF8.GetString(data, valueIdx, valueEnd - valueIdx);
args[key] = value;
}
keyIndex = valueEnd + 1;
}
}
// execute OnControllerCommand once for every session that has changed.
OnControllerCommand(command, args, (bEnabling ? sessionChanged : -sessionChanged), etwSessionId);
}
#endif
}
else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_DISABLE_PROVIDER)
{
m_enabled = false;
m_level = 0;
m_anyKeywordMask = 0;
m_allKeywordMask = 0;
#if ES_SESSION_INFO || FEATURE_ACTIVITYSAMPLING
m_liveSessions = null;
#endif
}
else if (controlCode == UnsafeNativeMethods.ManifestEtw.EVENT_CONTROL_CODE_CAPTURE_STATE)
{
command = ControllerCommand.SendManifest;
}
else
return; // per spec you ignore commands you don't recognize.
if (!skipFinalOnControllerCommand)
OnControllerCommand(command, args, 0, 0);
}
catch (Exception)
{
// We want to ignore any failures that happen as a result of turning on this provider as to
// not crash the app.
}
}
// New in CLR4.0
protected virtual void OnControllerCommand(ControllerCommand command, IDictionary<string, string> arguments, int sessionId, int etwSessionId) { }
protected EventLevel Level { get { return (EventLevel)m_level; } set { m_level = (byte)value; } }
protected EventKeywords MatchAnyKeyword { get { return (EventKeywords)m_anyKeywordMask; } set { m_anyKeywordMask = unchecked((long)value); } }
protected EventKeywords MatchAllKeyword { get { return (EventKeywords)m_allKeywordMask; } set { m_allKeywordMask = unchecked((long)value); } }
static private int FindNull(byte[] buffer, int idx)
{
while (idx < buffer.Length && buffer[idx] != 0)
idx++;
return idx;
}
#if ES_SESSION_INFO || FEATURE_ACTIVITYSAMPLING
/// <summary>
/// Determines the ETW sessions that have been added and/or removed to the set of
/// sessions interested in the current provider. It does so by (1) enumerating over all
/// ETW sessions that enabled 'this.m_Guid' for the current process ID, and (2)
/// comparing the current list with a list it cached on the previous invocation.
///
/// The return value is a list of tuples, where the SessionInfo specifies the
/// ETW session that was added or remove, and the bool specifies whether the
/// session was added or whether it was removed from the set.
/// </summary>
[System.Security.SecuritySafeCritical]
private List<Tuple<SessionInfo, bool>> GetSessions()
{
List<SessionInfo> liveSessionList = null;
GetSessionInfo((Action<int, long>)
((etwSessionId, matchAllKeywords) =>
GetSessionInfoCallback(etwSessionId, matchAllKeywords, ref liveSessionList)));
List<Tuple<SessionInfo, bool>> changedSessionList = new List<Tuple<SessionInfo, bool>>();
// first look for sessions that have gone away (or have changed)
// (present in the m_liveSessions but not in the new liveSessionList)
if (m_liveSessions != null)
{
foreach (SessionInfo s in m_liveSessions)
{
int idx;
if ((idx = IndexOfSessionInList(liveSessionList, s.etwSessionId)) < 0 ||
(liveSessionList[idx].sessionIdBit != s.sessionIdBit))
changedSessionList.Add(Tuple.Create(s, false));
}
}
// next look for sessions that were created since the last callback (or have changed)
// (present in the new liveSessionList but not in m_liveSessions)
if (liveSessionList != null)
{
foreach (SessionInfo s in liveSessionList)
{
int idx;
if ((idx = IndexOfSessionInList(m_liveSessions, s.etwSessionId)) < 0 ||
(m_liveSessions[idx].sessionIdBit != s.sessionIdBit))
changedSessionList.Add(Tuple.Create(s, true));
}
}
m_liveSessions = liveSessionList;
return changedSessionList;
}
/// <summary>
/// This method is the callback used by GetSessions() when it calls into GetSessionInfo().
/// It updates a List{SessionInfo} based on the etwSessionId and matchAllKeywords that
/// GetSessionInfo() passes in.
/// </summary>
private static void GetSessionInfoCallback(int etwSessionId, long matchAllKeywords,
ref List<SessionInfo> sessionList)
{
uint sessionIdBitMask = (uint)SessionMask.FromEventKeywords(unchecked((ulong)matchAllKeywords));
// an ETW controller that specifies more than the mandated bit for our EventSource
// will be ignored...
if (bitcount(sessionIdBitMask) > 1)
return;
if (sessionList == null)
sessionList = new List<SessionInfo>(8);
if (bitcount(sessionIdBitMask) == 1)
{
// activity-tracing-aware etw session
sessionList.Add(new SessionInfo(bitindex(sessionIdBitMask) + 1, etwSessionId));
}
else
{
// legacy etw session
sessionList.Add(new SessionInfo(bitcount((uint)SessionMask.All) + 1, etwSessionId));
}
}
/// <summary>
/// This method enumerates over all active ETW sessions that have enabled 'this.m_Guid'
/// for the current process ID, calling 'action' for each session, and passing it the
/// ETW session and the 'AllKeywords' the session enabled for the current provider.
/// </summary>
[System.Security.SecurityCritical]
private unsafe void GetSessionInfo(Action<int, long> action)
{
// We wish the EventSource package to be legal for Windows Store applications.
// Currently EnumerateTraceGuidsEx is not an allowed API, so we avoid its use here
// and use the information in the registry instead. This means that ETW controllers
// that do not publish their intent to the registry (basically all controllers EXCEPT
// TraceEventSesion) will not work properly
// However the framework version of EventSource DOES have ES_SESSION_INFO defined and thus
// does not have this issue.
#if ES_SESSION_INFO
int buffSize = 256; // An initial guess that probably works most of the time.
byte* buffer;
for (; ; )
{
var space = stackalloc byte[buffSize];
buffer = space;
var hr = 0;
fixed (Guid* provider = &m_providerId)
{
hr = UnsafeNativeMethods.ManifestEtw.EnumerateTraceGuidsEx(UnsafeNativeMethods.ManifestEtw.TRACE_QUERY_INFO_CLASS.TraceGuidQueryInfo,
provider, sizeof(Guid), buffer, buffSize, ref buffSize);
}
if (hr == 0)
break;
if (hr != 122 /* ERROR_INSUFFICIENT_BUFFER */)
return;
}
var providerInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_GUID_INFO*)buffer;
var providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&providerInfos[1];
int processId = unchecked((int)Win32Native.GetCurrentProcessId());
// iterate over the instances of the EventProvider in all processes
for (int i = 0; i < providerInfos->InstanceCount; i++)
{
if (providerInstance->Pid == processId)
{
var enabledInfos = (UnsafeNativeMethods.ManifestEtw.TRACE_ENABLE_INFO*)&providerInstance[1];
// iterate over the list of active ETW sessions "listening" to the current provider
for (int j = 0; j < providerInstance->EnableCount; j++)
action(enabledInfos[j].LoggerId, enabledInfos[j].MatchAllKeyword);
}
if (providerInstance->NextOffset == 0)
break;
Contract.Assert(0 <= providerInstance->NextOffset && providerInstance->NextOffset < buffSize);
var structBase = (byte*)providerInstance;
providerInstance = (UnsafeNativeMethods.ManifestEtw.TRACE_PROVIDER_INSTANCE_INFO*)&structBase[providerInstance->NextOffset];
}
#else
#if !ES_BUILD_PCL && !FEATURE_PAL // TODO command arguments don't work on PCL builds...
// Determine our session from what is in the registry.
string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}";
if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8)
regKey = @"Software" + @"\Wow6432Node" + regKey;
else
regKey = @"Software" + regKey;
var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(regKey);
if (key != null)
{
foreach (string valueName in key.GetValueNames())
{
if (valueName.StartsWith("ControllerData_Session_"))
{
string strId = valueName.Substring(23); // strip of the ControllerData_Session_
int etwSessionId;
if (int.TryParse(strId, out etwSessionId))
{
// we need to assert this permission for partial trust scenarios
(new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert();
var data = key.GetValue(valueName) as byte[];
if (data != null)
{
var dataAsString = System.Text.Encoding.UTF8.GetString(data);
int keywordIdx = dataAsString.IndexOf("EtwSessionKeyword");
if (0 <= keywordIdx)
{
int startIdx = keywordIdx + 18;
int endIdx = dataAsString.IndexOf('\0', startIdx);
string keywordBitString = dataAsString.Substring(startIdx, endIdx-startIdx);
int keywordBit;
if (0 < endIdx && int.TryParse(keywordBitString, out keywordBit))
action(etwSessionId, 1L << keywordBit);
}
}
}
}
}
}
#endif
#endif
}
/// <summary>
/// Returns the index of the SesisonInfo from 'sessions' that has the specified 'etwSessionId'
/// or -1 if the value is not present.
/// </summary>
private static int IndexOfSessionInList(List<SessionInfo> sessions, int etwSessionId)
{
if (sessions == null)
return -1;
// for non-coreclr code we could use List<T>.FindIndex(Predicate<T>), but we need this to compile
// on coreclr as well
for (int i = 0; i < sessions.Count; ++i)
if (sessions[i].etwSessionId == etwSessionId)
return i;
return -1;
}
#endif
/// <summary>
/// Gets any data to be passed from the controller to the provider. It starts with what is passed
/// into the callback, but unfortunately this data is only present for when the provider is active
/// at the time the controller issues the command. To allow for providers to activate after the
/// controller issued a command, we also check the registry and use that to get the data. The function
/// returns an array of bytes representing the data, the index into that byte array where the data
/// starts, and the command being issued associated with that data.
/// </summary>
[System.Security.SecurityCritical]
private unsafe bool GetDataFromController(int etwSessionId,
UnsafeNativeMethods.ManifestEtw.EVENT_FILTER_DESCRIPTOR* filterData,
out ControllerCommand command, out byte[] data, out int dataStart)
{
data = null;
dataStart = 0;
if (filterData == null)
{
#if (!ES_BUILD_PCL && !PROJECTN && !FEATURE_PAL)
string regKey = @"\Microsoft\Windows\CurrentVersion\Winevt\Publishers\{" + m_providerId + "}";
if (System.Runtime.InteropServices.Marshal.SizeOf(typeof(IntPtr)) == 8)
regKey = @"HKEY_LOCAL_MACHINE\Software" + @"\Wow6432Node" + regKey;
else
regKey = @"HKEY_LOCAL_MACHINE\Software" + regKey;
string valueName = "ControllerData_Session_" + etwSessionId.ToString(CultureInfo.InvariantCulture);
// we need to assert this permission for partial trust scenarios
(new RegistryPermission(RegistryPermissionAccess.Read, regKey)).Assert();
data = Microsoft.Win32.Registry.GetValue(regKey, valueName, null) as byte[];
if (data != null)
{
// We only used the persisted data from the registry for updates.
command = ControllerCommand.Update;
return true;
}
#endif
}
else
{
if (filterData->Ptr != 0 && 0 < filterData->Size && filterData->Size <= 1024)
{
data = new byte[filterData->Size];
Marshal.Copy((IntPtr)filterData->Ptr, data, 0, data.Length);
}
command = (ControllerCommand)filterData->Type;
return true;
}
command = ControllerCommand.Update;
return false;
}
/// <summary>
/// IsEnabled, method used to test if provider is enabled
/// </summary>
public bool IsEnabled()
{
return m_enabled;
}
/// <summary>
/// IsEnabled, method used to test if event is enabled
/// </summary>
/// <param name="level">
/// Level to test
/// </param>
/// <param name="keywords">
/// Keyword to test
/// </param>
public bool IsEnabled(byte level, long keywords)
{
//
// If not enabled at all, return false.
//
if (!m_enabled)
{
return false;
}
// This also covers the case of Level == 0.
if ((level <= m_level) ||
(m_level == 0))
{
//
// Check if Keyword is enabled
//
if ((keywords == 0) ||
(((keywords & m_anyKeywordMask) != 0) &&
((keywords & m_allKeywordMask) == m_allKeywordMask)))
{
return true;
}
}
return false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public static WriteEventErrorCode GetLastWriteEventError()
{
return s_returnCode;
}
//
// Helper function to set the last error on the thread
//
private static void SetLastError(int error)
{
switch (error)
{
case UnsafeNativeMethods.ManifestEtw.ERROR_ARITHMETIC_OVERFLOW:
case UnsafeNativeMethods.ManifestEtw.ERROR_MORE_DATA:
s_returnCode = WriteEventErrorCode.EventTooBig;
break;
case UnsafeNativeMethods.ManifestEtw.ERROR_NOT_ENOUGH_MEMORY:
s_returnCode = WriteEventErrorCode.NoFreeBuffers;
break;
}
}
// <SecurityKernel Critical="True" Ring="0">
// <UsesUnsafeCode Name="Local intptrPtr of type: IntPtr*" />
// <UsesUnsafeCode Name="Local intptrPtr of type: Int32*" />
// <UsesUnsafeCode Name="Local longptr of type: Int64*" />
// <UsesUnsafeCode Name="Local uintptr of type: UInt32*" />
// <UsesUnsafeCode Name="Local ulongptr of type: UInt64*" />
// <UsesUnsafeCode Name="Local charptr of type: Char*" />
// <UsesUnsafeCode Name="Local byteptr of type: Byte*" />
// <UsesUnsafeCode Name="Local shortptr of type: Int16*" />
// <UsesUnsafeCode Name="Local sbyteptr of type: SByte*" />
// <UsesUnsafeCode Name="Local ushortptr of type: UInt16*" />
// <UsesUnsafeCode Name="Local floatptr of type: Single*" />
// <UsesUnsafeCode Name="Local doubleptr of type: Double*" />
// <UsesUnsafeCode Name="Local boolptr of type: Boolean*" />
// <UsesUnsafeCode Name="Local guidptr of type: Guid*" />
// <UsesUnsafeCode Name="Local decimalptr of type: Decimal*" />
// <UsesUnsafeCode Name="Local booleanptr of type: Boolean*" />
// <UsesUnsafeCode Name="Parameter dataDescriptor of type: EventData*" />
// <UsesUnsafeCode Name="Parameter dataBuffer of type: Byte*" />
// </SecurityKernel>
[System.Security.SecurityCritical]
private static unsafe object EncodeObject(ref object data, ref EventData* dataDescriptor, ref byte* dataBuffer, ref uint totalEventSize)
/*++
Routine Description:
This routine is used by WriteEvent to unbox the object type and
to fill the passed in ETW data descriptor.
Arguments:
data - argument to be decoded
dataDescriptor - pointer to the descriptor to be filled (updated to point to the next empty entry)
dataBuffer - storage buffer for storing user data, needed because cant get the address of the object
(updated to point to the next empty entry)
Return Value:
null if the object is a basic type other than string or byte[]. String otherwise
--*/
{
Again:
dataDescriptor->Reserved = 0;
string sRet = data as string;
byte[] blobRet = null;
if (sRet != null)
{
dataDescriptor->Size = ((uint)sRet.Length + 1) * 2;
}
else if ((blobRet = data as byte[]) != null)
{
// first store array length
*(int*)dataBuffer = blobRet.Length;
dataDescriptor->Ptr = (ulong)dataBuffer;
dataDescriptor->Size = 4;
totalEventSize += dataDescriptor->Size;
// then the array parameters
dataDescriptor++;
dataBuffer += s_basicTypeAllocationBufferSize;
dataDescriptor->Size = (uint)blobRet.Length;
}
else if (data is IntPtr)
{
dataDescriptor->Size = (uint)sizeof(IntPtr);
IntPtr* intptrPtr = (IntPtr*)dataBuffer;
*intptrPtr = (IntPtr)data;
dataDescriptor->Ptr = (ulong)intptrPtr;
}
else if (data is int)
{
dataDescriptor->Size = (uint)sizeof(int);
int* intptr = (int*)dataBuffer;
*intptr = (int)data;
dataDescriptor->Ptr = (ulong)intptr;
}
else if (data is long)
{
dataDescriptor->Size = (uint)sizeof(long);
long* longptr = (long*)dataBuffer;
*longptr = (long)data;
dataDescriptor->Ptr = (ulong)longptr;
}
else if (data is uint)
{
dataDescriptor->Size = (uint)sizeof(uint);
uint* uintptr = (uint*)dataBuffer;
*uintptr = (uint)data;
dataDescriptor->Ptr = (ulong)uintptr;
}
else if (data is UInt64)
{
dataDescriptor->Size = (uint)sizeof(ulong);
UInt64* ulongptr = (ulong*)dataBuffer;
*ulongptr = (ulong)data;
dataDescriptor->Ptr = (ulong)ulongptr;
}
else if (data is char)
{
dataDescriptor->Size = (uint)sizeof(char);
char* charptr = (char*)dataBuffer;
*charptr = (char)data;
dataDescriptor->Ptr = (ulong)charptr;
}
else if (data is byte)
{
dataDescriptor->Size = (uint)sizeof(byte);
byte* byteptr = (byte*)dataBuffer;
*byteptr = (byte)data;
dataDescriptor->Ptr = (ulong)byteptr;
}
else if (data is short)
{
dataDescriptor->Size = (uint)sizeof(short);
short* shortptr = (short*)dataBuffer;
*shortptr = (short)data;
dataDescriptor->Ptr = (ulong)shortptr;
}
else if (data is sbyte)
{
dataDescriptor->Size = (uint)sizeof(sbyte);
sbyte* sbyteptr = (sbyte*)dataBuffer;
*sbyteptr = (sbyte)data;
dataDescriptor->Ptr = (ulong)sbyteptr;
}
else if (data is ushort)
{
dataDescriptor->Size = (uint)sizeof(ushort);
ushort* ushortptr = (ushort*)dataBuffer;
*ushortptr = (ushort)data;
dataDescriptor->Ptr = (ulong)ushortptr;
}
else if (data is float)
{
dataDescriptor->Size = (uint)sizeof(float);
float* floatptr = (float*)dataBuffer;
*floatptr = (float)data;
dataDescriptor->Ptr = (ulong)floatptr;
}
else if (data is double)
{
dataDescriptor->Size = (uint)sizeof(double);
double* doubleptr = (double*)dataBuffer;
*doubleptr = (double)data;
dataDescriptor->Ptr = (ulong)doubleptr;
}
else if (data is bool)
{
// WIN32 Bool is 4 bytes
dataDescriptor->Size = 4;
int* intptr = (int*)dataBuffer;
if (((bool)data))
{
*intptr = 1;
}
else
{
*intptr = 0;
}
dataDescriptor->Ptr = (ulong)intptr;
}
else if (data is Guid)
{
dataDescriptor->Size = (uint)sizeof(Guid);
Guid* guidptr = (Guid*)dataBuffer;
*guidptr = (Guid)data;
dataDescriptor->Ptr = (ulong)guidptr;
}
else if (data is decimal)
{
dataDescriptor->Size = (uint)sizeof(decimal);
decimal* decimalptr = (decimal*)dataBuffer;
*decimalptr = (decimal)data;
dataDescriptor->Ptr = (ulong)decimalptr;
}
else if (data is DateTime)
{
const long UTCMinTicks = 504911232000000000;
long dateTimeTicks = 0;
// We cannot translate dates sooner than 1/1/1601 in UTC.
// To avoid getting an ArgumentOutOfRangeException we compare with 1/1/1601 DateTime ticks
if (((DateTime)data).Ticks > UTCMinTicks)
dateTimeTicks = ((DateTime)data).ToFileTimeUtc();
dataDescriptor->Size = (uint)sizeof(long);
long* longptr = (long*)dataBuffer;
*longptr = dateTimeTicks;
dataDescriptor->Ptr = (ulong)longptr;
}
else
{
if (data is System.Enum)
{
Type underlyingType = Enum.GetUnderlyingType(data.GetType());
if (underlyingType == typeof(int))
{
#if !ES_BUILD_PCL
data = ((IConvertible)data).ToInt32(null);
#else
data = (int)data;
#endif
goto Again;
}
else if (underlyingType == typeof(long))
{
#if !ES_BUILD_PCL
data = ((IConvertible)data).ToInt64(null);
#else
data = (long)data;
#endif
goto Again;
}
}
// To our eyes, everything else is a just a string
if (data == null)
sRet = "";
else
sRet = data.ToString();
dataDescriptor->Size = ((uint)sRet.Length + 1) * 2;
}
totalEventSize += dataDescriptor->Size;
// advance buffers
dataDescriptor++;
dataBuffer += s_basicTypeAllocationBufferSize;
return (object)sRet ?? (object)blobRet;
}
/// <summary>
/// WriteEvent, method to write a parameters with event schema properties
/// </summary>
/// <param name="eventDescriptor">
/// Event Descriptor for this event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID GUID to log
/// </param>
/// <param name="childActivityID">
/// childActivityID is marked as 'related' to the current activity ID.
/// </param>
/// <param name="eventPayload">
/// Payload for the ETW event.
/// </param>
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" />
// <UsesUnsafeCode Name="Local dataBuffer of type: Byte*" />
// <UsesUnsafeCode Name="Local pdata of type: Char*" />
// <UsesUnsafeCode Name="Local userData of type: EventData*" />
// <UsesUnsafeCode Name="Local userDataPtr of type: EventData*" />
// <UsesUnsafeCode Name="Local currentBuffer of type: Byte*" />
// <UsesUnsafeCode Name="Local v0 of type: Char*" />
// <UsesUnsafeCode Name="Local v1 of type: Char*" />
// <UsesUnsafeCode Name="Local v2 of type: Char*" />
// <UsesUnsafeCode Name="Local v3 of type: Char*" />
// <UsesUnsafeCode Name="Local v4 of type: Char*" />
// <UsesUnsafeCode Name="Local v5 of type: Char*" />
// <UsesUnsafeCode Name="Local v6 of type: Char*" />
// <UsesUnsafeCode Name="Local v7 of type: Char*" />
// <ReferencesCritical Name="Method: EncodeObject(Object&, EventData*, Byte*):String" Ring="1" />
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "Performance-critical code")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
[System.Security.SecurityCritical]
internal unsafe bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, params object[] eventPayload)
{
int status = 0;
if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords))
{
int argCount = 0;
unsafe
{
argCount = eventPayload.Length;
if (argCount > s_etwMaxNumberArguments)
{
s_returnCode = WriteEventErrorCode.TooManyArgs;
return false;
}
uint totalEventSize = 0;
int index;
int refObjIndex = 0;
List<int> refObjPosition = new List<int>(s_etwAPIMaxRefObjCount);
List<object> dataRefObj = new List<object>(s_etwAPIMaxRefObjCount);
EventData* userData = stackalloc EventData[2 * argCount];
EventData* userDataPtr = (EventData*)userData;
byte* dataBuffer = stackalloc byte[s_basicTypeAllocationBufferSize * 2 * argCount]; // Assume 16 chars for non-string argument
byte* currentBuffer = dataBuffer;
//
// The loop below goes through all the arguments and fills in the data
// descriptors. For strings save the location in the dataString array.
// Calculates the total size of the event by adding the data descriptor
// size value set in EncodeObject method.
//
bool hasNonStringRefArgs = false;
for (index = 0; index < eventPayload.Length; index++)
{
if (eventPayload[index] != null)
{
object supportedRefObj;
supportedRefObj = EncodeObject(ref eventPayload[index], ref userDataPtr, ref currentBuffer, ref totalEventSize);
if (supportedRefObj != null)
{
// EncodeObject advanced userDataPtr to the next empty slot
int idx = (int)(userDataPtr - userData - 1);
if (!(supportedRefObj is string))
{
if (eventPayload.Length + idx + 1 - index > s_etwMaxNumberArguments)
{
s_returnCode = WriteEventErrorCode.TooManyArgs;
return false;
}
hasNonStringRefArgs = true;
}
dataRefObj.Add(supportedRefObj);
refObjPosition.Add(idx);
refObjIndex++;
}
}
else
{
s_returnCode = WriteEventErrorCode.NullInput;
return false;
}
}
// update argCount based on actual number of arguments written to 'userData'
argCount = (int)(userDataPtr - userData);
if (totalEventSize > s_traceEventMaximumSize)
{
s_returnCode = WriteEventErrorCode.EventTooBig;
return false;
}
// the optimized path (using "fixed" instead of allocating pinned GCHandles
if (!hasNonStringRefArgs && (refObjIndex < s_etwAPIMaxRefObjCount))
{
// Fast path: at most 8 string arguments
// ensure we have at least s_etwAPIMaxStringCount in dataString, so that
// the "fixed" statement below works
while (refObjIndex < s_etwAPIMaxRefObjCount)
{
dataRefObj.Add(null);
++refObjIndex;
}
//
// now fix any string arguments and set the pointer on the data descriptor
//
fixed (char* v0 = (string)dataRefObj[0], v1 = (string)dataRefObj[1], v2 = (string)dataRefObj[2], v3 = (string)dataRefObj[3],
v4 = (string)dataRefObj[4], v5 = (string)dataRefObj[5], v6 = (string)dataRefObj[6], v7 = (string)dataRefObj[7])
{
userDataPtr = (EventData*)userData;
if (dataRefObj[0] != null)
{
userDataPtr[refObjPosition[0]].Ptr = (ulong)v0;
}
if (dataRefObj[1] != null)
{
userDataPtr[refObjPosition[1]].Ptr = (ulong)v1;
}
if (dataRefObj[2] != null)
{
userDataPtr[refObjPosition[2]].Ptr = (ulong)v2;
}
if (dataRefObj[3] != null)
{
userDataPtr[refObjPosition[3]].Ptr = (ulong)v3;
}
if (dataRefObj[4] != null)
{
userDataPtr[refObjPosition[4]].Ptr = (ulong)v4;
}
if (dataRefObj[5] != null)
{
userDataPtr[refObjPosition[5]].Ptr = (ulong)v5;
}
if (dataRefObj[6] != null)
{
userDataPtr[refObjPosition[6]].Ptr = (ulong)v6;
}
if (dataRefObj[7] != null)
{
userDataPtr[refObjPosition[7]].Ptr = (ulong)v7;
}
status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData);
}
}
else
{
// Slow path: use pinned handles
userDataPtr = (EventData*)userData;
GCHandle[] rgGCHandle = new GCHandle[refObjIndex];
for (int i = 0; i < refObjIndex; ++i)
{
// below we still use "fixed" to avoid taking dependency on the offset of the first field
// in the object (the way we would need to if we used GCHandle.AddrOfPinnedObject)
rgGCHandle[i] = GCHandle.Alloc(dataRefObj[i], GCHandleType.Pinned);
if (dataRefObj[i] is string)
{
fixed (char* p = (string)dataRefObj[i])
userDataPtr[refObjPosition[i]].Ptr = (ulong)p;
}
else
{
fixed (byte* p = (byte[])dataRefObj[i])
userDataPtr[refObjPosition[i]].Ptr = (ulong)p;
}
}
status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, argCount, userData);
for (int i = 0; i < refObjIndex; ++i)
{
rgGCHandle[i].Free();
}
}
}
}
if (status != 0)
{
SetLastError((int)status);
return false;
}
return true;
}
/// <summary>
/// WriteEvent, method to be used by generated code on a derived class
/// </summary>
/// <param name="eventDescriptor">
/// Event Descriptor for this event.
/// </param>
/// <param name="activityID">
/// A pointer to the activity ID to log
/// </param>
/// <param name="childActivityID">
/// If this event is generating a child activity (WriteEventTransfer related activity) this is child activity
/// This can be null for events that do not generate a child activity.
/// </param>
/// <param name="dataCount">
/// number of event descriptors
/// </param>
/// <param name="data">
/// pointer do the event data
/// </param>
// <SecurityKernel Critical="True" Ring="0">
// <CallsSuppressUnmanagedCode Name="UnsafeNativeMethods.ManifestEtw.EventWrite(System.Int64,EventDescriptor&,System.UInt32,System.Void*):System.UInt32" />
// </SecurityKernel>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
[System.Security.SecurityCritical]
internal unsafe protected bool WriteEvent(ref EventDescriptor eventDescriptor, Guid* activityID, Guid* childActivityID, int dataCount, IntPtr data)
{
if (childActivityID != null)
{
// activity transfers are supported only for events that specify the Send or Receive opcode
Contract.Assert((EventOpcode)eventDescriptor.Opcode == EventOpcode.Send ||
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Receive ||
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Start ||
(EventOpcode)eventDescriptor.Opcode == EventOpcode.Stop);
}
int status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(m_regHandle, ref eventDescriptor, activityID, childActivityID, dataCount, (EventData*)data);
if (status != 0)
{
SetLastError(status);
return false;
}
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference")]
[System.Security.SecurityCritical]
internal unsafe bool WriteEventRaw(
ref EventDescriptor eventDescriptor,
Guid* activityID,
Guid* relatedActivityID,
int dataCount,
IntPtr data)
{
int status = UnsafeNativeMethods.ManifestEtw.EventWriteTransferWrapper(
m_regHandle,
ref eventDescriptor,
activityID,
relatedActivityID,
dataCount,
(EventData*)data);
if (status != 0)
{
SetLastError(status);
return false;
}
return true;
}
// These are look-alikes to the Manifest based ETW OS APIs that have been shimmed to work
// either with Manifest ETW or Classic ETW (if Manifest based ETW is not available).
[SecurityCritical]
private unsafe uint EventRegister(ref Guid providerId, UnsafeNativeMethods.ManifestEtw.EtwEnableCallback enableCallback)
{
m_providerId = providerId;
m_etwCallback = enableCallback;
return UnsafeNativeMethods.ManifestEtw.EventRegister(ref providerId, enableCallback, null, ref m_regHandle);
}
[SecurityCritical]
private uint EventUnregister()
{
uint status = UnsafeNativeMethods.ManifestEtw.EventUnregister(m_regHandle);
m_regHandle = 0;
return status;
}
static int[] nibblebits = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 };
private static int bitcount(uint n)
{
int count = 0;
for (; n != 0; n = n >> 4)
count += nibblebits[n & 0x0f];
return count;
}
private static int bitindex(uint n)
{
Contract.Assert(bitcount(n) == 1);
int idx = 0;
while ((n & (1 << idx)) == 0)
idx++;
return idx;
}
}
}
| |
using System.Linq;
using jQWidgets.AspNet.Core.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System;
using jQWidgets.AspNetCore.Mvc.TagHelpers;
using System.IO;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http.Internal;
namespace jQWidgets.AspNet.Core.Controllers
{
public class JSONData
{
public List<SalesEmployee> Employees
{
get;
set;
}
public int TotalRecords
{
get;
set;
}
}
public class TagHelpersController : Controller
{
private jQWidgetsDemosContext _context;
public TagHelpersController(jQWidgetsDemosContext context)
{
_context = context;
}
//
// GET: /Widgets/
public ActionResult Index()
{
return View("ScrollView/ScrollView");
return View("ScrollView/ScrollView", _context.SalesEmployees);
// return View("DataTable/DataTableRowDetails", _context.Employee.ToList());
}
[HttpPost]
public FileContentResult ExportData(FormPostBack data)
{
return ExportHelper.ExportData(data);
}
[HttpPost]
public string GetEmployees()
{
List<SalesEmployee> allEmployees = _context.SalesEmployees.ToList();
JSONData data = new JSONData();
data.TotalRecords = allEmployees.Count;
data.Employees = allEmployees;
return JsonConvert.SerializeObject(data);
}
[HttpPost]
public string GetChildren(string jsonData)
{
JToken token = JObject.Parse(jsonData);
string id = (string)token.SelectToken("ID");
List<SalesEmployee> allEmployees = _context.SalesEmployees.ToList();
JSONData data = new JSONData();
List<SalesEmployee> employees = new List<SalesEmployee>();
for (int i = 0; i < allEmployees.Count; i++)
{
if (String.IsNullOrEmpty(id))
{
if (i < 5)
{
employees.Add(allEmployees[i]);
}
}
else
{
if (allEmployees[i].ReportsTo == Int32.Parse(id))
{
employees.Add(allEmployees[i]);
}
}
}
data.TotalRecords = allEmployees.Count;
data.Employees = employees;
return JsonConvert.SerializeObject(data);
}
[HttpPost]
public string GetPageData(string jsonData)
{
JToken token = JObject.Parse(jsonData);
List<JToken> filterGroups = token.SelectToken("filterGroups").Children().ToList();
int pageSize = (int)token.SelectToken("pagesize");
int pageNum = (int)token.SelectToken("pagenum");
string sortField = (string)token.SelectToken("sortdatafield");
string sortOrder = (string)token.SelectToken("sortorder");
int count = 0;
List<SalesEmployee> employees = new List<SalesEmployee>();
List<SalesEmployee> allEmployees = _context.SalesEmployees.ToList();
if (sortField != "")
{
if (sortOrder == "asc")
{
allEmployees = (from p in allEmployees
orderby (p.GetType().GetProperty(sortField).GetValue(p))
select p).ToList();
}
else if (sortOrder == "desc")
{
allEmployees = (from p in allEmployees
orderby (p.GetType().GetProperty(sortField).GetValue(p)) descending
select p).ToList();
}
}
if (filterGroups.Count > 0)
{
List<SalesEmployee> filteredEmployees = allEmployees;
for (int j = 0; j < filterGroups.Count; j++)
{
List<JToken> filters = filterGroups[j].SelectToken("filters").Children().ToList();
List<SalesEmployee> filterGroup = filteredEmployees;
List<SalesEmployee> filterGroupResult = new List<SalesEmployee>();
for (int i = 0; i < filters.Count; i++)
{
string filterLabel = (string)filters[i].SelectToken("label");
string filterValue = (string)filters[i].SelectToken("value");
string filterDataField = (string)filters[i].SelectToken("field");
string filterCondition = (string)filters[i].SelectToken("condition");
string filterType = (string)filters[i].SelectToken("type");
string filterOperator = (string)filters[i].SelectToken("operator");
List<SalesEmployee> currentResult = new List<SalesEmployee>();
switch (filterCondition)
{
case "NOT_EMPTY":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)) != null)
select p).ToList();
break;
case "NOT_NULL":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)).ToString() != "")
select p).ToList();
break;
case "NULL":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)) == null)
select p).ToList();
break;
case "EMPTY":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)).ToString() == "")
select p).ToList();
break;
case "CONTAINS_CASE_SENSITIVE":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)).ToString().Contains(filterValue))
select p).ToList();
break;
case "CONTAINS":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)).ToString().IndexOf(filterValue, StringComparison.CurrentCultureIgnoreCase) != -1)
select p).ToList();
break;
case "DOES_NOT_CONTAIN_CASE_SENSITIVE":
currentResult = (from p in filterGroup
where (!(p.GetType().GetProperty(filterDataField).GetValue(p)).ToString().Contains(filterValue))
select p).ToList();
break;
case "DOES_NOT_CONTAIN":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)).ToString().IndexOf(filterValue, StringComparison.CurrentCultureIgnoreCase) == -1)
select p).ToList();
break;
case "EQUAL_CASE_SENSITIVE":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)).ToString() == filterValue)
select p).ToList();
break;
case "EQUAL":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)).ToString().IndexOf(filterValue, StringComparison.CurrentCultureIgnoreCase) == 0)
select p).ToList();
break;
case "NOT_EQUAL_CASE_SENSITIVE":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)).ToString() != filterValue)
select p).ToList();
break;
case "NOT_EQUAL":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)).ToString().IndexOf(filterValue, StringComparison.CurrentCultureIgnoreCase) != 0)
select p).ToList();
break;
case "GREATER_THAN":
currentResult = (from p in filterGroup
where (float.Parse(p.GetType().GetProperty(filterDataField).GetValue(p).ToString()) > float.Parse(filterValue))
select p).ToList();
break;
case "LESS_THAN":
currentResult = (from p in filterGroup
where (float.Parse(p.GetType().GetProperty(filterDataField).GetValue(p).ToString()) < float.Parse(filterValue))
select p).ToList();
break;
case "GREATER_THAN_OR_EQUAL":
currentResult = (from p in filterGroup
where (float.Parse(p.GetType().GetProperty(filterDataField).GetValue(p).ToString()) >= float.Parse(filterValue))
select p).ToList();
break;
case "LESS_THAN_OR_EQUAL":
currentResult = (from p in filterGroup
where (float.Parse(p.GetType().GetProperty(filterDataField).GetValue(p).ToString()) <= float.Parse(filterValue))
select p).ToList();
break;
case "STARTS_WITH_CASE_SENSITIVE":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)).ToString().StartsWith(filterValue))
select p).ToList();
break;
case "STARTS_WITH":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)).ToString().StartsWith(filterValue, StringComparison.CurrentCultureIgnoreCase))
select p).ToList();
break;
case "ENDS_WITH_CASE_SENSITIVE":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)).ToString().EndsWith(filterValue))
select p).ToList();
break;
case "ENDS_WITH":
currentResult = (from p in filterGroup
where ((p.GetType().GetProperty(filterDataField).GetValue(p)).ToString().EndsWith(filterValue, StringComparison.CurrentCultureIgnoreCase))
select p).ToList();
break;
}
if (filterOperator == "or")
{
filterGroupResult.AddRange(currentResult);
}
else
{
filterGroup = currentResult;
filterGroupResult = currentResult;
}
}
filteredEmployees = filterGroupResult;
}
allEmployees = filteredEmployees;
}
for (int i = pageNum * pageSize; i < allEmployees.Count && count < pageSize; i++)
{
employees.Add(allEmployees[i]);
count++;
}
JSONData data = new JSONData();
data.TotalRecords = allEmployees.Count;
data.Employees = employees;
return JsonConvert.SerializeObject(data);
}
[HttpPost]
public bool AddItem(string jsonData)
{
JToken token = JObject.Parse(jsonData);
string label = (string)token.SelectToken("label");
SalesEmployee employee = new SalesEmployee() { Name = label };
_context.SalesEmployees.Add(employee);
return true;
}
[HttpPost]
public bool DeleteItem(string jsonData)
{
JToken token = JObject.Parse(jsonData);
string id = (string)token.SelectToken("value");
string label = (string)token.SelectToken("label");
for (int i = 0; i < _context.SalesEmployees.Count; i++)
{
SalesEmployee currentEmployee = _context.SalesEmployees[i];
if (currentEmployee.ID == id)
{
_context.SalesEmployees.Remove(currentEmployee);
return true;
}
}
return false;
}
[HttpPost]
public bool EditItem(string jsonData)
{
JToken token = JObject.Parse(jsonData);
string id = (string)token.SelectToken("value");
string label = (string)token.SelectToken("label");
for (int i = 0; i < _context.SalesEmployees.Count; i++)
{
SalesEmployee currentEmployee = _context.SalesEmployees[i];
if (currentEmployee.ID == id)
{
currentEmployee.Name = label;
return true;
}
}
return false;
}
[HttpPost]
public bool Add(string jsonData)
{
SalesEmployee employee = (SalesEmployee)JsonConvert.DeserializeObject(jsonData, typeof(SalesEmployee));
_context.SalesEmployees.Add(employee);
return true;
}
[HttpPost]
public bool Delete(string jsonData)
{
SalesEmployee employee = (SalesEmployee)JsonConvert.DeserializeObject(jsonData, typeof(SalesEmployee));
for (int i = 0; i < _context.SalesEmployees.Count; i++)
{
SalesEmployee currentEmployee = _context.SalesEmployees[i];
if (currentEmployee.ID == employee.ID)
{
_context.SalesEmployees.Remove(currentEmployee);
return true;
}
}
return false;
}
[HttpPost]
public bool Edit(string jsonData)
{
SalesEmployee employee = (SalesEmployee)JsonConvert.DeserializeObject(jsonData, typeof(SalesEmployee));
for (int i = 0; i < _context.SalesEmployees.Count; i++)
{
SalesEmployee currentEmployee = _context.SalesEmployees[i];
if (currentEmployee.ID == employee.ID)
{
currentEmployee.FirstName = employee.FirstName;
currentEmployee.LastName = employee.LastName;
currentEmployee.ProductName = employee.ProductName;
currentEmployee.Price = employee.Price;
currentEmployee.Quantity = employee.Quantity;
currentEmployee.Date = employee.Date;
currentEmployee.Available = employee.Available;
return true;
}
}
return false;
}
[HttpPost]
public bool AddAppointment(string jsonData)
{
JToken token = JObject.Parse(jsonData);
string id = (string)token.SelectToken("id");
string subject = (string)token.SelectToken("subject");
string from = (string)token.SelectToken("from");
string to = (string)token.SelectToken("to");
string description = (string)token.SelectToken("description");
string location = (string)token.SelectToken("location");
string resourceId = (string)token.SelectToken("resourceId");
DateTime fromDate =DateTime.Parse(from);
DateTime toDate = DateTime.Parse(to);
Appointment appointment = new Appointment() { Start = fromDate, End = toDate, Calendar = resourceId, Description = description, ID = id, Location = location, Name = subject };
_context.Appointments.Add(appointment);
return true;
}
[HttpPost]
public bool DeleteAppointment(string jsonData)
{
JToken token = JObject.Parse(jsonData);
string id = (string)token.SelectToken("id");
string subject = (string)token.SelectToken("subject");
string from = (string)token.SelectToken("from");
string to = (string)token.SelectToken("to");
string description = (string)token.SelectToken("description");
string location = (string)token.SelectToken("location");
string resourceId = (string)token.SelectToken("resourceId");
for (int i = 0; i < _context.Appointments.Count; i++)
{
Appointment currentAppointment = _context.Appointments[i];
if (currentAppointment.ID == id)
{
_context.Appointments.Remove(currentAppointment);
return true;
}
}
return false;
}
[HttpPost]
public bool EditAppointment(string jsonData)
{
JToken token = JObject.Parse(jsonData);
string id = (string)token.SelectToken("id");
string subject = (string)token.SelectToken("subject");
string from = (string)token.SelectToken("from");
string to = (string)token.SelectToken("to");
string description = (string)token.SelectToken("description");
string location = (string)token.SelectToken("location");
string resourceId = (string)token.SelectToken("resourceId");
DateTime fromDate = DateTime.Parse(from);
DateTime toDate = DateTime.Parse(to);
for (int i = 0; i < _context.Appointments.Count; i++)
{
Appointment currentAppointment = _context.Appointments[i];
if (currentAppointment.ID == id)
{
currentAppointment.Calendar = resourceId;
currentAppointment.Description = description;
currentAppointment.End = toDate;
currentAppointment.Start = fromDate;
currentAppointment.Location = location;
currentAppointment.Name = subject;
return true;
}
}
return false;
}
// Bar Gauge
public ActionResult BarGauge(string theme)
{
ViewData["Theme"] = theme;
return View("BarGauge/BarGauge", _context);
}
// Bullet Chart
public ActionResult BulletChart(string theme)
{
ViewData["Theme"] = theme;
return View("BulletChart/BulletChart", _context);
}
public ActionResult BulletChartRangeStyling(string theme)
{
ViewData["Theme"] = theme;
return View("BulletChart/BulletChartRangeStyling", _context);
}
// Button
public ActionResult Button(string theme)
{
ViewData["Theme"] = theme;
return View("Button/Button", _context);
}
// ButtonGroup
public ActionResult ButtonGroup(string theme)
{
ViewData["Theme"] = theme;
return View("ButtonGroup/ButtonGroup", _context);
}
// Calendar
public ActionResult Calendar(string theme)
{
ViewData["Theme"] = theme;
return View("Calendar/Calendar", _context);
}
// Chart
public ActionResult Chart(string theme)
{
ViewData["Theme"] = theme;
return View("Chart/Chart", _context.BrowserShares);
}
public ActionResult ChartBubble(string theme)
{
ViewData["Theme"] = theme;
return View("Chart/ChartBubble", _context.ChartSalesData);
}
public ActionResult ChartScatter(string theme)
{
ViewData["Theme"] = theme;
return View("Chart/ChartScatter", _context.ChartSalesData);
}
public ActionResult ChartColumn(string theme)
{
ViewData["Theme"] = theme;
return View("Chart/ChartColumn", _context.ChartData);
}
public ActionResult ChartLine(string theme)
{
ViewData["Theme"] = theme;
return View("Chart/ChartLine", _context.ChartData);
}
public ActionResult ChartRangeSelector(string theme)
{
ViewData["Theme"] = theme;
return View("Chart/ChartRangeSelector", _context.StockData);
}
// CheckBox
public ActionResult CheckBox(string theme)
{
ViewData["Theme"] = theme;
return View("CheckBox/CheckBox", _context);
}
// ColorPicker
public ActionResult ColorPicker(string theme)
{
ViewData["Theme"] = theme;
return View("ColorPicker/ColorPicker", _context);
}
// ComboBox
public ActionResult ComboBox(string theme)
{
ViewData["Theme"] = theme;
return View("ComboBox/ComboBox", _context.SalesEmployees);
}
// ComplexInput
public ActionResult ComplexInput(string theme)
{
ViewData["Theme"] = theme;
return View("ComplexInput/ComplexInput", _context);
}
// DataTable
public ActionResult DataTable(string theme)
{
ViewData["Theme"] = theme;
return View("DataTable/DataTable", _context.Employee.ToList());
}
public ActionResult DataTableSorting(string theme)
{
ViewData["Theme"] = theme;
return View("DataTable/DataTableSorting", _context.Employee.ToList());
}
public ActionResult DataTableRowDetails(string theme)
{
ViewData["Theme"] = theme;
return View("DataTable/DataTableRowDetails", _context.SalesEmployees.ToList());
}
public ActionResult DataTableServerPaging(string theme)
{
ViewData["Theme"] = theme;
return View("DataTable/DataTableServerPaging", _context.SalesEmployees.ToList());
}
public ActionResult DataTableFiltering(string theme)
{
ViewData["Theme"] = theme;
return View("DataTable/DataTableFiltering", _context.SalesEmployees.ToList());
}
public ActionResult DataTableLocalization(string theme)
{
ViewData["Theme"] = theme;
return View("DataTable/DataTableLocalization", _context.Employee.ToList());
}
// DateTimeInput
public ActionResult DateTimeInput(string theme)
{
ViewData["Theme"] = theme;
return View("DateTimeInput/DateTimeInput", _context);
}
// Docking
public ActionResult Docking(string theme)
{
ViewData["Theme"] = theme;
return View("Docking/Docking", _context);
}
// DockingLayout
public ActionResult DockingLayout(string theme)
{
ViewData["Theme"] = theme;
return View("DockingLayout/DockingLayout", _context.TreeData);
}
// DropDownList
public ActionResult DropDownList(string theme)
{
ViewData["Theme"] = theme;
return View("DropDownList/DropDownList", _context.SalesEmployees);
}
// Editor
public ActionResult Editor(string theme)
{
ViewData["Theme"] = theme;
return View("Editor/Editor", _context);
}
// Expander
public ActionResult Expander(string theme)
{
ViewData["Theme"] = theme;
return View("Expander/Expander", _context);
}
// FileUpload
public ActionResult FileUpload(string theme)
{
ViewData["Theme"] = theme;
return View("FileUpload/FileUpload", _context);
}
// FormattedInput
public ActionResult FormattedInput(string theme)
{
ViewData["Theme"] = theme;
return View("FormattedInput/FormattedInput", _context);
}
// Gauge
public ActionResult Gauge(string theme)
{
ViewData["Theme"] = theme;
return View("Gauge/Gauge", _context);
}
// GET: /Widgets//Grid
public ActionResult Grid(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/Grid", _context.Employee.ToList());
}
public ActionResult GridAggregates(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/GridAggregates", _context.SalesEmployees.ToList());
}
public ActionResult GridCellEdit(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/GridCellEdit", _context.SalesEmployees.ToList());
}
public ActionResult GridCellsRendering(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/GridCellsRendering", _context.SalesEmployees.ToList());
}
public ActionResult GridEdit(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/GridEdit", _context.SalesEmployees.ToList());
}
public ActionResult GridExport(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/GridExport", _context.SalesEmployees.ToList());
}
public ActionResult GridFilter(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/GridFilter", _context.Employee.ToList());
}
public ActionResult GridGrouping(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/GridGrouping", _context.SalesEmployees.ToList());
}
public ActionResult GridLocalization(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/GridLocalization", _context.Employee.ToList());
}
public ActionResult GridRightToLeft(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/GridRightToLeft", _context.Employee.ToList());
}
public ActionResult GridRowDetails(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/GridRowDetails", _context.SalesEmployees.ToList());
}
public ActionResult GridServerEditPagingSortingFiltering(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/GridServerPaging", _context.SalesEmployees.ToList());
}
public ActionResult GridServerPaging(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/GridServerPaging", _context.SalesEmployees.ToList());
}
public ActionResult GridSort(string theme)
{
ViewData["Theme"] = theme;
return View("Grid/GridSort", _context.SalesEmployees.ToList());
}
// Input
public ActionResult Input(string theme)
{
ViewData["Theme"] = theme;
return View("Input/Input", _context.SalesEmployees.ToList());
}
// Kanban
public ActionResult Kanban(string theme)
{
ViewData["Theme"] = theme;
return View("Kanban/Kanban", _context);
}
// Knob
public ActionResult Knob(string theme)
{
ViewData["Theme"] = theme;
return View("Knob/Knob", _context);
}
// Knob
public ActionResult Layout(string theme)
{
ViewData["Theme"] = theme;
return View("Layout/Layout", _context.TreeData);
}
// LinearGauge
public ActionResult LinearGauge(string theme)
{
ViewData["Theme"] = theme;
return View("LinearGauge/LinearGauge", _context);
}
// LinkButton
public ActionResult LinkButton(string theme)
{
ViewData["Theme"] = theme;
return View("LinkButton/LinkButton", _context);
}
// ListBox
public ActionResult ListBox(string theme)
{
ViewData["Theme"] = theme;
return View("ListBox/ListBox", _context.SalesEmployees);
}
// ListMenu
public ActionResult ListMenu(string theme)
{
ViewData["Theme"] = theme;
return View("ListMenu/ListMenu", _context);
}
// MaskedInput
public ActionResult MaskedInput(string theme)
{
ViewData["Theme"] = theme;
return View("MaskedInput/MaskedInput", _context);
}
// Menu
public ActionResult Menu(string theme)
{
ViewData["Theme"] = theme;
return View("Menu/Menu", _context);
}
// NavigationBar
public ActionResult NavigationBar(string theme)
{
ViewData["Theme"] = theme;
return View("NavigationBar/NavigationBar", _context);
}
// Notification
public ActionResult Notification(string theme)
{
ViewData["Theme"] = theme;
return View("Notification/Notification", _context);
}
// NumberInput
public ActionResult NumberInput(string theme)
{
ViewData["Theme"] = theme;
return View("NumberInput/NumberInput", _context);
}
// Panel
public ActionResult Panel(string theme)
{
ViewData["Theme"] = theme;
return View("Panel/Panel", _context);
}
// PasswordInput
public ActionResult PasswordInput(string theme)
{
ViewData["Theme"] = theme;
return View("PasswordInput/PasswordInput", _context);
}
// Popover
public ActionResult Popover(string theme)
{
ViewData["Theme"] = theme;
return View("Popover/Popover", _context);
}
// ProgressBar
public ActionResult ProgressBar(string theme)
{
ViewData["Theme"] = theme;
return View("ProgressBar/ProgressBar", _context);
}
// RadioButton
public ActionResult RadioButton(string theme)
{
ViewData["Theme"] = theme;
return View("RadioButton/RadioButton", _context);
}
// Rating
public ActionResult Rating(string theme)
{
ViewData["Theme"] = theme;
return View("Rating/Rating", _context);
}
public ActionResult RangeSelector(string theme)
{
ViewData["Theme"] = theme;
return View("RangeSelector/RangeSelector", _context);
}
// Ribbon
public ActionResult Ribbon(string theme)
{
ViewData["Theme"] = theme;
return View("Ribbon/Ribbon", _context);
}
// Scheduler
public ActionResult Scheduler(string theme)
{
ViewData["Theme"] = theme;
return View("Scheduler/Scheduler", _context);
}
public ActionResult SchedulerServerProcessing(string theme)
{
ViewData["Theme"] = theme;
return View("Scheduler/SchedulerServerProcessing", _context);
}
public ActionResult SchedulerTimelineViews(string theme)
{
ViewData["Theme"] = theme;
return View("Scheduler/SchedulerTimelineViews", _context);
}
public ActionResult SchedulerTimeRuler(string theme)
{
ViewData["Theme"] = theme;
return View("Scheduler/SchedulerTimeRuler", _context);
}
// Scrollbar
public ActionResult Scrollbar(string theme)
{
ViewData["Theme"] = theme;
return View("Scrollbar/Scrollbar", _context);
}
// ScrollView
public ActionResult ScrollView(string theme)
{
ViewData["Theme"] = theme;
return View("ScrollView/ScrollView", _context);
}
// Slider
public ActionResult Slider(string theme)
{
ViewData["Theme"] = theme;
return View("Slider/Slider", _context);
}
// Splitter
public ActionResult Splitter(string theme)
{
ViewData["Theme"] = theme;
return View("Splitter/Splitter", _context);
}
// SwitchButton
public ActionResult SwitchButton(string theme)
{
ViewData["Theme"] = theme;
return View("SwitchButton/SwitchButton", _context);
}
// Tabs
public ActionResult Tabs(string theme)
{
ViewData["Theme"] = theme;
return View("Tabs/Tabs", _context);
}
// TextArea
public ActionResult TextArea(string theme)
{
ViewData["Theme"] = theme;
return View("TextArea/TextArea", _context.SalesEmployees);
}
// Toolbar
public ActionResult Toolbar(string theme)
{
ViewData["Theme"] = theme;
return View("Toolbar/Toolbar", _context);
}
// Tooltip
public ActionResult Tooltip(string theme)
{
ViewData["Theme"] = theme;
return View("Tooltip/Tooltip", _context);
}
// Tree
public ActionResult Tree(string theme)
{
ViewData["Theme"] = theme;
return View("Tree/Tree", _context.TreeData);
}
public ActionResult TreeHtmlStructure(string theme)
{
ViewData["Theme"] = theme;
return View("Tree/TreeHtmlStructure", _context);
}
// Tree Grid
public ActionResult TreeGrid(string theme)
{
ViewData["Theme"] = theme;
return View("TreeGrid/TreeGrid", _context.Employee.ToList());
}
public ActionResult TreeGridLoadOnDemand(string theme)
{
ViewData["Theme"] = theme;
return View("TreeGrid/TreeGridLoadOnDemand", _context.SalesEmployees.ToList());
}
public ActionResult TreeGridConditionalFormatting(string theme)
{
ViewData["Theme"] = theme;
return View("TreeGrid/TreeGridConditionalFormatting", _context.SalesEmployees.ToList());
}
public ActionResult TreeGridLocalization(string theme)
{
ViewData["Theme"] = theme;
return View("TreeGrid/TreeGridLocalization", _context.Employee.ToList());
}
// TreeMap
public ActionResult TreeMap(string theme)
{
ViewData["Theme"] = theme;
return View("TreeMap/TreeMap", _context.Employee);
}
// Validator
public ActionResult Validator(string theme)
{
ViewData["Theme"] = theme;
return View("Validator/Validator", _context.Employee);
}
// Window
public ActionResult Window(string theme)
{
ViewData["Theme"] = theme;
return View("Window/Window", _context.SalesEmployees);
}
// GET: /Widgets//Tree
//public ActionResult Tree()
//{
// object items = Request.Form["tree"];
// if (null == items)
// items = "";
// ViewData["Tree Items"] = items;
// return View();
//}
[HttpPost]
public void Year()
{
this._context.ContractDuration = Contract.Year;
}
[HttpPost]
public void HalfYear()
{
this._context.ContractDuration = Contract.HalfYear;
}
[HttpPost]
public void QuarterYear()
{
this._context.ContractDuration = Contract.QuarterYear;
}
[HttpPost]
public void Month()
{
this._context.ContractDuration = Contract.Month;
}
[HttpPost]
public void Increment()
{
this._context.ClickCount++;
}
[HttpPost]
public int ButtonValue()
{
return _context.ClickCount;
}
// GET: /Widgets//Store
public ActionResult Store()
{
string shirt = Request.Form["shirt"];
if (shirt != null)
{
string price = "0.00";
switch (shirt)
{
case "Brown":
price = "5.00";
break;
case "Red":
price = "6.00";
break;
case "Green":
price = "7.75";
break;
case "Black":
price = "8.25";
break;
case "White":
price = "9.50";
break;
}
return Json(price);
}
ViewData["Color"] = Request.Form["shirtDropdownList"];
ViewData["Size"] = Request.Form["shirtDropDownListSize"];
ViewData["Price"] = Request.Form["priceInput"];
return View();
}
// /Widgets/LoginFailed
public ActionResult LoginFailed()
{
return View();
}
// /Widgets/Login
[HttpPost]
public ActionResult Login()
{
ViewData["username"] = Request.Form["username"];
ViewData["password"] = Request.Form["password"];
ViewData["rememberme"] = Request.Form["rememberMe"];
if (Request.Form["username"] != "admin" || Request.Form["password"] != "admin123")
{
return RedirectToAction("LoginFailed");
}
return View();
}
// /Widgets/RegistrationForm
public ActionResult RegistrationForm(string theme)
{
ViewData["Theme"] = theme;
return View("RegistrationForm");
}
// /Widgets/LoginForm
public ActionResult LoginForm(string theme)
{
ViewData["Theme"] = theme;
return View("LoginForm");
}
[HttpPost]
public FileContentResult UploadFile()
{
FormFileCollection files = (FormFileCollection)Request.Form.Files;
Stream file = files[0].OpenReadStream();
byte[] binaryWriteArray = new byte[file.Length];
file.Read(binaryWriteArray, 0,
(int)file.Length);
string contentDisposition = Request.Form.Files[0].ContentDisposition;
string fileName = contentDisposition.Substring(contentDisposition.IndexOf("filename=") + 10).Replace("\"", "");
FileContentResult result = new FileContentResult(binaryWriteArray, files[0].ContentType)
{
FileDownloadName = fileName
};
file.Dispose();
return result;
}
[HttpPost]
public ActionResult CarFeatures(string data)
{
for (int i = 0; i < _context.CarFeatures.Count; i++)
{
bool newValue = Boolean.Parse(Request.Form["carFeatures"][i]);
_context.CarFeatures[i] = new KeyValuePair<string, bool>(_context.CarFeatures[i].Key, newValue);
}
return View("CheckBox/CheckBox", _context);
}
}
}
| |
// 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.Arm\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.Arm;
namespace JIT.HardwareIntrinsics.Arm
{
public static partial class Program
{
private static void Abs_Vector128_UInt32()
{
var test = new SimpleUnaryOpTest__Abs_Vector128_UInt32();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (AdvSimd.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
}
// Validates passing a static member works
test.RunClsVarScenario();
if (AdvSimd.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 (AdvSimd.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
}
// Validates passing the field of a local class works
test.RunClassLclFldScenario();
if (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 (AdvSimd.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 SimpleUnaryOpTest__Abs_Vector128_UInt32
{
private struct DataTable
{
private byte[] inArray1;
private byte[] outArray;
private GCHandle inHandle1;
private GCHandle outHandle;
private ulong alignment;
public DataTable(Int32[] inArray1, UInt32[] outArray, int alignment)
{
int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int32>();
int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<UInt32>();
if ((alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfoutArray)
{
throw new ArgumentException("Invalid value of alignment");
}
this.inArray1 = new byte[alignment * 2];
this.outArray = new byte[alignment * 2];
this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned);
this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned);
this.alignment = (ulong)alignment;
Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int32, byte>(ref inArray1[0]), (uint)sizeOfinArray1);
}
public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment);
public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment);
public void Dispose()
{
inHandle1.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<Int32> _fld1;
public static TestStruct Create()
{
var testStruct = new TestStruct();
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref testStruct._fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
return testStruct;
}
public void RunStructFldScenario(SimpleUnaryOpTest__Abs_Vector128_UInt32 testClass)
{
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
public void RunStructFldScenario_Load(SimpleUnaryOpTest__Abs_Vector128_UInt32 testClass)
{
fixed (Vector128<Int32>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Int32*)(pFld1))
);
Unsafe.Write(testClass._dataTable.outArrayPtr, result);
testClass.ValidateResult(_fld1, testClass._dataTable.outArrayPtr);
}
}
}
private static readonly int LargestVectorSize = 16;
private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32);
private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<UInt32>>() / sizeof(UInt32);
private static Int32[] _data1 = new Int32[Op1ElementCount];
private static Vector128<Int32> _clsVar1;
private Vector128<Int32> _fld1;
private DataTable _dataTable;
static SimpleUnaryOpTest__Abs_Vector128_UInt32()
{
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
}
public SimpleUnaryOpTest__Abs_Vector128_UInt32()
{
Succeeded = true;
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetInt32(); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int32>>());
for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = -TestLibrary.Generator.GetInt32(); }
_dataTable = new DataTable(_data1, new UInt32[RetElementCount], LargestVectorSize);
}
public bool IsSupported => AdvSimd.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead));
var result = AdvSimd.Abs(
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load));
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load));
var result = typeof(AdvSimd).GetMethod(nameof(AdvSimd.Abs), new Type[] { typeof(Vector128<Int32>) })
.Invoke(null, new object[] {
AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt32>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario));
var result = AdvSimd.Abs(
_clsVar1
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
public void RunClsVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load));
fixed (Vector128<Int32>* pClsVar1 = &_clsVar1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Int32*)(pClsVar1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _dataTable.outArrayPtr);
}
}
public void RunLclVarScenario_UnsafeRead()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead));
var op1 = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr);
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load));
var op1 = AdvSimd.LoadVector128((Int32*)(_dataTable.inArray1Ptr));
var result = AdvSimd.Abs(op1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(op1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario));
var test = new SimpleUnaryOpTest__Abs_Vector128_UInt32();
var result = AdvSimd.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunClassLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load));
var test = new SimpleUnaryOpTest__Abs_Vector128_UInt32();
fixed (Vector128<Int32>* pFld1 = &test._fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Int32*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
}
public void RunClassFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario));
var result = AdvSimd.Abs(_fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
public void RunClassFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load));
fixed (Vector128<Int32>* pFld1 = &_fld1)
{
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Int32*)(pFld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _dataTable.outArrayPtr);
}
}
public void RunStructLclFldScenario()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario));
var test = TestStruct.Create();
var result = AdvSimd.Abs(test._fld1);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _dataTable.outArrayPtr);
}
public void RunStructLclFldScenario_Load()
{
TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load));
var test = TestStruct.Create();
var result = AdvSimd.Abs(
AdvSimd.LoadVector128((Int32*)(&test._fld1))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, _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<Int32> op1, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.WriteUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), op1);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(void* op1, void* result, [CallerMemberName] string method = "")
{
Int32[] inArray1 = new Int32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int32>>());
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<UInt32>>());
ValidateResult(inArray1, outArray, method);
}
private void ValidateResult(Int32[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
bool succeeded = true;
if (result[0] != (uint)Math.Abs(firstOp[0]))
{
succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (result[i] != (uint)Math.Abs(firstOp[i]))
{
succeeded = false;
break;
}
}
}
if (!succeeded)
{
TestLibrary.TestFramework.LogInformation($"{nameof(AdvSimd)}.{nameof(AdvSimd.Abs)}<UInt32>(Vector128<Int32>): {method} failed:");
TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})");
TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})");
TestLibrary.TestFramework.LogInformation(string.Empty);
Succeeded = false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Licensed under the MIT License. See LICENSE.txt in the project root for license information.
using System;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.TestPlatform.UnitTestFramework;
using System.Numerics;
namespace NumericsTests
{
[TestClass()]
public class Vector3Test
{
// A test for Cross (Vector3, Vector3)
[TestMethod]
public void Vector3CrossTest()
{
Vector3 a = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 b = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 expected = new Vector3(0.0f, 0.0f, 1.0f);
Vector3 actual;
actual = Vector3.Cross(a, b);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Cross did not return the expected value.");
}
// A test for Cross (Vector3, Vector3)
// Cross test of the same vector
[TestMethod]
public void Vector3CrossTest1()
{
Vector3 a = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 b = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 expected = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 actual = Vector3.Cross(a, b);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Cross did not return the expected value.");
}
// A test for Distance (Vector3, Vector3)
[TestMethod]
public void Vector3DistanceTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float expected = (float)System.Math.Sqrt(27);
float actual;
actual = Vector3.Distance(a, b);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Distance did not return the expected value.");
}
// A test for Distance (Vector3, Vector3)
// Distance from the same point
[TestMethod]
public void Vector3DistanceTest1()
{
Vector3 a = new Vector3(1.051f, 2.05f, 3.478f);
Vector3 b = new Vector3(new Vector2(1.051f, 0.0f), 1);
b.Y = 2.05f;
b.Z = 3.478f;
float actual = Vector3.Distance(a, b);
Assert.AreEqual(0.0f, actual, "Vector3.Distance did not return the expected value.");
}
// A test for DistanceSquared (Vector3, Vector3)
[TestMethod]
public void Vector3DistanceSquaredTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float expected = 27.0f;
float actual;
actual = Vector3.DistanceSquared(a, b);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.DistanceSquared did not return the expected value.");
}
// A test for Dot (Vector3, Vector3)
[TestMethod]
public void Vector3DotTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float expected = 32.0f;
float actual;
actual = Vector3.Dot(a, b);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Dot did not return the expected value.");
}
// A test for Dot (Vector3, Vector3)
// Dot test for perpendicular vector
[TestMethod]
public void Vector3DotTest1()
{
Vector3 a = new Vector3(1.55f, 1.55f, 1);
Vector3 b = new Vector3(2.5f, 3, 1.5f);
Vector3 c = Vector3.Cross(a, b);
float expected = 0.0f;
float actual1 = Vector3.Dot(a, c);
float actual2 = Vector3.Dot(b, c);
Assert.IsTrue(MathHelper.Equal(expected, actual1), "Vector3.Dot did not return the expected value.");
Assert.IsTrue(MathHelper.Equal(expected, actual2), "Vector3.Dot did not return the expected value.");
}
// A test for Length ()
[TestMethod]
public void Vector3LengthTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
float z = 3.0f;
Vector3 target = new Vector3(a, z);
float expected = (float)System.Math.Sqrt(14.0f);
float actual;
actual = target.Length();
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Length did not return the expected value.");
}
// A test for Length ()
// Length test where length is zero
[TestMethod]
public void Vector3LengthTest1()
{
Vector3 target = new Vector3();
float expected = 0.0f;
float actual = target.Length();
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Length did not return the expected value.");
}
// A test for LengthSquared ()
[TestMethod]
public void Vector3LengthSquaredTest()
{
Vector2 a = new Vector2(1.0f, 2.0f);
float z = 3.0f;
Vector3 target = new Vector3(a, z);
float expected = 14.0f;
float actual;
actual = target.LengthSquared();
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.LengthSquared did not return the expected value.");
}
// A test for Min (Vector3, Vector3)
[TestMethod]
public void Vector3MinTest()
{
Vector3 a = new Vector3(-1.0f, 4.0f, -3.0f);
Vector3 b = new Vector3(2.0f, 1.0f, -1.0f);
Vector3 expected = new Vector3(-1.0f, 1.0f, -3.0f);
Vector3 actual;
actual = Vector3.Min(a, b);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Min did not return the expected value.");
}
// A test for Max (Vector3, Vector3)
[TestMethod]
public void Vector3MaxTest()
{
Vector3 a = new Vector3(-1.0f, 4.0f, -3.0f);
Vector3 b = new Vector3(2.0f, 1.0f, -1.0f);
Vector3 expected = new Vector3(2.0f, 4.0f, -1.0f);
Vector3 actual;
actual = Vector3.Max(a, b);
Assert.IsTrue(MathHelper.Equal(expected, actual), "vector3.Max did not return the expected value.");
}
[TestMethod]
public void Vector3MinMaxCodeCoverageTest()
{
Vector3 min = Vector3.Zero;
Vector3 max = Vector3.One;
Vector3 actual;
// Min.
actual = Vector3.Min(min, max);
Assert.AreEqual(actual, min);
actual = Vector3.Min(max, min);
Assert.AreEqual(actual, min);
// Max.
actual = Vector3.Max(min, max);
Assert.AreEqual(actual, max);
actual = Vector3.Max(max, min);
Assert.AreEqual(actual, max);
}
// A test for Lerp (Vector3, Vector3, float)
[TestMethod]
public void Vector3LerpTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = 0.5f;
Vector3 expected = new Vector3(2.5f, 3.5f, 4.5f);
Vector3 actual;
actual = Vector3.Lerp(a, b, t);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3, Vector3, float)
// Lerp test with factor zero
[TestMethod]
public void Vector3LerpTest1()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = 0.0f;
Vector3 expected = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3, Vector3, float)
// Lerp test with factor one
[TestMethod]
public void Vector3LerpTest2()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = 1.0f;
Vector3 expected = new Vector3(4.0f, 5.0f, 6.0f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3, Vector3, float)
// Lerp test with factor > 1
[TestMethod]
public void Vector3LerpTest3()
{
Vector3 a = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = 2.0f;
Vector3 expected = new Vector3(8.0f, 10.0f, 12.0f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3, Vector3, float)
// Lerp test with factor < 0
[TestMethod]
public void Vector3LerpTest4()
{
Vector3 a = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
float t = -2.0f;
Vector3 expected = new Vector3(-8.0f, -10.0f, -12.0f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Lerp did not return the expected value.");
}
// A test for Lerp (Vector3, Vector3, float)
// Lerp test from the same point
[TestMethod]
public void Vector3LerpTest5()
{
Vector3 a = new Vector3(1.68f, 2.34f, 5.43f);
Vector3 b = a;
float t = 0.18f;
Vector3 expected = new Vector3(1.68f, 2.34f, 5.43f);
Vector3 actual = Vector3.Lerp(a, b, t);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Lerp did not return the expected value.");
}
// A test for Reflect (Vector3, Vector3)
[TestMethod]
public void Vector3ReflectTest()
{
Vector3 a = Vector3.Normalize(new Vector3(1.0f, 1.0f, 1.0f));
// Reflect on XZ plane.
Vector3 n = new Vector3(0.0f, 1.0f, 0.0f);
Vector3 expected = new Vector3(a.X, -a.Y, a.Z);
Vector3 actual = Vector3.Reflect(a, n);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Reflect did not return the expected value.");
// Reflect on XY plane.
n = new Vector3(0.0f, 0.0f, 1.0f);
expected = new Vector3(a.X, a.Y, -a.Z);
actual = Vector3.Reflect(a, n);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Reflect did not return the expected value.");
// Reflect on YZ plane.
n = new Vector3(1.0f, 0.0f, 0.0f);
expected = new Vector3(-a.X, a.Y, a.Z);
actual = Vector3.Reflect(a, n);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Reflect did not return the expected value.");
}
// A test for Reflect (Vector3, Vector3)
// Reflection when normal and source are the same
[TestMethod]
public void Vector3ReflectTest1()
{
Vector3 n = new Vector3(0.45f, 1.28f, 0.86f);
n = Vector3.Normalize(n);
Vector3 a = n;
Vector3 expected = -n;
Vector3 actual = Vector3.Reflect(a, n);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Reflect did not return the expected value.");
}
// A test for Reflect (Vector3, Vector3)
// Reflection when normal and source are negation
[TestMethod]
public void Vector3ReflectTest2()
{
Vector3 n = new Vector3(0.45f, 1.28f, 0.86f);
n = Vector3.Normalize(n);
Vector3 a = -n;
Vector3 expected = n;
Vector3 actual = Vector3.Reflect(a, n);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Reflect did not return the expected value.");
}
// A test for Reflect (Vector3, Vector3)
// Reflection when normal and source are perpendicular (a dot n = 0)
[TestMethod]
public void Vector3ReflectTest3()
{
Vector3 n = new Vector3(0.45f, 1.28f, 0.86f);
Vector3 temp = new Vector3(1.28f, 0.45f, 0.01f);
// find a perpendicular vector of n
Vector3 a = Vector3.Cross(temp, n);
Vector3 expected = a;
Vector3 actual = Vector3.Reflect(a, n);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Reflect did not return the expected value.");
}
// A test for Transform(Vector3, Matrix4x4)
[TestMethod]
public void Vector3TransformTest()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Vector3 expected = new Vector3(12.191987f, 21.533493f, 32.616024f);
Vector3 actual;
actual = Vector3.Transform(v, m);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Transform did not return the expected value.");
}
// A test for Clamp (Vector3, Vector3, Vector3)
[TestMethod]
public void Vector3ClampTest()
{
Vector3 a = new Vector3(0.5f, 0.3f, 0.33f);
Vector3 min = new Vector3(0.0f, 0.1f, 0.13f);
Vector3 max = new Vector3(1.0f, 1.1f, 1.13f);
// Normal case.
// Case N1: specfied value is in the range.
Vector3 expected = new Vector3(0.5f, 0.3f, 0.33f);
Vector3 actual = Vector3.Clamp(a, min, max);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Clamp did not return the expected value.");
// Normal case.
// Case N2: specfied value is bigger than max value.
a = new Vector3(2.0f, 3.0f, 4.0f);
expected = max;
actual = Vector3.Clamp(a, min, max);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Clamp did not return the expected value.");
// Case N3: specfied value is smaller than max value.
a = new Vector3(-2.0f, -3.0f, -4.0f);
expected = min;
actual = Vector3.Clamp(a, min, max);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Clamp did not return the expected value.");
// Case N4: combination case.
a = new Vector3(-2.0f, 0.5f, 4.0f);
expected = new Vector3(min.X, a.Y, max.Z);
actual = Vector3.Clamp(a, min, max);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Clamp did not return the expected value.");
// User specfied min value is bigger than max value.
max = new Vector3(0.0f, 0.1f, 0.13f);
min = new Vector3(1.0f, 1.1f, 1.13f);
// Case W1: specfied value is in the range.
a = new Vector3(0.5f, 0.3f, 0.33f);
expected = min;
actual = Vector3.Clamp(a, min, max);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Clamp did not return the expected value.");
// Normal case.
// Case W2: specfied value is bigger than max and min value.
a = new Vector3(2.0f, 3.0f, 4.0f);
expected = min;
actual = Vector3.Clamp(a, min, max);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Clamp did not return the expected value.");
// Case W3: specfied value is smaller than min and max value.
a = new Vector3(-2.0f, -3.0f, -4.0f);
expected = min;
actual = Vector3.Clamp(a, min, max);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Clamp did not return the expected value.");
}
// A test for TransformNormal (Vector3, Matrix4x4)
[TestMethod]
public void Vector3TransformNormalTest()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
m.M41 = 10.0f;
m.M42 = 20.0f;
m.M43 = 30.0f;
Vector3 expected = new Vector3(2.19198728f, 1.53349364f, 2.61602545f);
Vector3 actual;
actual = Vector3.TransformNormal(v, m);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.TransformNormal did not return the expected value.");
}
// A test for Transform (Vector3, Quaternion)
[TestMethod]
public void Vector3TransformByQuaternionTest()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Matrix4x4 m =
Matrix4x4.CreateRotationX(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationY(MathHelper.ToRadians(30.0f)) *
Matrix4x4.CreateRotationZ(MathHelper.ToRadians(30.0f));
Quaternion q = Quaternion.CreateFromRotationMatrix(m);
Vector3 expected = Vector3.Transform(v, m);
Vector3 actual = Vector3.Transform(v, q);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Transform did not return the expected value.");
}
// A test for Transform (Vector3, Quaternion)
// Transform vector3 with zero quaternion
[TestMethod]
public void Vector3TransformByQuaternionTest1()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Quaternion q = new Quaternion();
Vector3 expected = v;
Vector3 actual = Vector3.Transform(v, q);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Transform did not return the expected value.");
}
// A test for Transform (Vector3, Quaternion)
// Transform vector3 with identity quaternion
[TestMethod]
public void Vector3TransformByQuaternionTest2()
{
Vector3 v = new Vector3(1.0f, 2.0f, 3.0f);
Quaternion q = Quaternion.Identity;
Vector3 expected = v;
Vector3 actual = Vector3.Transform(v, q);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Transform did not return the expected value.");
}
// A test for Normalize (Vector3)
[TestMethod]
public void Vector3NormalizeTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(
0.26726124191242438468455348087975f,
0.53452248382484876936910696175951f,
0.80178372573727315405366044263926f);
Vector3 actual;
actual = Vector3.Normalize(a);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Normalize did not return the expected value.");
}
// A test for Normalize (Vector3)
// Normalize vector of length one
[TestMethod]
public void Vector3NormalizeTest1()
{
Vector3 a = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 expected = new Vector3(1.0f, 0.0f, 0.0f);
Vector3 actual = Vector3.Normalize(a);
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.Normalize did not return the expected value.");
}
// A test for Normalize (Vector3)
// Normalize vector of length zero
[TestMethod]
public void Vector3NormalizeTest2()
{
Vector3 a = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 expected = new Vector3(0.0f, 0.0f, 0.0f);
Vector3 actual = Vector3.Normalize(a);
Assert.IsTrue(float.IsNaN(actual.X) && float.IsNaN(actual.Y) && float.IsNaN(actual.Z), "Vector3.Normalize did not return the expected value.");
}
// A test for operator - (Vector3)
[TestMethod]
public void Vector3UnaryNegationTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(-1.0f, -2.0f, -3.0f);
Vector3 actual;
actual = -a;
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.operator - did not return the expected value.");
}
// A test for operator - (Vector3, Vector3)
[TestMethod]
public void Vector3SubtractionTest()
{
Vector3 a = new Vector3(4.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 5.0f, 7.0f);
Vector3 expected = new Vector3(3.0f, -3.0f, -4.0f);
Vector3 actual;
actual = a - b;
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.operator - did not return the expected value.");
}
// A test for operator * (Vector3, float)
[TestMethod]
public void Vector3MultiplyTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
float factor = 2.0f;
Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f);
Vector3 actual;
actual = a * factor;
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.operator * did not return the expected value.");
}
// A test for operator * (Vector3, Vector3)
[TestMethod]
public void Vector3MultiplyTest1()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
Vector3 expected = new Vector3(4.0f, 10.0f, 18.0f);
Vector3 actual;
actual = a * b;
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.operator * did not return the expected value.");
}
// A test for operator / (Vector3, float)
[TestMethod]
public void Vector3DivisionTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
float div = 2.0f;
Vector3 expected = new Vector3(0.5f, 1.0f, 1.5f);
Vector3 actual;
actual = a / div;
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.operator / did not return the expected value.");
}
// A test for operator / (Vector3, Vector3)
[TestMethod]
public void Vector3DivisionTest1()
{
Vector3 a = new Vector3(4.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 5.0f, 6.0f);
Vector3 expected = new Vector3(4.0f, 0.4f, 0.5f);
Vector3 actual;
actual = a / b;
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.operator / did not return the expected value.");
}
// A test for operator / (Vector3, Vector3)
// Divide by zero
[TestMethod]
public void Vector3DivisionTest2()
{
Vector3 a = new Vector3(-2.0f, 3.0f, float.MaxValue);
float div = 0.0f;
Vector3 actual = a / div;
Assert.IsTrue(float.IsNegativeInfinity(actual.X), "Vector3.operator / did not return the expected value.");
Assert.IsTrue(float.IsPositiveInfinity(actual.Y), "Vector3.operator / did not return the expected value.");
Assert.IsTrue(float.IsPositiveInfinity(actual.Z), "Vector3.operator / did not return the expected value.");
}
// A test for operator / (Vector3, Vector3)
// Divide by zero
[TestMethod]
public void Vector3DivisionTest3()
{
Vector3 a = new Vector3(0.047f, -3.0f, float.NegativeInfinity);
Vector3 b = new Vector3();
Vector3 actual = a / b;
Assert.IsTrue(float.IsPositiveInfinity(actual.X), "Vector3.operator / did not return the expected value.");
Assert.IsTrue(float.IsNegativeInfinity(actual.Y), "Vector3.operator / did not return the expected value.");
Assert.IsTrue(float.IsNegativeInfinity(actual.Z), "Vector3.operator / did not return the expected value.");
}
// A test for operator + (Vector3, Vector3)
[TestMethod]
public void Vector3AdditionTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(4.0f, 5.0f, 6.0f);
Vector3 expected = new Vector3(5.0f, 7.0f, 9.0f);
Vector3 actual;
actual = a + b;
Assert.IsTrue(MathHelper.Equal(expected, actual), "Vector3.operator + did not return the expected value.");
}
// A test for Vector3 (float, float, float)
[TestMethod]
public void Vector3ConstructorTest()
{
float x = 1.0f;
float y = 2.0f;
float z = 3.0f;
Vector3 target = new Vector3(x, y, z);
Assert.IsTrue(MathHelper.Equal(target.X, x) && MathHelper.Equal(target.Y, y) && MathHelper.Equal(target.Z, z), "Vector3.constructor (x,y,z) did not return the expected value.");
}
// A test for Vector3 (Vector2, float)
[TestMethod]
public void Vector3ConstructorTest1()
{
Vector2 a = new Vector2(1.0f, 2.0f);
float z = 3.0f;
Vector3 target = new Vector3(a, z);
Assert.IsTrue(MathHelper.Equal(target.X, a.X) && MathHelper.Equal(target.Y, a.Y) && MathHelper.Equal(target.Z, z), "Vector3.constructor (Vector2,z) did not return the expected value.");
}
// A test for Vector3 ()
// Constructor with no parameter
[TestMethod]
public void Vector3ConstructorTest3()
{
Vector3 a = new Vector3();
Assert.AreEqual(a.X, 0.0f, "Vector3.constructor () did not return the expected value.");
Assert.AreEqual(a.Y, 0.0f, "Vector3.constructor () did not return the expected value.");
Assert.AreEqual(a.Z, 0.0f, "Vector3.constructor () did not return the expected value.");
}
// A test for Vector2 (float, float)
// Constructor with special floating values
[TestMethod]
public void Vector3ConstructorTest4()
{
Vector3 target = new Vector3(float.NaN, float.MaxValue, float.PositiveInfinity);
Assert.IsTrue(float.IsNaN(target.X), "Vector3.constructor (Vector3) did not return the expected value.");
Assert.IsTrue(float.Equals(float.MaxValue, target.Y), "Vector3.constructor (Vector3) did not return the expected value.");
Assert.IsTrue(float.IsPositiveInfinity(target.Z), "Vector3.constructor (Vector3) did not return the expected value.");
}
// A test for ToString ()
[TestMethod]
public void Vector3ToStringTest()
{
Vector3 target = new Vector3(1.0f, 2.2f, 3.3f);
string expected = "{X:1 Y:2.2 Z:3.3}";
string actual;
actual = target.ToString();
Assert.AreEqual(expected, actual, "Vector3.ToString did not return the expected value.");
}
// A test for Add (Vector3, Vector3)
[TestMethod]
public void Vector3AddTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(5.0f, 6.0f, 7.0f);
Vector3 expected = new Vector3(6.0f, 8.0f, 10.0f);
Vector3 actual;
actual = Vector3.Add(a, b);
Assert.AreEqual(expected, actual, "Vector3.Add did not return the expected value.");
}
// A test for Divide (Vector3, float)
[TestMethod]
public void Vector3DivideTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
float div = 2.0f;
Vector3 expected = new Vector3(0.5f, 1.0f, 1.5f);
Vector3 actual;
actual = Vector3.Divide(a, div);
Assert.AreEqual(expected, actual, "Vector3.Divide did not return the expected value.");
}
// A test for Divide (Vector3, Vector3)
[TestMethod]
public void Vector3DivideTest1()
{
Vector3 a = new Vector3(1.0f, 6.0f, 7.0f);
Vector3 b = new Vector3(5.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(1.0f / 5.0f, 6.0f / 2.0f, 7.0f / 3.0f);
Vector3 actual;
actual = Vector3.Divide(a, b);
Assert.AreEqual(expected, actual, "Vector3.Divide did not return the expected value.");
}
// A test for Equals (object)
[TestMethod]
public void Vector3EqualsTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 2.0f, 3.0f);
// case 1: compare between same values
object obj = b;
bool expected = true;
bool actual = a.Equals(obj);
Assert.AreEqual(expected, actual, "Vector3.Equals did not return the expected value.");
// case 2: compare between different values
b.X = 10.0f;
obj = b;
expected = false;
actual = a.Equals(obj);
Assert.AreEqual(expected, actual, "Vector3.Equals did not return the expected value.");
// case 3: compare between different types.
obj = new Quaternion();
expected = false;
actual = a.Equals(obj);
Assert.AreEqual(expected, actual, "Vector3.Equals did not return the expected value.");
// case 3: compare against null.
obj = null;
expected = false;
actual = a.Equals(obj);
Assert.AreEqual(expected, actual, "Vector3.Equals did not return the expected value.");
}
// A test for GetHashCode ()
[TestMethod]
public void Vector3GetHashCodeTest()
{
Vector3 target = new Vector3(1.0f, 2.0f, 3.0f);
int expected = target.X.GetHashCode() + target.Y.GetHashCode() + target.Z.GetHashCode();
int actual;
actual = target.GetHashCode();
Assert.AreEqual(expected, actual, "Vector3.GetHashCode did not return the expected value.");
}
// A test for Multiply (Vector3, float)
[TestMethod]
public void Vector3MultiplyTest2()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
float factor = 2.0f;
Vector3 expected = new Vector3(2.0f, 4.0f, 6.0f);
Vector3 actual = Vector3.Multiply(a, factor);
Assert.AreEqual(expected, actual, "Vector3.Multiply did not return the expected value.");
}
// A test for Multiply (Vector3, Vector3)
[TestMethod]
public void Vector3MultiplyTest3()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(5.0f, 6.0f, 7.0f);
Vector3 expected = new Vector3(5.0f, 12.0f, 21.0f);
Vector3 actual;
actual = Vector3.Multiply(a, b);
Assert.AreEqual(expected, actual, "Vector3.Multiply did not return the expected value.");
}
// A test for Negate (Vector3)
[TestMethod]
public void Vector3NegateTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(-1.0f, -2.0f, -3.0f);
Vector3 actual;
actual = Vector3.Negate(a);
Assert.AreEqual(expected, actual, "Vector3.Negate did not return the expected value.");
}
// A test for operator != (Vector3, Vector3)
[TestMethod]
public void Vector3InequalityTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 2.0f, 3.0f);
// case 1: compare between same values
bool expected = false;
bool actual = a != b;
Assert.AreEqual(expected, actual, "Vector3.operator != did not return the expected value.");
// case 2: compare between different values
b.X = 10.0f;
expected = true;
actual = a != b;
Assert.AreEqual(expected, actual, "Vector3.operator != did not return the expected value.");
}
// A test for operator == (Vector3, Vector3)
[TestMethod]
public void Vector3EqualityTest()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 2.0f, 3.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a == b;
Assert.AreEqual(expected, actual, "Vector3.operator == did not return the expected value.");
// case 2: compare between different values
b.X = 10.0f;
expected = false;
actual = a == b;
Assert.AreEqual(expected, actual, "Vector3.operator == did not return the expected value.");
}
// A test for Subtract (Vector3, Vector3)
[TestMethod]
public void Vector3SubtractTest()
{
Vector3 a = new Vector3(1.0f, 6.0f, 3.0f);
Vector3 b = new Vector3(5.0f, 2.0f, 3.0f);
Vector3 expected = new Vector3(-4.0f, 4.0f, 0.0f);
Vector3 actual;
actual = Vector3.Subtract(a, b);
Assert.AreEqual(expected, actual, "Vector3.Subtract did not return the expected value.");
}
// A test for One
[TestMethod]
public void Vector3OneTest()
{
Vector3 val = new Vector3(1.0f, 1.0f, 1.0f);
Assert.AreEqual(val, Vector3.One, "Vector3.One was not set correctly.");
}
// A test for UnitX
[TestMethod]
public void Vector3UnitXTest()
{
Vector3 val = new Vector3(1.0f, 0.0f, 0.0f);
Assert.AreEqual(val, Vector3.UnitX, "Vector3.UnitX was not set correctly.");
}
// A test for UnitY
[TestMethod]
public void Vector3UnitYTest()
{
Vector3 val = new Vector3(0.0f, 1.0f, 0.0f);
Assert.AreEqual(val, Vector3.UnitY, "Vector3.UnitY was not set correctly.");
}
// A test for UnitZ
[TestMethod]
public void Vector3UnitZTest()
{
Vector3 val = new Vector3(0.0f, 0.0f, 1.0f);
Assert.AreEqual(val, Vector3.UnitZ, "Vector3.UnitZ was not set correctly.");
}
// A test for Zero
[TestMethod]
public void Vector3ZeroTest()
{
Vector3 val = new Vector3(0.0f, 0.0f, 0.0f);
Assert.AreEqual(val, Vector3.Zero, "Vector3.Zero was not set correctly.");
}
// A test for Equals (Vector3)
[TestMethod]
public void Vector3EqualsTest1()
{
Vector3 a = new Vector3(1.0f, 2.0f, 3.0f);
Vector3 b = new Vector3(1.0f, 2.0f, 3.0f);
// case 1: compare between same values
bool expected = true;
bool actual = a.Equals(b);
Assert.AreEqual(expected, actual, "Vector3.Equals did not return the expected value.");
// case 2: compare between different values
b.X = 10.0f;
expected = false;
actual = a.Equals(b);
Assert.AreEqual(expected, actual, "Vector3.Equals did not return the expected value.");
}
// A test for Vector3 (float)
[TestMethod]
public void Vector3ConstructorTest5()
{
float value = 1.0f;
Vector3 target = new Vector3(value);
Vector3 expected = new Vector3(value, value, value);
Assert.AreEqual(expected, target, "Vector3.cstr did not return the expected value.");
value = 2.0f;
target = new Vector3(value);
expected = new Vector3(value, value, value);
Assert.AreEqual(expected, target, "Vector3.cstr did not return the expected value.");
}
// A test for Vector3 comparison involving NaN values
[TestMethod]
public void Vector3EqualsNanTest()
{
Vector3 a = new Vector3(float.NaN, 0, 0);
Vector3 b = new Vector3(0, float.NaN, 0);
Vector3 c = new Vector3(0, 0, float.NaN);
Assert.IsFalse(a == Vector3.Zero);
Assert.IsFalse(b == Vector3.Zero);
Assert.IsFalse(c == Vector3.Zero);
Assert.IsTrue(a != Vector3.Zero);
Assert.IsTrue(b != Vector3.Zero);
Assert.IsTrue(c != Vector3.Zero);
Assert.IsFalse(a.Equals(Vector3.Zero));
Assert.IsFalse(b.Equals(Vector3.Zero));
Assert.IsFalse(c.Equals(Vector3.Zero));
// Counterintuitive result - IEEE rules for NaN comparison are weird!
Assert.IsFalse(a.Equals(a));
Assert.IsFalse(b.Equals(b));
Assert.IsFalse(c.Equals(c));
}
// A test to make sure these types are blittable directly into GPU buffer memory layouts
[TestMethod]
public unsafe void Vector3SizeofTest()
{
Assert.AreEqual(12, sizeof(Vector3));
Assert.AreEqual(24, sizeof(Vector3_2x));
Assert.AreEqual(16, sizeof(Vector3PlusFloat));
Assert.AreEqual(32, sizeof(Vector3PlusFloat_2x));
}
[StructLayout(LayoutKind.Sequential)]
struct Vector3_2x
{
Vector3 a;
Vector3 b;
}
[StructLayout(LayoutKind.Sequential)]
struct Vector3PlusFloat
{
Vector3 v;
float f;
}
[StructLayout(LayoutKind.Sequential)]
struct Vector3PlusFloat_2x
{
Vector3PlusFloat a;
Vector3PlusFloat b;
}
// A test to make sure the fields are laid out how we expect
[TestMethod]
public unsafe void Vector3FieldOffsetTest()
{
Vector3 value;
Assert.AreEqual(0 + new IntPtr(&value).ToInt64(), new IntPtr(&value.X).ToInt64());
Assert.AreEqual(4 + new IntPtr(&value).ToInt64(), new IntPtr(&value.Y).ToInt64());
Assert.AreEqual(8 + new IntPtr(&value).ToInt64(), new IntPtr(&value.Z).ToInt64());
}
// A test to validate interop between .NET (System.Numerics) and WinRT (Microsoft.Graphics.Canvas.Numerics)
[TestMethod]
public void Vector3WinRTInteropTest()
{
Vector3 a = new Vector3(23, 42, -1);
Microsoft.Graphics.Canvas.Numerics.Vector3 b = a;
Assert.AreEqual(a.X, b.X);
Assert.AreEqual(a.Y, b.Y);
Assert.AreEqual(a.Z, b.Z);
Vector3 c = b;
Assert.AreEqual(a, c);
}
}
}
| |
//#define ASTAR_POOL_DEBUG //Enables debugging of path pooling. Will log warnings and info messages about paths not beeing pooled correctly.
using UnityEngine;
using System.Collections;
using Pathfinding;
using System.Collections.Generic;
namespace Pathfinding {
/** Base class for all path types */
public abstract class Path {
/** Data for the thread calculating this path */
public PathHandler pathHandler;
/** Callback to call when the path is complete.
* This is usually sent to the Seeker component which post processes the path and then calls a callback to the script which requested the path
*/
public OnPathDelegate callback;
private PathState state;
private System.Object stateLock = new object();
/** Current state of the path.
* \see #CompleteState
*/
private PathCompleteState pathCompleteState;
/** Current state of the path */
public PathCompleteState CompleteState {
get { return pathCompleteState; }
protected set { pathCompleteState = value; }
}
/** If the path failed, this is true.
* \see #errorLog */
public bool error { get { return CompleteState == PathCompleteState.Error; }}
/** Additional info on what went wrong.
* \see #error */
private string _errorLog = "";
/** Log messages with info about eventual errors. */
public string errorLog {
get { return _errorLog; }
}
private GraphNode[] _path;
private Vector3[] _vectorPath;
/** Holds the path as a Node array. All nodes the path traverses. This might not be the same as all nodes the smoothed path traverses. */
public List<GraphNode> path;
/** Holds the (perhaps post processed) path as a Vector3 array */
public List<Vector3> vectorPath;
/** The max number of milliseconds per iteration (frame, in case of non-multithreading) */
protected float maxFrameTime;
/** The node currently being processed */
protected PathNode currentR;
public float duration; /**< The duration of this path in ms. How long it took to calculate the path */
/**< The number of frames/iterations this path has executed.
* This is the number of frames when not using multithreading.
* When using multithreading, this value is quite irrelevant
*/
public int searchIterations = 0;
public int searchedNodes; /**< Number of nodes this path has searched */
/** When the call was made to start the pathfinding for this path */
public System.DateTime callTime;
/* True if the path has been calculated (even if it had an error).
* Used by the multithreaded pathfinder to signal that this path object is safe to return. */
//public bool processed = false;
/** True if the path is currently recycled (i.e in the path pool).
* Do not set this value. Only read. It is used internally.
*/
public bool recycled = false;
/** True if the Reset function has been called.
* Used to allert users when they are doing it wrong.
*/
protected bool hasBeenReset = false;
/** Constraint for how to search for nodes */
public NNConstraint nnConstraint = PathNNConstraint.Default;
/** The next path to be searched.
* Linked list implementation.
* \warning You should never change this if you do not know what you are doing
*/
public Path next;
//These are variables which different scripts and custom graphs can use to get a bit more info about What is searching
//Not all are used in the standard graph types
//These variables are put here because it is a lot faster to access fields than, for example make use of a lookup table (e.g dictionary)
//Note: These variables needs to be filled in by an external script to be usable
/** Radius for the unit searching for the path.
* \note Not used by any built-in pathfinders.
* These common name variables are put here because it is a lot faster to access fields than, for example make use of a lookup table (e.g dictionary).
* Or having to cast to another path type for acess.
*/
public int radius;
/** A mask for defining what type of ground a unit can traverse, not used in any default standard graph. \see #enabledTags
* \note Not used by any built-in pathfinders.
* These variables are put here because it is a lot faster to access fields than, for example make use of a lookup table (e.g dictionary)
*/
public int walkabilityMask = -1;
/** Height of the character. Not used currently */
public int height;
/** Turning radius of the character. Not used currently */
public int turnRadius;
/** Speed of the character. Not used currently */
public int speed;
/* To store additional data. Note: this is SLOW. About 10-100 times slower than using the fields above.
* \since Removed in 3.0.8
* Currently not used */
//public Dictionary<string,int> customData = null;//new Dictionary<string,int>();
/** Determines which heuristic to use */
public Heuristic heuristic;
/** Scale of the heuristic values */
public float heuristicScale = 1F;
/** ID of this path. Used to distinguish between different paths */
public ushort pathID;
protected Int3 hTarget; /**< Target to use for H score calculations. \see Pathfinding.Node.H */
/** Which graph tags are traversable.
* This is a bitmask so -1 = all bits set = all tags traversable.
* For example, to set bit 5 to true, you would do
* \code myPath.enabledTags |= 1 << 5; \endcode
* To set it to false, you would do
* \code myPath.enabledTags &= ~(1 << 5); \endcode
*
* The Seeker has a popup field where you can set which tags to use.
* \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath.
* So you need to change the Seeker value via script, not set this value if you want to change it via script.
*
* \see CanTraverse
*/
public int enabledTags = -1;
/** Penalties for each tag.
*/
protected int[] _tagPenalties = new int[0];
/** Penalties for each tag.
* Tag 0 which is the default tag, will have added a penalty of tagPenalties[0].
* These should only be positive values since the A* algorithm cannot handle negative penalties.
* \note This array will never be null. If you try to set it to null or with a lenght which is not 32. It will be set to "new int[0]".
*
* \note If you are using a Seeker. The Seeker will set this value to what is set in the inspector field on StartPath.
* So you need to change the Seeker value via script, not set this value if you want to change it via script.
*
* \see Seeker.tagPenalties
*/
public int[] tagPenalties {
get {
return _tagPenalties;
}
set {
if (value == null || value.Length != 32) _tagPenalties = new int[0];
else _tagPenalties = value;
}
}
/** Total Length of the path.
* Calculates the total length of the #vectorPath.
* Cache this rather than call this function every time since it will calculate the length every time, not just return a cached value.
* \returns Total length of #vectorPath, if #vectorPath is null positive infinity is returned.
*/
public float GetTotalLength () {
if (vectorPath == null) return float.PositiveInfinity;
float tot = 0;
for (int i=0;i<vectorPath.Count-1;i++) tot += Vector3.Distance (vectorPath[i],vectorPath[i+1]);
return tot;
}
/** Waits until this path has been calculated and returned.
* Allows for very easy scripting.
\code
//In an IEnumerator function
Path p = Seeker.StartPath (transform.position, transform.position + Vector3.forward * 10);
yield return StartCoroutine (p.WaitForPath ());
//The path is calculated at this stage
\endcode
* \note Do not confuse this with AstarPath.WaitForPath. This one will wait using yield until it has been calculated
* while AstarPath.WaitForPath will halt all operations until the path has been calculated.
*
* \throws System.InvalidOperationException if the path is not started. Send the path to Seeker.StartPath or AstarPath.StartPath before calling this function.
*
* \see AstarPath.WaitForPath
*/
public IEnumerator WaitForPath () {
if (GetState () == PathState.Created) throw new System.InvalidOperationException ("This path has not been started yet");
while (GetState () != PathState.Returned) yield return null;
}
public uint CalculateHScore (GraphNode node) {
switch (heuristic) {
case Heuristic.Euclidean:
return (uint)(((GetHTarget () - node.position).costMagnitude)*heuristicScale);
case Heuristic.Manhattan:
Int3 p2 = node.position;
return (uint)((System.Math.Abs (hTarget.x-p2.x) + System.Math.Abs (hTarget.y-p2.y) + System.Math.Abs (hTarget.z-p2.z))*heuristicScale);
case Heuristic.DiagonalManhattan:
Int3 p = GetHTarget () - node.position;
p.x = System.Math.Abs (p.x);
p.y = System.Math.Abs (p.y);
p.z = System.Math.Abs (p.z);
int diag = System.Math.Min (p.x,p.z);
int diag2 = System.Math.Max (p.x,p.z);
return (uint)((((14*diag)/10) + (diag2-diag) + p.y) * heuristicScale);
}
return 0U;
}
/** Returns penalty for the given tag.
* \param tag A value between 0 (inclusive) and 31 (inclusive).
*/
public uint GetTagPenalty (int tag) {
return tag < _tagPenalties.Length ? (uint)_tagPenalties[tag] : 0;
}
public Int3 GetHTarget () {
return hTarget;
}
/** Returns if the node can be traversed.
* This per default equals to if the node is walkable and if the node's tag is included in #enabledTags */
public bool CanTraverse (GraphNode node) {
unchecked { return node.Walkable && (enabledTags >> (int)node.Tag & 0x1) != 0; }
}
public uint GetTraversalCost (GraphNode node) {
unchecked { return GetTagPenalty ((int)node.Tag ) + node.Penalty; }
}
/** May be called by graph nodes to get a special cost for some connections.
* Nodes may call it when PathNode.flag2 is set to true, for example mesh nodes, which have
* a very large area can be marked on the start and end nodes, this method will be called
* to get the actual cost for moving from the start position to its neighbours instead
* of as would otherwise be the case, from the start node's position to its neighbours.
* The position of a node and the actual start point on the node can vary quite a lot.
*
* The default behaviour of this method is to return the previous cost of the connection,
* essentiall making no change at all.
*
* This method should return the same regardless of the order of a and b.
* That is f(a,b) == f(b,a) should hold.
*
* \param a Moving from this node
* \param b Moving to this node
* \param currentCost The cost of moving between the nodes. Return this value if there is no meaningful special cost to return.
*/
public virtual uint GetConnectionSpecialCost (GraphNode a, GraphNode b, uint currentCost) {
return currentCost;
}
/** Returns if this path is done calculating.
* \returns If CompleteState is not PathCompleteState.NotCalculated.
*
* \note The path might not have been returned yet.
*
* \since Added in 3.0.8
*
* \see Seeker.IsDone
*/
public bool IsDone () {
return CompleteState != PathCompleteState.NotCalculated;
}
/** Threadsafe increment of the state */
public void AdvanceState (PathState s) {
lock (stateLock) {
state = (PathState)System.Math.Max ((int)state, (int)s);
}
}
/** Returns the state of the path in the pathfinding pipeline */
public PathState GetState () {
return (PathState)state;
}
/** Appends \a msg to #errorLog and logs \a msg to the console.
* Debug.Log call is only made if AstarPath.logPathResults is not equal to None and not equal to InGame.
* Consider calling Error() along with this call.
*/
// Ugly Code Inc. wrote the below code :D
// What it does is that it disables the LogError function if ASTAR_NO_LOGGING is enabled
// since the DISABLED define will never be enabled
// Ugly way of writing Conditional("!ASTAR_NO_LOGGING")
public void LogError (string msg) {
// Optimize for release builds
if (!(!AstarPath.isEditor && AstarPath.active.logPathResults == PathLog.None)) {
_errorLog += msg;
}
if (AstarPath.active.logPathResults != PathLog.None && AstarPath.active.logPathResults != PathLog.InGame) {
//Debug.LogWarning (msg);
}
}
/** Logs an error and calls Error() to true.
* This is called only if something is very wrong or the user is doing something he/she really should not be doing.
*/
public void ForceLogError (string msg) {
Error();
_errorLog += msg;
Debug.LogError (msg);
}
/** Appends a message to the #errorLog.
* Nothing is logged to the console.
*
* \note If AstarPath.logPathResults is PathLog.None and this is a standalone player, nothing will be logged as an optimization.
*/
public void Log (string msg) {
// Optimize for release builds
if (!(!AstarPath.isEditor && AstarPath.active.logPathResults == PathLog.None)) {
_errorLog += msg;
}
}
/** Aborts the path because of an error.
* Sets #error to true.
* This function is called when an error has ocurred (e.g a valid path could not be found).
* \see LogError
*/
public void Error () {
CompleteState = PathCompleteState.Error;
}
/** Does some error checking.
* Makes sure the user isn't using old code paths and that no major errors have been done.
*
* \throws An exception if any errors are found
*/
private void ErrorCheck () {
if (!hasBeenReset) throw new System.Exception ("The path has never been reset. Use pooling API or call Reset() after creating the path with the default constructor.");
if (recycled) throw new System.Exception ("The path is currently in a path pool. Are you sending the path for calculation twice?");
if (pathHandler == null) throw new System.Exception ("Field pathHandler is not set. Please report this bug.");
if (GetState() > PathState.Processing) throw new System.Exception ("This path has already been processed. Do not request a path with the same path object twice.");
}
/** Called when the path enters the pool.
* This method should release e.g pooled lists and other pooled resources
* The base version of this method releases vectorPath and path lists.
* Reset() will be called after this function, not before.
* \warning Do not call this function manually.
*/
public virtual void OnEnterPool () {
if (vectorPath != null) Pathfinding.Util.ListPool<Vector3>.Release (vectorPath);
if (path != null) Pathfinding.Util.ListPool<GraphNode>.Release (path);
vectorPath = null;
path = null;
}
/** Reset all values to their default values.
*
* \note All inheriting path types (e.g ConstantPath, RandomPath, etc.) which declare their own variables need to
* override this function, resetting ALL their variables to enable recycling of paths.
* If this is not done, trying to use that path type for pooling might result in weird behaviour.
* The best way is to reset to default values the variables declared in the extended path type and then
* call this base function in inheriting types with base.Reset ().
*
* \warning This function should not be called manually.
*/
public virtual void Reset () {
if (AstarPath.active == null)
throw new System.NullReferenceException ("No AstarPath object found in the scene. " +
"Make sure there is one or do not create paths in Awake");
hasBeenReset = true;
state = (int)PathState.Created;
releasedNotSilent = false;
pathHandler = null;
callback = null;
_errorLog = "";
pathCompleteState = PathCompleteState.NotCalculated;
path = Pathfinding.Util.ListPool<GraphNode>.Claim();
vectorPath = Pathfinding.Util.ListPool<Vector3>.Claim();
currentR = null;
duration = 0;
searchIterations = 0;
searchedNodes = 0;
//calltime
nnConstraint = PathNNConstraint.Default;
next = null;
radius = 0;
walkabilityMask = -1;
height = 0;
turnRadius = 0;
speed = 0;
//heuristic = (Heuristic)0;
//heuristicScale = 1F;
heuristic = AstarPath.active.heuristic;
heuristicScale = AstarPath.active.heuristicScale;
pathID = 0;
enabledTags = -1;
tagPenalties = null;
callTime = System.DateTime.UtcNow;
pathID = AstarPath.active.GetNextPathID ();
hTarget = Int3.zero;
}
protected bool HasExceededTime (int searchedNodes, long targetTime) {
return System.DateTime.UtcNow.Ticks >= targetTime;
}
/** Recycle the path.
* Calling this means that the path and any variables on it are not needed anymore and the path can be pooled.
* All path data will be reset.
* Implement this in inheriting path types to support recycling of paths.
\code
public override void Recycle () {
//Recycle the Path (<Path> should be replaced by the path type it is implemented in)
PathPool<Path>.Recycle (this);
}
\endcode
*
* \warning Do not call this function directly, instead use the #Claim and #Release functions.
* \see Pathfinding.PathPool
* \see Reset
* \see Claim
* \see Release
*/
protected abstract void Recycle ();// {
// PathPool<Path>.Recycle (this);
//}
/** List of claims on this path with reference objects */
private List<System.Object> claimed = new List<System.Object>();
/** True if the path has been released with a non-silent call yet.
*
* \see Release
* \see ReleaseSilent
* \see Claim
*/
private bool releasedNotSilent = false;
/** Claim this path.
* A claim on a path will ensure that it is not recycled.
* If you are using a path, you will want to claim it when you first get it and then release it when you will not
* use it anymore. When there are no claims on the path, it will be recycled and put in a pool.
*
* \see Release
* \see Recycle
*/
public void Claim (System.Object o) {
if (o == null) throw new System.ArgumentNullException ("o");
if (claimed.Contains (o)) {
throw new System.ArgumentException ("You have already claimed the path with that object ("+o.ToString()+"). Are you claiming the path with the same object twice?");
}
claimed.Add (o);
}
/** Releases the path silently.
* This will remove the claim by the specified object, but the path will not be recycled if the claim count reches zero unless a Release call (not silent) has been made earlier.
* This is used by the internal pathfinding components such as Seeker and AstarPath so that they will not recycle paths.
* This enables users to skip the claim/release calls if they want without the path being recycled by the Seeker or AstarPath.
*/
public void ReleaseSilent (System.Object o) {
if (o == null) throw new System.ArgumentNullException ("o");
for (int i=0;i<claimed.Count;i++) {
if (claimed[i] == o) {
claimed.RemoveAt (i);
if (releasedNotSilent && claimed.Count == 0) {
Recycle ();
}
return;
}
}
if (claimed.Count == 0) {
throw new System.ArgumentException ("You are releasing a path which is not claimed at all (most likely it has been pooled already). " +
"Are you releasing the path with the same object ("+o.ToString()+") twice?");
} else {
throw new System.ArgumentException ("You are releasing a path which has not been claimed with this object ("+o.ToString()+"). " +
"Are you releasing the path with the same object twice?");
}
}
/** Releases a path claim.
* Removes the claim of the path by the specified object.
* When the claim count reaches zero, the path will be recycled, all variables will be cleared and the path will be put in a pool to be used again.
* This is great for memory since less allocations are made.
* \see Claim
*/
public void Release (System.Object o) {
if (o == null) throw new System.ArgumentNullException ("o");
for (int i=0;i<claimed.Count;i++) {
if (claimed[i] == o) {
claimed.RemoveAt (i);
releasedNotSilent = true;
if (claimed.Count == 0) {
Recycle ();
}
return;
}
}
if (claimed.Count == 0) {
throw new System.ArgumentException ("You are releasing a path which is not claimed at all (most likely it has been pooled already). " +
"Are you releasing the path with the same object ("+o.ToString()+") twice?");
} else {
throw new System.ArgumentException ("You are releasing a path which has not been claimed with this object ("+o.ToString()+"). " +
"Are you releasing the path with the same object twice?");
}
}
/** Traces the calculated path from the end node to the start.
* This will build an array (#path) of the nodes this path will pass through and also set the #vectorPath array to the #path arrays positions.
* Assumes the #vectorPath and #path are empty and not null (which will be the case for a correctly initialized path).
*/
protected virtual void Trace (PathNode from) {
int count = 0;
PathNode c = from;
while (c != null) {
c = c.parent;
count++;
if (count > 1024) {
Debug.LogWarning ("Inifinity loop? >1024 node path. Remove this message if you really have that long paths (Path.cs, Trace function)");
break;
}
}
//Ensure capacities for lists
AstarProfiler.StartProfile ("Check List Capacities");
if (path.Capacity < count) path.Capacity = count;
if (vectorPath.Capacity < count) vectorPath.Capacity = count;
AstarProfiler.EndProfile ();
c = from;
for (int i = 0;i<count;i++) {
path.Add (c.node);
c = c.parent;
}
int half = count/2;
for (int i=0;i<half;i++) {
GraphNode tmp = path[i];
path[i] = path[count-i-1];
path[count - i - 1] = tmp;
}
for (int i=0;i<count;i++) {
vectorPath.Add ((Vector3)path[i].position);
}
}
/** Returns a debug string for this path.
*/
public virtual string DebugString (PathLog logMode) {
if (logMode == PathLog.None || (!error && logMode == PathLog.OnlyErrors)) {
return "";
}
//debugStringBuilder.Length = 0;
System.Text.StringBuilder text = pathHandler.DebugStringBuilder;
text.Length = 0;
text.Append (error ? "Path Failed : " : "Path Completed : ");
text.Append ("Computation Time ");
text.Append ((duration).ToString (logMode == PathLog.Heavy ? "0.000 ms " : "0.00 ms "));
text.Append ("Searched Nodes ");
text.Append (searchedNodes);
if (!error) {
text.Append (" Path Length ");
text.Append (path == null ? "Null" : path.Count.ToString ());
if (logMode == PathLog.Heavy) {
text.Append ("\nSearch Iterations "+searchIterations);
//text.Append ("\nBinary Heap size at complete: ");
// -2 because numberOfItems includes the next item to be added and item zero is not used
//text.Append (pathHandler.open == null ? "null" : (pathHandler.open.numberOfItems-2).ToString ());
}
/*"\nEnd node\n G = "+p.endNode.g+"\n H = "+p.endNode.h+"\n F = "+p.endNode.f+"\n Point "+p.endPoint
+"\nStart Point = "+p.startPoint+"\n"+"Start Node graph: "+p.startNode.graphIndex+" End Node graph: "+p.endNode.graphIndex+
"\nBinary Heap size at completion: "+(p.open == null ? "Null" : p.open.numberOfItems.ToString ())*/
}
if (error) {
text.Append ("\nError: ");
text.Append (errorLog);
}
if (logMode == PathLog.Heavy && !AstarPath.IsUsingMultithreading ) {
text.Append ("\nCallback references ");
if (callback != null) text.Append(callback.Target.GetType().FullName).AppendLine();
else text.AppendLine ("NULL");
}
text.Append ("\nPath Number ");
text.Append (pathID);
return text.ToString ();
}
/** Calls callback to return the calculated path. \see #callback */
public virtual void ReturnPath () {
if (callback != null) {
callback (this);
}
}
/** Prepares low level path variables for calculation.
* Called before a path search will take place.
* Always called before the Prepare, Initialize and CalculateStep functions
*/
public void PrepareBase (PathHandler pathHandler) {
//Path IDs have overflowed 65K, cleanup is needed
//Since pathIDs are handed out sequentially, we can do this
if (pathHandler.PathID > pathID) {
pathHandler.ClearPathIDs ();
}
//Make sure the path has a reference to the pathHandler
this.pathHandler = pathHandler;
//Assign relevant path data to the pathHandler
pathHandler.InitializeForPath (this);
try {
ErrorCheck ();
} catch (System.Exception e) {
ForceLogError ("Exception in path "+pathID+"\n"+e.ToString());
}
}
public abstract void Prepare ();
/** Always called after the path has been calculated.
* Guaranteed to be called before other paths have been calculated on
* the same thread.
* Use for cleaning up things like node tagging and similar.
*/
public virtual void Cleanup () {}
/** Initializes the path.
* Sets up the open list and adds the first node to it
*/
public abstract void Initialize ();
/** Calculates the path until time has gone past \a targetTick */
public abstract void CalculateStep (long targetTick);
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2010 Leopold Bushkin. 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;
using System.Collections.Generic;
using System.Linq;
public static partial class MoreEnumerable
{
/// <summary>
/// The private implementation class that produces permutations of a sequence.
/// </summary>
class PermutationEnumerator<T> : IEnumerator<IList<T>>
{
// NOTE: The algorithm used to generate permutations uses the fact that any set
// can be put into 1-to-1 correspondence with the set of ordinals number (0..n).
// The implementation here is based on the algorithm described by Kenneth H. Rosen,
// in Discrete Mathematics and Its Applications, 2nd edition, pp. 282-284.
//
// There are two significant changes from the original implementation.
// First, the algorithm uses lazy evaluation and streaming to fit well into the
// nature of most LINQ evaluations.
//
// Second, the algorithm has been modified to use dynamically generated nested loop
// state machines, rather than an integral computation of the factorial function
// to determine when to terminate. The original algorithm required a priori knowledge
// of the number of iterations necessary to produce all permutations. This is a
// necessary step to avoid overflowing the range of the permutation arrays used.
// The number of permutation iterations is defined as the factorial of the original
// set size minus 1.
//
// However, there's a fly in the ointment. The factorial function grows VERY rapidly.
// 13! overflows the range of a Int32; while 28! overflows the range of decimal.
// To overcome these limitations, the algorithm relies on the fact that the factorial
// of N is equivalent to the evaluation of N-1 nested loops. Unfortunatley, you can't
// just code up a variable number of nested loops ... this is where .NET generators
// with their elegant 'yield return' syntax come to the rescue.
//
// The methods of the Loop extension class (For and NestedLoops) provide the implementation
// of dynamic nested loops using generators and sequence composition. In a nutshell,
// the two Repeat() functions are the constructor of loops and nested loops, respectively.
// The NestedLoops() function produces a composition of loops where the loop counter
// for each nesting level is defined in a separate sequence passed in the call.
//
// For example: NestedLoops( () => DoSomething(), new[] { 6, 8 } )
//
// is equivalent to: for( int i = 0; i < 6; i++ )
// for( int j = 0; j < 8; j++ )
// DoSomething();
readonly IList<T> _valueSet;
readonly int[] _permutation;
readonly IEnumerable<Action> _generator;
IEnumerator<Action> _generatorIterator;
bool _hasMoreResults;
public PermutationEnumerator(IEnumerable<T> valueSet)
{
_valueSet = valueSet.ToArray();
_permutation = new int[_valueSet.Count];
// The nested loop construction below takes into account the fact that:
// 1) for empty sets and sets of cardinality 1, there exists only a single permutation.
// 2) for sets larger than 1 element, the number of nested loops needed is: set.Count-1
_generator = NestedLoops(NextPermutation, Enumerable.Range(2, Math.Max(0, _valueSet.Count - 1)));
Reset();
}
public void Reset()
{
_generatorIterator?.Dispose();
// restore lexographic ordering of the permutation indexes
for (var i = 0; i < _permutation.Length; i++)
_permutation[i] = i;
// start a newiteration over the nested loop generator
_generatorIterator = _generator.GetEnumerator();
// we must advance the nestedloop iterator to the initial element,
// this ensures that we only ever produce N!-1 calls to NextPermutation()
_generatorIterator.MoveNext();
_hasMoreResults = true; // there's always at least one permutation: the original set itself
}
public IList<T> Current { get; private set; }
object IEnumerator.Current => Current;
public bool MoveNext()
{
Current = PermuteValueSet();
// check if more permutation left to enumerate
var prevResult = _hasMoreResults;
_hasMoreResults = _generatorIterator.MoveNext();
if (_hasMoreResults)
_generatorIterator.Current(); // produce the next permutation ordering
// we return prevResult rather than m_HasMoreResults because there is always
// at least one permtuation: the original set. Also, this provides a simple way
// to deal with the disparity between sets that have only one loop level (size 0-2)
// and those that have two or more (size > 2).
return prevResult;
}
void IDisposable.Dispose() { }
/// <summary>
/// Transposes elements in the cached permutation array to produce the next permutation
/// </summary>
void NextPermutation()
{
// find the largest index j with m_Permutation[j] < m_Permutation[j+1]
var j = _permutation.Length - 2;
while (_permutation[j] > _permutation[j + 1])
j--;
// find index k such that m_Permutation[k] is the smallest integer
// greater than m_Permutation[j] to the right of m_Permutation[j]
var k = _permutation.Length - 1;
while (_permutation[j] > _permutation[k])
k--;
// interchange m_Permutation[j] and m_Permutation[k]
var oldValue = _permutation[k];
_permutation[k] = _permutation[j];
_permutation[j] = oldValue;
// move the tail of the permutation after the jth position in increasing order
var x = _permutation.Length - 1;
var y = j + 1;
while (x > y)
{
oldValue = _permutation[y];
_permutation[y] = _permutation[x];
_permutation[x] = oldValue;
x--;
y++;
}
}
/// <summary>
/// Creates a new list containing the values from the original
/// set in their new permuted order.
/// </summary>
/// <remarks>
/// The reason we return a new permuted value set, rather than reuse
/// an existing collection, is that we have no control over what the
/// consumer will do with the results produced. They could very easily
/// generate and store a set of permutations and only then begin to
/// process them. If we reused the same collection, the caller would
/// be surprised to discover that all of the permutations looked the
/// same.
/// </remarks>
/// <returns>List of permuted source sequence values</returns>
IList<T> PermuteValueSet()
{
var permutedSet = new T[_permutation.Length];
for (var i = 0; i < _permutation.Length; i++)
permutedSet[i] = _valueSet[_permutation[i]];
return permutedSet;
}
}
/// <summary>
/// Generates a sequence of lists that represent the permutations of the original sequence.
/// </summary>
/// <remarks>
/// A permutation is a unique re-ordering of the elements of the sequence.<br/>
/// This operator returns permutations in a deferred, streaming fashion; however, each
/// permutation is materialized into a new list. There are N! permutations of a sequence,
/// where N => sequence.Count().<br/>
/// Be aware that the original sequence is considered one of the permutations and will be
/// returned as one of the results.
/// </remarks>
/// <typeparam name="T">The type of the elements in the sequence</typeparam>
/// <param name="sequence">The original sequence to permute</param>
/// <returns>A sequence of lists representing permutations of the original sequence</returns>
public static IEnumerable<IList<T>> Permutations<T>(this IEnumerable<T> sequence)
{
if (sequence == null) throw new ArgumentNullException(nameof(sequence));
return _(); IEnumerable<IList<T>> _()
{
using (var iter = new PermutationEnumerator<T>(sequence))
{
while (iter.MoveNext())
yield return iter.Current;
}
}
}
}
}
| |
// Copyright (C) 2014 dot42
//
// Original filename: PropertyInfo.cs
//
// 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 Dot42;
using Dot42.Internal;
using Dot42.Internal.Generics;
namespace System.Reflection
{
/// <summary>
/// Property reflection info.
/// </summary>
public class PropertyInfo : MemberInfo, IAttributesProvider
{
private static readonly ParameterInfo[] EmptyParameterInfo = new ParameterInfo[0];
private readonly string name;
private readonly MethodInfo getter;
private readonly MethodInfo setter;
private readonly IAttribute[] attributes;
private readonly Type declaringType;
private Type propertyType;
/// <summary>
/// Default ctor
/// </summary>
internal PropertyInfo(Type declaringType, string name, MethodInfo getter, MethodInfo setter, IAttribute[] attributes)
{
this.declaringType = declaringType;
this.name = name;
this.getter = getter;
this.setter = setter;
this.attributes = attributes;
}
public override Type DeclaringType { get { return declaringType; } }
/// <summary>
/// Gets the name of this property
/// </summary>
public override string Name { get { return name; } }
public override MemberTypes MemberType { get { return MemberTypes.Property; } }
/// <summary>
/// Gets this property be read from?
/// </summary>
public virtual bool CanRead { get { return (getter != null); } }
/// <summary>
/// Gets this property be written to?
/// </summary>
public virtual bool CanWrite { get { return (setter != null); } }
/// <summary>
/// Gets the get accessor method.
/// </summary>
public virtual MethodInfo GetGetMethod() { return getter; }
public virtual MethodInfo GetMethod { get { return getter; } }
public virtual MethodInfo GetGetMethod(bool nonPublic) { return getter!=null&&getter.IsPublic?getter:null; }
/// <summary>
/// Gets the set accessor method.
/// </summary>
public virtual MethodInfo GetSetMethod() { return setter; }
public virtual MethodInfo SetMethod { get { return setter; } }
public virtual MethodInfo GetSetMethod(bool nonPublic) { return setter != null && setter.IsPublic ? getter : null; }
/// <summary>
/// this is not supported and always returns an empty array.
/// </summary>
[NotImplemented]
public ParameterInfo[] GetIndexParameters()
{
return EmptyParameterInfo;
}
/// <summary>
/// Gets the type of this property
/// </summary>
public virtual Type PropertyType
{
get
{
if (propertyType == null)
{
if (getter != null)
{
propertyType = GenericsReflection.GetMemberType(getter.ReturnType, DeclaringType, getter.JavaMethod);
}
else if (setter != null)
{
var paramType = setter.JavaMethod.ParameterTypes.Last();
var genericInfo = (IGenericDefinition)setter.JavaMethod.ParameterAnnotations
.Last()
.FirstOrDefault(x => x.AnnotationType() == typeof (IGenericDefinition));
if (genericInfo != null)
{
propertyType = GenericsReflection.ToGenericInstanceType(paramType, DeclaringType, genericInfo);
}
else
{
propertyType = paramType;
}
}
}
return propertyType;
}
}
/// <summary>
/// Gets a value of the property for a given instance.
/// </summary>
public object GetValue(object instance)
{
if (getter == null)
throw new InvalidOperationException("property has no getter");
return getter.Invoke(instance, null);
}
/// <summary>
/// Gets a value of the property for a given instance.
/// </summary>
public object GetValue(object instance, object[] index)
{
if (index != null && index.Length > 0)
throw new ArgumentException("index");
if (getter == null)
throw new InvalidOperationException("property has no getter");
return getter.Invoke(instance,null);
}
/// <summary>
/// Sets a value of the property for a given instance.
/// </summary>
public void SetValue(object instance, object value, object[] index)
{
if(index != null && index.Length > 0)
throw new ArgumentException("index");
if (setter == null)
throw new InvalidOperationException("property has no setter");
value = ConvertParameterIfRequired(PropertyType, value);
setter.Invoke(instance, new [] {value});
}
/// <summary>
/// Sets a value of the property for a given instance.
/// </summary>
public void SetValue(object instance, object value)
{
if (setter == null)
throw new ArgumentException("property has no setter");
value = ConvertParameterIfRequired(PropertyType, value);
setter.Invoke(instance, new[] { value });
}
public override object[] GetCustomAttributes(bool inherit)
{
return CustomAttributeProvider.GetCustomAttributes(this, inherit);
}
public override object[] GetCustomAttributes(Type attributeType, bool inherit)
{
return CustomAttributeProvider.GetCustomAttributes(this, attributeType, inherit);
}
public override bool IsDefined(Type attributeType, bool inherit)
{
return CustomAttributeProvider.IsDefined(this, attributeType, inherit);
}
public override string ToString()
{
return DeclaringType.Name + " " + Name;
}
/// <summary>
/// Gets all attributes
/// </summary>
IAttributes IAttributesProvider.Attributes()
{
return new AttributesWrapper(attributes);
}
protected bool Equals(PropertyInfo other)
{
return declaringType == other.declaringType && Equals(name, other.name);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((PropertyInfo)obj);
}
public override int GetHashCode()
{
unchecked
{
return (declaringType.GetHashCode() * 397) ^ (name != null ? name.GetHashCode() : 0);
}
}
}
}
| |
// 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.Specialized;
using Xunit;
namespace System.ComponentModel.Design.Tests
{
public class MenuCommandTests
{
public static IEnumerable<object[]> Ctor_EventHandler_CommandID_TestData()
{
yield return new object[] { new EventHandler(EventHandler), new CommandID(Guid.NewGuid(), 10) };
yield return new object[] { null, null };
}
[Theory]
[MemberData(nameof(Ctor_EventHandler_CommandID_TestData))]
public void Ctor_EventHandler_CommandID(EventHandler handler, CommandID commandId)
{
var command = new MenuCommand(handler, commandId);
Assert.False(command.Checked);
Assert.Same(commandId, command.CommandID);
Assert.True(command.Enabled);
Assert.Equal(3, command.OleStatus);
Assert.IsType<HybridDictionary>(command.Properties);
Assert.Empty(command.Properties);
Assert.Same(command.Properties, command.Properties);
Assert.True(command.Supported);
Assert.True(command.Visible);
}
[Theory]
[InlineData(true, 7, 3)]
[InlineData(false, 3, 7)]
public void Checked_Set_GetReturnsExpected(bool value, int expectedOleStatus1, int expectedOleStatus2)
{
var command = new MenuCommand(null, null)
{
Checked = value
};
Assert.Equal(value, command.Checked);
Assert.Equal(expectedOleStatus1, command.OleStatus);
// Set same.
command.Checked = value;
Assert.Equal(value, command.Checked);
Assert.Equal(expectedOleStatus1, command.OleStatus);
// Set different.
command.Checked = !value;
Assert.Equal(!value, command.Checked);
Assert.Equal(expectedOleStatus2, command.OleStatus);
}
[Fact]
public void Checked_SetWithCommandChanged_CallsHandler()
{
var command = new MenuCommand(null, null);
int callCount = 0;
EventHandler handler = (sender, e) =>
{
Assert.Same(command, sender);
Assert.Same(EventArgs.Empty, e);
callCount++;
};
command.CommandChanged += handler;
// Set different.
command.Checked = true;
Assert.True(command.Checked);
Assert.Equal(1, callCount);
// Set same.
command.Checked = true;
Assert.True(command.Checked);
Assert.Equal(1, callCount);
// Set different.
command.Checked = false;
Assert.False(command.Checked);
Assert.Equal(2, callCount);
// Remove handler.
command.CommandChanged -= handler;
command.Checked = true;
Assert.True(command.Checked);
Assert.Equal(2, callCount);
}
[Theory]
[InlineData(true, 3, 1)]
[InlineData(false, 1, 3)]
public void Enabled_Set_GetReturnsExpected(bool value, int expectedOleStatus1, int expectedOleStatus2)
{
var command = new MenuCommand(null, null)
{
Enabled = value
};
Assert.Equal(value, command.Enabled);
Assert.Equal(expectedOleStatus1, command.OleStatus);
// Set same.
command.Enabled = value;
Assert.Equal(value, command.Enabled);
Assert.Equal(expectedOleStatus1, command.OleStatus);
// Set different.
command.Enabled = !value;
Assert.Equal(!value, command.Enabled);
Assert.Equal(expectedOleStatus2, command.OleStatus);
}
[Fact]
public void Enabled_SetWithCommandChanged_CallsHandler()
{
var command = new MenuCommand(null, null);
int callCount = 0;
EventHandler handler = (sender, e) =>
{
Assert.Same(command, sender);
Assert.Same(EventArgs.Empty, e);
callCount++;
};
command.CommandChanged += handler;
// Set different.
command.Enabled = false;
Assert.False(command.Enabled);
Assert.Equal(1, callCount);
// Set same.
command.Enabled = false;
Assert.False(command.Enabled);
Assert.Equal(1, callCount);
// Set different.
command.Enabled = true;
Assert.True(command.Enabled);
Assert.Equal(2, callCount);
// Remove handler.
command.CommandChanged -= handler;
command.Enabled = false;
Assert.False(command.Enabled);
Assert.Equal(2, callCount);
}
[Theory]
[InlineData(true, 3, 2)]
[InlineData(false, 2, 3)]
public void Supported_Set_GetReturnsExpected(bool value, int expectedOleStatus1, int expectedOleStatus2)
{
var command = new MenuCommand(null, null)
{
Supported = value
};
Assert.Equal(value, command.Supported);
Assert.Equal(expectedOleStatus1, command.OleStatus);
// Set same.
command.Supported = value;
Assert.Equal(value, command.Supported);
Assert.Equal(expectedOleStatus1, command.OleStatus);
// Set different.
command.Supported = !value;
Assert.Equal(!value, command.Supported);
Assert.Equal(expectedOleStatus2, command.OleStatus);
}
[Fact]
public void Supported_SetWithCommandChanged_CallsHandler()
{
var command = new MenuCommand(null, null);
int callCount = 0;
EventHandler handler = (sender, e) =>
{
Assert.Same(command, sender);
Assert.Same(EventArgs.Empty, e);
callCount++;
};
command.CommandChanged += handler;
// Set different.
command.Supported = false;
Assert.False(command.Supported);
Assert.Equal(1, callCount);
// Set same.
command.Supported = false;
Assert.False(command.Supported);
Assert.Equal(1, callCount);
// Set different.
command.Supported = true;
Assert.True(command.Supported);
Assert.Equal(2, callCount);
// Remove handler.
command.CommandChanged -= handler;
command.Supported = false;
Assert.False(command.Supported);
Assert.Equal(2, callCount);
}
[Theory]
[InlineData(true, 3, 19)]
[InlineData(false, 19, 3)]
public void Visible_Set_GetReturnsExpected(bool value, int expectedOleStatus1, int expectedOleStatus2)
{
var command = new MenuCommand(null, null)
{
Visible = value
};
Assert.Equal(value, command.Visible);
Assert.Equal(expectedOleStatus1, command.OleStatus);
// Set same.
command.Visible = value;
Assert.Equal(value, command.Visible);
Assert.Equal(expectedOleStatus1, command.OleStatus);
// Set different.
command.Visible = !value;
Assert.Equal(!value, command.Visible);
Assert.Equal(expectedOleStatus2, command.OleStatus);
}
[Fact]
public void Visible_SetWithCommandChanged_CallsHandler()
{
var command = new MenuCommand(null, null);
int callCount = 0;
EventHandler handler = (sender, e) =>
{
Assert.Same(command, sender);
Assert.Same(EventArgs.Empty, e);
callCount++;
};
command.CommandChanged += handler;
// Set different.
command.Visible = false;
Assert.False(command.Visible);
Assert.Equal(1, callCount);
// Set same.
command.Visible = false;
Assert.False(command.Visible);
Assert.Equal(1, callCount);
// Set different.
command.Visible = true;
Assert.True(command.Visible);
Assert.Equal(2, callCount);
// Remove handler.
command.CommandChanged -= handler;
command.Visible = false;
Assert.False(command.Visible);
Assert.Equal(2, callCount);
}
public static IEnumerable<object[]> OnCommandChanged_TestData()
{
yield return new object[] { null };
yield return new object[] { new EventArgs() };
}
[Theory]
[MemberData(nameof(OnCommandChanged_TestData))]
public void OnCommandChanged_Invoke_CallsCommandChanged(EventArgs eventArgs)
{
var command = new SubMenuCommand(null, null);
int callCount = 0;
EventHandler handler = (sender, e) =>
{
Assert.Same(command, sender);
Assert.Same(eventArgs, e);
callCount++;
};
command.CommandChanged += handler;
// Call with handler.
command.OnCommandChanged(eventArgs);
Assert.Equal(1, callCount);
// Remove handler.
command.CommandChanged -= handler;
command.OnCommandChanged(eventArgs);
Assert.Equal(1, callCount);
}
public static IEnumerable<object[]> ToString_TestData()
{
yield return new object[]
{
new MenuCommand(new EventHandler(EventHandler), new CommandID(Guid.Empty, 0))
{
Enabled = false,
Checked = false,
Supported = false,
Visible = false
},
"00000000-0000-0000-0000-000000000000 : 0 : "
};
yield return new object[]
{
new MenuCommand(new EventHandler(EventHandler), new CommandID(Guid.Empty, 0))
{
Enabled = true,
Checked = true,
Supported = true,
Visible = true
},
"00000000-0000-0000-0000-000000000000 : 0 : Supported|Enabled|Visible|Checked"
};
yield return new object[] { new MenuCommand(new EventHandler(EventHandler), null), " : Supported|Enabled|Visible" };
}
[Theory]
[MemberData(nameof(ToString_TestData))]
public void ToString_Invoke_ReturnsExpected(MenuCommand command, string expected)
{
Assert.Equal(expected, command.ToString());
}
[Fact]
public void Invoke_NonNullEventHandler_Success()
{
var command = new MenuCommand(new EventHandler(EventHandler), new CommandID(Guid.NewGuid(), 10));
command.Invoke();
Assert.Same(command, CalledEventSender);
}
[Fact]
public void Invoke_EventHandlerThrowsCanceledCheckoutException_Nop()
{
var command = new MenuCommand(new EventHandler(ThrowCanceledCheckoutException), new CommandID(Guid.NewGuid(), 10));
command.Invoke();
command.Invoke("arg");
}
[Fact]
public void Invoke_EventHandlerThrowsCanceledCheckoutException_ThrowsException()
{
var command = new MenuCommand(new EventHandler(ThrowNonCanceledCheckoutException), new CommandID(Guid.NewGuid(), 10));
Assert.Throws<CheckoutException>(() => command.Invoke());
Assert.Throws<CheckoutException>(() => command.Invoke("arg"));
}
[Fact]
public void Invoke_NullEventHandler_Nop()
{
var command = new MenuCommand(null, new CommandID(Guid.NewGuid(), 10));
command.Invoke();
command.Invoke("arg");
}
private static object CalledEventSender { get; set; }
private static void EventHandler(object sender, EventArgs e)
{
CalledEventSender = sender;
Assert.Same(EventArgs.Empty, e);
}
private static void ThrowCanceledCheckoutException(object sender, EventArgs e)
{
throw CheckoutException.Canceled;
}
private static void ThrowNonCanceledCheckoutException(object sender, EventArgs e)
{
throw new CheckoutException();
}
private class SubMenuCommand : MenuCommand
{
public SubMenuCommand(EventHandler handler, CommandID command) : base(handler, command)
{
}
public new void OnCommandChanged(EventArgs e) => base.OnCommandChanged(e);
}
}
}
| |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;
namespace Stratus
{
/// <summary>
/// Provides an object-oriented way of drawing GUI elements
/// </summary>
public struct StratusGUIObject
{
//------------------------------------------------------------------------/
// Properties
//------------------------------------------------------------------------/
/// <summary>
/// The current GUI event in Unity
/// </summary>
public UnityEngine.Event currentEvent => UnityEngine.Event.current;
/// <summary>
/// The current rect used by the object
/// </summary>
public Rect rect { get; private set; }
/// <summary>
/// The label to be used by this object
/// </summary>
public string label { get; set; }
/// <summary>
/// Additional information about this object
/// </summary>
public string description { get; set; }
/// <summary>
/// The tooltip string for this object
/// </summary>
public string tooltip { get; set; }
/// <summary>
/// Whether to show the description of this button alongside its label
/// </summary>
public bool showDescription { get; set; }
/// <summary>
/// Whether to concatenate the description with the label
/// </summary>
public bool descriptionsWithLabel { get; set; }
/// <summary>
/// The method to invoke when this button is left clicked
/// </summary>
public System.Action onLeftClickDown { get; set; }
/// <summary>
/// The method to invoke when this button is left clicked, then released
/// </summary>
public System.Action onLeftClickUp { get; set; }
/// <summary>
/// The method to invoke when this button is clicked by the middle mouse button
/// </summary>
public System.Action onMiddleClickDown { get; set; }
/// <summary>
/// The method to invoke when this button is clicked by the middle mouse button, then released
/// </summary>
public System.Action onMiddleClickUp { get; set; }
/// <summary>
/// The method to invoke when this button is clicked by the right mouse button
/// </summary>
public System.Action onRightClickDown { get; set; }
/// <summary>
/// The method to invoke when this button is clicked by the right mouse button and released
/// </summary>
public System.Action onRightClickUp { get; set; }
/// <summary>
/// The method to invoke when this button is being dragged
/// </summary>
public System.Action onDrag { get; set; }
/// <summary>
/// The method to invoke when an object is drag and dropped onto this button
/// </summary>
public System.Action<object> onDrop { get; set; }
/// <summary>
/// The string identifier for what type of dragged data to accept
/// </summary>
public string dragDataIdentifier { get; set; }
/// <summary>
/// The data to be used when this button is dragged
/// </summary>
public object dragData { get; set; }
/// <summary>
/// The data to be used when this button is dragged
/// </summary>
public Func<object, bool> onValidateDrag { get; set; }
/// <summary>
/// The background color to use
/// </summary>
public Color backgroundColor { get; set; } // = Color.white;
/// <summary>
/// Outline color to use
/// </summary>
public Color outlineColor { get; set; }
/// <summary>
/// Whether this button is currently moused over
/// </summary>
public bool isMousedOver
{
get
{
return rect.Contains(currentEvent.mousePosition);
}
}
public bool isSelected { get; set; }
/// <summary>
/// Whether this button is draggable
/// </summary>
public bool isDraggable => dragData != null && dragDataIdentifier != null;
/// <summary>
/// Whether this button accepts a drop operation from a drag
/// </summary>
public bool isDroppable => onDrop != null && dragDataIdentifier != null;
/// <summary>
/// Whether one of these buttons is currentl being dragged
/// </summary>
public static bool isDragging { get; private set; }
/// <summary>
/// What to do on certain key presses
/// </summary>
private Dictionary<KeyCode, System.Action> keyMap { get; set; } // = new Dictionary<KeyCode, System.Action>();
/// <summary>
/// Whether this object is checking for keys
/// </summary>
public bool hasKeys => keyMap != null;
//------------------------------------------------------------------------/
// Fields
//------------------------------------------------------------------------/
//------------------------------------------------------------------------/
// CTOR
//------------------------------------------------------------------------/
//public GUIObject(string label = null)
//{
// this.label = label;
// onValidateDrag = null;
// dragData = null;
// dragDataIdentifier = null;
// onDrag = null;
// onDrop = null;
// onRightClickDown = onRightClickUp = null;
// onLeftClickDown = onLeftClickUp= null;
// onMiddleClickDown = onMiddleClickUp= null;
// showDescription = descriptionsWithLabel = false;
// tooltip = description = string.Empty;
// backgroundColor = Color.white;
//}
//------------------------------------------------------------------------/
// Methods
//------------------------------------------------------------------------/
/// <summary>
/// Draws this button using Unity's GUILayout system
/// </summary>
/// <param name="style"></param>
/// <param name="options"></param>
/// <returns>True if the mouse was moused over this control</returns>
public bool Draw(GUIStyle style = null, params GUILayoutOption[] options)
{
GUIContent content = new GUIContent(showDescription ? $"{label}\n{description}" : label, tooltip);
if (backgroundColor != default(Color)) GUI.backgroundColor = backgroundColor;
{
GUILayout.Box(content, style, options);
rect = GUILayoutUtility.GetLastRect();
}
if (backgroundColor != default(Color)) GUI.backgroundColor = Color.white;
if (outlineColor != default(Color) && isSelected) StratusGUIStyles.DrawOutline(rect, outlineColor);
//Vector2 style .CalcSize(content)
// Keyboard
if (isSelected)
{
if (OnKey())
return true;
}
// Mouse
if (isMousedOver)
{
OnMouse();
return true;
}
return false;
}
/// <summary>
/// Handles mouse events
/// </summary>
private void OnMouse()
{
if (isMousedOver)
{
switch (currentEvent.type)
{
case EventType.MouseDown:
if (isDraggable)
{
DragAndDrop.PrepareStartDrag();
DragAndDrop.objectReferences = new UnityEngine.Object[] { (UnityEngine.Object)dragData };
DragAndDrop.SetGenericData(dragDataIdentifier, dragData);
}
switch (currentEvent.button)
{
case 0: onLeftClickDown?.Invoke(); break;
case 1: onRightClickDown?.Invoke(); break;
case 2: onMiddleClickDown?.Invoke(); break;
}
currentEvent.Use();
break;
case EventType.MouseUp:
switch (currentEvent.button)
{
case 0: onLeftClickUp?.Invoke(); break;
case 1: onRightClickUp?.Invoke(); break;
case 2: onMiddleClickUp?.Invoke(); break;
}
if (isDraggable)
{
DragAndDrop.PrepareStartDrag();
isDragging = false;
}
currentEvent.Use();
//int control = GUIUtility.GetControlID(FocusType.Keyboard);
//GUIUtility.hotControl = control;
//Selection.SetActiveObjectWithContext()
break;
case EventType.MouseDrag:
// If the drag was started here
if (isDraggable)
{
object existingDragData = DragAndDrop.GetGenericData(dragDataIdentifier);
if (existingDragData != null)
{
DragAndDrop.StartDrag($"Dragging {label}");
onDrag?.Invoke();
currentEvent.Use();
isDragging = true;
}
}
break;
case EventType.DragUpdated:
if (isDraggable)
{
if (ValidateDragData())
DragAndDrop.visualMode = DragAndDropVisualMode.Link;
else
DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
}
currentEvent.Use();
break;
case EventType.DragPerform:
if (isDroppable)
{
DragAndDrop.AcceptDrag();
object receivedDragData = DragAndDrop.GetGenericData(dragDataIdentifier);
if (receivedDragData != null)
{
onDrop(receivedDragData);
}
}
currentEvent.Use();
break;
case EventType.DragExited:
if (isDraggable)
{
isDragging = false;
DragAndDrop.PrepareStartDrag();
}
break;
}
}
}
/// <summary>
/// Handles keyboard events
/// </summary>
private bool OnKey()
{
if (hasKeys && currentEvent.isKey && currentEvent.type == EventType.KeyDown)
{
if (keyMap.ContainsKey(currentEvent.keyCode))
{
keyMap[currentEvent.keyCode].Invoke();
return true;
}
}
return false;
}
public void AddKey(KeyCode key, System.Action onKey)
{
if (keyMap == null)
keyMap = new Dictionary<KeyCode, System.Action>();
keyMap.Add(key, onKey);
}
/// <summary>
/// Validates the current dragging data
/// </summary>
/// <returns></returns>
private bool ValidateDragData()
{
object receivedDragData = DragAndDrop.GetGenericData(dragDataIdentifier);
if (receivedDragData != null && onValidateDrag != null && onValidateDrag(receivedDragData))
return true;
return 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.
using System.Collections.Generic;
using System.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class IntersectTests
{
private const int DuplicateFactor = 4;
private static IEnumerable<int> RightCounts(int leftCount)
{
return new[] { 0, 1, Math.Max(DuplicateFactor * 2, leftCount), 2 * Math.Max(DuplicateFactor, leftCount * 2) }.Distinct();
}
public static IEnumerable<object[]> IntersectUnorderedData(int[] leftCounts)
{
foreach (int leftCount in leftCounts.DefaultIfEmpty(Sources.OuterLoopCount / 4))
{
foreach (int rightCount in RightCounts(leftCount))
{
int rightStart = 0 - rightCount / 2;
yield return new object[] { leftCount, rightStart, rightCount, Math.Min(leftCount, (rightCount + 1) / 2) };
}
}
}
public static IEnumerable<object[]> IntersectData(int[] leftCounts)
{
foreach (int leftCount in leftCounts.DefaultIfEmpty(Sources.OuterLoopCount / 4))
{
foreach (int rightCount in RightCounts(leftCount))
{
int rightStart = 0 - rightCount / 2;
foreach (object[] left in Sources.Ranges(new[] { leftCount }))
{
yield return left.Concat(new object[] { UnorderedSources.Default(rightStart, rightCount), rightCount, Math.Min(leftCount, (rightCount + 1) / 2) }).ToArray();
}
}
}
}
public static IEnumerable<object[]> IntersectSourceMultipleData(int[] counts)
{
foreach (int leftCount in counts.DefaultIfEmpty(Sources.OuterLoopCount / DuplicateFactor / 2))
{
ParallelQuery<int> left = Enumerable.Range(0, leftCount * DuplicateFactor).Select(x => x % leftCount).ToArray().AsParallel().AsOrdered();
foreach (int rightCount in RightCounts(leftCount))
{
int rightStart = 0 - rightCount / 2;
yield return new object[] { left, leftCount, UnorderedSources.Default(rightStart, rightCount), rightCount, Math.Min(leftCount, (rightCount + 1) / 2) };
}
}
}
//
// Intersect
//
[Theory]
[MemberData(nameof(IntersectUnorderedData), new[] { 0, 1, 2, 16 })]
public static void Intersect_Unordered(int leftCount, int rightStart, int rightCount, int count)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(rightStart, rightCount);
IntegerRangeSet seen = new IntegerRangeSet(0, count);
foreach (int i in leftQuery.Intersect(rightQuery))
{
seen.Add(i);
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectUnorderedData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Intersect_Unordered_Longrunning(int leftCount, int rightStart, int rightCount, int count)
{
Intersect_Unordered(leftCount, rightStart, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectData), new[] { 0, 1, 2, 16 })]
public static void Intersect(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
int seen = 0;
foreach (int i in leftQuery.Intersect(rightQuery))
{
Assert.Equal(seen++, i);
}
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Intersect_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> right, int rightCount, int count)
{
Intersect(left, leftCount, right, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectUnorderedData), new[] { 0, 1, 2, 16 })]
public static void Intersect_Unordered_NotPipelined(int leftCount, int rightStart, int rightCount, int count)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(rightStart, rightCount);
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(leftQuery.Intersect(rightQuery).ToList(), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectUnorderedData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Intersect_Unordered_NotPipelined_Longrunning(int leftCount, int rightStart, int rightCount, int count)
{
Intersect_Unordered_NotPipelined(leftCount, rightStart, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectData), new[] { 0, 1, 2, 16 })]
public static void Intersect_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
int seen = 0;
Assert.All(leftQuery.Intersect(rightQuery).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Intersect_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Intersect_NotPipelined(left, leftCount, rightQuery, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectUnorderedData), new[] { 0, 1, 2, 16 })]
public static void Intersect_Unordered_Distinct(int leftCount, int rightStart, int rightCount, int count)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(rightStart, rightCount);
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, rightCount));
foreach (int i in leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)))
{
seen.Add(i % (DuplicateFactor * 2));
}
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectUnorderedData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Intersect_Unordered_Distinct_Longrunning(int leftCount, int rightStart, int rightCount, int count)
{
Intersect_Unordered_Distinct(leftCount, rightStart, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectData), new[] { 0, 1, 2, 16 })]
public static void Intersect_Distinct(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
int seen = 0;
foreach (int i in leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)))
{
Assert.Equal(seen++, i);
}
Assert.Equal(Math.Min(leftCount, rightCount), seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Intersect_Distinct_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Intersect_Distinct(left, leftCount, rightQuery, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectUnorderedData), new[] { 0, 1, 2, 16 })]
public static void Intersect_Unordered_Distinct_NotPipelined(int leftCount, int rightStart, int rightCount, int count)
{
ParallelQuery<int> leftQuery = UnorderedSources.Default(leftCount);
ParallelQuery<int> rightQuery = UnorderedSources.Default(rightStart, rightCount);
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
IntegerRangeSet seen = new IntegerRangeSet(0, Math.Min(leftCount, rightCount));
Assert.All(leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => seen.Add(x % (DuplicateFactor * 2)));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectUnorderedData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Intersect_Unordered_Distinct_NotPipelined_Longrunning(int leftCount, int rightStart, int rightCount, int count)
{
Intersect_Unordered_Distinct_NotPipelined(leftCount, rightStart, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectData), new[] { 0, 1, 2, 16 })]
public static void Intersect_Distinct_NotPipelined(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
ParallelQuery<int> leftQuery = left.Item;
leftCount = Math.Min(DuplicateFactor * 2, leftCount);
rightCount = Math.Min(DuplicateFactor, (rightCount + 1) / 2);
int seen = 0;
Assert.All(leftQuery.Intersect(rightQuery.Select(x => Math.Abs(x) % DuplicateFactor), new ModularCongruenceComparer(DuplicateFactor * 2)).ToList(), x => Assert.Equal(seen++, x));
Assert.Equal(Math.Min(leftCount, rightCount), seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Intersect_Distinct_NotPipelined_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Intersect_Distinct_NotPipelined(left, leftCount, rightQuery, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectSourceMultipleData), new[] { 0, 1, 2, 16 })]
public static void Intersect_Unordered_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
// The difference between this test and the previous, is that it's not possible to
// get non-unique results from ParallelEnumerable.Range()...
// Those tests either need modification of source (via .Select(x => x /DuplicateFactor) or similar,
// or via a comparator that considers some elements equal.
IntegerRangeSet seen = new IntegerRangeSet(0, count);
Assert.All(leftQuery.AsUnordered().Intersect(rightQuery), x => seen.Add(x));
seen.AssertComplete();
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectSourceMultipleData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Intersect_Unordered_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Intersect_Unordered_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Theory]
[MemberData(nameof(IntersectSourceMultipleData), new[] { 0, 1, 2, 16 })]
public static void Intersect_SourceMultiple(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
int seen = 0;
Assert.All(leftQuery.Intersect(rightQuery), x => Assert.Equal(seen++, x));
Assert.Equal(count, seen);
}
[Theory]
[OuterLoop]
[MemberData(nameof(IntersectSourceMultipleData), new int[] { /* Sources.OuterLoopCount */ })]
public static void Intersect_SourceMultiple_Longrunning(ParallelQuery<int> leftQuery, int leftCount, ParallelQuery<int> rightQuery, int rightCount, int count)
{
Intersect_SourceMultiple(leftQuery, leftCount, rightQuery, rightCount, count);
}
[Fact]
public static void Intersect_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Intersect(Enumerable.Range(0, 1)));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).Intersect(Enumerable.Range(0, 1), null));
#pragma warning restore 618
}
[Fact]
// Should not get the same setting from both operands.
public static void Intersect_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).Intersect(ParallelEnumerable.Range(0, 1).WithCancellation(t)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).Intersect(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).Intersect(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).Intersect(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default)));
}
[Fact]
public static void Intersect_ArgumentNullException()
{
Assert.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Intersect(ParallelEnumerable.Range(0, 1)));
Assert.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Intersect(null));
Assert.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).Intersect(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default));
Assert.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).Intersect(null, EqualityComparer<int>.Default));
}
}
}
| |
#region License
/*
* All content copyright Terracotta, Inc., unless otherwise indicated. 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
using System;
namespace Quartz
{
/// <summary>
/// DateBuilder is used to conveniently create
/// <see cref="DateTimeOffset" /> instances that meet particular criteria.
/// </summary>
/// <remarks>
/// <para>
/// Quartz provides a builder-style API for constructing scheduling-related
/// entities via a Domain-Specific Language (DSL). The DSL can best be
/// utilized through the usage of static imports of the methods on the classes
/// <see cref="TriggerBuilder" />, <see cref="JobBuilder" />,
/// <see cref="DateBuilder" />, <see cref="JobKey" />, <see cref="TriggerKey" />
/// and the various <see cref="IScheduleBuilder" /> implementations.
/// </para>
/// <para>Client code can then use the DSL to write code such as this:</para>
/// <code>
/// IJobDetail job = JobBuilder.Create<MyJob>()
/// .WithIdentity("myJob")
/// .Build();
/// ITrigger trigger = newTrigger()
/// .WithIdentity(triggerKey("myTrigger", "myTriggerGroup"))
/// .WithSimpleSchedule(x => x
/// .WithIntervalInHours(1)
/// .RepeatForever())
/// .StartAt(DateBuilder.FutureDate(10, IntervalUnit.Minutes))
/// .Build();
/// scheduler.scheduleJob(job, trigger);
/// </code>
/// </remarks>
/// <seealso cref="TriggerBuilder" />
/// <seealso cref="JobBuilder" />
public class DateBuilder
{
private int month;
private int day;
private int year;
private int hour;
private int minute;
private int second;
private TimeZoneInfo tz;
/// <summary>
/// Create a DateBuilder, with initial settings for the current date
/// and time in the system default timezone.
/// </summary>
private DateBuilder()
{
DateTime now = DateTime.Now;
month = now.Month;
day = now.Day;
year = now.Year;
hour = now.Hour;
minute = now.Minute;
second = now.Second;
}
/// <summary>
/// Create a DateBuilder, with initial settings for the current date and time in the given timezone.
/// </summary>
/// <param name="tz"></param>
private DateBuilder(TimeZoneInfo tz)
{
DateTime now = DateTime.Now;
month = now.Month;
day = now.Day;
year = now.Year;
hour = now.Hour;
minute = now.Minute;
second = now.Second;
this.tz = tz;
}
/// <summary>
/// Create a DateBuilder, with initial settings for the current date and time in the system default timezone.
/// </summary>
/// <returns></returns>
public static DateBuilder NewDate()
{
return new DateBuilder();
}
/// <summary>
/// Create a DateBuilder, with initial settings for the current date and time in the given timezone.
/// </summary>
/// <param name="tz">Time zone to use.</param>
/// <returns></returns>
public static DateBuilder NewDateInTimeZone(TimeZoneInfo tz)
{
return new DateBuilder(tz);
}
/// <summary>
/// Build the <see cref="DateTimeOffset" /> defined by this builder instance.
/// </summary>
/// <returns>New date time based on builder parameters.</returns>
public DateTimeOffset Build()
{
DateTimeOffset cal;
if (tz != null)
{
cal = new DateTimeOffset(year, month, day, hour, minute, second, 0, tz.BaseUtcOffset);
}
else
{
var utcOffset = TimeZoneInfo.Local.GetUtcOffset(new DateTime(year, month, day, hour, minute, second));
cal = new DateTimeOffset(year, month, day, hour, minute, second, utcOffset);
}
return cal;
}
/// <summary>
/// Set the hour (0-23) for the Date that will be built by this builder.
/// </summary>
/// <param name="hour"></param>
/// <returns></returns>
public DateBuilder AtHourOfDay(int hour)
{
ValidateHour(hour);
this.hour = hour;
return this;
}
/// <summary>
/// Set the minute (0-59) for the Date that will be built by this builder.
/// </summary>
/// <param name="minute"></param>
/// <returns></returns>
public DateBuilder AtMinute(int minute)
{
ValidateMinute(minute);
this.minute = minute;
return this;
}
/// <summary>
/// Set the second (0-59) for the Date that will be built by this builder, and truncate the milliseconds to 000.
/// </summary>
/// <param name="second"></param>
/// <returns></returns>
public DateBuilder AtSecond(int second)
{
ValidateSecond(second);
this.second = second;
return this;
}
public DateBuilder AtHourMinuteAndSecond(int hour, int minute, int second)
{
ValidateHour(hour);
ValidateMinute(minute);
ValidateSecond(second);
this.hour = hour;
this.second = second;
this.minute = minute;
return this;
}
/// <summary>
/// Set the day of month (1-31) for the Date that will be built by this builder.
/// </summary>
/// <param name="day"></param>
/// <returns></returns>
public DateBuilder OnDay(int day)
{
ValidateDayOfMonth(day);
this.day = day;
return this;
}
/// <summary>
/// Set the month (1-12) for the Date that will be built by this builder.
/// </summary>
/// <param name="month"></param>
/// <returns></returns>
public DateBuilder InMonth(int month)
{
ValidateMonth(month);
this.month = month;
return this;
}
public DateBuilder InMonthOnDay(int month, int day)
{
ValidateMonth(month);
ValidateDayOfMonth(day);
this.month = month;
this.day = day;
return this;
}
/// <summary>
/// Set the year for the Date that will be built by this builder.
/// </summary>
/// <param name="year"></param>
/// <returns></returns>
public DateBuilder InYear(int year)
{
ValidateYear(year);
this.year = year;
return this;
}
/// <summary>
/// Set the TimeZoneInfo for the Date that will be built by this builder (if "null", system default will be used)
/// </summary>
/// <param name="tz"></param>
/// <returns></returns>
public DateBuilder InTimeZone(TimeZoneInfo tz)
{
this.tz = tz;
return this;
}
public static DateTimeOffset FutureDate(int interval, IntervalUnit unit)
{
return TranslatedAdd(SystemTime.Now(), unit, interval);
}
/// <summary>
/// Get a <see cref="DateTimeOffset" /> object that represents the given time, on
/// tomorrow's date.
/// </summary>
/// <param name="hour"></param>
/// <param name="minute"></param>
/// <param name="second"></param>
/// <returns></returns>
public static DateTimeOffset TomorrowAt(int hour, int minute, int second)
{
ValidateSecond(second);
ValidateMinute(minute);
ValidateHour(hour);
DateTimeOffset now = DateTimeOffset.Now;
DateTimeOffset c = new DateTimeOffset(
now.Year,
now.Month,
now.Day,
hour,
minute,
second,
0,
now.Offset);
// advance one day
c = c.AddDays(1);
return c;
}
/// <summary>
/// Get a <see cref="DateTimeOffset" /> object that represents the given time, on
/// today's date (equivalent to <see cref="DateOf(int,int,int)" />).
/// </summary>
/// <param name="hour"></param>
/// <param name="minute"></param>
/// <param name="second"></param>
/// <returns></returns>
public static DateTimeOffset TodayAt(int hour, int minute, int second)
{
return DateOf(hour, minute, second);
}
private static DateTimeOffset TranslatedAdd(DateTimeOffset date, IntervalUnit unit, int amountToAdd)
{
switch (unit)
{
case IntervalUnit.Day:
return date.AddDays(amountToAdd);
case IntervalUnit.Hour:
return date.AddHours(amountToAdd);
case IntervalUnit.Minute:
return date.AddMinutes(amountToAdd);
case IntervalUnit.Month:
return date.AddMonths(amountToAdd);
case IntervalUnit.Second:
return date.AddSeconds(amountToAdd);
case IntervalUnit.Millisecond:
return date.AddMilliseconds(amountToAdd);
case IntervalUnit.Week:
return date.AddDays(amountToAdd*7);
case IntervalUnit.Year:
return date.AddYears(amountToAdd);
default:
throw new ArgumentException("Unknown IntervalUnit");
}
}
/// <summary>
/// Get a <see cref="DateTimeOffset" /> object that represents the given time, on today's date.
/// </summary>
/// <param name="second">The value (0-59) to give the seconds field of the date</param>
/// <param name="minute">The value (0-59) to give the minutes field of the date</param>
/// <param name="hour">The value (0-23) to give the hours field of the date</param>
/// <returns>the new date</returns>
public static DateTimeOffset DateOf(int hour, int minute, int second)
{
ValidateSecond(second);
ValidateMinute(minute);
ValidateHour(hour);
DateTimeOffset c = SystemTime.Now();
var utcOffset = TimeZoneInfo.Local.GetUtcOffset(new DateTime(c.Year, c.Month, c.Day, hour, minute, second));
return new DateTimeOffset(c.Year, c.Month, c.Day, hour, minute, second, utcOffset);
}
/// <summary>
/// Get a <see cref="DateTimeOffset" /> object that represents the given time, on the
/// given date.
/// </summary>
/// <param name="second">The value (0-59) to give the seconds field of the date</param>
/// <param name="minute">The value (0-59) to give the minutes field of the date</param>
/// <param name="hour">The value (0-23) to give the hours field of the date</param>
/// <param name="dayOfMonth">The value (1-31) to give the day of month field of the date</param>
/// <param name="month">The value (1-12) to give the month field of the date</param>
/// <returns>the new date</returns>
public static DateTimeOffset DateOf(int hour, int minute, int second,
int dayOfMonth, int month)
{
ValidateSecond(second);
ValidateMinute(minute);
ValidateHour(hour);
ValidateDayOfMonth(dayOfMonth);
ValidateMonth(month);
DateTimeOffset c = SystemTime.Now();
var utcOffset = TimeZoneInfo.Local.GetUtcOffset(new DateTime(c.Year, month, dayOfMonth, hour, minute, second));
return new DateTimeOffset(c.Year, month, dayOfMonth, hour, minute, second, utcOffset);
}
/// <summary>
/// Get a <see cref="DateTimeOffset" /> object that represents the given time, on the
/// given date.
/// </summary>
/// <remarks>
/// </remarks>
/// <param name="second">The value (0-59) to give the seconds field of the date</param>
/// <param name="minute">The value (0-59) to give the minutes field of the date</param>
/// <param name="hour">The value (0-23) to give the hours field of the date</param>
/// <param name="dayOfMonth">The value (1-31) to give the day of month field of the date</param>
/// <param name="month">The value (1-12) to give the month field of the date</param>
/// <param name="year">The value (1970-2099) to give the year field of the date</param>
/// <returns>the new date</returns>
public static DateTimeOffset DateOf(int hour, int minute, int second,
int dayOfMonth, int month, int year)
{
ValidateSecond(second);
ValidateMinute(minute);
ValidateHour(hour);
ValidateDayOfMonth(dayOfMonth);
ValidateMonth(month);
ValidateYear(year);
var utcOffset = TimeZoneInfo.Local.GetUtcOffset(new DateTime(year, month, dayOfMonth, hour, minute, second));
return new DateTimeOffset(year, month, dayOfMonth, hour, minute, second, utcOffset);
}
/// <summary>
/// Returns a date that is rounded to the next even hour after the current time.
/// </summary>
/// <remarks>
/// For example a current time of 08:13:54 would result in a date
/// with the time of 09:00:00. If the date's time is in the 23rd hour, the
/// date's 'day' will be promoted, and the time will be set to 00:00:00.
/// </remarks>
/// <returns>the new rounded date</returns>
public static DateTimeOffset EvenHourDateAfterNow()
{
return EvenHourDate(null);
}
/// <summary>
/// Returns a date that is rounded to the next even hour above the given date.
/// </summary>
/// <remarks>
/// For example an input date with a time of 08:13:54 would result in a date
/// with the time of 09:00:00. If the date's time is in the 23rd hour, the
/// date's 'day' will be promoted, and the time will be set to 00:00:00.
/// </remarks>
/// <param name="date">the Date to round, if <see langword="null" /> the current time will
/// be used</param>
/// <returns>the new rounded date</returns>
public static DateTimeOffset EvenHourDate(DateTimeOffset? date)
{
if (!date.HasValue)
{
date = SystemTime.Now();
}
DateTimeOffset d = date.Value.AddHours(1);
return new DateTimeOffset(d.Year, d.Month, d.Day, d.Hour, 0, 0, d.Offset);
}
/// <summary>
/// Returns a date that is rounded to the previous even hour below the given date.
/// </summary>
/// <remarks>
/// For example an input date with a time of 08:13:54 would result in a date
/// with the time of 08:00:00.
/// </remarks>
/// <param name="date">the Date to round, if <see langword="null" /> the current time will
/// be used</param>
/// <returns>the new rounded date</returns>
public static DateTimeOffset EvenHourDateBefore(DateTimeOffset? date)
{
if (!date.HasValue)
{
date = SystemTime.Now();
}
return new DateTimeOffset(date.Value.Year, date.Value.Month, date.Value.Day, date.Value.Hour, 0, 0, date.Value.Offset);
}
/// <summary>
/// <para>
/// Returns a date that is rounded to the next even minute after the current time.
/// </para>
/// </summary>
/// <remarks>
/// For example a current time of 08:13:54 would result in a date
/// with the time of 08:14:00. If the date's time is in the 59th minute,
/// then the hour (and possibly the day) will be promoted.
/// </remarks>
/// <returns>the new rounded date</returns>
public static DateTimeOffset EvenMinuteDateAfterNow()
{
return EvenMinuteDate(SystemTime.Now());
}
/// <summary>
/// Returns a date that is rounded to the next even minute above the given date.
/// </summary>
/// <remarks>
/// For example an input date with a time of 08:13:54 would result in a date
/// with the time of 08:14:00. If the date's time is in the 59th minute,
/// then the hour (and possibly the day) will be promoted.
/// </remarks>
/// <param name="date">The Date to round, if <see langword="null" /> the current time will be used</param>
/// <returns>The new rounded date</returns>
public static DateTimeOffset EvenMinuteDate(DateTimeOffset? date)
{
if (!date.HasValue)
{
date = SystemTime.Now();
}
DateTimeOffset d = date.Value;
d = d.AddMinutes(1);
return new DateTimeOffset(d.Year, d.Month, d.Day, d.Hour, d.Minute, 0, d.Offset);
}
/// <summary>
/// Returns a date that is rounded to the previous even minute below the given date.
/// </summary>
/// <remarks>
/// For example an input date with a time of 08:13:54 would result in a date
/// with the time of 08:13:00.
/// </remarks>
/// <param name="date">the Date to round, if <see langword="null" /> the current time will
/// be used</param>
/// <returns>the new rounded date</returns>
public static DateTimeOffset EvenMinuteDateBefore(DateTimeOffset? date)
{
if (!date.HasValue)
{
date = SystemTime.Now();
}
DateTimeOffset d = date.Value;
return new DateTimeOffset(d.Year, d.Month, d.Day, d.Hour, d.Minute, 0, d.Offset);
}
/// <summary>
/// Returns a date that is rounded to the next even second after the current time.
/// </summary>
/// <returns>the new rounded date</returns>
public static DateTimeOffset EvenSecondDateAfterNow()
{
return EvenSecondDate(SystemTime.Now());
}
/// <summary>
/// Returns a date that is rounded to the next even second above the given date.
/// </summary>
/// <param name="date"></param>
/// the Date to round, if <see langword="null" /> the current time will
/// be used
/// <returns>the new rounded date</returns>
public static DateTimeOffset EvenSecondDate(DateTimeOffset date)
{
date = date.AddSeconds(1);
return new DateTimeOffset(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0, date.Offset);
}
/// <summary>
/// Returns a date that is rounded to the previous even second below the
/// given date.
/// </summary>
/// <remarks>
/// <para>
/// For example an input date with a time of 08:13:54.341 would result in a
/// date with the time of 08:13:00.000.
/// </para>
/// </remarks>
/// <param name="date"></param>
/// the Date to round, if <see langword="null" /> the current time will
/// be used
/// <returns>the new rounded date</returns>
public static DateTimeOffset EvenSecondDateBefore(DateTimeOffset date)
{
return new DateTimeOffset(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0, date.Offset);
}
/// <summary>
/// Returns a date that is rounded to the next even multiple of the given
/// minute.
/// </summary>
/// <remarks>
/// <para>
/// For example an input date with a time of 08:13:54, and an input
/// minute-base of 5 would result in a date with the time of 08:15:00. The
/// same input date with an input minute-base of 10 would result in a date
/// with the time of 08:20:00. But a date with the time 08:53:31 and an
/// input minute-base of 45 would result in 09:00:00, because the even-hour
/// is the next 'base' for 45-minute intervals.
/// </para>
/// <para>
/// More examples: <table>
/// <tr>
/// <th>Input Time</th>
/// <th>Minute-Base</th>
/// <th>Result Time</th>
/// </tr>
/// <tr>
/// <td>11:16:41</td>
/// <td>20</td>
/// <td>11:20:00</td>
/// </tr>
/// <tr>
/// <td>11:36:41</td>
/// <td>20</td>
/// <td>11:40:00</td>
/// </tr>
/// <tr>
/// <td>11:46:41</td>
/// <td>20</td>
/// <td>12:00:00</td>
/// </tr>
/// <tr>
/// <td>11:26:41</td>
/// <td>30</td>
/// <td>11:30:00</td>
/// </tr>
/// <tr>
/// <td>11:36:41</td>
/// <td>30</td>
/// <td>12:00:00</td>
/// </tr>
/// <tr>
/// <td>11:16:41</td>
/// <td>17</td>
/// <td>11:17:00</td>
/// </tr>
/// <tr>
/// <td>11:17:41</td>
/// <td>17</td>
/// <td>11:34:00</td>
/// </tr>
/// <tr>
/// <td>11:52:41</td>
/// <td>17</td>
/// <td>12:00:00</td>
/// </tr>
/// <tr>
/// <td>11:52:41</td>
/// <td>5</td>
/// <td>11:55:00</td>
/// </tr>
/// <tr>
/// <td>11:57:41</td>
/// <td>5</td>
/// <td>12:00:00</td>
/// </tr>
/// <tr>
/// <td>11:17:41</td>
/// <td>0</td>
/// <td>12:00:00</td>
/// </tr>
/// <tr>
/// <td>11:17:41</td>
/// <td>1</td>
/// <td>11:08:00</td>
/// </tr>
/// </table>
/// </para>
/// </remarks>
/// <param name="date"></param>
/// the Date to round, if <see langword="null" /> the current time will
/// be used
/// <param name="minuteBase"></param>
/// the base-minute to set the time on
/// <returns>the new rounded date</returns>
/// <seealso cref="NextGivenSecondDate(DateTimeOffset?, int)" />
public static DateTimeOffset NextGivenMinuteDate(DateTimeOffset? date, int minuteBase)
{
if (minuteBase < 0 || minuteBase > 59)
{
throw new ArgumentException("minuteBase must be >=0 and <= 59");
}
DateTimeOffset c = date ?? SystemTime.Now();
if (minuteBase == 0)
{
return new DateTimeOffset(c.Year, c.Month, c.Day, c.Hour, 0, 0, 0, c.Offset).AddHours(1);
}
int minute = c.Minute;
int arItr = minute/minuteBase;
int nextMinuteOccurance = minuteBase*(arItr + 1);
if (nextMinuteOccurance < 60)
{
return new DateTimeOffset(c.Year, c.Month, c.Day, c.Hour, nextMinuteOccurance, 0, 0, c.Offset);
}
else
{
return new DateTimeOffset(c.Year, c.Month, c.Day, c.Hour, 0, 0, 0, c.Offset).AddHours(1);
}
}
/// <summary>
/// Returns a date that is rounded to the next even multiple of the given
/// minute.
/// </summary>
/// <remarks>
/// The rules for calculating the second are the same as those for
/// calculating the minute in the method <see cref="NextGivenMinuteDate" />.
/// </remarks>
/// <param name="date">the Date to round, if <see langword="null" /> the current time will</param>
/// be used
/// <param name="secondBase">the base-second to set the time on</param>
/// <returns>the new rounded date</returns>
/// <seealso cref="NextGivenMinuteDate(DateTimeOffset?, int)" />
public static DateTimeOffset NextGivenSecondDate(DateTimeOffset? date, int secondBase)
{
if (secondBase < 0 || secondBase > 59)
{
throw new ArgumentException("secondBase must be >=0 and <= 59");
}
DateTimeOffset c = date ?? SystemTime.Now();
if (secondBase == 0)
{
return new DateTimeOffset(c.Year, c.Month, c.Day, c.Hour, c.Minute, 0, 0, c.Offset).AddMinutes(1);
}
int second = c.Second;
int arItr = second/secondBase;
int nextSecondOccurance = secondBase*(arItr + 1);
if (nextSecondOccurance < 60)
{
return new DateTimeOffset(c.Year, c.Month, c.Day, c.Hour, c.Minute, nextSecondOccurance, 0, c.Offset);
}
else
{
return new DateTimeOffset(c.Year, c.Month, c.Day, c.Hour, c.Minute, 0, 0, c.Offset).AddMinutes(1);
}
}
public static void ValidateHour(int hour)
{
if (hour < 0 || hour > 23)
{
throw new ArgumentException("Invalid hour (must be >= 0 and <= 23).");
}
}
public static void ValidateMinute(int minute)
{
if (minute < 0 || minute > 59)
{
throw new ArgumentException("Invalid minute (must be >= 0 and <= 59).");
}
}
public static void ValidateSecond(int second)
{
if (second < 0 || second > 59)
{
throw new ArgumentException("Invalid second (must be >= 0 and <= 59).");
}
}
public static void ValidateDayOfMonth(int day)
{
if (day < 1 || day > 31)
{
throw new ArgumentException("Invalid day of month.");
}
}
public static void ValidateMonth(int month)
{
if (month < 1 || month > 12)
{
throw new ArgumentException("Invalid month (must be >= 1 and <= 12).");
}
}
public static void ValidateYear(int year)
{
if (year < 1970 || year > 2099)
{
throw new ArgumentException("Invalid year (must be >= 1970 and <= 2099).");
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------
//------------------------------------------------------------
using System.Runtime.Serialization;
using System.Diagnostics;
using System.Globalization;
using System.Text;
namespace System.Xml
{
internal enum ValueHandleConstStringType
{
String = 0,
Number = 1,
Array = 2,
Object = 3,
Boolean = 4,
Null = 5,
}
internal static class ValueHandleLength
{
public const int Int8 = 1;
public const int Int16 = 2;
public const int Int32 = 4;
public const int Int64 = 8;
public const int UInt64 = 8;
public const int Single = 4;
public const int Double = 8;
public const int Decimal = 16;
public const int DateTime = 8;
public const int TimeSpan = 8;
public const int Guid = 16;
public const int UniqueId = 16;
}
internal enum ValueHandleType
{
Empty,
True,
False,
Zero,
One,
Int8,
Int16,
Int32,
Int64,
UInt64,
Single,
Double,
Decimal,
DateTime,
TimeSpan,
Guid,
UniqueId,
UTF8,
EscapedUTF8,
Base64,
Dictionary,
List,
Char,
Unicode,
QName,
ConstString
}
internal class ValueHandle
{
private XmlBufferReader _bufferReader;
private ValueHandleType _type;
private int _offset;
private int _length;
private static Base64Encoding s_base64Encoding;
private static string[] s_constStrings = {
"string",
"number",
"array",
"object",
"boolean",
"null",
};
public ValueHandle(XmlBufferReader bufferReader)
{
_bufferReader = bufferReader;
_type = ValueHandleType.Empty;
}
private static Base64Encoding Base64Encoding
{
get
{
if (s_base64Encoding == null)
s_base64Encoding = new Base64Encoding();
return s_base64Encoding;
}
}
public void SetConstantValue(ValueHandleConstStringType constStringType)
{
_type = ValueHandleType.ConstString;
_offset = (int)constStringType;
}
public void SetValue(ValueHandleType type)
{
_type = type;
}
public void SetDictionaryValue(int key)
{
SetValue(ValueHandleType.Dictionary, key, 0);
}
public void SetCharValue(int ch)
{
SetValue(ValueHandleType.Char, ch, 0);
}
public void SetQNameValue(int prefix, int key)
{
SetValue(ValueHandleType.QName, key, prefix);
}
public void SetValue(ValueHandleType type, int offset, int length)
{
_type = type;
_offset = offset;
_length = length;
}
public bool IsWhitespace()
{
switch (_type)
{
case ValueHandleType.UTF8:
return _bufferReader.IsWhitespaceUTF8(_offset, _length);
case ValueHandleType.Dictionary:
return _bufferReader.IsWhitespaceKey(_offset);
case ValueHandleType.Char:
int ch = GetChar();
if (ch > char.MaxValue)
return false;
return XmlConverter.IsWhitespace((char)ch);
case ValueHandleType.EscapedUTF8:
return _bufferReader.IsWhitespaceUTF8(_offset, _length);
case ValueHandleType.Unicode:
return _bufferReader.IsWhitespaceUnicode(_offset, _length);
case ValueHandleType.True:
case ValueHandleType.False:
case ValueHandleType.Zero:
case ValueHandleType.One:
return false;
case ValueHandleType.ConstString:
return s_constStrings[_offset].Length == 0;
default:
return _length == 0;
}
}
public Type ToType()
{
switch (_type)
{
case ValueHandleType.False:
case ValueHandleType.True:
return typeof(bool);
case ValueHandleType.Zero:
case ValueHandleType.One:
case ValueHandleType.Int8:
case ValueHandleType.Int16:
case ValueHandleType.Int32:
return typeof(int);
case ValueHandleType.Int64:
return typeof(long);
case ValueHandleType.UInt64:
return typeof(ulong);
case ValueHandleType.Single:
return typeof(float);
case ValueHandleType.Double:
return typeof(double);
case ValueHandleType.Decimal:
return typeof(decimal);
case ValueHandleType.DateTime:
return typeof(DateTime);
case ValueHandleType.Empty:
case ValueHandleType.UTF8:
case ValueHandleType.Unicode:
case ValueHandleType.EscapedUTF8:
case ValueHandleType.Dictionary:
case ValueHandleType.Char:
case ValueHandleType.QName:
case ValueHandleType.ConstString:
return typeof(string);
case ValueHandleType.Base64:
return typeof(byte[]);
case ValueHandleType.List:
return typeof(object[]);
case ValueHandleType.UniqueId:
return typeof(UniqueId);
case ValueHandleType.Guid:
return typeof(Guid);
case ValueHandleType.TimeSpan:
return typeof(TimeSpan);
default:
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
}
}
public Boolean ToBoolean()
{
ValueHandleType type = _type;
if (type == ValueHandleType.False)
return false;
if (type == ValueHandleType.True)
return true;
if (type == ValueHandleType.UTF8)
return XmlConverter.ToBoolean(_bufferReader.Buffer, _offset, _length);
if (type == ValueHandleType.Int8)
{
int value = GetInt8();
if (value == 0)
return false;
if (value == 1)
return true;
}
return XmlConverter.ToBoolean(GetString());
}
public int ToInt()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type == ValueHandleType.Int8)
return GetInt8();
if (type == ValueHandleType.Int16)
return GetInt16();
if (type == ValueHandleType.Int32)
return GetInt32();
if (type == ValueHandleType.Int64)
{
long value = GetInt64();
if (value >= int.MinValue && value <= int.MaxValue)
{
return (int)value;
}
}
if (type == ValueHandleType.UInt64)
{
ulong value = GetUInt64();
if (value <= int.MaxValue)
{
return (int)value;
}
}
if (type == ValueHandleType.UTF8)
return XmlConverter.ToInt32(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToInt32(GetString());
}
public long ToLong()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type == ValueHandleType.Int8)
return GetInt8();
if (type == ValueHandleType.Int16)
return GetInt16();
if (type == ValueHandleType.Int32)
return GetInt32();
if (type == ValueHandleType.Int64)
return GetInt64();
if (type == ValueHandleType.UInt64)
{
ulong value = GetUInt64();
if (value <= long.MaxValue)
{
return (long)value;
}
}
if (type == ValueHandleType.UTF8)
{
return XmlConverter.ToInt64(_bufferReader.Buffer, _offset, _length);
}
return XmlConverter.ToInt64(GetString());
}
public ulong ToULong()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type >= ValueHandleType.Int8 && type <= ValueHandleType.Int64)
{
long value = ToLong();
if (value >= 0)
return (ulong)value;
}
if (type == ValueHandleType.UInt64)
return GetUInt64();
if (type == ValueHandleType.UTF8)
return XmlConverter.ToUInt64(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToUInt64(GetString());
}
public Single ToSingle()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Single)
return GetSingle();
if (type == ValueHandleType.Double)
{
double value = GetDouble();
if ((value >= Single.MinValue && value <= Single.MaxValue) || double.IsInfinity(value) || double.IsNaN(value))
return (Single)value;
}
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type == ValueHandleType.Int8)
return GetInt8();
if (type == ValueHandleType.Int16)
return GetInt16();
if (type == ValueHandleType.UTF8)
return XmlConverter.ToSingle(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToSingle(GetString());
}
public Double ToDouble()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Double)
return GetDouble();
if (type == ValueHandleType.Single)
return GetSingle();
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type == ValueHandleType.Int8)
return GetInt8();
if (type == ValueHandleType.Int16)
return GetInt16();
if (type == ValueHandleType.Int32)
return GetInt32();
if (type == ValueHandleType.UTF8)
return XmlConverter.ToDouble(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToDouble(GetString());
}
public Decimal ToDecimal()
{
ValueHandleType type = _type;
if (type == ValueHandleType.Decimal)
return GetDecimal();
if (type == ValueHandleType.Zero)
return 0;
if (type == ValueHandleType.One)
return 1;
if (type >= ValueHandleType.Int8 && type <= ValueHandleType.Int64)
return ToLong();
if (type == ValueHandleType.UInt64)
return GetUInt64();
if (type == ValueHandleType.UTF8)
return XmlConverter.ToDecimal(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToDecimal(GetString());
}
public DateTime ToDateTime()
{
if (_type == ValueHandleType.DateTime)
{
return XmlConverter.ToDateTime(GetInt64());
}
if (_type == ValueHandleType.UTF8)
{
return XmlConverter.ToDateTime(_bufferReader.Buffer, _offset, _length);
}
return XmlConverter.ToDateTime(GetString());
}
public UniqueId ToUniqueId()
{
if (_type == ValueHandleType.UniqueId)
return GetUniqueId();
if (_type == ValueHandleType.UTF8)
return XmlConverter.ToUniqueId(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToUniqueId(GetString());
}
public TimeSpan ToTimeSpan()
{
if (_type == ValueHandleType.TimeSpan)
return new TimeSpan(GetInt64());
if (_type == ValueHandleType.UTF8)
return XmlConverter.ToTimeSpan(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToTimeSpan(GetString());
}
public Guid ToGuid()
{
if (_type == ValueHandleType.Guid)
return GetGuid();
if (_type == ValueHandleType.UTF8)
return XmlConverter.ToGuid(_bufferReader.Buffer, _offset, _length);
return XmlConverter.ToGuid(GetString());
}
public override string ToString()
{
return GetString();
}
public byte[] ToByteArray()
{
if (_type == ValueHandleType.Base64)
{
byte[] buffer = new byte[_length];
GetBase64(buffer, 0, _length);
return buffer;
}
if (_type == ValueHandleType.UTF8 && (_length % 4) == 0)
{
try
{
int expectedLength = _length / 4 * 3;
if (_length > 0)
{
if (_bufferReader.Buffer[_offset + _length - 1] == '=')
{
expectedLength--;
if (_bufferReader.Buffer[_offset + _length - 2] == '=')
expectedLength--;
}
}
byte[] buffer = new byte[expectedLength];
int actualLength = Base64Encoding.GetBytes(_bufferReader.Buffer, _offset, _length, buffer, 0);
if (actualLength != buffer.Length)
{
byte[] newBuffer = new byte[actualLength];
Buffer.BlockCopy(buffer, 0, newBuffer, 0, actualLength);
buffer = newBuffer;
}
return buffer;
}
catch (FormatException)
{
// Something unhappy with the characters, fall back to the hard way
}
}
try
{
return Base64Encoding.GetBytes(XmlConverter.StripWhitespace(GetString()));
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(exception.Message, exception.InnerException));
}
}
public string GetString()
{
ValueHandleType type = _type;
if (type == ValueHandleType.UTF8)
return GetCharsText();
switch (type)
{
case ValueHandleType.False:
return "false";
case ValueHandleType.True:
return "true";
case ValueHandleType.Zero:
return "0";
case ValueHandleType.One:
return "1";
case ValueHandleType.Int8:
case ValueHandleType.Int16:
case ValueHandleType.Int32:
return XmlConverter.ToString(ToInt());
case ValueHandleType.Int64:
return XmlConverter.ToString(GetInt64());
case ValueHandleType.UInt64:
return XmlConverter.ToString(GetUInt64());
case ValueHandleType.Single:
return XmlConverter.ToString(GetSingle());
case ValueHandleType.Double:
return XmlConverter.ToString(GetDouble());
case ValueHandleType.Decimal:
return XmlConverter.ToString(GetDecimal());
case ValueHandleType.DateTime:
return XmlConverter.ToString(ToDateTime());
case ValueHandleType.Empty:
return string.Empty;
case ValueHandleType.UTF8:
return GetCharsText();
case ValueHandleType.Unicode:
return GetUnicodeCharsText();
case ValueHandleType.EscapedUTF8:
return GetEscapedCharsText();
case ValueHandleType.Char:
return GetCharText();
case ValueHandleType.Dictionary:
return GetDictionaryString().Value;
case ValueHandleType.Base64:
byte[] bytes = ToByteArray();
DiagnosticUtility.DebugAssert(bytes != null, "");
return Base64Encoding.GetString(bytes, 0, bytes.Length);
case ValueHandleType.List:
return XmlConverter.ToString(ToList());
case ValueHandleType.UniqueId:
return XmlConverter.ToString(ToUniqueId());
case ValueHandleType.Guid:
return XmlConverter.ToString(ToGuid());
case ValueHandleType.TimeSpan:
return XmlConverter.ToString(ToTimeSpan());
case ValueHandleType.QName:
return GetQNameDictionaryText();
case ValueHandleType.ConstString:
return s_constStrings[_offset];
default:
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
}
}
// ASSUMPTION (Microsoft): all chars in str will be ASCII
public bool Equals2(string str, bool checkLower)
{
if (_type != ValueHandleType.UTF8)
return GetString() == str;
if (_length != str.Length)
return false;
byte[] buffer = _bufferReader.Buffer;
for (int i = 0; i < _length; ++i)
{
DiagnosticUtility.DebugAssert(str[i] < 128, "");
byte ch = buffer[i + _offset];
if (ch == str[i])
continue;
if (checkLower && char.ToLowerInvariant((char)ch) == str[i])
continue;
return false;
}
return true;
}
public object[] ToList()
{
return _bufferReader.GetList(_offset, _length);
}
public object ToObject()
{
switch (_type)
{
case ValueHandleType.False:
case ValueHandleType.True:
return ToBoolean();
case ValueHandleType.Zero:
case ValueHandleType.One:
case ValueHandleType.Int8:
case ValueHandleType.Int16:
case ValueHandleType.Int32:
return ToInt();
case ValueHandleType.Int64:
return ToLong();
case ValueHandleType.UInt64:
return GetUInt64();
case ValueHandleType.Single:
return ToSingle();
case ValueHandleType.Double:
return ToDouble();
case ValueHandleType.Decimal:
return ToDecimal();
case ValueHandleType.DateTime:
return ToDateTime();
case ValueHandleType.Empty:
case ValueHandleType.UTF8:
case ValueHandleType.Unicode:
case ValueHandleType.EscapedUTF8:
case ValueHandleType.Dictionary:
case ValueHandleType.Char:
case ValueHandleType.ConstString:
return ToString();
case ValueHandleType.Base64:
return ToByteArray();
case ValueHandleType.List:
return ToList();
case ValueHandleType.UniqueId:
return ToUniqueId();
case ValueHandleType.Guid:
return ToGuid();
case ValueHandleType.TimeSpan:
return ToTimeSpan();
default:
throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException());
}
}
public bool TryReadBase64(byte[] buffer, int offset, int count, out int actual)
{
if (_type == ValueHandleType.Base64)
{
actual = Math.Min(_length, count);
GetBase64(buffer, offset, actual);
_offset += actual;
_length -= actual;
return true;
}
if (_type == ValueHandleType.UTF8 && count >= 3 && (_length % 4) == 0)
{
try
{
int charCount = Math.Min(count / 3 * 4, _length);
actual = Base64Encoding.GetBytes(_bufferReader.Buffer, _offset, charCount, buffer, offset);
_offset += charCount;
_length -= charCount;
return true;
}
catch (FormatException)
{
// Something unhappy with the characters, fall back to the hard way
}
}
actual = 0;
return false;
}
public bool TryReadChars(char[] chars, int offset, int count, out int actual)
{
if (_type == ValueHandleType.Unicode)
return TryReadUnicodeChars(chars, offset, count, out actual);
if (_type != ValueHandleType.UTF8)
{
actual = 0;
return false;
}
int charOffset = offset;
int charCount = count;
byte[] bytes = _bufferReader.Buffer;
int byteOffset = _offset;
int byteCount = _length;
while (true)
{
while (charCount > 0 && byteCount > 0)
{
byte b = bytes[byteOffset];
if (b >= 0x80)
break;
chars[charOffset] = (char)b;
byteOffset++;
byteCount--;
charOffset++;
charCount--;
}
if (charCount == 0 || byteCount == 0)
break;
int actualByteCount;
int actualCharCount;
UTF8Encoding encoding = new UTF8Encoding(false, true);
try
{
// If we're asking for more than are possibly available, or more than are truly available then we can return the entire thing
if (charCount >= encoding.GetMaxCharCount(byteCount) || charCount >= encoding.GetCharCount(bytes, byteOffset, byteCount))
{
actualCharCount = encoding.GetChars(bytes, byteOffset, byteCount, chars, charOffset);
actualByteCount = byteCount;
}
else
{
Decoder decoder = encoding.GetDecoder();
// Since x bytes can never generate more than x characters this is a safe estimate as to what will fit
actualByteCount = Math.Min(charCount, byteCount);
// We use a decoder so we don't error if we fall across a character boundary
actualCharCount = decoder.GetChars(bytes, byteOffset, actualByteCount, chars, charOffset);
// We might've gotten zero characters though if < 3 chars were requested
// (e.g. 1 char requested, 1 char in the buffer represented in 3 bytes)
while (actualCharCount == 0)
{
// Request a few more bytes to get at least one character
actualCharCount = decoder.GetChars(bytes, byteOffset + actualByteCount, 1, chars, charOffset);
actualByteCount++;
}
// Now that we actually retrieved some characters, figure out how many bytes it actually was
actualByteCount = encoding.GetByteCount(chars, charOffset, actualCharCount);
}
}
catch (FormatException exception)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlExceptionHelper.CreateEncodingException(bytes, byteOffset, byteCount, exception));
}
// Advance
byteOffset += actualByteCount;
byteCount -= actualByteCount;
charOffset += actualCharCount;
charCount -= actualCharCount;
}
_offset = byteOffset;
_length = byteCount;
actual = (count - charCount);
return true;
}
private bool TryReadUnicodeChars(char[] chars, int offset, int count, out int actual)
{
int charCount = Math.Min(count, _length / sizeof(char));
for (int i = 0; i < charCount; i++)
{
chars[offset + i] = (char)_bufferReader.GetInt16(_offset + i * sizeof(char));
}
_offset += charCount * sizeof(char);
_length -= charCount * sizeof(char);
actual = charCount;
return true;
}
public bool TryGetDictionaryString(out XmlDictionaryString value)
{
if (_type == ValueHandleType.Dictionary)
{
value = GetDictionaryString();
return true;
}
else
{
value = null;
return false;
}
}
public bool TryGetByteArrayLength(out int length)
{
if (_type == ValueHandleType.Base64)
{
length = _length;
return true;
}
length = 0;
return false;
}
private string GetCharsText()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.UTF8, "");
if (_length == 1 && _bufferReader.GetByte(_offset) == '1')
return "1";
return _bufferReader.GetString(_offset, _length);
}
private string GetUnicodeCharsText()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Unicode, "");
return _bufferReader.GetUnicodeString(_offset, _length);
}
private string GetEscapedCharsText()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.EscapedUTF8, "");
return _bufferReader.GetEscapedString(_offset, _length);
}
private string GetCharText()
{
int ch = GetChar();
if (ch > char.MaxValue)
{
SurrogateChar surrogate = new SurrogateChar(ch);
char[] chars = new char[2];
chars[0] = surrogate.HighChar;
chars[1] = surrogate.LowChar;
return new string(chars, 0, 2);
}
else
{
return ((char)ch).ToString();
}
}
private int GetChar()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Char, "");
return _offset;
}
private int GetInt8()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int8, "");
return _bufferReader.GetInt8(_offset);
}
private int GetInt16()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int16, "");
return _bufferReader.GetInt16(_offset);
}
private int GetInt32()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int32, "");
return _bufferReader.GetInt32(_offset);
}
private long GetInt64()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Int64 || _type == ValueHandleType.TimeSpan || _type == ValueHandleType.DateTime, "");
return _bufferReader.GetInt64(_offset);
}
private ulong GetUInt64()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.UInt64, "");
return _bufferReader.GetUInt64(_offset);
}
private float GetSingle()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Single, "");
return _bufferReader.GetSingle(_offset);
}
private double GetDouble()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Double, "");
return _bufferReader.GetDouble(_offset);
}
private decimal GetDecimal()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Decimal, "");
return _bufferReader.GetDecimal(_offset);
}
private UniqueId GetUniqueId()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.UniqueId, "");
return _bufferReader.GetUniqueId(_offset);
}
private Guid GetGuid()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Guid, "");
return _bufferReader.GetGuid(_offset);
}
private void GetBase64(byte[] buffer, int offset, int count)
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Base64, "");
_bufferReader.GetBase64(_offset, buffer, offset, count);
}
private XmlDictionaryString GetDictionaryString()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.Dictionary, "");
return _bufferReader.GetDictionaryString(_offset);
}
private string GetQNameDictionaryText()
{
DiagnosticUtility.DebugAssert(_type == ValueHandleType.QName, "");
return string.Concat(PrefixHandle.GetString(PrefixHandle.GetAlphaPrefix(_length)), ":", _bufferReader.GetDictionaryString(_offset));
}
}
}
| |
// 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.Threading;
using Xunit;
namespace System.Linq.Parallel.Tests
{
public static class SequenceEqualTests
{
private const int DuplicateFactor = 8;
//
// SequenceEqual
//
public static IEnumerable<object[]> SequenceEqualData(int[] counts)
{
foreach (object[] left in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 4)))
{
foreach (object[] right in Sources.Ranges(new[] { (int)left[1] }))
{
yield return new object[] { left[0], right[0], right[1] };
}
}
}
public static IEnumerable<object[]> SequenceEqualUnequalSizeData(int[] counts)
{
foreach (object[] left in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 4)))
{
foreach (object[] right in Sources.Ranges(new[] { 1, ((int)left[1] - 1) / 2 + 1, (int)left[1] * 2 + 1 }.Distinct()))
{
yield return new object[] { left[0], left[1], right[0], right[1] };
}
}
}
public static IEnumerable<object[]> SequenceEqualUnequalData(int[] counts)
{
foreach (object[] left in Sources.Ranges(counts.DefaultIfEmpty(Sources.OuterLoopCount / 4)))
{
Func<int, IEnumerable<int>> items = x => new[] { 0, x / 8, x / 2, x * 7 / 8, x - 1 }.Distinct();
foreach (object[] right in Sources.Ranges(new[] { (int)left[1] }, items))
{
yield return new object[] { left[0], right[0], right[1], right[2] };
}
}
}
[Theory]
[MemberData(nameof(SequenceEqualData), new[] { 0, 1, 2, 16 })]
public static void SequenceEqual(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
Assert.True(leftQuery.SequenceEqual(rightQuery));
Assert.True(rightQuery.SequenceEqual(leftQuery));
Assert.True(leftQuery.SequenceEqual(leftQuery));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SequenceEqualData), new int[] { /* Sources.OuterLoopCount */ })]
public static void SequenceEqual_Longrunning(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
SequenceEqual(left, right, count);
}
[Theory]
[MemberData(nameof(SequenceEqualData), new[] { 0, 1, 2, 16 })]
public static void SequenceEqual_CustomComparator(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
Assert.True(leftQuery.SequenceEqual(rightQuery, new ModularCongruenceComparer(DuplicateFactor)));
Assert.True(rightQuery.SequenceEqual(leftQuery, new ModularCongruenceComparer(DuplicateFactor)));
Assert.True(leftQuery.SequenceEqual(leftQuery, new ModularCongruenceComparer(DuplicateFactor)));
ParallelQuery<int> repeating = Enumerable.Range(0, (count + (DuplicateFactor - 1)) / DuplicateFactor).SelectMany(x => Enumerable.Range(0, DuplicateFactor)).Take(count).AsParallel().AsOrdered();
Assert.True(leftQuery.SequenceEqual(repeating, new ModularCongruenceComparer(DuplicateFactor)));
Assert.True(rightQuery.SequenceEqual(repeating, new ModularCongruenceComparer(DuplicateFactor)));
Assert.True(repeating.SequenceEqual(rightQuery, new ModularCongruenceComparer(DuplicateFactor)));
Assert.True(repeating.SequenceEqual(leftQuery, new ModularCongruenceComparer(DuplicateFactor)));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SequenceEqualData), new int[] { /* Sources.OuterLoopCount */ })]
public static void SequenceEqual_CustomComparator_Longrunning(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
SequenceEqual_CustomComparator(left, right, count);
}
[Theory]
[MemberData(nameof(SequenceEqualUnequalSizeData), new[] { 0, 4, 16 })]
public static void SequenceEqual_UnequalSize(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
Assert.False(leftQuery.SequenceEqual(rightQuery));
Assert.False(rightQuery.SequenceEqual(leftQuery));
Assert.False(leftQuery.SequenceEqual(rightQuery, new ModularCongruenceComparer(2)));
Assert.False(rightQuery.SequenceEqual(leftQuery, new ModularCongruenceComparer(2)));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SequenceEqualUnequalSizeData), new int[] { /* Sources.OuterLoopCount */ })]
public static void SequenceEqual_UnequalSize_Longrunning(Labeled<ParallelQuery<int>> left, int leftCount, Labeled<ParallelQuery<int>> right, int rightCount)
{
SequenceEqual_UnequalSize(left, leftCount, right, rightCount);
}
[Theory]
[MemberData(nameof(SequenceEqualUnequalData), new[] { 1, 2, 16 })]
public static void SequenceEqual_Unequal(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count, int item)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item.Select(x => x == item ? -1 : x);
Assert.False(leftQuery.SequenceEqual(rightQuery));
Assert.False(rightQuery.SequenceEqual(leftQuery));
Assert.True(leftQuery.SequenceEqual(leftQuery));
}
[Theory]
[OuterLoop]
[MemberData(nameof(SequenceEqualUnequalData), new int[] { /* Sources.OuterLoopCount */ })]
public static void SequenceEqual_Unequal_Longrunning(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count, int item)
{
SequenceEqual_Unequal(left, right, count, item);
}
public static void SequenceEqual_NotSupportedException()
{
#pragma warning disable 618
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).SequenceEqual(Enumerable.Range(0, 1)));
Assert.Throws<NotSupportedException>(() => ParallelEnumerable.Range(0, 1).SequenceEqual(Enumerable.Range(0, 1), null));
#pragma warning restore 618
}
[Fact]
public static void SequenceEqual_OperationCanceledException()
{
AssertThrows.EventuallyCanceled((source, canceler) => source.OrderBy(x => x).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered(), new CancelingEqualityComparer<int>(canceler)));
AssertThrows.EventuallyCanceled((source, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(source.OrderBy(x => x), new CancelingEqualityComparer<int>(canceler)));
}
[Fact]
public static void SequenceEqual_AggregateException_Wraps_OperationCanceledException()
{
AssertThrows.OtherTokenCanceled((source, canceler) => source.OrderBy(x => x).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered(), new CancelingEqualityComparer<int>(canceler)));
AssertThrows.OtherTokenCanceled((source, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(source.OrderBy(x => x), new CancelingEqualityComparer<int>(canceler)));
AssertThrows.SameTokenNotCanceled((source, canceler) => source.OrderBy(x => x).SequenceEqual(ParallelEnumerable.Range(0, 128).AsOrdered(), new CancelingEqualityComparer<int>(canceler)));
AssertThrows.SameTokenNotCanceled((source, canceler) => ParallelEnumerable.Range(0, 128).AsOrdered().SequenceEqual(source.OrderBy(x => x), new CancelingEqualityComparer<int>(canceler)));
}
[Fact]
public static void SequenceEqual_OperationCanceledException_PreCanceled()
{
AssertThrows.AlreadyCanceled(source => source.SequenceEqual(ParallelEnumerable.Range(0, 2)));
AssertThrows.AlreadyCanceled(source => source.SequenceEqual(ParallelEnumerable.Range(0, 2), new ModularCongruenceComparer(1)));
AssertThrows.AlreadyCanceled(source => ParallelEnumerable.Range(0, 2).SequenceEqual(source));
AssertThrows.AlreadyCanceled(source => ParallelEnumerable.Range(0, 2).SequenceEqual(source, new ModularCongruenceComparer(1)));
}
[Theory]
[MemberData(nameof(SequenceEqualData), new[] { 4 })]
public static void SequenceEqual_AggregateException(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
AssertThrows.Wrapped<DeliberateTestException>(() => left.Item.SequenceEqual(right.Item, new FailingEqualityComparer<int>()));
}
[Fact]
// Should not get the same setting from both operands.
public static void SequenceEqual_NoDuplicateSettings()
{
CancellationToken t = new CancellationTokenSource().Token;
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithCancellation(t).SequenceEqual(ParallelEnumerable.Range(0, 1).WithCancellation(t)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1).SequenceEqual(ParallelEnumerable.Range(0, 1).WithDegreeOfParallelism(1)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default).SequenceEqual(ParallelEnumerable.Range(0, 1).WithExecutionMode(ParallelExecutionMode.Default)));
Assert.Throws<InvalidOperationException>(() => ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default).SequenceEqual(ParallelEnumerable.Range(0, 1).WithMergeOptions(ParallelMergeOptions.Default)));
}
[Fact]
public static void SequenceEqual_ArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).SequenceEqual(ParallelEnumerable.Range(0, 1)));
AssertExtensions.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).SequenceEqual((ParallelQuery<int>)null));
AssertExtensions.Throws<ArgumentNullException>("first", () => ((ParallelQuery<int>)null).SequenceEqual(ParallelEnumerable.Range(0, 1), EqualityComparer<int>.Default));
AssertExtensions.Throws<ArgumentNullException>("second", () => ParallelEnumerable.Range(0, 1).SequenceEqual((ParallelQuery<int>)null, EqualityComparer<int>.Default));
}
[Theory]
[MemberData(nameof(SequenceEqualData), new[] { 0, 1, 2, 16 })]
public static void SequenceEqual_DisposeException(Labeled<ParallelQuery<int>> left, Labeled<ParallelQuery<int>> right, int count)
{
ParallelQuery<int> leftQuery = left.Item;
ParallelQuery<int> rightQuery = right.Item;
AssertThrows.Wrapped<TestDisposeException>(() => leftQuery.SequenceEqual(new DisposeExceptionEnumerable<int>(rightQuery).AsParallel()));
AssertThrows.Wrapped<TestDisposeException>(() => new DisposeExceptionEnumerable<int>(leftQuery).AsParallel().SequenceEqual(rightQuery));
}
private class DisposeExceptionEnumerable<T> : IEnumerable<T>
{
private IEnumerable<T> _enumerable;
public DisposeExceptionEnumerable(IEnumerable<T> enumerable)
{
_enumerable = enumerable;
}
public IEnumerator<T> GetEnumerator()
{
return new DisposeExceptionEnumerator(_enumerable.GetEnumerator());
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private class DisposeExceptionEnumerator : IEnumerator<T>
{
private IEnumerator<T> _enumerator;
public DisposeExceptionEnumerator(IEnumerator<T> enumerator)
{
_enumerator = enumerator;
}
public T Current
{
get { return _enumerator.Current; }
}
public void Dispose()
{
throw new TestDisposeException();
}
object IEnumerator.Current
{
get { return Current; }
}
public bool MoveNext()
{
return _enumerator.MoveNext();
}
public void Reset()
{
_enumerator.Reset();
}
}
}
private class TestDisposeException : Exception
{
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Abp.App.TestWebAPI.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
internal const int DefaultCollectionSize = 2;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// 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;
namespace Repro
{
class Program
{
static int Test(
int a00, int a01, int a02, int a03, int a04, int a05, int a06, int a07, int a08, int a09,
int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19,
int a20, int a21, int a22, int a23, int a24, int a25, int a26, int a27, int a28, int a29,
int a30, int a31, int a32, int a33, int a34, int a35, int a36, int a37, int a38, int a39,
int a40, int a41, int a42, int a43, int a44, int a45, int a46, int a47, int a48, int a49,
int a50, int a51, int a52, int a53, int a54, int a55, int a56, int a57, int a58, int a59,
int a60, int a61, int a62, int a63, int a64, int a65, int a66, int a67, int a68, int a69,
int a70, int a71, int a72, int a73, int a74, int a75, int a76, int a77, int a78, int a79,
int a80, int a81, int a82, int a83, int a84, int a85, int a86, int a87, int a88, int a89,
int a90, int a91, int a92, int a93, int a94, int a95, int a96, int a97, int a98, int a99,
int b00, int b01, int b02, int b03, int b04, int b05, int b06, int b07, int b08, int b09,
int b10, int b11, int b12, int b13, int b14, int b15, int b16, int b17, int b18, int b19,
int b20, int b21, int b22, int b23, int b24, int b25, int b26, int b27, int b28, int b29,
int b30, int b31, int b32, int b33, int b34, int b35, int b36, int b37, int b38, int b39,
int b40, int b41, int b42, int b43, int b44, int b45, int b46, int b47, int b48, int b49,
int b50, int b51, int b52, int b53, int b54, int b55, int b56, int b57, int b58, int b59,
int b60, int b61, int b62, int b63, int b64, int b65, int b66, int b67, int b68, int b69,
int b70, int b71, int b72, int b73, int b74, int b75, int b76, int b77, int b78, int b79,
int b80, int b81, int b82, int b83, int b84, int b85, int b86, int b87, int b88, int b89,
int b90, int b91, int b92, int b93, int b94, int b95, int b96, int b97, int b98, int b99)
{
int result = a00 + a30 + a60 + a90 + b20 + b50 + b80;
// We will make one recursive call to Test()
if (a00 == 1)
{
return result;
}
else
{
// Using the ? : operator causes us to spill the entire stack and reload it after each arg
// This creates N^2 LclVar temps 200 * 200 = 40000
// If the OutgoingArg variable number is setup after these 40,000 LclVars it will
// cause the emitter to hit an IMPL_LIMITATION when storing into the OutGoingArg area:
// This shows up as
//
// Unhandled Exception: System.InvalidProgramException:
// at Repro.Program.Test(...
//
// Since our arguments are sorted this code simply shuffles the arguments downward
// like this: Test(a1, a2, a3 ...
//
return result +
Test(
(a00 < a01) ? a01 : a00,
(a01 < a02) ? a02 : a01,
(a02 < a03) ? a03 : a02,
(a03 < a04) ? a04 : a03,
(a04 < a05) ? a05 : a04,
(a05 < a06) ? a06 : a05,
(a06 < a07) ? a07 : a06,
(a07 < a08) ? a08 : a07,
(a08 < a09) ? a09 : a08,
(a09 < a10) ? a10 : a09,
(a10 < a11) ? a11 : a10,
(a11 < a12) ? a12 : a11,
(a12 < a13) ? a13 : a12,
(a13 < a14) ? a14 : a13,
(a14 < a15) ? a15 : a14,
(a15 < a16) ? a16 : a15,
(a16 < a17) ? a17 : a16,
(a17 < a18) ? a18 : a17,
(a18 < a19) ? a19 : a18,
(a19 < a10) ? a10 : a19,
(a20 < a21) ? a21 : a20,
(a21 < a22) ? a22 : a21,
(a22 < a23) ? a23 : a22,
(a23 < a24) ? a24 : a23,
(a24 < a25) ? a25 : a24,
(a25 < a26) ? a26 : a25,
(a26 < a27) ? a27 : a26,
(a27 < a28) ? a28 : a27,
(a28 < a29) ? a29 : a28,
(a29 < a20) ? a20 : a29,
(a30 < a31) ? a31 : a30,
(a31 < a32) ? a32 : a31,
(a32 < a33) ? a33 : a32,
(a33 < a34) ? a34 : a33,
(a34 < a35) ? a35 : a34,
(a35 < a36) ? a36 : a35,
(a36 < a37) ? a37 : a36,
(a37 < a38) ? a38 : a37,
(a38 < a39) ? a39 : a38,
(a39 < a30) ? a30 : a39,
(a40 < a41) ? a41 : a40,
(a41 < a42) ? a42 : a41,
(a42 < a43) ? a43 : a42,
(a43 < a44) ? a44 : a43,
(a44 < a45) ? a45 : a44,
(a45 < a46) ? a46 : a45,
(a46 < a47) ? a47 : a46,
(a47 < a48) ? a48 : a47,
(a48 < a49) ? a49 : a48,
(a49 < a40) ? a40 : a49,
(a50 < a51) ? a51 : a50,
(a51 < a52) ? a52 : a51,
(a52 < a53) ? a53 : a52,
(a53 < a54) ? a54 : a53,
(a54 < a55) ? a55 : a54,
(a55 < a56) ? a56 : a55,
(a56 < a57) ? a57 : a56,
(a57 < a58) ? a58 : a57,
(a58 < a59) ? a59 : a58,
(a59 < a50) ? a50 : a59,
(a60 < a61) ? a61 : a60,
(a61 < a62) ? a62 : a61,
(a62 < a63) ? a63 : a62,
(a63 < a64) ? a64 : a63,
(a64 < a65) ? a65 : a64,
(a65 < a66) ? a66 : a65,
(a66 < a67) ? a67 : a66,
(a67 < a68) ? a68 : a67,
(a68 < a69) ? a69 : a68,
(a69 < a60) ? a60 : a69,
(a70 < a71) ? a71 : a70,
(a71 < a72) ? a72 : a71,
(a72 < a73) ? a73 : a72,
(a73 < a74) ? a74 : a73,
(a74 < a75) ? a75 : a74,
(a75 < a76) ? a76 : a75,
(a76 < a77) ? a77 : a76,
(a77 < a78) ? a78 : a77,
(a78 < a79) ? a79 : a78,
(a79 < a70) ? a70 : a79,
(a80 < a81) ? a81 : a80,
(a81 < a82) ? a82 : a81,
(a82 < a83) ? a83 : a82,
(a83 < a84) ? a84 : a83,
(a84 < a85) ? a85 : a84,
(a85 < a86) ? a86 : a85,
(a86 < a87) ? a87 : a86,
(a87 < a88) ? a88 : a87,
(a88 < a89) ? a89 : a88,
(a89 < a80) ? a80 : a89,
(a90 < a91) ? a91 : a90,
(a91 < a92) ? a92 : a91,
(a92 < a93) ? a93 : a92,
(a93 < a94) ? a94 : a93,
(a94 < a95) ? a95 : a94,
(a95 < a96) ? a96 : a95,
(a96 < a97) ? a97 : a96,
(a97 < a98) ? a98 : a97,
(a98 < a99) ? a99 : a98,
(a99 < b00) ? b00 : a99,
(b00 < b01) ? b01 : b00,
(b01 < b02) ? b02 : b01,
(b02 < b03) ? b03 : b02,
(b03 < b04) ? b04 : b03,
(b04 < b05) ? b05 : b04,
(b05 < b06) ? b06 : b05,
(b06 < b07) ? b07 : b06,
(b07 < b08) ? b08 : b07,
(b08 < b09) ? b09 : b08,
(b09 < b10) ? b10 : b09,
(b10 < b11) ? b11 : b10,
(b11 < b12) ? b12 : b11,
(b12 < b13) ? b13 : b12,
(b13 < b14) ? b14 : b13,
(b14 < b15) ? b15 : b14,
(b15 < b16) ? b16 : b15,
(b16 < b17) ? b17 : b16,
(b17 < b18) ? b18 : b17,
(b18 < b19) ? b19 : b18,
(b19 < b10) ? b10 : b19,
(b20 < b21) ? b21 : b20,
(b21 < b22) ? b22 : b21,
(b22 < b23) ? b23 : b22,
(b23 < b24) ? b24 : b23,
(b24 < b25) ? b25 : b24,
(b25 < b26) ? b26 : b25,
(b26 < b27) ? b27 : b26,
(b27 < b28) ? b28 : b27,
(b28 < b29) ? b29 : b28,
(b29 < b20) ? b20 : b29,
(b30 < b31) ? b31 : b30,
(b31 < b32) ? b32 : b31,
(b32 < b33) ? b33 : b32,
(b33 < b34) ? b34 : b33,
(b34 < b35) ? b35 : b34,
(b35 < b36) ? b36 : b35,
(b36 < b37) ? b37 : b36,
(b37 < b38) ? b38 : b37,
(b38 < b39) ? b39 : b38,
(b39 < b30) ? b30 : b39,
(b40 < b41) ? b41 : b40,
(b41 < b42) ? b42 : b41,
(b42 < b43) ? b43 : b42,
(b43 < b44) ? b44 : b43,
(b44 < b45) ? b45 : b44,
(b45 < b46) ? b46 : b45,
(b46 < b47) ? b47 : b46,
(b47 < b48) ? b48 : b47,
(b48 < b49) ? b49 : b48,
(b49 < b40) ? b40 : b49,
(b50 < b51) ? b51 : b50,
(b51 < b52) ? b52 : b51,
(b52 < b53) ? b53 : b52,
(b53 < b54) ? b54 : b53,
(b54 < b55) ? b55 : b54,
(b55 < b56) ? b56 : b55,
(b56 < b57) ? b57 : b56,
(b57 < b58) ? b58 : b57,
(b58 < b59) ? b59 : b58,
(b59 < b50) ? b50 : b59,
(b60 < b61) ? b61 : b60,
(b61 < b62) ? b62 : b61,
(b62 < b63) ? b63 : b62,
(b63 < b64) ? b64 : b63,
(b64 < b65) ? b65 : b64,
(b65 < b66) ? b66 : b65,
(b66 < b67) ? b67 : b66,
(b67 < b68) ? b68 : b67,
(b68 < b69) ? b69 : b68,
(b69 < b60) ? b60 : b69,
(b70 < b71) ? b71 : b70,
(b71 < b72) ? b72 : b71,
(b72 < b73) ? b73 : b72,
(b73 < b74) ? b74 : b73,
(b74 < b75) ? b75 : b74,
(b75 < b76) ? b76 : b75,
(b76 < b77) ? b77 : b76,
(b77 < b78) ? b78 : b77,
(b78 < b79) ? b79 : b78,
(b79 < b70) ? b70 : b79,
(b80 < b81) ? b81 : b80,
(b81 < b82) ? b82 : b81,
(b82 < b83) ? b83 : b82,
(b83 < b84) ? b84 : b83,
(b84 < b85) ? b85 : b84,
(b85 < b86) ? b86 : b85,
(b86 < b87) ? b87 : b86,
(b87 < b88) ? b88 : b87,
(b88 < b89) ? b89 : b88,
(b89 < b80) ? b80 : b89,
(b90 < b91) ? b91 : b90,
(b91 < b92) ? b92 : b91,
(b92 < b93) ? b93 : b92,
(b93 < b94) ? b94 : b93,
(b94 < b95) ? b95 : b94,
(b95 < b96) ? b96 : b95,
(b96 < b97) ? b97 : b96,
(b97 < b98) ? b98 : b97,
(b98 < b99) ? b99 : b98,
(b99 < a00) ? a00 : b99);
}
}
static int Main(string[] args)
{
int result = Test( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99,
100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
130, 131, 132, 133, 134, 135, 136, 137, 138, 139,
140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
150, 151, 152, 153, 154, 155, 156, 157, 158, 159,
160, 161, 162, 163, 164, 165, 166, 167, 168, 169,
170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
190, 191, 192, 193, 194, 195, 196, 197, 198, 199);
if (result == 1267)
{
Console.WriteLine("Test Passed");
// Correct result
return 100;
}
else
{
Console.WriteLine("*** FAILED ***, result was " + result);
// Incorrect result
return -1;
}
}
}
}
| |
/*
Copyright (c) 2001 Lapo Luchini.
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 names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 AUTHORS
OR ANY CONTRIBUTORS TO THIS 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.
*/
/*
* This program is based on zlib-1.1.3, so all credit should go authors
* Jean-loup Gailly(jloup@gzip.org) and Mark Adler(madler@alumni.caltech.edu)
* and contributors of zlib.
*/
/* This file is a port of jzlib v1.0.7, com.jcraft.jzlib.ZInputStream.java
*/
using Renci.SshNet.Compression;
using System;
using System.Diagnostics;
using System.IO;
namespace Org.BouncyCastle.Utilities.Zlib
{
public class ZInputStream : Stream
{
private const int BufferSize = 512;
//private ZStream z = new ZStream();
private ICompressor _compressor;
// TODO Allow custom buf
private byte[] _buffer = new byte[BufferSize];
private CompressionMode _compressionMode;
private Stream _input;
private bool _isClosed;
private bool _noMoreInput = false;
public FlushType FlushMode { get; private set; }
public ZInputStream()
{
this.FlushMode = FlushType.Z_PARTIAL_FLUSH;
}
public ZInputStream(Stream input)
: this(input, false)
{
}
public ZInputStream(Stream input, bool nowrap)
: this()
{
Debug.Assert(input.CanRead);
this._input = input;
this._compressor = new Inflate(nowrap);
//this._compressor.inflateInit(nowrap);
this._compressionMode = CompressionMode.Decompress;
this._compressor.next_in = _buffer;
this._compressor.next_in_index = 0;
this._compressor.avail_in = 0;
}
public ZInputStream(Stream input, CompressionLevel level)
: this()
{
Debug.Assert(input.CanRead);
this._input = input;
this._compressor = new Deflate(level);
//this._compressor.deflateInit(level);
this._compressionMode = CompressionMode.Compress;
this._compressor.next_in = _buffer;
this._compressor.next_in_index = 0;
this._compressor.avail_in = 0;
}
#region Stream implementation
public sealed override bool CanRead
{
get { return !_isClosed; }
}
public sealed override bool CanSeek
{
get { return false; }
}
public sealed override bool CanWrite
{
get { return false; }
}
public override void Flush()
{
}
public override long Length
{
get { throw new NotSupportedException(); }
}
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override int Read(byte[] buffer, int offset, int count)
{
if (count == 0)
return 0;
this._compressor.next_out = buffer;
this._compressor.next_out_index = offset;
this._compressor.avail_out = count;
ZLibStatus err = ZLibStatus.Z_OK;
do
{
if (this._compressor.avail_in == 0 && !_noMoreInput)
{
// if buffer is empty and more input is available, refill it
this._compressor.next_in_index = 0;
this._compressor.avail_in = _input.Read(_buffer, 0, _buffer.Length); //(bufsize<z.avail_out ? bufsize : z.avail_out));
if (this._compressor.avail_in <= 0)
{
this._compressor.avail_in = 0;
_noMoreInput = true;
}
}
switch (_compressionMode)
{
case CompressionMode.Compress:
err = this._compressor.deflate(this.FlushMode);
break;
case CompressionMode.Decompress:
err = this._compressor.inflate(this.FlushMode);
break;
default:
break;
}
if (_noMoreInput && err == ZLibStatus.Z_BUF_ERROR)
return 0;
if ((_noMoreInput || err == ZLibStatus.Z_STREAM_END) && this._compressor.avail_out == count)
return 0;
}
while (this._compressor.avail_out == count && err == ZLibStatus.Z_OK);
//Console.Error.WriteLine("("+(len-z.avail_out)+")");
return count - this._compressor.avail_out;
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
#endregion
public override void Close()
{
if (!_isClosed)
{
_isClosed = true;
_input.Close();
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="StringUtil.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* StringUtil class
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web.Util {
using System.Text;
using System.Globalization;
using System.Runtime.InteropServices;
/*
* Various string handling utilities
*/
internal static class StringUtil {
internal static string CheckAndTrimString(string paramValue, string paramName) {
return CheckAndTrimString(paramValue, paramName, true);
}
internal static string CheckAndTrimString(string paramValue, string paramName, bool throwIfNull) {
return CheckAndTrimString(paramValue, paramName, throwIfNull, -1);
}
internal static string CheckAndTrimString(string paramValue, string paramName,
bool throwIfNull, int lengthToCheck) {
if (paramValue == null) {
if (throwIfNull) {
throw new ArgumentNullException(paramName);
}
return null;
}
string trimmedValue = paramValue.Trim();
if (trimmedValue.Length == 0) {
throw new ArgumentException(
SR.GetString(SR.PersonalizationProviderHelper_TrimmedEmptyString,
paramName));
}
if (lengthToCheck > -1 && trimmedValue.Length > lengthToCheck) {
throw new ArgumentException(
SR.GetString(SR.StringUtil_Trimmed_String_Exceed_Maximum_Length,
paramValue, paramName, lengthToCheck.ToString(CultureInfo.InvariantCulture)));
}
return trimmedValue;
}
internal static bool Equals(string s1, string s2) {
if (s1 == s2) {
return true;
}
if (String.IsNullOrEmpty(s1) && String.IsNullOrEmpty(s2)) {
return true;
}
return false;
}
unsafe internal static bool Equals(string s1, int offset1, string s2, int offset2, int length) {
if (offset1 < 0)
throw new ArgumentOutOfRangeException("offset1");
if (offset2 < 0)
throw new ArgumentOutOfRangeException("offset2");
if (length < 0)
throw new ArgumentOutOfRangeException("length");
if ((s1 == null ? 0 : s1.Length) - offset1 < length)
throw new ArgumentOutOfRangeException(SR.GetString(SR.InvalidOffsetOrCount, "offset1", "length"));
if ((s2 == null ? 0 : s2.Length) - offset2 < length)
throw new ArgumentOutOfRangeException(SR.GetString(SR.InvalidOffsetOrCount, "offset2", "length"));
if (String.IsNullOrEmpty(s1) || String.IsNullOrEmpty(s2))
return true;
fixed (char * pch1 = s1, pch2 = s2) {
char * p1 = pch1 + offset1, p2 = pch2 + offset2;
int c = length;
while (c-- > 0) {
if (*p1++ != *p2++)
return false;
}
}
return true;
}
internal static bool EqualsIgnoreCase(string s1, string s2) {
if (String.IsNullOrEmpty(s1) && String.IsNullOrEmpty(s2)) {
return true;
}
if (String.IsNullOrEmpty(s1) || String.IsNullOrEmpty(s2)) {
return false;
}
if(s2.Length != s1.Length) {
return false;
}
return 0 == string.Compare(s1, 0, s2, 0, s2.Length, StringComparison.OrdinalIgnoreCase);
}
internal static bool EqualsIgnoreCase(string s1, int index1, string s2, int index2, int length) {
return String.Compare(s1, index1, s2, index2, length, StringComparison.OrdinalIgnoreCase) == 0;
}
internal static string StringFromWCharPtr(IntPtr ip, int length) {
unsafe {
return new string((char *) ip, 0, length);
}
}
internal static string StringFromCharPtr(IntPtr ip, int length) {
return Marshal.PtrToStringAnsi(ip, length);
}
/*
* Determines if the string ends with the specified character.
* Fast, non-culture aware.
*/
internal static bool StringEndsWith(string s, char c) {
int len = s.Length;
return len != 0 && s[len - 1] == c;
}
/*
* Determines if the first string ends with the second string.
* Fast, non-culture aware.
*/
unsafe internal static bool StringEndsWith(string s1, string s2) {
int offset = s1.Length - s2.Length;
if (offset < 0) {
return false;
}
fixed (char * pch1=s1, pch2=s2) {
char * p1 = pch1 + offset, p2=pch2;
int c = s2.Length;
while (c-- > 0) {
if (*p1++ != *p2++)
return false;
}
}
return true;
}
/*
* Determines if the first string ends with the second string, ignoring case.
* Fast, non-culture aware.
*/
internal static bool StringEndsWithIgnoreCase(string s1, string s2) {
int offset = s1.Length - s2.Length;
if (offset < 0) {
return false;
}
return 0 == string.Compare(s1, offset, s2, 0, s2.Length, StringComparison.OrdinalIgnoreCase);
}
/*
* Determines if the string starts with the specified character.
* Fast, non-culture aware.
*/
internal static bool StringStartsWith(string s, char c) {
return s.Length != 0 && (s[0] == c);
}
/*
* Determines if the first string starts with the second string.
* Fast, non-culture aware.
*/
unsafe internal static bool StringStartsWith(string s1, string s2) {
if (s2.Length > s1.Length) {
return false;
}
fixed (char * pch1=s1, pch2=s2) {
char * p1 = pch1, p2=pch2;
int c = s2.Length;
while (c-- > 0) {
if (*p1++ != *p2++)
return false;
}
}
return true;
}
/*
* Determines if the first string starts with the second string, ignoring case.
* Fast, non-culture aware.
*/
internal static bool StringStartsWithIgnoreCase(string s1, string s2) {
if (String.IsNullOrEmpty(s1) || String.IsNullOrEmpty(s2)) {
return false;
}
if (s2.Length > s1.Length) {
return false;
}
return 0 == string.Compare(s1, 0, s2, 0, s2.Length, StringComparison.OrdinalIgnoreCase);
}
internal unsafe static void UnsafeStringCopy(string src, int srcIndex, char[] dest, int destIndex, int len) {
// We do not verify the parameters in this function, as the callers are assumed
// to have done so. This is important for users such as HttpWriter that already
// do the argument checking, and are called several times per request.
Debug.Assert(len >= 0, "len >= 0");
Debug.Assert(src != null, "src != null");
Debug.Assert(srcIndex >= 0, "srcIndex >= 0");
Debug.Assert(srcIndex + len <= src.Length, "src");
Debug.Assert(dest != null, "dest != null");
Debug.Assert(destIndex >= 0, "destIndex >= 0");
Debug.Assert(destIndex + len <= dest.Length, "dest");
int cb = len * sizeof(char);
fixed (char * pchSrc = src, pchDest = dest) {
byte* pbSrc = (byte *) (pchSrc + srcIndex);
byte* pbDest = (byte*) (pchDest + destIndex);
memcpyimpl(pbSrc, pbDest, cb);
}
}
internal static bool StringArrayEquals(string[] a, string [] b) {
if ((a == null) != (b == null)) {
return false;
}
if (a == null) {
return true;
}
int n = a.Length;
if (n != b.Length) {
return false;
}
for (int i = 0; i < n; i++) {
if (a[i] != b[i]) {
return false;
}
}
return true;
}
// This is copied from String.GetHashCode. We want our own copy, because the result of
// String.GetHashCode is not guaranteed to be the same from build to build. But we want a
// stable hash, since we persist things to disk (e.g. precomp scenario). VSWhidbey 399279.
internal static int GetStringHashCode(string s) {
unsafe {
fixed (char* src = s) {
int hash1 = (5381 << 16) + 5381;
int hash2 = hash1;
// 32bit machines.
int* pint = (int*)src;
int len = s.Length;
while (len > 0) {
hash1 = ((hash1 << 5) + hash1 + (hash1 >> 27)) ^ pint[0];
if (len <= 2) {
break;
}
hash2 = ((hash2 << 5) + hash2 + (hash2 >> 27)) ^ pint[1];
pint += 2;
len -= 4;
}
return hash1 + (hash2 * 1566083941);
}
}
}
internal static int GetNullTerminatedByteArray(Encoding enc, string s, out byte[] bytes)
{
bytes = null;
if (s == null)
return 0;
// Encoding.GetMaxByteCount is faster than GetByteCount, but will probably allocate more
// memory than needed. Working with small short-lived strings here, so that's probably ok.
bytes = new byte[enc.GetMaxByteCount(s.Length) + 1];
return enc.GetBytes(s, 0, s.Length, bytes, 0);
}
internal unsafe static void memcpyimpl(byte* src, byte* dest, int len) {
Debug.Assert(len >= 0, "Negative length in memcpyimpl!");
#if FEATURE_PAL
// Portable naive implementation
while (len-- > 0)
*dest++ = *src++;
#else
#if IA64
long dstAlign = (7 & (8 - (((long)dest) & 7))); // number of bytes to copy before dest is 8-byte aligned
while ((dstAlign > 0) && (len > 0))
{
// <
*dest++ = *src++;
len--;
dstAlign--;
}
if (len > 0)
{
long srcAlign = 8 - (((long)src) & 7);
if (srcAlign != 8)
{
if (4 == srcAlign)
{
while (len >= 4)
{
((int*)dest)[0] = ((int*)src)[0];
dest += 4;
src += 4;
len -= 4;
}
srcAlign = 2; // fall through to 2-byte copies
}
if ((2 == srcAlign) || (6 == srcAlign))
{
while (len >= 2)
{
((short*)dest)[0] = ((short*)src)[0];
dest += 2;
src += 2;
len -= 2;
}
}
while (len-- > 0)
{
*dest++ = *src++;
}
}
else
{
if (len >= 16)
{
do
{
((long*)dest)[0] = ((long*)src)[0];
((long*)dest)[1] = ((long*)src)[1];
dest += 16;
src += 16;
} while ((len -= 16) >= 16);
}
if(len > 0) // protection against negative len and optimization for len==16*N
{
if ((len & 8) != 0)
{
((long*)dest)[0] = ((long*)src)[0];
dest += 8;
src += 8;
}
if ((len & 4) != 0)
{
((int*)dest)[0] = ((int*)src)[0];
dest += 4;
src += 4;
}
if ((len & 2) != 0)
{
((short*)dest)[0] = ((short*)src)[0];
dest += 2;
src += 2;
}
if ((len & 1) != 0)
{
*dest++ = *src++;
}
}
}
}
#else
// <STRIP>This is Peter Sollich's faster memcpy implementation, from
// COMString.cpp. For our strings, this beat the processor's
// repeat & move single byte instruction, which memcpy expands into.
// (You read that correctly.)
// This is 3x faster than a simple while loop copying byte by byte,
// for large copies.</STRIP>
if (len >= 16) {
do {
#if AMD64
((long*)dest)[0] = ((long*)src)[0];
((long*)dest)[1] = ((long*)src)[1];
#else
((int*)dest)[0] = ((int*)src)[0];
((int*)dest)[1] = ((int*)src)[1];
((int*)dest)[2] = ((int*)src)[2];
((int*)dest)[3] = ((int*)src)[3];
#endif
dest += 16;
src += 16;
} while ((len -= 16) >= 16);
}
if(len > 0) // protection against negative len and optimization for len==16*N
{
if ((len & 8) != 0) {
#if AMD64
((long*)dest)[0] = ((long*)src)[0];
#else
((int*)dest)[0] = ((int*)src)[0];
((int*)dest)[1] = ((int*)src)[1];
#endif
dest += 8;
src += 8;
}
if ((len & 4) != 0) {
((int*)dest)[0] = ((int*)src)[0];
dest += 4;
src += 4;
}
if ((len & 2) != 0) {
((short*)dest)[0] = ((short*)src)[0];
dest += 2;
src += 2;
}
if ((len & 1) != 0)
*dest++ = *src++;
}
#endif
#endif // FEATURE_PAL
}
internal static string[] ObjectArrayToStringArray(object[] objectArray) {
String[] stringKeys = new String[objectArray.Length];
objectArray.CopyTo(stringKeys, 0);
return stringKeys;
}
}
}
| |
//////////////////////////////////////////////////////////////////////////////
//
// OpenMBase
//
// Copyright 2005-2017, Meta Alternative Ltd. All rights reserved.
//
//
//////////////////////////////////////////////////////////////////////////////
using System;
using System.Collections;
using System.IO;
using System.Reflection;
namespace Meta.Scripting
{
#region Compiler
public interface Code
{
Object run(Object[] frame, Object[] envframe);
}
public delegate Object SimpleCode(Object[] frame);
public class Precompiler
{
static Symbol lambda = Symbol.make("lambda");
static Symbol quote = Symbol.make("quote");
static Symbol argref = Symbol.make("arg-ref");
static Symbol envref = Symbol.make("env-ref");
static Symbol begin = Symbol.make("begin");
static Symbol theif = Symbol.make("if");
static Symbol thetb = Symbol.make("top-begin");
static Symbol thedowhile = Symbol.make("do-while");
// non-bootstrap stuff: .net-specific
static Symbol thetry = Symbol.make("try");
///////
///
public Runtime rt;
public static System.Collections.Generic.Dictionary<Symbol, object> symbols = new System.Collections.Generic.Dictionary<Symbol, object>();
public static System.Collections.Generic.Dictionary<Symbol, object> macros = new System.Collections.Generic.Dictionary<Symbol, object>();
public static SimpleCode wrap(Object o, int n)
{
MakeApp ap = new MakeApp(o, new Object[n]);
return new SimpleCode(ap.run2);
}
public static Code compile(Object o)
{
try
{
if (o is Pair) return compile((Pair)o);
else if (o is Symbol)
{
Symbol s = (Symbol)o;
if (symbols.ContainsKey(s))
return new MakeConstant(symbols[s]);
else
if (Runtime.comp_hash[((Symbol)o).v] != null) {
object valu = Runtime.makedelegate((Symbol)o);
Console.WriteLine("DELEGATE: " + o.ToString() + " --- " + valu.ToString());
symbols[s] = valu;
return new MakeConstant(valu);
}
{
Console.WriteLine("global name " + s.v + " undefined");
throw new
Meta.Scripting.MBaseException("global name " +
s.v + " undefined");
}
}
else if (o is Code)
{
return (Code)o;
}
else return new MakeConstant(o);
}
catch (Exception e)
{
Console.WriteLine("Exception in " + (Runtime.print(o)));
throw e;
}
}
public static Code compile(Pair p)
{
if (p.caris(lambda))
{
int narg = ((System.Int32)p.caadr());
Object fl = (p.cdadr());
if (fl is Pair)
{
return new MakeFrameLambda(narg, (Pair)p.cdadr(), compile(p.caddr()));
}
else
{
return new MakeLambda(narg, compile(p.caddr()));
}
}
else if (p.caris(quote))
{
return new MakeConstant(p.cadr());
}
else if (p.caris(argref))
{
return new MakeArgRef((Int32)(p.cadr()));
}
else if (p.caris(envref))
{
return new MakeEnvRef((Int32)(p.cadr()));
}
else if (p.caris(begin))
{
Pair l = p.pcdr;
if (l.length() == 1)
{
return compile(p.cadr());
}
else
{
return new MakeSequence(p.pcdr);
}
}
else if (p.caris(theif))
{
Object p1 = p.cadr();
Object p2 = p.caddr();
Object p3x = Pair.Cdr(p.cddr());
Object p3;
if (p3x != null) p3 = Pair.Car(p3x); else p3 = null;
return new MakeIf(
compile(p1),
compile(p2),
(p3 == null) ? NIL : compile(p3), p);
}
else if (p.caris(thedowhile)) {
return new MakeDoWhile(compile(p.cadr()));
}
else if (p.caris(thetry))
{
Object p1 = p.cadr();
Pair p2 = (Pair)p.cddr();
Object p2x = p2.car;
Object p2y = p2.cadr();
return new MakeTry(compile(p1), compile(p2x), compile(p2y));
}
else if (p.caris(thetb)) // suppress execution - already executed!
{
return NIL;
}
else // it is a function application
{
return new MakeApp(p);
}
}
private static Code NIL = new MakeConstant(null);
}
#endregion
#region Evaluation atomic blocks
class MakeTry : Code
{
Code ca, cex, cthen;
public MakeTry(Code a, Code excpn, Code then)
{
ca = a; cex = excpn; cthen = then;
}
public Object run(Object[] frame, Object[] envframe)
{
try
{
return ca.run(frame, envframe);
}
catch (Exception ex)
{
Type oe = (Type)cex.run(frame, envframe);
if (oe.IsAssignableFrom(ex.GetType()))
{
MakeApp ap = new MakeApp(cthen, new Object[] { ex });
return ap.run(frame, envframe);
}
// otherwise:
throw ex;
}
}
}
class MakeIf : Code
{
Code a, b, c;
object _source;
public MakeIf(Code cond, Code iftrue, Code iffalse, object src)
{
a = cond; b = iftrue; c = iffalse;
_source = src;
}
public Object run(Object[] frame, Object[] envframe)
{
Object res = a.run(frame, envframe);
if (res == null) return c.run(frame, envframe);
else
return b.run(frame, envframe);
}
}
class MakeApp : Code
{
Object[] parts;
public MakeApp(Pair p)
{
int l = p.length();
parts = new Object[l];
Pair pp = p;
for (int i = 0; i < l; i++)
{
Object h = pp.car;
pp = pp.pcdr;
if (h is Pair)
{
parts[i] = Precompiler.compile(h);
} else
if (h is Symbol)
{
Symbol sh = (Symbol)h;
Object test;
Precompiler.symbols.TryGetValue(sh,out test);
if (test == null && !Precompiler.symbols.ContainsKey(sh))
{
if (Runtime.comp_hash[sh.v] != null)
{
test = Runtime.makedelegate(sh);
}
else
{
Console.WriteLine("sclmglobal name " + sh.v + " undefined");
}
}
parts[i] = test;
}
else
{
parts[i] = h; // optimize constants
}
}
}
public MakeApp(Object f, Object[] args)
{
parts = new Object[args.Length + 1];
for (int i = 1; i < args.Length + 1; i++) parts[i] = args[i - 1];
parts[0] = f;
}
public Object run2(Object[] frame)
{
return run(frame, null);
}
public Object run(Object[] frame, Object[] envframe)
{
int len0 = parts.Length - 1;
Object fun = runone(frame, envframe, parts[0]);
bool isclosure = fun is Closure;
Object[] newframe = new Object[len0];
Object[] newenvframe;
if (isclosure && ((Closure)fun).frame != null)
{
newenvframe = ((Closure)fun).frame;
}
else { newenvframe = envframe;}
for (int i = 0; i < len0; i++)
{
newframe[i] = runone(frame, envframe, parts[i + 1]);
}
if (isclosure)
{
return ((Closure)fun).c.run(newframe, newenvframe);
}
if (fun is SimpleCode) return ((SimpleCode)fun)(newframe);
if (fun is Code) return ((Code)fun).run(newframe, newenvframe);
if (Runtime.clr != null)
{
Object o =
Runtime.clr(newframe, fun);
return o;
}
return fun; // error
}
private static Object runone(Object[] frame, Object[] envframe, Object part)
{
if (part is Code) return ((Code)part).run(frame, envframe);
return part;
}
}
class MakeSequence : Code
{
Code[] sqn;
public MakeSequence(Pair p)
{
int l = p.length();
sqn = new Code[l];
Pair pp = p;
for (int i = 0; i < l; i++)
{
Object h = pp.car;
pp = pp.pcdr;
sqn[i] = Precompiler.compile(h);
}
}
public Object run(Object[] fr, Object[] envframe)
{
Object res = null;
for (int i = 0; i < sqn.Length; i++)
{
res = sqn[i].run(fr, envframe);
}
return res;
}
}
class MakeDoWhile : Code
{
Code _body;
public MakeDoWhile(Code body)
{
_body = body;
}
public Object run(Object[] fr, Object[] envframe)
{
Object res = null;
do {
res = _body.run(fr, envframe);
} while (res != null);
return null;
}
}
class MakeArgRef : Code
{
int i;
public MakeArgRef(Int32 c)
{
i = c;
}
public Object run(Object[] frame, Object[] envframe)
{
return frame[i];
}
}
class MakeEnvRef : Code
{
int i;
public MakeEnvRef(Int32 c)
{
i = c;
}
public Object run(Object[] frame, Object[] envframe)
{
return envframe[i];
}
}
class MakeConstant : Code
{
Object ob;
public MakeConstant(Object o) { ob = o; }
public Object run(Object[] o, Object[] envframe)
{
return ob;
}
}
class MakeLambda : Code
{
int nars;
Code code;
public MakeLambda(int narg, Code c)
{
nars = narg;
code = c;
}
public Object run(Object[] frame, Object[] envframe)
{
Closure cl = new Closure();
cl.frame = null;
cl.c = code;
cl.nargs = nars;
return cl;
}
}
class MakeFrameLambda : Code
{
static Symbol thearg = Symbol.make("arg");
static Symbol theenv = Symbol.make("env");
static Symbol theself = Symbol.make("self");
int flen;
int nars;
Code code;
int[] patch;
int[] epatch;
public MakeFrameLambda(int narg, Pair alist, Code icode)
{
int alen = alist.length(); nars = narg;
code = icode;
flen = alen;
patch = new int[alen];
epatch = new int[alen];
Pair c = alist;
for (int i = 0; i < alen; i++)
{
object ccadr = ((Pair)c.car).cadr ();
if (ccadr==thearg)
{
patch[i] = ((Int32)c.caar()); epatch[i] = -1;
} else if(ccadr==theenv) {
epatch[i] = ((Int32)c.caar()); patch[i] = -1;
} else { // self
epatch[i] = -1; patch[i] = -1;
}
c = (Pair)Pair.Cdr(c);
}
}
public Object run(Object[] o, Object[] envframe)
{
Object[] newframe = new Object[flen];
Closure cl = new Closure();
for (int j = 0; j < flen; j++)
{
int t = patch[j]; int p = epatch[j];
if (t>=0) newframe[j] = o[t]; else if (p>=0) newframe[j] = envframe[p]; else {
newframe[j] = cl;
}
}
cl.nargs = nars;
cl.c = code;
cl.frame = newframe;
return cl;
}
}
#endregion
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Web.Http.Description;
using System.Xml.Linq;
using Newtonsoft.Json;
namespace WK.Orion.Applications.DPM.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
/* ====================================================================
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.
==================================================================== */
/* ================================================================
* About NPOI
* Author: Tony Qu
* Author's email: tonyqus (at) gmail.com
* Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn)
* HomePage: http://www.codeplex.com/npoi
* Contributors:
*
* ==============================================================*/
namespace NPOI.HPSF
{
using System;
using System.IO;
using NPOI.Util;
/// <summary>
/// Class for writing little-endian data and more.
/// @author Rainer Klute
/// <a href="mailto:klute@rainer-klute.de"><klute@rainer-klute.de></a>
/// @since 2003-02-20
/// </summary>
public class TypeWriter
{
/// <summary>
/// Writes a two-byte value (short) To an output stream.
/// </summary>
/// <param name="out1">The stream To Write To..</param>
/// <param name="n">The number of bytes that have been written.</param>
/// <returns></returns>
public static int WriteToStream(Stream out1, short n)
{
LittleEndian.PutShort( out1, n ); // FIXME: unsigned
return LittleEndian.SHORT_SIZE;
}
/**
* Writes a four-byte value To an output stream.
*
* @param out The stream To Write To.
* @param n The value To Write.
* @exception IOException if an I/O error occurs
* @return The number of bytes written To the output stream.
*/
public static int WriteToStream(Stream out1, int n)
{
LittleEndian.PutInt( n, out1 );
return LittleEndian.INT_SIZE;
}
/**
* Writes a four-byte value To an output stream.
*
* @param out The stream To Write To.
* @param n The value To Write.
* @exception IOException if an I/O error occurs
* @return The number of bytes written To the output stream.
*/
[Obsolete]
public static int WriteToStream(Stream out1, uint n)
{
int l = LittleEndianConsts.INT_SIZE;
byte[] buffer = new byte[l];
LittleEndian.PutUInt(buffer, 0, n);
out1.Write(buffer, 0, l);
return l;
}
/**
* Writes a eight-byte value To an output stream.
*
* @param out The stream To Write To.
* @param n The value To Write.
* @exception IOException if an I/O error occurs
* @return The number of bytes written To the output stream.
*/
public static int WriteToStream(Stream out1, long n)
{
LittleEndian.PutLong( n, out1 );
return LittleEndian.LONG_SIZE;
}
/**
* Writes an unsigned two-byte value To an output stream.
*
* @param out The stream To Write To
* @param n The value To Write
* @exception IOException if an I/O error occurs
*/
public static void WriteUShortToStream(Stream out1, int n)
{
int high = n & unchecked((int)0xFFFF0000);
if (high != 0)
throw new IllegalPropertySetDataException
("Value " + n + " cannot be represented by 2 bytes.");
//WriteToStream(out1, (short)n);
LittleEndian.PutUShort( n, out1 );
}
/**
* Writes an unsigned four-byte value To an output stream.
*
* @param out The stream To Write To.
* @param n The value To Write.
* @return The number of bytes that have been written To the output stream.
* @exception IOException if an I/O error occurs
*/
public static int WriteUIntToStream(Stream out1, uint n)
{
ulong high = (ulong)(n & unchecked((long)0xFFFFFFFF00000000L));
if (high != 0 && high != 0xFFFFFFFF00000000L)
throw new IllegalPropertySetDataException
("Value " + n + " cannot be represented by 4 bytes.");
LittleEndian.PutUInt( n, out1 );
return LittleEndian.INT_SIZE;
}
/**
* Writes a 16-byte {@link ClassID} To an output stream.
*
* @param out The stream To Write To
* @param n The value To Write
* @return The number of bytes written
* @exception IOException if an I/O error occurs
*/
public static int WriteToStream(Stream out1, ClassID n)
{
byte[] b = new byte[16];
n.Write(b, 0);
out1.Write(b, 0, b.Length);
return b.Length;
}
/**
* Writes an array of {@link Property} instances To an output stream
* according To the Horrible Property Format.
*
* @param out The stream To Write To
* @param properties The array To Write To the stream
* @param codepage The codepage number To use for writing strings
* @exception IOException if an I/O error occurs
* @throws UnsupportedVariantTypeException if HPSF does not support some
* variant type.
*/
public static void WriteToStream(Stream out1,
Property[] properties,
int codepage)
{
/* If there are no properties don't Write anything. */
if (properties == null)
return;
/* Write the property list. This is a list containing pairs of property
* ID and offset into the stream. */
for (int i = 0; i < properties.Length; i++)
{
Property p = properties[i];
WriteUIntToStream(out1, (uint)p.ID);
WriteUIntToStream(out1, (uint)p.Count);
}
/* Write the properties themselves. */
for (int i = 0; i < properties.Length; i++)
{
Property p = properties[i];
long type = p.Type;
WriteUIntToStream(out1, (uint)type);
VariantSupport.Write(out1, (int)type, p.Value, codepage);
}
}
/**
* Writes a double value value To an output stream.
*
* @param out The stream To Write To.
* @param n The value To Write.
* @exception IOException if an I/O error occurs
* @return The number of bytes written To the output stream.
*/
public static int WriteToStream(Stream out1, double n)
{
LittleEndian.PutDouble( n, out1 );
return LittleEndian.DOUBLE_SIZE;
}
}
}
| |
#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
#if !SILVERLIGHT || WINDOWS_PHONE
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Xml;
#if !NET20
using System.Xml.Linq;
#endif
using Newtonsoft.Json4.Utilities;
using System.Linq;
namespace Newtonsoft.Json4.Converters
{
#region XmlNodeWrappers
#if !SILVERLIGHT
internal class XmlDocumentWrapper : XmlNodeWrapper, IXmlDocument
{
private readonly XmlDocument _document;
public XmlDocumentWrapper(XmlDocument document)
: base(document)
{
_document = document;
}
public IXmlNode CreateComment(string data)
{
return new XmlNodeWrapper(_document.CreateComment(data));
}
public IXmlNode CreateTextNode(string text)
{
return new XmlNodeWrapper(_document.CreateTextNode(text));
}
public IXmlNode CreateCDataSection(string data)
{
return new XmlNodeWrapper(_document.CreateCDataSection(data));
}
public IXmlNode CreateWhitespace(string text)
{
return new XmlNodeWrapper(_document.CreateWhitespace(text));
}
public IXmlNode CreateSignificantWhitespace(string text)
{
return new XmlNodeWrapper(_document.CreateSignificantWhitespace(text));
}
public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone)
{
return new XmlNodeWrapper(_document.CreateXmlDeclaration(version, encoding, standalone));
}
public IXmlNode CreateProcessingInstruction(string target, string data)
{
return new XmlNodeWrapper(_document.CreateProcessingInstruction(target, data));
}
public IXmlElement CreateElement(string elementName)
{
return new XmlElementWrapper(_document.CreateElement(elementName));
}
public IXmlElement CreateElement(string qualifiedName, string namespaceUri)
{
return new XmlElementWrapper(_document.CreateElement(qualifiedName, namespaceUri));
}
public IXmlNode CreateAttribute(string name, string value)
{
XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(name));
attribute.Value = value;
return attribute;
}
public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value)
{
XmlNodeWrapper attribute = new XmlNodeWrapper(_document.CreateAttribute(qualifiedName, namespaceUri));
attribute.Value = value;
return attribute;
}
public IXmlElement DocumentElement
{
get
{
if (_document.DocumentElement == null)
return null;
return new XmlElementWrapper(_document.DocumentElement);
}
}
}
internal class XmlElementWrapper : XmlNodeWrapper, IXmlElement
{
private readonly XmlElement _element;
public XmlElementWrapper(XmlElement element)
: base(element)
{
_element = element;
}
public void SetAttributeNode(IXmlNode attribute)
{
XmlNodeWrapper xmlAttributeWrapper = (XmlNodeWrapper)attribute;
_element.SetAttributeNode((XmlAttribute) xmlAttributeWrapper.WrappedNode);
}
public string GetPrefixOfNamespace(string namespaceUri)
{
return _element.GetPrefixOfNamespace(namespaceUri);
}
}
internal class XmlDeclarationWrapper : XmlNodeWrapper, IXmlDeclaration
{
private readonly XmlDeclaration _declaration;
public XmlDeclarationWrapper(XmlDeclaration declaration)
: base(declaration)
{
_declaration = declaration;
}
public string Version
{
get { return _declaration.Version; }
}
public string Encoding
{
get { return _declaration.Encoding; }
set { _declaration.Encoding = value; }
}
public string Standalone
{
get { return _declaration.Standalone; }
set { _declaration.Standalone = value; }
}
}
internal class XmlNodeWrapper : IXmlNode
{
private readonly XmlNode _node;
public XmlNodeWrapper(XmlNode node)
{
_node = node;
}
public object WrappedNode
{
get { return _node; }
}
public XmlNodeType NodeType
{
get { return _node.NodeType; }
}
public string Name
{
get { return _node.Name; }
}
public string LocalName
{
get { return _node.LocalName; }
}
public IList<IXmlNode> ChildNodes
{
get { return _node.ChildNodes.Cast<XmlNode>().Select(n => WrapNode(n)).ToList(); }
}
private IXmlNode WrapNode(XmlNode node)
{
switch (node.NodeType)
{
case XmlNodeType.Element:
return new XmlElementWrapper((XmlElement) node);
case XmlNodeType.XmlDeclaration:
return new XmlDeclarationWrapper((XmlDeclaration) node);
default:
return new XmlNodeWrapper(node);
}
}
public IList<IXmlNode> Attributes
{
get
{
if (_node.Attributes == null)
return null;
return _node.Attributes.Cast<XmlAttribute>().Select(a => WrapNode(a)).ToList();
}
}
public IXmlNode ParentNode
{
get
{
XmlNode node = (_node is XmlAttribute)
? ((XmlAttribute) _node).OwnerElement
: _node.ParentNode;
if (node == null)
return null;
return WrapNode(node);
}
}
public string Value
{
get { return _node.Value; }
set { _node.Value = value; }
}
public IXmlNode AppendChild(IXmlNode newChild)
{
XmlNodeWrapper xmlNodeWrapper = (XmlNodeWrapper) newChild;
_node.AppendChild(xmlNodeWrapper._node);
return newChild;
}
public string Prefix
{
get { return _node.Prefix; }
}
public string NamespaceUri
{
get { return _node.NamespaceURI; }
}
}
#endif
#endregion
#region Interfaces
internal interface IXmlDocument : IXmlNode
{
IXmlNode CreateComment(string text);
IXmlNode CreateTextNode(string text);
IXmlNode CreateCDataSection(string data);
IXmlNode CreateWhitespace(string text);
IXmlNode CreateSignificantWhitespace(string text);
IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone);
IXmlNode CreateProcessingInstruction(string target, string data);
IXmlElement CreateElement(string elementName);
IXmlElement CreateElement(string qualifiedName, string namespaceUri);
IXmlNode CreateAttribute(string name, string value);
IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value);
IXmlElement DocumentElement { get; }
}
internal interface IXmlDeclaration : IXmlNode
{
string Version { get; }
string Encoding { get; set; }
string Standalone { get; set; }
}
internal interface IXmlElement : IXmlNode
{
void SetAttributeNode(IXmlNode attribute);
string GetPrefixOfNamespace(string namespaceUri);
}
internal interface IXmlNode
{
XmlNodeType NodeType { get; }
string LocalName { get; }
IList<IXmlNode> ChildNodes { get; }
IList<IXmlNode> Attributes { get; }
IXmlNode ParentNode { get; }
string Value { get; set; }
IXmlNode AppendChild(IXmlNode newChild);
string NamespaceUri { get; }
object WrappedNode { get; }
}
#endregion
#region XNodeWrappers
#if !NET20
internal class XDeclarationWrapper : XObjectWrapper, IXmlDeclaration
{
internal XDeclaration Declaration { get; private set; }
public XDeclarationWrapper(XDeclaration declaration)
: base(null)
{
Declaration = declaration;
}
public override XmlNodeType NodeType
{
get { return XmlNodeType.XmlDeclaration; }
}
public string Version
{
get { return Declaration.Version; }
}
public string Encoding
{
get { return Declaration.Encoding; }
set { Declaration.Encoding = value; }
}
public string Standalone
{
get { return Declaration.Standalone; }
set { Declaration.Standalone = value; }
}
}
internal class XDocumentWrapper : XContainerWrapper, IXmlDocument
{
private XDocument Document
{
get { return (XDocument)WrappedNode; }
}
public XDocumentWrapper(XDocument document)
: base(document)
{
}
public override IList<IXmlNode> ChildNodes
{
get
{
IList<IXmlNode> childNodes = base.ChildNodes;
if (Document.Declaration != null)
childNodes.Insert(0, new XDeclarationWrapper(Document.Declaration));
return childNodes;
}
}
public IXmlNode CreateComment(string text)
{
return new XObjectWrapper(new XComment(text));
}
public IXmlNode CreateTextNode(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateCDataSection(string data)
{
return new XObjectWrapper(new XCData(data));
}
public IXmlNode CreateWhitespace(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateSignificantWhitespace(string text)
{
return new XObjectWrapper(new XText(text));
}
public IXmlNode CreateXmlDeclaration(string version, string encoding, string standalone)
{
return new XDeclarationWrapper(new XDeclaration(version, encoding, standalone));
}
public IXmlNode CreateProcessingInstruction(string target, string data)
{
return new XProcessingInstructionWrapper(new XProcessingInstruction(target, data));
}
public IXmlElement CreateElement(string elementName)
{
return new XElementWrapper(new XElement(elementName));
}
public IXmlElement CreateElement(string qualifiedName, string namespaceUri)
{
string localName = MiscellaneousUtils.GetLocalName(qualifiedName);
return new XElementWrapper(new XElement(XName.Get(localName, namespaceUri)));
}
public IXmlNode CreateAttribute(string name, string value)
{
return new XAttributeWrapper(new XAttribute(name, value));
}
public IXmlNode CreateAttribute(string qualifiedName, string namespaceUri, string value)
{
string localName = MiscellaneousUtils.GetLocalName(qualifiedName);
return new XAttributeWrapper(new XAttribute(XName.Get(localName, namespaceUri), value));
}
public IXmlElement DocumentElement
{
get
{
if (Document.Root == null)
return null;
return new XElementWrapper(Document.Root);
}
}
public override IXmlNode AppendChild(IXmlNode newChild)
{
XDeclarationWrapper declarationWrapper = newChild as XDeclarationWrapper;
if (declarationWrapper != null)
{
Document.Declaration = declarationWrapper.Declaration;
return declarationWrapper;
}
else
{
return base.AppendChild(newChild);
}
}
}
internal class XTextWrapper : XObjectWrapper
{
private XText Text
{
get { return (XText)WrappedNode; }
}
public XTextWrapper(XText text)
: base(text)
{
}
public override string Value
{
get { return Text.Value; }
set { Text.Value = value; }
}
public override IXmlNode ParentNode
{
get
{
if (Text.Parent == null)
return null;
return XContainerWrapper.WrapNode(Text.Parent);
}
}
}
internal class XCommentWrapper : XObjectWrapper
{
private XComment Text
{
get { return (XComment)WrappedNode; }
}
public XCommentWrapper(XComment text)
: base(text)
{
}
public override string Value
{
get { return Text.Value; }
set { Text.Value = value; }
}
public override IXmlNode ParentNode
{
get
{
if (Text.Parent == null)
return null;
return XContainerWrapper.WrapNode(Text.Parent);
}
}
}
internal class XProcessingInstructionWrapper : XObjectWrapper
{
private XProcessingInstruction ProcessingInstruction
{
get { return (XProcessingInstruction)WrappedNode; }
}
public XProcessingInstructionWrapper(XProcessingInstruction processingInstruction)
: base(processingInstruction)
{
}
public override string LocalName
{
get { return ProcessingInstruction.Target; }
}
public override string Value
{
get { return ProcessingInstruction.Data; }
set { ProcessingInstruction.Data = value; }
}
}
internal class XContainerWrapper : XObjectWrapper
{
private XContainer Container
{
get { return (XContainer)WrappedNode; }
}
public XContainerWrapper(XContainer container)
: base(container)
{
}
public override IList<IXmlNode> ChildNodes
{
get { return Container.Nodes().Select(n => WrapNode(n)).ToList(); }
}
public override IXmlNode ParentNode
{
get
{
if (Container.Parent == null)
return null;
return WrapNode(Container.Parent);
}
}
internal static IXmlNode WrapNode(XObject node)
{
if (node is XDocument)
return new XDocumentWrapper((XDocument)node);
else if (node is XElement)
return new XElementWrapper((XElement)node);
else if (node is XContainer)
return new XContainerWrapper((XContainer)node);
else if (node is XProcessingInstruction)
return new XProcessingInstructionWrapper((XProcessingInstruction)node);
else if (node is XText)
return new XTextWrapper((XText)node);
else if (node is XComment)
return new XCommentWrapper((XComment)node);
else if (node is XAttribute)
return new XAttributeWrapper((XAttribute) node);
else
return new XObjectWrapper(node);
}
public override IXmlNode AppendChild(IXmlNode newChild)
{
Container.Add(newChild.WrappedNode);
return newChild;
}
}
internal class XObjectWrapper : IXmlNode
{
private readonly XObject _xmlObject;
public XObjectWrapper(XObject xmlObject)
{
_xmlObject = xmlObject;
}
public object WrappedNode
{
get { return _xmlObject; }
}
public virtual XmlNodeType NodeType
{
get { return _xmlObject.NodeType; }
}
public virtual string LocalName
{
get { return null; }
}
public virtual IList<IXmlNode> ChildNodes
{
get { return new List<IXmlNode>(); }
}
public virtual IList<IXmlNode> Attributes
{
get { return null; }
}
public virtual IXmlNode ParentNode
{
get { return null; }
}
public virtual string Value
{
get { return null; }
set { throw new InvalidOperationException(); }
}
public virtual IXmlNode AppendChild(IXmlNode newChild)
{
throw new InvalidOperationException();
}
public virtual string NamespaceUri
{
get { return null; }
}
}
internal class XAttributeWrapper : XObjectWrapper
{
private XAttribute Attribute
{
get { return (XAttribute)WrappedNode; }
}
public XAttributeWrapper(XAttribute attribute)
: base(attribute)
{
}
public override string Value
{
get { return Attribute.Value; }
set { Attribute.Value = value; }
}
public override string LocalName
{
get { return Attribute.Name.LocalName; }
}
public override string NamespaceUri
{
get { return Attribute.Name.NamespaceName; }
}
public override IXmlNode ParentNode
{
get
{
if (Attribute.Parent == null)
return null;
return XContainerWrapper.WrapNode(Attribute.Parent);
}
}
}
internal class XElementWrapper : XContainerWrapper, IXmlElement
{
private XElement Element
{
get { return (XElement) WrappedNode; }
}
public XElementWrapper(XElement element)
: base(element)
{
}
public void SetAttributeNode(IXmlNode attribute)
{
XObjectWrapper wrapper = (XObjectWrapper)attribute;
Element.Add(wrapper.WrappedNode);
}
public override IList<IXmlNode> Attributes
{
get { return Element.Attributes().Select(a => new XAttributeWrapper(a)).Cast<IXmlNode>().ToList(); }
}
public override string Value
{
get { return Element.Value; }
set { Element.Value = value; }
}
public override string LocalName
{
get { return Element.Name.LocalName; }
}
public override string NamespaceUri
{
get { return Element.Name.NamespaceName; }
}
public string GetPrefixOfNamespace(string namespaceUri)
{
return Element.GetPrefixOfNamespace(namespaceUri);
}
}
#endif
#endregion
/// <summary>
/// Converts XML to and from JSON.
/// </summary>
public class XmlNodeConverter : JsonConverter
{
private const string TextName = "#text";
private const string CommentName = "#comment";
private const string CDataName = "#cdata-section";
private const string WhitespaceName = "#whitespace";
private const string SignificantWhitespaceName = "#significant-whitespace";
private const string DeclarationName = "?xml";
private const string JsonNamespaceUri = "http://james.newtonking.com/projects/json";
/// <summary>
/// Gets or sets the name of the root element to insert when deserializing to XML if the JSON structure has produces multiple root elements.
/// </summary>
/// <value>The name of the deserialize root element.</value>
public string DeserializeRootElementName { get; set; }
/// <summary>
/// Gets or sets a flag to indicate whether to write the Json.NET array attribute.
/// This attribute helps preserve arrays when converting the written XML back to JSON.
/// </summary>
/// <value><c>true</c> if the array attibute is written to the XML; otherwise, <c>false</c>.</value>
public bool WriteArrayAttribute { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to write the root JSON object.
/// </summary>
/// <value><c>true</c> if the JSON root object is omitted; otherwise, <c>false</c>.</value>
public bool OmitRootObject { get; set; }
#region Writing
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="serializer">The calling serializer.</param>
/// <param name="value">The value.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
IXmlNode node = WrapXml(value);
XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
PushParentNamespaces(node, manager);
if (!OmitRootObject)
writer.WriteStartObject();
SerializeNode(writer, node, manager, !OmitRootObject);
if (!OmitRootObject)
writer.WriteEndObject();
}
private IXmlNode WrapXml(object value)
{
#if !NET20
if (value is XObject)
return XContainerWrapper.WrapNode((XObject)value);
#endif
#if !SILVERLIGHT
if (value is XmlNode)
return new XmlNodeWrapper((XmlNode)value);
#endif
throw new ArgumentException("Value must be an XML object.", "value");
}
private void PushParentNamespaces(IXmlNode node, XmlNamespaceManager manager)
{
List<IXmlNode> parentElements = null;
IXmlNode parent = node;
while ((parent = parent.ParentNode) != null)
{
if (parent.NodeType == XmlNodeType.Element)
{
if (parentElements == null)
parentElements = new List<IXmlNode>();
parentElements.Add(parent);
}
}
if (parentElements != null)
{
parentElements.Reverse();
foreach (IXmlNode parentElement in parentElements)
{
manager.PushScope();
foreach (IXmlNode attribute in parentElement.Attributes)
{
if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/" && attribute.LocalName != "xmlns")
manager.AddNamespace(attribute.LocalName, attribute.Value);
}
}
}
}
private string ResolveFullName(IXmlNode node, XmlNamespaceManager manager)
{
string prefix = (node.NamespaceUri == null || (node.LocalName == "xmlns" && node.NamespaceUri == "http://www.w3.org/2000/xmlns/"))
? null
: manager.LookupPrefix(node.NamespaceUri);
if (!string.IsNullOrEmpty(prefix))
return prefix + ":" + node.LocalName;
else
return node.LocalName;
}
private string GetPropertyName(IXmlNode node, XmlNamespaceManager manager)
{
switch (node.NodeType)
{
case XmlNodeType.Attribute:
if (node.NamespaceUri == JsonNamespaceUri)
return "$" + node.LocalName;
else
return "@" + ResolveFullName(node, manager);
case XmlNodeType.CDATA:
return CDataName;
case XmlNodeType.Comment:
return CommentName;
case XmlNodeType.Element:
return ResolveFullName(node, manager);
case XmlNodeType.ProcessingInstruction:
return "?" + ResolveFullName(node, manager);
case XmlNodeType.XmlDeclaration:
return DeclarationName;
case XmlNodeType.SignificantWhitespace:
return SignificantWhitespaceName;
case XmlNodeType.Text:
return TextName;
case XmlNodeType.Whitespace:
return WhitespaceName;
default:
throw new JsonSerializationException("Unexpected XmlNodeType when getting node name: " + node.NodeType);
}
}
private bool IsArray(IXmlNode node)
{
IXmlNode jsonArrayAttribute = (node.Attributes != null)
? node.Attributes.SingleOrDefault(a => a.LocalName == "Array" && a.NamespaceUri == JsonNamespaceUri)
: null;
return (jsonArrayAttribute != null && XmlConvert.ToBoolean(jsonArrayAttribute.Value));
}
private void SerializeGroupedNodes(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName)
{
// group nodes together by name
Dictionary<string, List<IXmlNode>> nodesGroupedByName = new Dictionary<string, List<IXmlNode>>();
for (int i = 0; i < node.ChildNodes.Count; i++)
{
IXmlNode childNode = node.ChildNodes[i];
string nodeName = GetPropertyName(childNode, manager);
List<IXmlNode> nodes;
if (!nodesGroupedByName.TryGetValue(nodeName, out nodes))
{
nodes = new List<IXmlNode>();
nodesGroupedByName.Add(nodeName, nodes);
}
nodes.Add(childNode);
}
// loop through grouped nodes. write single name instances as normal,
// write multiple names together in an array
foreach (KeyValuePair<string, List<IXmlNode>> nodeNameGroup in nodesGroupedByName)
{
List<IXmlNode> groupedNodes = nodeNameGroup.Value;
bool writeArray;
if (groupedNodes.Count == 1)
{
writeArray = IsArray(groupedNodes[0]);
}
else
{
writeArray = true;
}
if (!writeArray)
{
SerializeNode(writer, groupedNodes[0], manager, writePropertyName);
}
else
{
string elementNames = nodeNameGroup.Key;
if (writePropertyName)
writer.WritePropertyName(elementNames);
writer.WriteStartArray();
for (int i = 0; i < groupedNodes.Count; i++)
{
SerializeNode(writer, groupedNodes[i], manager, false);
}
writer.WriteEndArray();
}
}
}
private void SerializeNode(JsonWriter writer, IXmlNode node, XmlNamespaceManager manager, bool writePropertyName)
{
switch (node.NodeType)
{
case XmlNodeType.Document:
case XmlNodeType.DocumentFragment:
SerializeGroupedNodes(writer, node, manager, writePropertyName);
break;
case XmlNodeType.Element:
if (IsArray(node) && node.ChildNodes.All(n => n.LocalName == node.LocalName) && node.ChildNodes.Count > 0)
{
SerializeGroupedNodes(writer, node, manager, false);
}
else
{
foreach (IXmlNode attribute in node.Attributes)
{
if (attribute.NamespaceUri == "http://www.w3.org/2000/xmlns/")
{
string prefix = (attribute.LocalName != "xmlns")
? attribute.LocalName
: string.Empty;
manager.AddNamespace(prefix, attribute.Value);
}
}
if (writePropertyName)
writer.WritePropertyName(GetPropertyName(node, manager));
if (!ValueAttributes(node.Attributes).Any() && node.ChildNodes.Count == 1
&& node.ChildNodes[0].NodeType == XmlNodeType.Text)
{
// write elements with a single text child as a name value pair
writer.WriteValue(node.ChildNodes[0].Value);
}
else if (node.ChildNodes.Count == 0 && CollectionUtils.IsNullOrEmpty(node.Attributes))
{
// empty element
writer.WriteNull();
}
else
{
writer.WriteStartObject();
for (int i = 0; i < node.Attributes.Count; i++)
{
SerializeNode(writer, node.Attributes[i], manager, true);
}
SerializeGroupedNodes(writer, node, manager, true);
writer.WriteEndObject();
}
}
break;
case XmlNodeType.Comment:
if (writePropertyName)
writer.WriteComment(node.Value);
break;
case XmlNodeType.Attribute:
case XmlNodeType.Text:
case XmlNodeType.CDATA:
case XmlNodeType.ProcessingInstruction:
case XmlNodeType.Whitespace:
case XmlNodeType.SignificantWhitespace:
if (node.NamespaceUri == "http://www.w3.org/2000/xmlns/" && node.Value == JsonNamespaceUri)
return;
if (node.NamespaceUri == JsonNamespaceUri)
{
if (node.LocalName == "Array")
return;
}
if (writePropertyName)
writer.WritePropertyName(GetPropertyName(node, manager));
writer.WriteValue(node.Value);
break;
case XmlNodeType.XmlDeclaration:
IXmlDeclaration declaration = (IXmlDeclaration)node;
writer.WritePropertyName(GetPropertyName(node, manager));
writer.WriteStartObject();
if (!string.IsNullOrEmpty(declaration.Version))
{
writer.WritePropertyName("@version");
writer.WriteValue(declaration.Version);
}
if (!string.IsNullOrEmpty(declaration.Encoding))
{
writer.WritePropertyName("@encoding");
writer.WriteValue(declaration.Encoding);
}
if (!string.IsNullOrEmpty(declaration.Standalone))
{
writer.WritePropertyName("@standalone");
writer.WriteValue(declaration.Standalone);
}
writer.WriteEndObject();
break;
default:
throw new JsonSerializationException("Unexpected XmlNodeType when serializing nodes: " + node.NodeType);
}
}
#endregion
#region Reading
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
XmlNamespaceManager manager = new XmlNamespaceManager(new NameTable());
IXmlDocument document = null;
IXmlNode rootNode = null;
#if !NET20
if (typeof(XObject).IsAssignableFrom(objectType))
{
if (objectType != typeof (XDocument) && objectType != typeof (XElement))
throw new JsonSerializationException("XmlNodeConverter only supports deserializing XDocument or XElement.");
XDocument d = new XDocument();
document = new XDocumentWrapper(d);
rootNode = document;
}
#endif
#if !SILVERLIGHT
if (typeof(XmlNode).IsAssignableFrom(objectType))
{
if (objectType != typeof (XmlDocument))
throw new JsonSerializationException("XmlNodeConverter only supports deserializing XmlDocuments");
XmlDocument d = new XmlDocument();
document = new XmlDocumentWrapper(d);
rootNode = document;
}
#endif
if (document == null || rootNode == null)
throw new JsonSerializationException("Unexpected type when converting XML: " + objectType);
if (reader.TokenType != JsonToken.StartObject)
throw new JsonSerializationException("XmlNodeConverter can only convert JSON that begins with an object.");
if (!string.IsNullOrEmpty(DeserializeRootElementName))
{
//rootNode = document.CreateElement(DeserializeRootElementName);
//document.AppendChild(rootNode);
ReadElement(reader, document, rootNode, DeserializeRootElementName, manager);
}
else
{
reader.Read();
DeserializeNode(reader, document, manager, rootNode);
}
#if !NET20
if (objectType == typeof(XElement))
{
XElement element = (XElement)document.DocumentElement.WrappedNode;
element.Remove();
return element;
}
#endif
return document.WrappedNode;
}
private void DeserializeValue(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, string propertyName, IXmlNode currentNode)
{
switch (propertyName)
{
case TextName:
currentNode.AppendChild(document.CreateTextNode(reader.Value.ToString()));
break;
case CDataName:
currentNode.AppendChild(document.CreateCDataSection(reader.Value.ToString()));
break;
case WhitespaceName:
currentNode.AppendChild(document.CreateWhitespace(reader.Value.ToString()));
break;
case SignificantWhitespaceName:
currentNode.AppendChild(document.CreateSignificantWhitespace(reader.Value.ToString()));
break;
default:
// processing instructions and the xml declaration start with ?
if (!string.IsNullOrEmpty(propertyName) && propertyName[0] == '?')
{
CreateInstruction(reader, document, currentNode, propertyName);
}
else
{
if (reader.TokenType == JsonToken.StartArray)
{
// handle nested arrays
ReadArrayElements(reader, document, propertyName, currentNode, manager);
return;
}
// have to wait until attributes have been parsed before creating element
// attributes may contain namespace info used by the element
ReadElement(reader, document, currentNode, propertyName, manager);
}
break;
}
}
private void ReadElement(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager)
{
if (string.IsNullOrEmpty(propertyName))
throw new JsonSerializationException("XmlNodeConverter cannot convert JSON with an empty property name to XML.");
Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager);
string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);
IXmlElement element = CreateElement(propertyName, document, elementPrefix, manager);
currentNode.AppendChild(element);
// add attributes to newly created element
foreach (KeyValuePair<string, string> nameValue in attributeNameValues)
{
string attributePrefix = MiscellaneousUtils.GetPrefix(nameValue.Key);
IXmlNode attribute = (!string.IsNullOrEmpty(attributePrefix))
? document.CreateAttribute(nameValue.Key, manager.LookupNamespace(attributePrefix), nameValue.Value)
: document.CreateAttribute(nameValue.Key, nameValue.Value);
element.SetAttributeNode(attribute);
}
if (reader.TokenType == JsonToken.String
|| reader.TokenType == JsonToken.Integer
|| reader.TokenType == JsonToken.Float
|| reader.TokenType == JsonToken.Boolean
|| reader.TokenType == JsonToken.Date)
{
element.AppendChild(document.CreateTextNode(ConvertTokenToXmlValue(reader)));
}
else if (reader.TokenType == JsonToken.Null)
{
// empty element. do nothing
}
else
{
// finished element will have no children to deserialize
if (reader.TokenType != JsonToken.EndObject)
{
manager.PushScope();
DeserializeNode(reader, document, manager, element);
manager.PopScope();
}
}
}
private string ConvertTokenToXmlValue(JsonReader reader)
{
if (reader.TokenType == JsonToken.String)
{
return reader.Value.ToString();
}
else if (reader.TokenType == JsonToken.Integer)
{
return XmlConvert.ToString(Convert.ToInt64(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Float)
{
return XmlConvert.ToString(Convert.ToDouble(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Boolean)
{
return XmlConvert.ToString(Convert.ToBoolean(reader.Value, CultureInfo.InvariantCulture));
}
else if (reader.TokenType == JsonToken.Date)
{
DateTime d = Convert.ToDateTime(reader.Value, CultureInfo.InvariantCulture);
return XmlConvert.ToString(d, DateTimeUtils.ToSerializationMode(d.Kind));
}
else if (reader.TokenType == JsonToken.Null)
{
return null;
}
else
{
throw new Exception("Cannot get an XML string value from token type '{0}'.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
}
private void ReadArrayElements(JsonReader reader, IXmlDocument document, string propertyName, IXmlNode currentNode, XmlNamespaceManager manager)
{
string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);
IXmlElement nestedArrayElement = CreateElement(propertyName, document, elementPrefix, manager);
currentNode.AppendChild(nestedArrayElement);
int count = 0;
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
DeserializeValue(reader, document, manager, propertyName, nestedArrayElement);
count++;
}
if (WriteArrayAttribute)
{
AddJsonArrayAttribute(nestedArrayElement, document);
}
if (count == 1 && WriteArrayAttribute)
{
IXmlElement arrayElement = nestedArrayElement.ChildNodes.CastValid<IXmlElement>().Single(n => n.LocalName == propertyName);
AddJsonArrayAttribute(arrayElement, document);
}
}
private void AddJsonArrayAttribute(IXmlElement element, IXmlDocument document)
{
element.SetAttributeNode(document.CreateAttribute("json:Array", JsonNamespaceUri, "true"));
#if !NET20
// linq to xml doesn't automatically include prefixes via the namespace manager
if (element is XElementWrapper)
{
if (element.GetPrefixOfNamespace(JsonNamespaceUri) == null)
{
element.SetAttributeNode(document.CreateAttribute("xmlns:json", "http://www.w3.org/2000/xmlns/", JsonNamespaceUri));
}
}
#endif
}
private Dictionary<string, string> ReadAttributeElements(JsonReader reader, XmlNamespaceManager manager)
{
Dictionary<string, string> attributeNameValues = new Dictionary<string, string>();
bool finishedAttributes = false;
bool finishedElement = false;
// a string token means the element only has a single text child
if (reader.TokenType != JsonToken.String
&& reader.TokenType != JsonToken.Null
&& reader.TokenType != JsonToken.Boolean
&& reader.TokenType != JsonToken.Integer
&& reader.TokenType != JsonToken.Float
&& reader.TokenType != JsonToken.Date
&& reader.TokenType != JsonToken.StartConstructor)
{
// read properties until first non-attribute is encountered
while (!finishedAttributes && !finishedElement && reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string attributeName = reader.Value.ToString();
if (!string.IsNullOrEmpty(attributeName))
{
char firstChar = attributeName[0];
string attributeValue;
switch (firstChar)
{
case '@':
attributeName = attributeName.Substring(1);
reader.Read();
attributeValue = ConvertTokenToXmlValue(reader);
attributeNameValues.Add(attributeName, attributeValue);
string namespacePrefix;
if (IsNamespaceAttribute(attributeName, out namespacePrefix))
{
manager.AddNamespace(namespacePrefix, attributeValue);
}
break;
case '$':
attributeName = attributeName.Substring(1);
reader.Read();
attributeValue = reader.Value.ToString();
// check that JsonNamespaceUri is in scope
// if it isn't then add it to document and namespace manager
string jsonPrefix = manager.LookupPrefix(JsonNamespaceUri);
if (jsonPrefix == null)
{
// ensure that the prefix used is free
int? i = null;
while (manager.LookupNamespace("json" + i) != null)
{
i = i.GetValueOrDefault() + 1;
}
jsonPrefix = "json" + i;
attributeNameValues.Add("xmlns:" + jsonPrefix, JsonNamespaceUri);
manager.AddNamespace(jsonPrefix, JsonNamespaceUri);
}
attributeNameValues.Add(jsonPrefix + ":" + attributeName, attributeValue);
break;
default:
finishedAttributes = true;
break;
}
}
else
{
finishedAttributes = true;
}
break;
case JsonToken.EndObject:
finishedElement = true;
break;
default:
throw new JsonSerializationException("Unexpected JsonToken: " + reader.TokenType);
}
}
}
return attributeNameValues;
}
private void CreateInstruction(JsonReader reader, IXmlDocument document, IXmlNode currentNode, string propertyName)
{
if (propertyName == DeclarationName)
{
string version = null;
string encoding = null;
string standalone = null;
while (reader.Read() && reader.TokenType != JsonToken.EndObject)
{
switch (reader.Value.ToString())
{
case "@version":
reader.Read();
version = reader.Value.ToString();
break;
case "@encoding":
reader.Read();
encoding = reader.Value.ToString();
break;
case "@standalone":
reader.Read();
standalone = reader.Value.ToString();
break;
default:
throw new JsonSerializationException("Unexpected property name encountered while deserializing XmlDeclaration: " + reader.Value);
}
}
IXmlNode declaration = document.CreateXmlDeclaration(version, encoding, standalone);
currentNode.AppendChild(declaration);
}
else
{
IXmlNode instruction = document.CreateProcessingInstruction(propertyName.Substring(1), reader.Value.ToString());
currentNode.AppendChild(instruction);
}
}
private IXmlElement CreateElement(string elementName, IXmlDocument document, string elementPrefix, XmlNamespaceManager manager)
{
return (!string.IsNullOrEmpty(elementPrefix))
? document.CreateElement(elementName, manager.LookupNamespace(elementPrefix))
: document.CreateElement(elementName);
}
private void DeserializeNode(JsonReader reader, IXmlDocument document, XmlNamespaceManager manager, IXmlNode currentNode)
{
do
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
if (currentNode.NodeType == XmlNodeType.Document && document.DocumentElement != null)
throw new JsonSerializationException("JSON root object has multiple properties. The root object must have a single property in order to create a valid XML document. Consider specifing a DeserializeRootElementName.");
string propertyName = reader.Value.ToString();
reader.Read();
if (reader.TokenType == JsonToken.StartArray)
{
int count = 0;
while (reader.Read() && reader.TokenType != JsonToken.EndArray)
{
DeserializeValue(reader, document, manager, propertyName, currentNode);
count++;
}
if (count == 1 && WriteArrayAttribute)
{
IXmlElement arrayElement = currentNode.ChildNodes.CastValid<IXmlElement>().Single(n => n.LocalName == propertyName);
AddJsonArrayAttribute(arrayElement, document);
}
}
else
{
DeserializeValue(reader, document, manager, propertyName, currentNode);
}
break;
case JsonToken.StartConstructor:
string constructorName = reader.Value.ToString();
while (reader.Read() && reader.TokenType != JsonToken.EndConstructor)
{
DeserializeValue(reader, document, manager, constructorName, currentNode);
}
break;
case JsonToken.Comment:
currentNode.AppendChild(document.CreateComment((string)reader.Value));
break;
case JsonToken.EndObject:
case JsonToken.EndArray:
return;
default:
throw new JsonSerializationException("Unexpected JsonToken when deserializing node: " + reader.TokenType);
}
} while (reader.TokenType == JsonToken.PropertyName || reader.Read());
// don't read if current token is a property. token was already read when parsing element attributes
}
/// <summary>
/// Checks if the attributeName is a namespace attribute.
/// </summary>
/// <param name="attributeName">Attribute name to test.</param>
/// <param name="prefix">The attribute name prefix if it has one, otherwise an empty string.</param>
/// <returns>True if attribute name is for a namespace attribute, otherwise false.</returns>
private bool IsNamespaceAttribute(string attributeName, out string prefix)
{
if (attributeName.StartsWith("xmlns", StringComparison.Ordinal))
{
if (attributeName.Length == 5)
{
prefix = string.Empty;
return true;
}
else if (attributeName[5] == ':')
{
prefix = attributeName.Substring(6, attributeName.Length - 6);
return true;
}
}
prefix = null;
return false;
}
private IEnumerable<IXmlNode> ValueAttributes(IEnumerable<IXmlNode> c)
{
return c.Where(a => a.NamespaceUri != JsonNamespaceUri);
}
#endregion
/// <summary>
/// Determines whether this instance can convert the specified value type.
/// </summary>
/// <param name="valueType">Type of the value.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type valueType)
{
#if !NET20
if (typeof(XObject).IsAssignableFrom(valueType))
return true;
#endif
#if !SILVERLIGHT
if (typeof(XmlNode).IsAssignableFrom(valueType))
return true;
#endif
return false;
}
}
}
#endif
| |
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors.
// All rights reserved. Licensed under the BSD 3-Clause License; see License.txt.
using System;
using System.Collections.Generic;
using Xunit;
namespace Moq.Tests
{
public class ReturnsFixture
{
[Fact]
public void ReturnsValue()
{
var mock = new Mock<IBar>();
var clone = new object();
mock.Setup(x => x.Clone()).Returns(clone);
Assert.Equal(clone, mock.Object.Clone());
}
[Fact]
public void ReturnsNullValueIfSpecified()
{
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.Execute("Whatever")).Returns((string)null);
Assert.Null(mock.Object.Execute("Whatever"));
mock.VerifyAll();
}
[Fact]
public void ReturnsNullValueIfNullFunc()
{
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.Execute("Whatever")).Returns((Func<string>)null);
Assert.Null(mock.Object.Execute("Whatever"));
mock.VerifyAll();
}
[Fact]
public void ReturnsNullValueIfNullDelegate()
{
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.Execute("Whatever")).Returns((Delegate)null);
Assert.Null(mock.Object.Execute("Whatever"));
mock.VerifyAll();
}
[Fact]
public void ReturnsNullValueIfSpecifiedForStrictMock()
{
var mock = new Mock<IFoo>(MockBehavior.Strict);
mock.Setup(foo => foo.Execute("Whatever")).Returns((string)null);
Assert.Null(mock.Object.Execute("Whatever"));
mock.VerifyAll();
}
[Fact]
public void ReturnsNullValueIfNullFuncForStrictMock()
{
var mock = new Mock<IFoo>(MockBehavior.Strict);
mock.Setup(foo => foo.Execute("Whatever")).Returns((Func<string>)null);
Assert.Null(mock.Object.Execute("Whatever"));
mock.VerifyAll();
}
[Fact]
public void ReturnsNullValueIfNullDelegateForStrictMock()
{
var mock = new Mock<IFoo>(MockBehavior.Strict);
mock.Setup(foo => foo.Execute("Whatever")).Returns((Delegate)null);
Assert.Null(mock.Object.Execute("Whatever"));
mock.VerifyAll();
}
[Fact]
public void DifferentMethodCallsReturnDifferentValues()
{
var mock = new Mock<IFoo>();
mock.Setup(x => x.Execute("ping")).Returns("ack");
mock.Setup(x => x.Execute("ping", "foo")).Returns("ack2");
Assert.Equal("ack", mock.Object.Execute("ping"));
Assert.Equal("ack2", mock.Object.Execute("ping", "foo"));
}
[Fact]
public void DifferentArgumentsReturnDifferentValues()
{
var mock = new Mock<IFoo>();
mock.Setup(x => x.Execute("ping")).Returns("ack");
mock.Setup(x => x.Execute("send")).Returns("ok");
Assert.Equal("ack", mock.Object.Execute("ping"));
Assert.Equal("ok", mock.Object.Execute("send"));
}
[Fact]
public void DifferentiatesCallWithNullArgument()
{
var mock = new Mock<IFoo>();
mock.Setup(x => x.Execute(null)).Returns("null");
mock.Setup(x => x.Execute("ping")).Returns("ack");
Assert.Equal("null", mock.Object.Execute(null));
Assert.Equal("ack", mock.Object.Execute("ping"));
}
[Fact]
public void ReturnsValueFromVariable()
{
var value = "ack";
var mock = new Mock<IFoo>();
mock.Setup(x => x.Execute(null)).Returns(value);
Assert.Equal(value, mock.Object.Execute(null));
}
[Fact]
public void ReturnsValueFromLambdaLazyEvaluation()
{
var a = "25";
var mock = new Mock<IFoo>();
mock.Setup(x => x.Execute(a.ToString())).Returns(() => a);
a = "10";
Assert.Equal("10", mock.Object.Execute("10"));
a = "20";
Assert.Equal("20", mock.Object.Execute("20"));
}
[Fact]
public void PassesOneArgumentToReturns()
{
var mock = new Mock<IFoo>();
mock.Setup(x => x.Execute(It.IsAny<string>()))
.Returns((string s) => s.ToLower());
string result = mock.Object.Execute("blah1");
Assert.Equal("blah1", result);
}
[Fact]
public void PassesTwoArgumentsToReturns()
{
var mock = new Mock<IFoo>();
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>()))
.Returns((string s1, string s2) => s1 + s2);
string result = mock.Object.Execute("blah1", "blah2");
Assert.Equal("blah1blah2", result);
}
[Fact]
public void PassesThreeArgumentsToReturns()
{
var mock = new Mock<IFoo>();
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns((string s1, string s2, string s3) => s1 + s2 + s3);
string result = mock.Object.Execute("blah1", "blah2", "blah3");
Assert.Equal("blah1blah2blah3", result);
}
[Fact]
public void PassesFourArgumentsToReturns()
{
var mock = new Mock<IFoo>();
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns((string s1, string s2, string s3, string s4) => s1 + s2 + s3 + s4);
string result = mock.Object.Execute("blah1", "blah2", "blah3", "blah4");
Assert.Equal("blah1blah2blah3blah4", result);
}
[Fact]
public void PassesFiveArgumentsToReturns()
{
var mock = new Mock<IFoo>();
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns((string s1, string s2, string s3, string s4, string s5) => s1 + s2 + s3 + s4 + s5);
string result = mock.Object.Execute("blah1", "blah2", "blah3", "blah4", "blah5");
Assert.Equal("blah1blah2blah3blah4blah5", result);
}
[Fact]
public void PassesSixArgumentsToReturns()
{
var mock = new Mock<IFoo>();
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns((string s1, string s2, string s3, string s4, string s5, string s6) => s1 + s2 + s3 + s4 + s5 + s6);
string result = mock.Object.Execute("blah1", "blah2", "blah3", "blah4", "blah5", "blah6");
Assert.Equal("blah1blah2blah3blah4blah5blah6", result);
}
[Fact]
public void PassesSevenArgumentsToReturns()
{
var mock = new Mock<IFoo>();
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns((string s1, string s2, string s3, string s4, string s5, string s6, string s7) => s1 + s2 + s3 + s4 + s5 + s6 + s7);
string result = mock.Object.Execute("blah1", "blah2", "blah3", "blah4", "blah5", "blah6", "blah7");
Assert.Equal("blah1blah2blah3blah4blah5blah6blah7", result);
}
[Fact]
public void PassesEightArgumentsToReturns()
{
var mock = new Mock<IFoo>();
mock.Setup(x => x.Execute(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()))
.Returns((string s1, string s2, string s3, string s4, string s5, string s6, string s7, string s8) => s1 + s2 + s3 + s4 + s5 + s6 + s7 + s8);
string result = mock.Object.Execute("blah1", "blah2", "blah3", "blah4", "blah5", "blah6", "blah7", "blah8");
Assert.Equal("blah1blah2blah3blah4blah5blah6blah7blah8", result);
}
[Fact]
public void ReturnsDefaultValueType()
{
var mock = new Mock<IFoo>();
mock.SetReturnsDefault(true);
Assert.True(mock.Object.ReturnBool());
}
[Fact]
public void ReturnsDefaultReferenceValue()
{
var mock = new Mock<IFoo>();
mock.SetReturnsDefault<IList<int>>(new List<int>());
Assert.NotNull(mock.Object.ReturnIntList());
}
[Fact]
public void ReturnsDefaultValueOnProperty()
{
var mock = new Mock<IFoo>();
mock.SetReturnsDefault(int.MinValue);
Assert.Equal(int.MinValue, mock.Object.Value);
}
[Fact]
public void ReturnsValueFromBaseMethod()
{
var mock = new Mock<Foo>();
mock.Setup(foo => foo.Execute()).CallBase();
Assert.Equal("Ok", mock.Object.Execute());
}
[Fact]
public void ReturnsValueFromBaseProperty()
{
var mock = new Mock<Foo>();
mock.SetupGet(foo => foo.StringProperty).CallBase();
Assert.Equal("Text", mock.Object.StringProperty);
}
[Fact]
public void ReturnsWithRefParameterReceivesArguments()
{
var input = "input";
var received = default(string);
var mock = new Mock<IFoo>();
mock.Setup(f => f.Execute(ref input))
.Returns(new ExecuteRHandler((ref string arg1) =>
{
received = arg1;
return default(string);
}));
mock.Object.Execute(ref input);
Assert.Equal("input", input);
Assert.Equal(input, received);
}
[Fact]
public void ReturnsWithRefParameterProducesReturnValue()
{
var input = default(string);
var mock = new Mock<IFoo>();
mock.Setup(f => f.Execute(ref input))
.Returns(new ExecuteRHandler((ref string arg1) =>
{
return "result";
}));
var returnValue = mock.Object.Execute(ref input);
Assert.Equal("result", returnValue);
}
[Fact]
public void ReturnsWithRefParameterCanModifyRefParameter()
{
var value = "input";
var mock = new Mock<IFoo>();
mock.Setup(f => f.Execute(ref value))
.Returns(new ExecuteRHandler((ref string arg1) =>
{
arg1 = "output";
return default(string);
}));
Assert.Equal("input", value);
mock.Object.Execute(ref value);
Assert.Equal("output", value);
}
[Fact]
public void ReturnsWithRefParameterCannotModifyNonRefParameter()
{
var _ = default(string);
var value = "input";
var mock = new Mock<IFoo>();
mock.Setup(f => f.Execute(ref _, value))
.Returns(new ExecuteRVHandler((ref string arg1, string arg2) =>
{
arg2 = "output";
return default(string);
}));
Assert.Equal("input", value);
mock.Object.Execute(ref _, value);
Assert.Equal("input", value);
}
[Fact]
public void Method_returning_a_Delegate_can_be_set_up_to_return_null()
{
var mock = new Mock<IFoo>();
mock.Setup(_ => _.ReturnDelegate()).Returns((Delegate)null);
Assert.Null(mock.Object.ReturnDelegate());
}
[Fact]
public void Setting_up_method_returning_a_Delegate_to_return_a_Delegate_does_not_invoke_that_Delegate()
{
Delegate expectedResult = new Func<Delegate>(() => null);
var mock = new Mock<IFoo>();
mock.Setup(_ => _.ReturnDelegate()).Returns(expectedResult);
var actualResult = mock.Object.ReturnDelegate();
Assert.NotNull(actualResult); // would be null if invoked
Assert.Same(expectedResult, actualResult); // should be returned by method as is
}
[Fact]
public void Given_a_loose_mock_Return_value_of_setup_without_Returns_nor_CallBase_equals_return_value_if_setup_werent_there_at_all()
{
const int expected = 42;
var mock = new Mock<IFoo>(MockBehavior.Loose);
mock.SetReturnsDefault<int>(expected);
var actualWithoutSetup = mock.Object.Value;
Assert.Equal(expected, actualWithoutSetup);
mock.SetupGet(m => m.Value);
var actualWithSetup = mock.Object.Value;
Assert.Equal(actualWithoutSetup, actualWithSetup);
}
[Fact]
public void Given_a_loose_mock_with_CallBase_Return_value_of_setup_without_Returns_nor_CallBase_equals_return_value_if_setup_werent_there_at_all()
{
var mock = new Mock<Foo>(MockBehavior.Loose) { CallBase = true };
var expected = mock.Object.StringProperty;
mock.SetupGet(m => m.StringProperty);
var actual = mock.Object.StringProperty;
Assert.Equal(expected, actual);
}
public interface IFoo
{
void Execute();
string Execute(string command);
string Execute(string arg1, string arg2);
string Execute(string arg1, string arg2, string arg3);
string Execute(string arg1, string arg2, string arg3, string arg4);
string Execute(string arg1, string arg2, string arg3, string arg4, string arg5);
string Execute(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6);
string Execute(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7);
string Execute(string arg1, string arg2, string arg3, string arg4, string arg5, string arg6, string arg7, string arg8);
string Execute(ref string arg1);
string Execute(ref string arg1, string arg2);
bool ReturnBool();
IList<int> ReturnIntList();
Delegate ReturnDelegate();
int Value { get; set; }
}
public delegate string ExecuteRHandler(ref string arg1);
public delegate string ExecuteRVHandler(ref string arg1, string arg2);
public delegate Delegate ReturnDelegateHandler();
public class Foo
{
public virtual string Execute()
{
return "Ok";
}
public virtual string StringProperty
{
get { return "Text"; }
}
}
public interface IBar
{
object Clone();
}
}
}
| |
/*
Copyright 2012 Michael Edwards
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.
*/
//-CRE-
using System;
using System.Collections.Specialized;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using Glass.Mapper.Sc.RenderField;
using Glass.Mapper.Sc.Web.Ui;
using Sitecore.Mvc.Configuration;
using Sitecore.Shell.Applications.Dialogs.ItemLister;
using Sitecore.Data.Items;
namespace Glass.Mapper.Sc.Web.Mvc
{
/// <summary>
///
/// </summary>
/// <typeparam name="TModel"></typeparam>
public abstract class GlassView<TModel> : WebViewPage<TModel> where TModel : class
{
public static bool HasDataSource<T>() where T : class
{
if (Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull == null || Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull.Rendering == null)
return false;
//this has been taken from Sitecore.Mvc.Presentation.Rendering class
#if (SC70)
return Sitecore.Context.Database.GetItem(Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull.Rendering.DataSource) != null;
#else
return MvcSettings.ItemLocator.GetItem(Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull.Rendering.DataSource) != null;
#endif
}
/// <summary>
///
/// </summary>
public IGlassHtml GlassHtml { get; private set; }
public ISitecoreContext SitecoreContext { get; private set; }
/// <summary>
/// Gets a value indicating whether this instance is in editing mode.
/// </summary>
/// <value><c>true</c> if this instance is in editing mode; otherwise, <c>false</c>.</value>
public bool IsInEditingMode
{
get { return Sc.GlassHtml.IsInEditingMode; }
}
/// <summary>
/// Returns either the item specified by the DataSource or the current context item
/// </summary>
/// <value>The layout item.</value>
public Item LayoutItem
{
get
{
return DataSourceItem ?? ContextItem;
}
}
/// <summary>
/// Returns either the item specified by the current context item
/// </summary>
/// <value>The layout item.</value>
public Item ContextItem
{
get { return global::Sitecore.Context.Item; }
}
/// <summary>
/// Returns the item specificed by the data source only. Returns null if no datasource set
/// </summary>
public Item DataSourceItem
{
get
{
if (Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull == null ||
Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull.Rendering == null ||
Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull.Rendering.DataSource.IsNullOrEmpty())
{
return null;
}
else
return global::Sitecore.Context.Database.GetItem(Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull.Rendering.DataSource);
}
}
/// <summary>
/// Returns the Context Item as strongly typed
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetContextItem<T>(bool isLazy = false, bool inferType = false) where T : class
{
return SitecoreContext.Cast<T>(ContextItem, isLazy, inferType);
}
/// <summary>
/// Returns the Data Source Item as strongly typed
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetDataSourceItem<T>(bool isLazy = false, bool inferType = false) where T : class
{
return SitecoreContext.Cast<T>(DataSourceItem, isLazy, inferType);
}
/// <summary>
/// Returns the Layout Item as strongly typed
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public T GetLayoutItem<T>(bool isLazy = false, bool inferType = false) where T : class
{
return SitecoreContext.Cast<T>(LayoutItem, isLazy, inferType);
}
/// <summary>
/// Inits the helpers.
/// </summary>
public override void InitHelpers()
{
base.InitHelpers();
SitecoreContext = Sc.SitecoreContext.GetFromHttpContext();
GlassHtml = new GlassHtml(SitecoreContext);
if (Model == null && this.ViewData.Model == null)
{
this.ViewData.Model = GetModel();
}
}
protected virtual TModel GetModel()
{
return SitecoreContext.Cast<TModel>(LayoutItem);
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <param name="field">The field that should be made editable</param>
/// <param name="parameters"> </param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public HtmlString Editable<T>(T target, Expression<Func<T, object>> field, object parameters = null)
{
return new HtmlString(GlassHtml.Editable(target, field, parameters));
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <typeparam name="T">A class loaded by Glass.Sitecore.Mapper</typeparam>
/// <param name="target">The target object that contains the item to be edited</param>
/// <param name="field">The field that should be made editable</param>
/// <param name="standardOutput">The output to display when the Sitecore Page Editor is not being used</param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public HtmlString Editable<T>(T target, Expression<Func<T, object>> field,
Expression<Func<T, string>> standardOutput, object parameters = null)
{
return new HtmlString(GlassHtml.Editable(target, field, standardOutput, parameters));
}
/// <summary>
/// Renders an image allowing simple page editor support
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model that contains the image field</param>
/// <param name="field">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param>
/// <param name="parameters">Image parameters, e.g. width, height</param>
/// <param name="isEditable">Indicates if the field should be editable</param>
/// <param name="outputHeightWidth">Indicates if the height and width attributes should be rendered to the HTML element</param>
/// <returns></returns>
public virtual HtmlString RenderImage<T>(T target, Expression<Func<T, object>> field,
object parameters = null,
bool isEditable = false,
bool outputHeightWidth = false)
{
return new HtmlString(GlassHtml.RenderImage<T>(target, field, parameters, isEditable, outputHeightWidth));
}
/// <summary>
/// Render HTML for a link with contents
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model</param>
/// <param name="field">The link field to user</param>
/// <param name="attributes">Any additional link attributes</param>
/// <param name="isEditable">Make the link editable</param>
/// <returns></returns>
public virtual RenderingResult BeginRenderLink<T>(T model, Expression<Func<T, object>> field,
object attributes = null, bool isEditable = false)
{
return GlassHtml.BeginRenderLink(model, field, this.Output, attributes, isEditable);
}
/// <summary>
/// Render HTML for a link
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model</param>
/// <param name="field">The link field to user</param>
/// <param name="attributes">Any additional link attributes</param>
/// <param name="isEditable">Make the link editable</param>
/// <param name="contents">Content to override the default decription or item name</param>
/// <returns></returns>
public virtual HtmlString RenderLink<T>(T model, Expression<Func<T, object>> field, object attributes = null, bool isEditable = false, string contents = null)
{
return new HtmlString(GlassHtml.RenderLink(model, field, attributes, isEditable, contents));
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <param name="field">The field that should be made editable</param>
/// <param name="parameters"></param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public HtmlString Editable(Expression<Func<TModel, object>> field, object parameters = null)
{
return new HtmlString(GlassHtml.Editable(Model, field, parameters));
}
/// <summary>
/// Makes the field editable using the Sitecore Page Editor. Using the specifed service to write data.
/// </summary>
/// <param name="field">The field that should be made editable</param>
/// <param name="standardOutput">The output to display when the Sitecore Page Editor is not being used</param>
/// <returns>HTML output to either render the editable controls or normal HTML</returns>
public HtmlString Editable(
Expression<Func<TModel, object>> field, Expression<Func<TModel, string>> standardOutput, object parameters = null)
{
return new HtmlString(GlassHtml.Editable(Model, field, standardOutput, parameters));
}
/// <summary>
/// Renders an image allowing simple page editor support
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model that contains the image field</param>
/// <param name="field">A lambda expression to the image field, should be of type Glass.Mapper.Sc.Fields.Image</param>
/// <param name="parameters">Image parameters, e.g. width, height</param>
/// <param name="isEditable">Indicates if the field should be editable</param>
/// <returns></returns>
public virtual HtmlString RenderImage(Expression<Func<TModel, object>> field,
object parameters = null,
bool isEditable = false,
bool outputHeightWidth = false)
{
return new HtmlString(GlassHtml.RenderImage(Model, field, parameters, isEditable, outputHeightWidth ));
}
/// <summary>
/// Render HTML for a link with contents
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model</param>
/// <param name="field">The link field to user</param>
/// <param name="attributes">Any additional link attributes</param>
/// <param name="isEditable">Make the link editable</param>
/// <returns></returns>
public virtual RenderingResult BeginRenderLink(Expression<Func<TModel, object>> field,
object attributes = null, bool isEditable = false)
{
return GlassHtml.BeginRenderLink(this.Model, field, this.Output, attributes, isEditable);
}
/// <summary>
/// Render HTML for a link
/// </summary>
/// <typeparam name="T">The model type</typeparam>
/// <param name="model">The model</param>
/// <param name="field">The link field to user</param>
/// <param name="attributes">Any additional link attributes</param>
/// <param name="isEditable">Make the link editable</param>
/// <param name="contents">Content to override the default decription or item name</param>
/// <returns></returns>
public virtual HtmlString RenderLink(Expression<Func<TModel, object>> field, object attributes = null, bool isEditable = false, string contents = null)
{
return new HtmlString(GlassHtml.RenderLink(this.Model, field, attributes, isEditable, contents));
}
/// <summary>
/// Returns an Sitecore Edit Frame
/// </summary>
/// <param name="buttons">The buttons.</param>
/// <param name="path">The path.</param>
/// <param name="output">The stream to write the editframe output to. If the value is null the HttpContext Response Stream is used.</param>
/// <returns>
/// GlassEditFrame.
/// </returns>
public GlassEditFrame BeginEditFrame<T>(T model, string title = null, params Expression<Func<T, object>>[] fields)
where T : class
{
return GlassHtml.EditFrame(model, title, this.Output, fields);
}
/// <summary>
/// Begins the edit frame.
/// </summary>
/// <param name="buttons">The buttons.</param>
/// <param name="dataSource">The data source.</param>
/// <returns></returns>
public GlassEditFrame BeginEditFrame(string buttons, string dataSource)
{
return GlassHtml.EditFrame(buttons, dataSource, this.Output);
}
/// <summary>
/// Creates an Edit Frame using the Default Buttons list
/// </summary>
/// <param name="dataSource"></param>
/// <returns></returns>
public GlassEditFrame BeginEditFrame(string dataSource)
{
return GlassHtml.EditFrame(GlassEditFrame.DefaultEditButtons, dataSource, this.Output);
}
/// <summary>
/// Creates an edit frame using the current context item
/// </summary>
/// <returns></returns>
public GlassEditFrame BeginEditFrame()
{
var frame = new GlassEditFrame(GlassEditFrame.DefaultEditButtons, this.Output);
frame.RenderFirstPart();
return frame;
}
public T GetRenderingParameters<T>() where T : class
{
if (Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull == null)
return null;
var parameters = Sitecore.Mvc.Presentation.RenderingContext.CurrentOrNull.Rendering[Sc.GlassHtml.Parameters];
return
GlassHtml.GetRenderingParameters<T>(parameters);
}
}
}
| |
using UnityEngine;
using Pathfinding.Serialization;
namespace Pathfinding {
public class PointNode : GraphNode {
public GraphNode[] connections;
public uint[] connectionCosts;
/** GameObject this node was created from (if any).
* \warning When loading a graph from a saved file or from cache, this field will be null.
*/
public GameObject gameObject;
/** Used for internal linked list structure.
* \warning Do not modify
*/
public PointNode next;
public void SetPosition (Int3 value) {
position = value;
}
public PointNode (AstarPath astar) : base (astar) {
}
public override void GetConnections (GraphNodeDelegate del) {
if (connections == null) return;
for (int i=0;i<connections.Length;i++) del (connections[i]);
}
public override void ClearConnections (bool alsoReverse) {
if (alsoReverse && connections != null) {
for (int i=0;i<connections.Length;i++) {
connections[i].RemoveConnection (this);
}
}
connections = null;
connectionCosts = null;
}
public override void UpdateRecursiveG (Path path, PathNode pathNode, PathHandler handler) {
UpdateG (path,pathNode);
handler.PushNode (pathNode);
for (int i=0;i<connections.Length;i++) {
GraphNode other = connections[i];
PathNode otherPN = handler.GetPathNode (other);
if (otherPN.parent == pathNode && otherPN.pathID == handler.PathID) {
other.UpdateRecursiveG (path, otherPN,handler);
}
}
}
public override bool ContainsConnection (GraphNode node) {
for (int i=0;i<connections.Length;i++) if (connections[i] == node) return true;
return false;
}
/** Add a connection from this node to the specified node.
* If the connection already exists, the cost will simply be updated and
* no extra connection added.
*
* \note Only adds a one-way connection. Consider calling the same function on the other node
* to get a two-way connection.
*/
public override void AddConnection (GraphNode node, uint cost) {
if (connections != null) {
for (int i=0;i<connections.Length;i++) {
if (connections[i] == node) {
connectionCosts[i] = cost;
return;
}
}
}
int connLength = connections != null ? connections.Length : 0;
var newconns = new GraphNode[connLength+1];
var newconncosts = new uint[connLength+1];
for (int i=0;i<connLength;i++) {
newconns[i] = connections[i];
newconncosts[i] = connectionCosts[i];
}
newconns[connLength] = node;
newconncosts[connLength] = cost;
connections = newconns;
connectionCosts = newconncosts;
}
/** Removes any connection from this node to the specified node.
* If no such connection exists, nothing will be done.
*
* \note This only removes the connection from this node to the other node.
* You may want to call the same function on the other node to remove its eventual connection
* to this node.
*/
public override void RemoveConnection (GraphNode node) {
if (connections == null) return;
for (int i=0;i<connections.Length;i++) {
if (connections[i] == node) {
int connLength = connections.Length;
var newconns = new GraphNode[connLength-1];
var newconncosts = new uint[connLength-1];
for (int j=0;j<i;j++) {
newconns[j] = connections[j];
newconncosts[j] = connectionCosts[j];
}
for (int j=i+1;j<connLength;j++) {
newconns[j-1] = connections[j];
newconncosts[j-1] = connectionCosts[j];
}
connections = newconns;
connectionCosts = newconncosts;
return;
}
}
}
public override void Open (Path path, PathNode pathNode, PathHandler handler) {
if (connections == null) return;
for (int i=0;i<connections.Length;i++) {
GraphNode other = connections[i];
if (path.CanTraverse (other)) {
PathNode pathOther = handler.GetPathNode (other);
if (pathOther.pathID != handler.PathID) {
pathOther.parent = pathNode;
pathOther.pathID = handler.PathID;
pathOther.cost = connectionCosts[i];
pathOther.H = path.CalculateHScore (other);
other.UpdateG (path, pathOther);
handler.PushNode (pathOther);
} else {
//If not we can test if the path from this node to the other one is a better one then the one already used
uint tmpCost = connectionCosts[i];
if (pathNode.G + tmpCost + path.GetTraversalCost(other) < pathOther.G) {
pathOther.cost = tmpCost;
pathOther.parent = pathNode;
other.UpdateRecursiveG (path, pathOther,handler);
}
else if (pathOther.G+tmpCost+path.GetTraversalCost(this) < pathNode.G && other.ContainsConnection (this)) {
//Or if the path from the other node to this one is better
pathNode.parent = pathOther;
pathNode.cost = tmpCost;
UpdateRecursiveG (path, pathNode,handler);
}
}
}
}
}
public override void SerializeNode (GraphSerializationContext ctx) {
base.SerializeNode (ctx);
ctx.writer.Write (position.x);
ctx.writer.Write (position.y);
ctx.writer.Write (position.z);
}
public override void DeserializeNode (GraphSerializationContext ctx) {
base.DeserializeNode (ctx);
position = new Int3 (ctx.reader.ReadInt32(), ctx.reader.ReadInt32(), ctx.reader.ReadInt32());
}
public override void SerializeReferences (GraphSerializationContext ctx) {
if (connections == null) {
ctx.writer.Write(-1);
} else {
ctx.writer.Write (connections.Length);
for (int i=0;i<connections.Length;i++) {
ctx.writer.Write (ctx.GetNodeIdentifier (connections[i]));
ctx.writer.Write (connectionCosts[i]);
}
}
}
public override void DeserializeReferences (GraphSerializationContext ctx) {
int count = ctx.reader.ReadInt32();
if (count == -1) {
connections = null;
connectionCosts = null;
} else {
connections = new GraphNode[count];
connectionCosts = new uint[count];
for (int i=0;i<count;i++) {
connections[i] = ctx.GetNodeFromIdentifier (ctx.reader.ReadInt32());
connectionCosts[i] = ctx.reader.ReadUInt32();
}
}
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="DetectedPlaneVisualizer.cs" company="Google LLC">
//
// Copyright 2017 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// </copyright>
//-----------------------------------------------------------------------
namespace GoogleARCore.Examples.Common
{
using System.Collections.Generic;
using GoogleARCore;
using UnityEngine;
/// <summary>
/// Visualizes a single DetectedPlane in the Unity scene.
/// </summary>
public class DetectedPlaneVisualizer : MonoBehaviour
{
private DetectedPlane m_DetectedPlane;
// Keep previous frame's mesh polygon to avoid mesh update every frame.
private List<Vector3> m_PreviousFrameMeshVertices = new List<Vector3>();
private List<Vector3> m_MeshVertices = new List<Vector3>();
private Vector3 m_PlaneCenter = new Vector3();
private List<Color> m_MeshColors = new List<Color>();
private List<int> m_MeshIndices = new List<int>();
private Mesh m_Mesh;
private MeshRenderer m_MeshRenderer;
/// <summary>
/// The Unity Awake() method.
/// </summary>
public void Awake()
{
m_Mesh = GetComponent<MeshFilter>().mesh;
m_MeshRenderer = GetComponent<UnityEngine.MeshRenderer>();
}
/// <summary>
/// The Unity Update() method.
/// </summary>
public void Update()
{
if (m_DetectedPlane == null)
{
return;
}
else if (m_DetectedPlane.SubsumedBy != null)
{
Destroy(gameObject);
return;
}
else if (m_DetectedPlane.TrackingState != TrackingState.Tracking)
{
m_MeshRenderer.enabled = false;
return;
}
m_MeshRenderer.enabled = true;
_UpdateMeshIfNeeded();
}
/// <summary>
/// Initializes the DetectedPlaneVisualizer with a DetectedPlane.
/// </summary>
/// <param name="plane">The plane to vizualize.</param>
public void Initialize(DetectedPlane plane)
{
m_DetectedPlane = plane;
m_MeshRenderer.material.SetColor("_GridColor", Color.white);
m_MeshRenderer.material.SetFloat("_UvRotation", Random.Range(0.0f, 360.0f));
Update();
}
/// <summary>
/// Update mesh with a list of Vector3 and plane's center position.
/// </summary>
private void _UpdateMeshIfNeeded()
{
m_DetectedPlane.GetBoundaryPolygon(m_MeshVertices);
if (_AreVerticesListsEqual(m_PreviousFrameMeshVertices, m_MeshVertices))
{
return;
}
m_PreviousFrameMeshVertices.Clear();
m_PreviousFrameMeshVertices.AddRange(m_MeshVertices);
m_PlaneCenter = m_DetectedPlane.CenterPose.position;
Vector3 planeNormal = m_DetectedPlane.CenterPose.rotation * Vector3.up;
m_MeshRenderer.material.SetVector("_PlaneNormal", planeNormal);
int planePolygonCount = m_MeshVertices.Count;
// The following code converts a polygon to a mesh with two polygons, inner polygon
// renders with 100% opacity and fade out to outter polygon with opacity 0%, as shown
// below. The indices shown in the diagram are used in comments below.
// _______________ 0_______________1
// | | |4___________5|
// | | | | | |
// | | => | | | |
// | | | | | |
// | | |7-----------6|
// --------------- 3---------------2
m_MeshColors.Clear();
// Fill transparent color to vertices 0 to 3.
for (int i = 0; i < planePolygonCount; ++i)
{
m_MeshColors.Add(Color.clear);
}
// Feather distance 0.2 meters.
const float featherLength = 0.2f;
// Feather scale over the distance between plane center and vertices.
const float featherScale = 0.2f;
// Add vertex 4 to 7.
for (int i = 0; i < planePolygonCount; ++i)
{
Vector3 v = m_MeshVertices[i];
// Vector from plane center to current point
Vector3 d = v - m_PlaneCenter;
float scale = 1.0f - Mathf.Min(featherLength / d.magnitude, featherScale);
m_MeshVertices.Add((scale * d) + m_PlaneCenter);
m_MeshColors.Add(Color.white);
}
m_MeshIndices.Clear();
int firstOuterVertex = 0;
int firstInnerVertex = planePolygonCount;
// Generate triangle (4, 5, 6) and (4, 6, 7).
for (int i = 0; i < planePolygonCount - 2; ++i)
{
m_MeshIndices.Add(firstInnerVertex);
m_MeshIndices.Add(firstInnerVertex + i + 1);
m_MeshIndices.Add(firstInnerVertex + i + 2);
}
// Generate triangle (0, 1, 4), (4, 1, 5), (5, 1, 2), (5, 2, 6), (6, 2, 3), (6, 3, 7)
// (7, 3, 0), (7, 0, 4)
for (int i = 0; i < planePolygonCount; ++i)
{
int outerVertex1 = firstOuterVertex + i;
int outerVertex2 = firstOuterVertex + ((i + 1) % planePolygonCount);
int innerVertex1 = firstInnerVertex + i;
int innerVertex2 = firstInnerVertex + ((i + 1) % planePolygonCount);
m_MeshIndices.Add(outerVertex1);
m_MeshIndices.Add(outerVertex2);
m_MeshIndices.Add(innerVertex1);
m_MeshIndices.Add(innerVertex1);
m_MeshIndices.Add(outerVertex2);
m_MeshIndices.Add(innerVertex2);
}
m_Mesh.Clear();
m_Mesh.SetVertices(m_MeshVertices);
m_Mesh.SetTriangles(m_MeshIndices, 0);
m_Mesh.SetColors(m_MeshColors);
}
private bool _AreVerticesListsEqual(List<Vector3> firstList, List<Vector3> secondList)
{
if (firstList.Count != secondList.Count)
{
return false;
}
for (int i = 0; i < firstList.Count; i++)
{
if (firstList[i] != secondList[i])
{
return false;
}
}
return true;
}
}
}
| |
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
namespace System
{
using Reflection;
public static class TypeExtensions
{
/// <summary>
/// Used for checking if a class implements an interface
/// </summary>
/// <typeparam name="T">Interface</typeparam>
/// <param name="type">Class Implementing the interface</param>
/// <returns></returns>
public static bool Implements<T>(this Type type)
{
type.MustNotBeNull();
return type.Implements(typeof (T));
}
/// <summary>
/// Creates a new instance of type using a public parameterless constructor
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static object CreateInstance(this Type type)
{
type.MustNotBeNull();
return Activator.CreateInstance(type);
}
/// <summary>
/// Used for checking if a class implements an interface
/// </summary>
/// <param name="type">Class Implementing the interface</param>
/// <param name="interfaceType">Type of an interface</param>
/// <returns></returns>
public static bool Implements(this Type type,Type interfaceType)
{
type.MustNotBeNull();
interfaceType.MustNotBeNull();
if (!interfaceType.IsInterface) throw new ArgumentException("The generic type '{0}' is not an interface".ToFormat(interfaceType));
return interfaceType.IsAssignableFrom(type);
}
/// <summary>
/// True if the type implements of extends T
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="type"></param>
/// <returns></returns>
public static bool DerivesFrom<T>(this Type type)
{
return type.DerivesFrom(typeof (T));
}
/// <summary>
/// True if the type implements of extends parent.
/// Doesn't work with generics
/// </summary>
/// <param name="type"></param>
/// <param name="parent"></param>
/// <returns></returns>
public static bool DerivesFrom(this Type type, Type parent)
{
type.MustNotBeNull();
parent.MustNotBeNull();
return parent.IsAssignableFrom(type);
}
public static bool CheckIfAnonymousType(this Type type)
{
if (type == null)
throw new ArgumentNullException("type");
return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
&& type.IsGenericType && type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))
&& (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
}
/// <summary>
///
/// </summary>
/// <param name="o"></param>
/// <param name="interfaceName">The intuitive interface name</param>
/// <param name="genericType">Interface's generic arguments types</param>
/// <returns></returns>
public static bool ImplementsGenericInterface(this object o, string interfaceName, params Type[] genericType)
{
Type tp = o.GetType();
if (o is Type)
{
tp = (Type)o;
}
var interfaces = tp.GetInterfaces().Where(i => i.IsGenericType && i.Name.StartsWith(interfaceName));
if (genericType.Length == 0)
{
return interfaces.Any();
}
return interfaces.Any(
i =>
{
var args = i.GetGenericArguments();
return args.HasTheSameElementsAs(genericType);
});
}
public static bool ExtendsGenericType(this Type tp, string typeName, params Type[] genericArgs)
{
tp.MustNotBeNull();
typeName.MustNotBeEmpty();
if (tp.BaseType == null) return false;
var baseType = tp.BaseType;
if (!baseType.IsGenericType || !baseType.Name.StartsWith(typeName)) return false;
if (genericArgs.Length > 0)
{
return baseType.GetGenericArguments().HasTheSameElementsAs(genericArgs);
}
return true;
}
/// <summary>
///
/// </summary>
/// <param name="tp">Generic type</param>
/// <param name="index">0 based index of the generic argument</param>
/// <exception cref="InvalidOperationException">When the type is not generic</exception>
/// <exception cref="ArgumentNullException"></exception>
/// <exception cref="ArgumentException"></exception>
/// <returns></returns>
public static Type GetGenericArgument(this Type tp, int index = 0)
{
tp.MustNotBeNull();
if (!tp.IsGenericType) throw new InvalidOperationException("Provided type is not generic");
var all=tp.GetGenericArguments();
if (index >= all.Length)
{
throw new ArgumentException("There is no generic argument at the specified index","index");
}
return all[index];
}
/// <summary>
/// Checks if type is a reference but also not
/// a string, array, Nullable, enum
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool IsUserDefinedClass(this Type type)
{
type.MustNotBeNull();
if (!type.IsClass) return false;
if (Type.GetTypeCode(type) != TypeCode.Object) return false;
if (type.IsArray) return false;
if (type.IsNullable()) return false;
return true;
}
/// <summary>
/// This always returns false if the type is taken from an instance.
/// That is always use typeof
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static bool IsNullable(this Type type)
{
type.MustNotBeNull();
return (type.IsGenericType && type.GetGenericTypeDefinition() == typeof (Nullable<>));
}
public static bool IsNullableOf(this Type type, Type other)
{
type.MustNotBeNull();
other.MustNotBeNull();
return type.IsNullable() && type.GetGenericArguments()[0].Equals(other);
}
public static bool IsNullableOf<T>(this Type type)
{
return type.IsNullableOf(typeof (T));
}
public static bool CanBeCastTo<T>(this Type type)
{
if (type == null) return false;
return CanBeCastTo(type, typeof(T));
}
public static bool CanBeCastTo(this Type type, Type other)
{
if (type == null) return false;
if (type == other) return true;
return other.IsAssignableFrom(type);
}
/// <summary>
/// Returns the version of assembly containing type
/// </summary>
/// <returns></returns>
public static Version AssemblyVersion(this Type tp)
{
return Assembly.GetAssembly(tp).Version();
}
/// <summary>
/// Returns the full name of type, including assembly but not version, public key etc, i.e: namespace.type, assembly
/// </summary>
/// <param name="t">Type</param>
/// <returns></returns>
public static string GetFullTypeName(this Type t)
{
if (t == null) throw new ArgumentNullException("t");
return String.Format("{0}, {1}", t.FullName, Assembly.GetAssembly(t).GetName().Name);
}
public static object GetDefault(this Type type)
{
if (type.IsValueType) return Activator.CreateInstance(type);
return null;
}
/// <summary>
/// Returns namespace without the assembly name
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
public static string StripNamespaceAssemblyName(this Type type)
{
var asmName = type.Assembly.GetName().Name;
return type.Namespace.Substring(asmName.Length + 1);
}
}
}
| |
using System;
using System.Runtime.CompilerServices;
using System.Text;
namespace Orleans.Serialization.WireProtocol
{
/// <summary>
/// Represents a field header.
/// </summary>
public struct Field
{
/// <summary>
/// The tag byte.
/// </summary>
public Tag Tag;
/// <summary>
/// The raw field identifier delta.
/// </summary>
public uint FieldIdDeltaRaw;
/// <summary>
/// The raw field type.
/// </summary>
public Type FieldTypeRaw;
/// <summary>
/// Initializes a new instance of the <see cref="Field"/> struct.
/// </summary>
/// <param name="tag">The tag.</param>
public Field(Tag tag)
{
Tag = tag;
FieldIdDeltaRaw = 0;
FieldTypeRaw = null;
}
/// <summary>
/// Initializes a new instance of the <see cref="Field"/> struct.
/// </summary>
/// <param name="tag">The tag.</param>
/// <param name="extendedFieldIdDelta">The extended field identifier delta.</param>
/// <param name="type">The type.</param>
public Field(Tag tag, uint extendedFieldIdDelta, Type type)
{
Tag = tag;
FieldIdDeltaRaw = extendedFieldIdDelta;
FieldTypeRaw = type;
}
/// <summary>
/// Gets or sets the field identifier delta.
/// </summary>
/// <value>The field identifier delta.</value>
public uint FieldIdDelta
{
// If the embedded field id delta is valid, return it, otherwise return the extended field id delta.
// The extended field id might not be valid if this field has the Extended wire type.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
if (Tag.IsFieldIdValid)
{
return Tag.FieldIdDelta;
}
#if DEBUG
if (!HasFieldId)
{
ThrowFieldIdInvalid();
}
#endif
return FieldIdDeltaRaw;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
// If the field id delta can fit into the tag, embed it there, otherwise invalidate the embedded field id delta and set the full field id delta.
if (value < 7)
{
Tag.FieldIdDelta = value;
FieldIdDeltaRaw = 0;
}
else
{
Tag.SetFieldIdInvalid();
FieldIdDeltaRaw = value;
}
}
}
/// <summary>
/// Gets or sets the type of the field.
/// </summary>
/// <value>The type of the field.</value>
public Type FieldType
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
#if DEBUG
if (!IsSchemaTypeValid)
{
ThrowFieldTypeInvalid();
}
#endif
return FieldTypeRaw;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
set
{
#if DEBUG
if (!IsSchemaTypeValid)
{
ThrowFieldTypeInvalid();
}
#endif
FieldTypeRaw = value;
}
}
/// <summary>
/// Gets a value indicating whether this instance has a field identifier.
/// </summary>
/// <value><see langword="true" /> if this instance has a field identifier; otherwise, <see langword="false" />.</value>
public bool HasFieldId
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Tag.WireType != WireType.Extended;
}
/// <summary>
/// Gets a value indicating whether this instance has an extended field identifier.
/// </summary>
/// <value><see langword="true" /> if this instance has an extended field identifier; otherwise, <see langword="false" />.</value>
public bool HasExtendedFieldId
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Tag.HasExtendedFieldId;
}
/// <summary>
/// Gets or sets the wire type.
/// </summary>
/// <value>The wire type.</value>
public WireType WireType
{
get => Tag.WireType;
set => Tag.WireType = value;
}
/// <summary>
/// Gets or sets the schema type.
/// </summary>
/// <value>The schema type.</value>
public SchemaType SchemaType
{
get
{
#if DEBUG
if (!IsSchemaTypeValid)
{
ThrowSchemaTypeInvalid();
}
#endif
return Tag.SchemaType;
}
set => Tag.SchemaType = value;
}
/// <summary>
/// Gets or sets the extended wire type.
/// </summary>
/// <value>The extended wire type.</value>
public ExtendedWireType ExtendedWireType
{
get
{
#if DEBUG
if (WireType != WireType.Extended)
{
ThrowExtendedWireTypeInvalid();
}
#endif
return Tag.ExtendedWireType;
}
set => Tag.ExtendedWireType = value;
}
/// <summary>
/// Gets a value indicating whether this instance has a valid schema type.
/// </summary>
/// <value><see langword="true" /> if this instance has a valid schema; otherwise, <see langword="false" />.</value>
public bool IsSchemaTypeValid => Tag.IsSchemaTypeValid;
/// <summary>
/// Gets a value indicating whether this instance has an extended schema type.
/// </summary>
/// <value><see langword="true" /> if this instance has an extended schema type; otherwise, <see langword="false" />.</value>
public bool HasExtendedSchemaType => IsSchemaTypeValid && SchemaType != SchemaType.Expected;
/// <summary>
/// Gets a value indicating whether this instance represents the end of base fields in a tag-delimited structure.
/// </summary>
/// <value><see langword="true" /> if this instance represents end of base fields in a tag-delimited structure; otherwise, <see langword="false" />.</value>
public bool IsEndBaseFields => Tag.HasExtendedWireType && Tag.ExtendedWireType == ExtendedWireType.EndBaseFields;
/// <summary>
/// Gets a value indicating whether this instance represents the end of a tag-delimited structure.
/// </summary>
/// <value><see langword="true" /> if this instance represents end of a tag-delimited structure; otherwise, <see langword="false" />.</value>
public bool IsEndObject => Tag.HasExtendedWireType && Tag.ExtendedWireType == ExtendedWireType.EndTagDelimited;
/// <summary>
/// Gets a value indicating whether this instance represents the end of a tag-delimited structure or the end of base fields in a tag-delimited structure.
/// </summary>
/// <value><see langword="true" /> if this instance represents the end of a tag-delimited structure or the end of base fields in a tag-delimited structure; otherwise, <see langword="false" />.</value>
public bool IsEndBaseOrEndObject
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => Tag.HasExtendedWireType &&
(Tag.ExtendedWireType == ExtendedWireType.EndTagDelimited ||
Tag.ExtendedWireType == ExtendedWireType.EndBaseFields);
}
/// <inheritdoc/>
public override string ToString()
{
var builder = new StringBuilder();
_ = builder.Append('[').Append((string)WireType.ToString());
if (HasFieldId)
{
_ = builder.Append($", IdDelta:{FieldIdDelta}");
}
if (IsSchemaTypeValid)
{
_ = builder.Append($", SchemaType:{SchemaType}");
}
if (HasExtendedSchemaType)
{
_ = builder.Append($", RuntimeType:{FieldType}");
}
if (WireType == WireType.Extended)
{
_ = builder.Append($": {ExtendedWireType}");
}
_ = builder.Append(']');
return builder.ToString();
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowFieldIdInvalid() => throw new FieldIdNotPresentException();
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowSchemaTypeInvalid() => throw new SchemaTypeInvalidException();
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowFieldTypeInvalid() => throw new FieldTypeInvalidException();
[MethodImpl(MethodImplOptions.NoInlining)]
private static void ThrowExtendedWireTypeInvalid() => throw new ExtendedWireTypeInvalidException();
}
}
| |
/*
* Copyright (c) 2006-2016, openmetaverse.co
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.co nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
namespace OpenMetaverse.Voice
{
public partial class VoiceGateway
{
#region Enums
public enum LoginState
{
LoggedOut = 0,
LoggedIn = 1,
Error = 4
}
public enum SessionState
{
Idle = 1,
Answering = 2,
InProgress = 3,
Connected = 4,
Disconnected = 5,
Hold = 6,
Refer = 7,
Ringing = 8
}
public enum ParticipantState
{
Idle = 1,
Pending = 2,
Incoming = 3,
Answering = 4,
InProgress = 5,
Ringing = 6,
Connected = 7,
Disconnecting = 8,
Disconnected = 9
}
public enum ParticipantType
{
User = 0,
Moderator = 1,
Focus = 2
}
public enum ResponseType
{
None = 0,
ConnectorCreate,
ConnectorInitiateShutdown,
MuteLocalMic,
MuteLocalSpeaker,
SetLocalMicVolume,
SetLocalSpeakerVolume,
GetCaptureDevices,
GetRenderDevices,
SetRenderDevice,
SetCaptureDevice,
CaptureAudioStart,
CaptureAudioStop,
SetMicLevel,
SetSpeakerLevel,
AccountLogin,
AccountLogout,
RenderAudioStart,
RenderAudioStop,
SessionCreate,
SessionConnect,
SessionTerminate,
SetParticipantVolumeForMe,
SetParticipantMuteForMe,
Set3DPosition
}
#endregion Enums
#region Logging
public class VoiceLoggingSettings
{
/// <summary>Enable logging</summary>
public bool Enabled;
/// <summary>The folder where any logs will be created</summary>
public string Folder;
/// <summary>This will be prepended to beginning of each log file</summary>
public string FileNamePrefix;
/// <summary>The suffix or extension to be appended to each log file</summary>
public string FileNameSuffix;
/// <summary>
/// 0: NONE - No logging
/// 1: ERROR - Log errors only
/// 2: WARNING - Log errors and warnings
/// 3: INFO - Log errors, warnings and info
/// 4: DEBUG - Log errors, warnings, info and debug
/// </summary>
public int LogLevel;
/// <summary>
/// Constructor for default logging settings
/// </summary>
public VoiceLoggingSettings()
{
Enabled = false;
Folder = String.Empty;
FileNamePrefix = "Connector";
FileNameSuffix = ".log";
LogLevel = 0;
}
}
#endregion Logging
public class VoiceResponseEventArgs : EventArgs
{
public readonly ResponseType Type;
public readonly int ReturnCode;
public readonly int StatusCode;
public readonly string Message;
// All Voice Response events carry these properties.
public VoiceResponseEventArgs(ResponseType type, int rcode, int scode, string text)
{
this.Type = type;
this.ReturnCode = rcode;
this.StatusCode = scode;
this.Message = text;
}
}
#region Session Event Args
public class VoiceSessionEventArgs : VoiceResponseEventArgs
{
public readonly string SessionHandle;
public VoiceSessionEventArgs(int rcode, int scode, string text, string shandle) :
base(ResponseType.SessionCreate, rcode, scode, text)
{
this.SessionHandle = shandle;
}
}
public class NewSessionEventArgs : EventArgs
{
public readonly string AccountHandle;
public readonly string SessionHandle;
public readonly string URI;
public readonly string Name;
public readonly string AudioMedia;
public NewSessionEventArgs(string AccountHandle, string SessionHandle, string URI, bool IsChannel, string Name, string AudioMedia)
{
this.AccountHandle = AccountHandle;
this.SessionHandle = SessionHandle;
this.URI = URI;
this.Name = Name;
this.AudioMedia = AudioMedia;
}
}
public class SessionMediaEventArgs : EventArgs
{
public readonly string SessionHandle;
public readonly bool HasText;
public readonly bool HasAudio;
public readonly bool HasVideo;
public readonly bool Terminated;
public SessionMediaEventArgs(string SessionHandle, bool HasText, bool HasAudio, bool HasVideo, bool Terminated)
{
this.SessionHandle = SessionHandle;
this.HasText = HasText;
this.HasAudio = HasAudio;
this.HasVideo = HasVideo;
this.Terminated = Terminated;
}
}
public class SessionStateChangeEventArgs : EventArgs
{
public readonly string SessionHandle;
public readonly int StatusCode;
public readonly string StatusString;
public readonly SessionState State;
public readonly string URI;
public readonly bool IsChannel;
public readonly string ChannelName;
public SessionStateChangeEventArgs(string SessionHandle, int StatusCode, string StatusString, SessionState State, string URI, bool IsChannel, string ChannelName)
{
this.SessionHandle = SessionHandle;
this.StatusCode = StatusCode;
this.StatusString = StatusString;
this.State = State;
this.URI = URI;
this.IsChannel = IsChannel;
this.ChannelName = ChannelName;
}
}
// Participants
public class ParticipantAddedEventArgs : EventArgs
{
public readonly string SessionHandle;
public readonly string SessionGroupHandle;
public readonly string URI;
public readonly string AccountName;
public readonly string DisplayName;
public readonly ParticipantType Type;
public readonly string Appllication;
public ParticipantAddedEventArgs(
string SessionGroupHandle,
string SessionHandle,
string ParticipantUri,
string AccountName,
string DisplayName,
ParticipantType type,
string Application)
{
this.SessionGroupHandle = SessionGroupHandle;
this.SessionHandle = SessionHandle;
this.URI = ParticipantUri;
this.AccountName = AccountName;
this.DisplayName = DisplayName;
this.Type = type;
this.Appllication = Application;
}
}
public class ParticipantRemovedEventArgs : EventArgs
{
public readonly string SessionGroupHandle;
public readonly string SessionHandle;
public readonly string URI;
public readonly string AccountName;
public readonly string Reason;
public ParticipantRemovedEventArgs(
string SessionGroupHandle,
string SessionHandle,
string ParticipantUri,
string AccountName,
string Reason)
{
this.SessionGroupHandle = SessionGroupHandle;
this.SessionHandle = SessionHandle;
this.URI = ParticipantUri;
this.AccountName = AccountName;
this.Reason = Reason;
}
}
public class ParticipantStateChangeEventArgs : EventArgs
{
public readonly string SessionHandle;
public readonly int StatusCode;
public readonly string StatusString;
public readonly ParticipantState State;
public readonly string URI;
public readonly string AccountName;
public readonly string DisplayName;
public readonly ParticipantType Type;
public ParticipantStateChangeEventArgs(string SessionHandle, int StatusCode, string StatusString,
ParticipantState State, string ParticipantURI, string AccountName,
string DisplayName, ParticipantType ParticipantType)
{
this.SessionHandle = SessionHandle;
this.StatusCode = StatusCode;
this.StatusString = StatusString;
this.State = State;
this.URI = ParticipantURI;
this.AccountName = AccountName;
this.DisplayName = DisplayName;
this.Type = ParticipantType;
}
}
public class ParticipantPropertiesEventArgs : EventArgs
{
public readonly string SessionHandle;
public readonly string URI;
public readonly bool IsLocallyMuted;
public readonly bool IsModeratorMuted;
public readonly bool IsSpeaking;
public readonly int Volume;
public readonly float Energy;
public ParticipantPropertiesEventArgs(string SessionHandle, string ParticipantURI,
bool IsLocallyMuted, bool IsModeratorMuted, bool IsSpeaking, int Volume, float Energy)
{
this.SessionHandle = SessionHandle;
this.URI = ParticipantURI;
this.IsLocallyMuted = IsLocallyMuted;
this.IsModeratorMuted = IsModeratorMuted;
this.IsSpeaking = IsSpeaking;
this.Volume = Volume;
this.Energy = Energy;
}
}
public class ParticipantUpdatedEventArgs : EventArgs
{
public readonly string SessionHandle;
public readonly string URI;
public readonly bool IsMuted;
public readonly bool IsSpeaking;
public readonly int Volume;
public readonly float Energy;
public ParticipantUpdatedEventArgs(string sessionHandle, string URI, bool isMuted, bool isSpeaking, int volume, float energy)
{
this.SessionHandle = sessionHandle;
this.URI = URI;
this.IsMuted = isMuted;
this.IsSpeaking = isSpeaking;
this.Volume = volume;
this.Energy = energy;
}
}
public class SessionAddedEventArgs : EventArgs
{
public readonly string SessionGroupHandle;
public readonly string SessionHandle;
public readonly string URI;
public readonly bool IsChannel;
public readonly bool IsIncoming;
public SessionAddedEventArgs(string sessionGroupHandle, string sessionHandle,
string URI, bool isChannel, bool isIncoming)
{
this.SessionGroupHandle = sessionGroupHandle;
this.SessionHandle = sessionHandle;
this.URI = URI;
this.IsChannel = isChannel;
this.IsIncoming = isIncoming;
}
}
public class SessionRemovedEventArgs : EventArgs
{
public readonly string SessionGroupHandle;
public readonly string SessionHandle;
public readonly string URI;
public SessionRemovedEventArgs(
string SessionGroupHandle,
string SessionHandle,
string Uri)
{
this.SessionGroupHandle = SessionGroupHandle;
this.SessionHandle = SessionHandle;
this.URI = Uri;
}
}
public class SessionUpdatedEventArgs : EventArgs
{
public readonly string SessionGroupHandle;
public readonly string SessionHandle;
public readonly string URI;
public readonly bool IsMuted;
public readonly int Volume;
public readonly bool TransmitEnabled;
public readonly bool IsFocused;
public SessionUpdatedEventArgs(string SessionGroupHandle,
string SessionHandle, string URI, bool IsMuted, int Volume,
bool TransmitEnabled, bool IsFocused)
{
this.SessionGroupHandle = SessionGroupHandle;
this.SessionHandle = SessionHandle;
this.URI = URI;
this.IsMuted = IsMuted;
this.Volume = Volume;
this.TransmitEnabled = TransmitEnabled;
this.IsFocused = IsFocused;
}
}
public class SessionGroupAddedEventArgs : EventArgs
{
public readonly string AccountHandle;
public readonly string SessionGroupHandle;
public readonly string Type;
public SessionGroupAddedEventArgs(string acctHandle, string sessionGroupHandle, string type)
{
this.AccountHandle = acctHandle;
this.SessionGroupHandle = sessionGroupHandle;
this.Type = type;
}
}
#endregion Session Event Args
#region Connector Delegates
public class VoiceConnectorEventArgs : VoiceResponseEventArgs
{
private readonly string m_Version;
private readonly string m_ConnectorHandle;
public string Version { get { return m_Version; } }
public string Handle { get { return m_ConnectorHandle; } }
public VoiceConnectorEventArgs(int rcode, int scode, string text, string version, string handle) :
base(ResponseType.ConnectorCreate, rcode, scode, text)
{
m_Version = version;
m_ConnectorHandle = handle;
}
}
#endregion Connector Delegates
#region Aux Event Args
public class VoiceDevicesEventArgs : VoiceResponseEventArgs
{
private readonly string m_CurrentDevice;
private readonly List<string> m_Available;
public string CurrentDevice { get { return m_CurrentDevice; } }
public List<string> Devices { get { return m_Available; } }
public VoiceDevicesEventArgs(ResponseType type, int rcode, int scode, string text, string current, List<string> avail) :
base(type, rcode, scode, text)
{
m_CurrentDevice = current;
m_Available = avail;
}
}
/// Audio Properties Events are sent after audio capture is started. These events are used to display a microphone VU meter
public class AudioPropertiesEventArgs : EventArgs
{
public readonly bool IsMicActive;
public readonly float MicEnergy;
public readonly int MicVolume;
public readonly int SpeakerVolume;
public AudioPropertiesEventArgs(bool MicIsActive, float MicEnergy, int MicVolume, int SpeakerVolume)
{
this.IsMicActive = MicIsActive;
this.MicEnergy = MicEnergy;
this.MicVolume = MicVolume;
this.SpeakerVolume = SpeakerVolume;
}
}
#endregion Aux Event Args
#region Account Event Args
public class VoiceAccountEventArgs : VoiceResponseEventArgs
{
private readonly string m_AccountHandle;
public string AccountHandle { get { return m_AccountHandle; } }
public VoiceAccountEventArgs(int rcode, int scode, string text, string ahandle) :
base(ResponseType.AccountLogin, rcode, scode, text)
{
this.m_AccountHandle = ahandle;
}
}
public class AccountLoginStateChangeEventArgs : EventArgs
{
public readonly string AccountHandle;
public readonly int StatusCode;
public readonly string StatusString;
public readonly LoginState State;
public AccountLoginStateChangeEventArgs(string AccountHandle, int StatusCode, string StatusString, LoginState State)
{
this.AccountHandle = AccountHandle;
this.StatusCode = StatusCode;
this.StatusString = StatusString;
this.State = State;
}
}
#endregion Account Event Args
/// <summary>
/// Event for most mundane request reposnses.
/// </summary>
public event EventHandler<VoiceResponseEventArgs> OnVoiceResponse;
#region Session Events
public event EventHandler<VoiceSessionEventArgs> OnSessionCreateResponse;
public event EventHandler<NewSessionEventArgs> OnSessionNewEvent;
public event EventHandler<SessionStateChangeEventArgs> OnSessionStateChangeEvent;
public event EventHandler<ParticipantStateChangeEventArgs> OnSessionParticipantStateChangeEvent;
public event EventHandler<ParticipantPropertiesEventArgs> OnSessionParticipantPropertiesEvent;
public event EventHandler<ParticipantUpdatedEventArgs> OnSessionParticipantUpdatedEvent;
public event EventHandler<ParticipantAddedEventArgs> OnSessionParticipantAddedEvent;
public event EventHandler<ParticipantRemovedEventArgs> OnSessionParticipantRemovedEvent;
public event EventHandler<SessionGroupAddedEventArgs> OnSessionGroupAddedEvent;
public event EventHandler<SessionAddedEventArgs> OnSessionAddedEvent;
public event EventHandler<SessionRemovedEventArgs> OnSessionRemovedEvent;
public event EventHandler<SessionUpdatedEventArgs> OnSessionUpdatedEvent;
public event EventHandler<SessionMediaEventArgs> OnSessionMediaEvent;
#endregion Session Events
#region Connector Events
/// <summary>Response to Connector.Create request</summary>
public event EventHandler<VoiceConnectorEventArgs> OnConnectorCreateResponse;
#endregion Connector Events
#region Aux Events
/// <summary>Response to Aux.GetCaptureDevices request</summary>
public event EventHandler<VoiceDevicesEventArgs> OnAuxGetCaptureDevicesResponse;
/// <summary>Response to Aux.GetRenderDevices request</summary>
public event EventHandler<VoiceDevicesEventArgs> OnAuxGetRenderDevicesResponse;
/// <summary>Audio Properties Events are sent after audio capture is started.
/// These events are used to display a microphone VU meter</summary>
public event EventHandler<AudioPropertiesEventArgs> OnAuxAudioPropertiesEvent;
#endregion Aux Events
#region Account Events
/// <summary>Response to Account.Login request</summary>
public event EventHandler<VoiceAccountEventArgs> OnAccountLoginResponse;
/// <summary>This event message is sent whenever the login state of the
/// particular Account has transitioned from one value to another</summary>
public event EventHandler<AccountLoginStateChangeEventArgs> OnAccountLoginStateChangeEvent;
#endregion Account Events
#region XML Serialization Classes
private XmlSerializer EventSerializer = new XmlSerializer(typeof(VoiceEvent));
private XmlSerializer ResponseSerializer = new XmlSerializer(typeof(VoiceResponse));
[XmlRoot("Event")]
public class VoiceEvent
{
[XmlAttribute("type")]
public string Type;
public string AccountHandle;
public string Application;
public string StatusCode;
public string StatusString;
public string State;
public string SessionHandle;
public string SessionGroupHandle;
public string URI;
public string Uri; // Yes, they send it with both capitalizations
public string IsChannel;
public string IsIncoming;
public string Incoming;
public string IsMuted;
public string Name;
public string AudioMedia;
public string ChannelName;
public string ParticipantUri;
public string AccountName;
public string DisplayName;
public string ParticipantType;
public string IsLocallyMuted;
public string IsModeratorMuted;
public string IsSpeaking;
public string Volume;
public string Energy;
public string MicIsActive;
public string MicEnergy;
public string MicVolume;
public string SpeakerVolume;
public string HasText;
public string HasAudio;
public string HasVideo;
public string Terminated;
public string Reason;
public string TransmitEnabled;
public string IsFocused;
}
[XmlRoot("Response")]
public class VoiceResponse
{
[XmlAttribute("requestId")]
public string RequestId;
[XmlAttribute("action")]
public string Action;
public string ReturnCode;
public VoiceResponseResults Results;
public VoiceInputXml InputXml;
}
public class CaptureDevice
{
public string Device;
}
public class RenderDevice
{
public string Device;
}
public class VoiceResponseResults
{
public string VersionID;
public string StatusCode;
public string StatusString;
public string ConnectorHandle;
public string AccountHandle;
public string SessionHandle;
public List<CaptureDevice> CaptureDevices;
public CaptureDevice CurrentCaptureDevice;
public List<RenderDevice> RenderDevices;
public RenderDevice CurrentRenderDevice;
}
public class VoiceInputXml
{
public VoiceRequest Request;
}
[XmlRoot("Request")]
public class VoiceRequest
{
[XmlAttribute("requestId")]
public string RequestId;
[XmlAttribute("action")]
public string Action;
public string RenderDeviceSpecifier;
public string CaptureDeviceSpecifier;
public string Duration;
public string Level;
public string ClientName;
public string AccountManagementServer;
public string MinimumPort;
public string MaximumPort;
public VoiceLoggingSettings Logging;
public string ConnectorHandle;
public string Value;
public string AccountName;
public string AccountPassword;
public string AudioSessionAnswerMode;
public string AccountURI;
public string ParticipantPropertyFrequency;
public string EnableBuddiesAndPresence;
public string URI;
public string Name;
public string Password;
public string JoinAudio;
public string JoinText;
public string PasswordHashAlgorithm;
public string SoundFilePath;
public string Loop;
public string SessionHandle;
public string OrientationType;
public VoicePosition SpeakerPosition;
public VoicePosition ListenerPosition;
public string ParticipantURI;
public string Volume;
}
#endregion XML Serialization Classes
}
public class VoicePosition
{
/// <summary>Positional vector of the users position</summary>
public Vector3d Position;
/// <summary>Velocity vector of the position</summary>
public Vector3d Velocity;
/// <summary>At Orientation (X axis) of the position</summary>
public Vector3d AtOrientation;
/// <summary>Up Orientation (Y axis) of the position</summary>
public Vector3d UpOrientation;
/// <summary>Left Orientation (Z axis) of the position</summary>
public Vector3d LeftOrientation;
}
}
| |
using System.Linq;
using Apache.NMS.Util;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace Lucene.Net.Analysis
{
/*
* 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 Lucene.Net.Analysis.Tokenattributes;
using Lucene.Net.Randomized.Generators;
using Lucene.Net.Support;
using System.Globalization;
using System.IO;
using Attribute = Lucene.Net.Util.Attribute;
using Directory = Lucene.Net.Store.Directory;
using Document = Documents.Document;
using Field = Field;
using FieldType = FieldType;
using IAttribute = Lucene.Net.Util.IAttribute;
using IOUtils = Lucene.Net.Util.IOUtils;
using LineFileDocs = Lucene.Net.Util.LineFileDocs;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using TestUtil = Lucene.Net.Util.TestUtil;
using TextField = TextField;
/// <summary>
/// base class for all Lucene unit tests that use TokenStreams.
/// <p>
/// When writing unit tests for analysis components, its highly recommended
/// to use the helper methods here (especially in conjunction with <seealso cref="MockAnalyzer"/> or
/// <seealso cref="MockTokenizer"/>), as they contain many assertions and checks to
/// catch bugs.
/// </summary>
/// <seealso cref= MockAnalyzer </seealso>
/// <seealso cref= MockTokenizer </seealso>
public abstract class BaseTokenStreamTestCase : LuceneTestCase
{
// some helpers to test Analyzers and TokenStreams:
/// <summary>
/// Attribute that records if it was cleared or not. this is used
/// for testing that ClearAttributes() was called correctly.
/// </summary>
public interface ICheckClearAttributesAttribute : IAttribute
{
bool AndResetClearCalled { get; }
}
/// <summary>
/// Attribute that records if it was cleared or not. this is used
/// for testing that ClearAttributes() was called correctly.
/// </summary>
public sealed class CheckClearAttributesAttribute : Attribute, ICheckClearAttributesAttribute
{
internal bool ClearCalled = false;
public bool AndResetClearCalled
{
get
{
bool old = ClearCalled;
ClearCalled = false;
return old;
}
}
public override void Clear()
{
ClearCalled = true;
}
public override bool Equals(object other)
{
return (other is CheckClearAttributesAttribute && ((CheckClearAttributesAttribute)other).ClearCalled == this.ClearCalled);
}
public override int GetHashCode()
{
return 76137213 ^ Convert.ToBoolean(ClearCalled).GetHashCode();
}
public override void CopyTo(Attribute target)
{
((CheckClearAttributesAttribute)target).Clear();
}
}
// offsetsAreCorrect also validates:
// - graph offsets are correct (all tokens leaving from
// pos X have the same startOffset; all tokens
// arriving to pos Y have the same endOffset)
// - offsets only move forwards (startOffset >=
// lastStartOffset)
public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int[] posLengths, int? finalOffset, int? finalPosInc, bool[] keywordAtts, bool offsetsAreCorrect)
{
Assert.IsNotNull(output);
var checkClearAtt = ts.AddAttribute<ICheckClearAttributesAttribute>();
ICharTermAttribute termAtt = null;
if (output.Length > 0)
{
Assert.IsTrue(ts.HasAttribute<ICharTermAttribute>(), "has no CharTermAttribute");
termAtt = ts.GetAttribute<ICharTermAttribute>();
}
IOffsetAttribute offsetAtt = null;
if (startOffsets != null || endOffsets != null || finalOffset != null)
{
Assert.IsTrue(ts.HasAttribute<IOffsetAttribute>(), "has no OffsetAttribute");
offsetAtt = ts.GetAttribute<IOffsetAttribute>();
}
ITypeAttribute typeAtt = null;
if (types != null)
{
Assert.IsTrue(ts.HasAttribute<ITypeAttribute>(), "has no TypeAttribute");
typeAtt = ts.GetAttribute<ITypeAttribute>();
}
IPositionIncrementAttribute posIncrAtt = null;
if (posIncrements != null || finalPosInc != null)
{
Assert.IsTrue(ts.HasAttribute<IPositionIncrementAttribute>(), "has no PositionIncrementAttribute");
posIncrAtt = ts.GetAttribute<IPositionIncrementAttribute>();
}
IPositionLengthAttribute posLengthAtt = null;
if (posLengths != null)
{
Assert.IsTrue(ts.HasAttribute<IPositionLengthAttribute>(), "has no PositionLengthAttribute");
posLengthAtt = ts.GetAttribute<IPositionLengthAttribute>();
}
IKeywordAttribute keywordAtt = null;
if (keywordAtts != null)
{
Assert.IsTrue(ts.HasAttribute<IKeywordAttribute>(), "has no KeywordAttribute");
keywordAtt = ts.GetAttribute<IKeywordAttribute>();
}
// Maps position to the start/end offset:
IDictionary<int?, int?> posToStartOffset = new Dictionary<int?, int?>();
IDictionary<int?, int?> posToEndOffset = new Dictionary<int?, int?>();
ts.Reset();
int pos = -1;
int lastStartOffset = 0;
for (int i = 0; i < output.Length; i++)
{
// extra safety to enforce, that the state is not preserved and also assign bogus values
ts.ClearAttributes();
termAtt.SetEmpty().Append("bogusTerm");
if (offsetAtt != null)
{
offsetAtt.SetOffset(14584724, 24683243);
}
if (typeAtt != null)
{
typeAtt.Type = "bogusType";
}
if (posIncrAtt != null)
{
posIncrAtt.PositionIncrement = 45987657;
}
if (posLengthAtt != null)
{
posLengthAtt.PositionLength = 45987653;
}
if (keywordAtt != null)
{
keywordAtt.Keyword = (i & 1) == 0;
}
bool reset = checkClearAtt.AndResetClearCalled; // reset it, because we called clearAttribute() before
Assert.IsTrue(ts.IncrementToken(), "token " + i + " does not exist");
Assert.IsTrue(reset, "ClearAttributes() was not called correctly in TokenStream chain");
Assert.AreEqual(output[i], termAtt.ToString(), "term " + i + ", output[i] = " + output[i] + ", termAtt = " + termAtt.ToString());
if (startOffsets != null)
{
Assert.AreEqual(startOffsets[i], offsetAtt.StartOffset(), "startOffset " + i);
}
if (endOffsets != null)
{
Assert.AreEqual(endOffsets[i], offsetAtt.EndOffset(), "endOffset " + i);
}
if (types != null)
{
Assert.AreEqual(types[i], typeAtt.Type, "type " + i);
}
if (posIncrements != null)
{
Assert.AreEqual(posIncrements[i], posIncrAtt.PositionIncrement, "posIncrement " + i);
}
if (posLengths != null)
{
Assert.AreEqual(posLengths[i], posLengthAtt.PositionLength, "posLength " + i);
}
if (keywordAtts != null)
{
Assert.AreEqual(keywordAtts[i], keywordAtt.Keyword, "keywordAtt " + i);
}
// we can enforce some basic things about a few attributes even if the caller doesn't check:
if (offsetAtt != null)
{
int startOffset = offsetAtt.StartOffset();
int endOffset = offsetAtt.EndOffset();
if (finalOffset != null)
{
Assert.IsTrue(startOffset <= (int)finalOffset, "startOffset must be <= finalOffset");
Assert.IsTrue(endOffset <= (int)finalOffset, "endOffset must be <= finalOffset: got endOffset=" + endOffset + " vs finalOffset=" + (int)finalOffset);
}
if (offsetsAreCorrect)
{
Assert.IsTrue(offsetAtt.StartOffset() >= lastStartOffset, "offsets must not go backwards startOffset=" + startOffset + " is < lastStartOffset=" + lastStartOffset);
lastStartOffset = offsetAtt.StartOffset();
}
if (offsetsAreCorrect && posLengthAtt != null && posIncrAtt != null)
{
// Validate offset consistency in the graph, ie
// all tokens leaving from a certain pos have the
// same startOffset, and all tokens arriving to a
// certain pos have the same endOffset:
int posInc = posIncrAtt.PositionIncrement;
pos += posInc;
int posLength = posLengthAtt.PositionLength;
if (!posToStartOffset.ContainsKey(pos))
{
// First time we've seen a token leaving from this position:
posToStartOffset[pos] = startOffset;
//System.out.println(" + s " + pos + " -> " + startOffset);
}
else
{
// We've seen a token leaving from this position
// before; verify the startOffset is the same:
//System.out.println(" + vs " + pos + " -> " + startOffset);
Assert.AreEqual((int)posToStartOffset[pos], startOffset, "pos=" + pos + " posLen=" + posLength + " token=" + termAtt);
}
int endPos = pos + posLength;
if (!posToEndOffset.ContainsKey(endPos))
{
// First time we've seen a token arriving to this position:
posToEndOffset[endPos] = endOffset;
//System.out.println(" + e " + endPos + " -> " + endOffset);
}
else
{
// We've seen a token arriving to this position
// before; verify the endOffset is the same:
//System.out.println(" + ve " + endPos + " -> " + endOffset);
Assert.AreEqual((int)posToEndOffset[endPos], endOffset, "pos=" + pos + " posLen=" + posLength + " token=" + termAtt);
}
}
}
if (posIncrAtt != null)
{
if (i == 0)
{
Assert.IsTrue(posIncrAtt.PositionIncrement >= 1, "first posIncrement must be >= 1");
}
else
{
Assert.IsTrue(posIncrAtt.PositionIncrement >= 0, "posIncrement must be >= 0");
}
}
if (posLengthAtt != null)
{
Assert.IsTrue(posLengthAtt.PositionLength >= 1, "posLength must be >= 1");
}
}
if (ts.IncrementToken())
{
Assert.Fail("TokenStream has more tokens than expected (expected count=" + output.Length + "); extra token=" + termAtt);
}
// repeat our extra safety checks for End()
ts.ClearAttributes();
if (termAtt != null)
{
termAtt.SetEmpty().Append("bogusTerm");
}
if (offsetAtt != null)
{
offsetAtt.SetOffset(14584724, 24683243);
}
if (typeAtt != null)
{
typeAtt.Type = "bogusType";
}
if (posIncrAtt != null)
{
posIncrAtt.PositionIncrement = 45987657;
}
if (posLengthAtt != null)
{
posLengthAtt.PositionLength = 45987653;
}
var reset_ = checkClearAtt.AndResetClearCalled; // reset it, because we called clearAttribute() before
ts.End();
Assert.IsTrue(checkClearAtt.AndResetClearCalled, "super.End()/ClearAttributes() was not called correctly in End()");
if (finalOffset != null)
{
Assert.AreEqual((int)finalOffset, offsetAtt.EndOffset(), "finalOffset");
}
if (offsetAtt != null)
{
Assert.IsTrue(offsetAtt.EndOffset() >= 0, "finalOffset must be >= 0");
}
if (finalPosInc != null)
{
Assert.AreEqual((int)finalPosInc, posIncrAtt.PositionIncrement, "finalPosInc");
}
ts.Dispose();
}
public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int[] posLengths, int? finalOffset, bool[] keywordAtts, bool offsetsAreCorrect)
{
AssertTokenStreamContents(ts, output, startOffsets, endOffsets, types, posIncrements, posLengths, finalOffset, null, null, offsetsAreCorrect);
}
public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int[] posLengths, int? finalOffset, bool offsetsAreCorrect)
{
AssertTokenStreamContents(ts, output, startOffsets, endOffsets, types, posIncrements, posLengths, finalOffset, null, offsetsAreCorrect);
}
public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int[] posLengths, int? finalOffset)
{
AssertTokenStreamContents(ts, output, startOffsets, endOffsets, types, posIncrements, posLengths, finalOffset, true);
}
public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int? finalOffset)
{
AssertTokenStreamContents(ts, output, startOffsets, endOffsets, types, posIncrements, null, finalOffset);
}
public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements)
{
AssertTokenStreamContents(ts, output, startOffsets, endOffsets, types, posIncrements, null, null);
}
public static void AssertTokenStreamContents(TokenStream ts, string[] output)
{
AssertTokenStreamContents(ts, output, null, null, null, null, null, null);
}
public static void AssertTokenStreamContents(TokenStream ts, string[] output, string[] types)
{
AssertTokenStreamContents(ts, output, null, null, types, null, null, null);
}
public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] posIncrements)
{
AssertTokenStreamContents(ts, output, null, null, null, posIncrements, null, null);
}
public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets)
{
AssertTokenStreamContents(ts, output, startOffsets, endOffsets, null, null, null, null);
}
public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, int? finalOffset)
{
AssertTokenStreamContents(ts, output, startOffsets, endOffsets, null, null, null, finalOffset);
}
public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, int[] posIncrements)
{
AssertTokenStreamContents(ts, output, startOffsets, endOffsets, null, posIncrements, null, null);
}
public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, int[] posIncrements, int? finalOffset)
{
AssertTokenStreamContents(ts, output, startOffsets, endOffsets, null, posIncrements, null, finalOffset);
}
public static void AssertTokenStreamContents(TokenStream ts, string[] output, int[] startOffsets, int[] endOffsets, int[] posIncrements, int[] posLengths, int? finalOffset)
{
AssertTokenStreamContents(ts, output, startOffsets, endOffsets, null, posIncrements, posLengths, finalOffset);
}
public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements)
{
CheckResetException(a, input);
AssertTokenStreamContents(a.TokenStream("dummy", new StringReader(input)), output, startOffsets, endOffsets, types, posIncrements, null, input.Length);
}
public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int[] posLengths)
{
CheckResetException(a, input);
AssertTokenStreamContents(a.TokenStream("dummy", new StringReader(input)), output, startOffsets, endOffsets, types, posIncrements, posLengths, input.Length);
}
public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, int[] startOffsets, int[] endOffsets, string[] types, int[] posIncrements, int[] posLengths, bool offsetsAreCorrect)
{
CheckResetException(a, input);
AssertTokenStreamContents(a.TokenStream("dummy", new StringReader(input)), output, startOffsets, endOffsets, types, posIncrements, posLengths, input.Length, offsetsAreCorrect);
}
public static void AssertAnalyzesTo(Analyzer a, string input, string[] output)
{
AssertAnalyzesTo(a, input, output, null, null, null, null, null);
}
public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, string[] types)
{
AssertAnalyzesTo(a, input, output, null, null, types, null, null);
}
public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, int[] posIncrements)
{
AssertAnalyzesTo(a, input, output, null, null, null, posIncrements, null);
}
public static void AssertAnalyzesToPositions(Analyzer a, string input, string[] output, int[] posIncrements, int[] posLengths)
{
AssertAnalyzesTo(a, input, output, null, null, null, posIncrements, posLengths);
}
public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, int[] startOffsets, int[] endOffsets)
{
AssertAnalyzesTo(a, input, output, startOffsets, endOffsets, null, null, null);
}
public static void AssertAnalyzesTo(Analyzer a, string input, string[] output, int[] startOffsets, int[] endOffsets, int[] posIncrements)
{
AssertAnalyzesTo(a, input, output, startOffsets, endOffsets, null, posIncrements, null);
}
internal static void CheckResetException(Analyzer a, string input)
{
TokenStream ts = a.TokenStream("bogus", new StringReader(input));
try
{
if (ts.IncrementToken())
{
ts.ReflectAsString(false);
Assert.Fail("didn't get expected exception when reset() not called");
}
}
catch (InvalidOperationException expected)
{
//ok
}
catch (AssertionException expected)
{
// ok: MockTokenizer
Assert.IsTrue(expected.Message != null && expected.Message.Contains("wrong state"), expected.Message);
}
catch (Exception unexpected)
{
//unexpected.printStackTrace(System.err);
Console.Error.WriteLine(unexpected.StackTrace);
Assert.Fail("got wrong exception when reset() not called: " + unexpected);
}
finally
{
// consume correctly
ts.Reset();
while (ts.IncrementToken())
{
}
ts.End();
ts.Dispose();
}
// check for a missing Close()
ts = a.TokenStream("bogus", new StringReader(input));
ts.Reset();
while (ts.IncrementToken())
{
}
ts.End();
try
{
ts = a.TokenStream("bogus", new StringReader(input));
Assert.Fail("didn't get expected exception when Close() not called");
}
catch (Exception)
{
// ok
}
finally
{
ts.Dispose();
}
}
// simple utility method for testing stemmers
public static void CheckOneTerm(Analyzer a, string input, string expected)
{
AssertAnalyzesTo(a, input, new string[] { expected });
}
/// <summary>
/// utility method for blasting tokenstreams with data to make sure they don't do anything crazy </summary>
public static void CheckRandomData(Random random, Analyzer a, int iterations)
{
CheckRandomData(random, a, iterations, 20, false, true);
}
/// <summary>
/// utility method for blasting tokenstreams with data to make sure they don't do anything crazy </summary>
public static void CheckRandomData(Random random, Analyzer a, int iterations, int maxWordLength)
{
CheckRandomData(random, a, iterations, maxWordLength, false, true);
}
/// <summary>
/// utility method for blasting tokenstreams with data to make sure they don't do anything crazy </summary>
/// <param name="simple"> true if only ascii strings will be used (try to avoid) </param>
public static void CheckRandomData(Random random, Analyzer a, int iterations, bool simple)
{
CheckRandomData(random, a, iterations, 20, simple, true);
}
internal class AnalysisThread : ThreadClass
{
internal readonly int Iterations;
internal readonly int MaxWordLength;
internal readonly long Seed;
internal readonly Analyzer a;
internal readonly bool UseCharFilter;
internal readonly bool Simple;
internal readonly bool OffsetsAreCorrect;
internal readonly RandomIndexWriter Iw;
private readonly CountDownLatch _latch;
// NOTE: not volatile because we don't want the tests to
// add memory barriers (ie alter how threads
// interact)... so this is just "best effort":
public bool Failed;
internal AnalysisThread(long seed, /*CountDownLatch latch,*/ Analyzer a, int iterations, int maxWordLength, bool useCharFilter, bool simple, bool offsetsAreCorrect, RandomIndexWriter iw)
{
this.Seed = seed;
this.a = a;
this.Iterations = iterations;
this.MaxWordLength = maxWordLength;
this.UseCharFilter = useCharFilter;
this.Simple = simple;
this.OffsetsAreCorrect = offsetsAreCorrect;
this.Iw = iw;
this._latch = null;
}
public override void Run()
{
bool success = false;
try
{
if (_latch != null) _latch.await();
// see the part in checkRandomData where it replays the same text again
// to verify reproducability/reuse: hopefully this would catch thread hazards.
CheckRandomData(new Random((int)Seed), a, Iterations, MaxWordLength, UseCharFilter, Simple, OffsetsAreCorrect, Iw);
success = true;
}
catch (Exception e)
{
Console.WriteLine("Exception in Thread: " + e);
throw;
}
finally
{
Failed = !success;
}
}
}
public static void CheckRandomData(Random random, Analyzer a, int iterations, int maxWordLength, bool simple)
{
CheckRandomData(random, a, iterations, maxWordLength, simple, true);
}
public static void CheckRandomData(Random random, Analyzer a, int iterations, int maxWordLength, bool simple, bool offsetsAreCorrect)
{
CheckResetException(a, "best effort");
long seed = random.Next();
bool useCharFilter = random.NextBoolean();
Directory dir = null;
RandomIndexWriter iw = null;
string postingsFormat = TestUtil.GetPostingsFormat("dummy");
bool codecOk = iterations * maxWordLength < 100000
|| !(postingsFormat.Equals("Memory") || postingsFormat.Equals("SimpleText"));
if (Rarely(random) && codecOk)
{
dir = NewFSDirectory(CreateTempDir("bttc"));
iw = new RandomIndexWriter(new Random((int)seed), dir, a);
}
bool success = false;
try
{
CheckRandomData(new Random((int)seed), a, iterations, maxWordLength, useCharFilter, simple, offsetsAreCorrect, iw);
// now test with multiple threads: note we do the EXACT same thing we did before in each thread,
// so this should only really fail from another thread if its an actual thread problem
int numThreads = TestUtil.NextInt(random, 2, 4);
var startingGun = new CountDownLatch(1);
var threads = new AnalysisThread[numThreads];
for (int i = 0; i < threads.Length; i++)
{
threads[i] = new AnalysisThread(seed, /*startingGun,*/ a, iterations, maxWordLength, useCharFilter, simple, offsetsAreCorrect, iw);
}
Array.ForEach(threads, thread => thread.Start());
startingGun.countDown();
foreach (var t in threads)
{
try
{
t.Join();
}
catch (ThreadInterruptedException e)
{
Fail("Thread interrupted");
}
}
if (threads.Any(x => x.Failed))
Fail("Thread interrupted");
success = true;
}
finally
{
if (success)
{
IOUtils.Close(iw, dir);
}
else
{
IOUtils.CloseWhileHandlingException(iw, dir); // checkindex
}
}
}
private static void CheckRandomData(Random random, Analyzer a, int iterations, int maxWordLength, bool useCharFilter, bool simple, bool offsetsAreCorrect, RandomIndexWriter iw)
{
LineFileDocs docs = new LineFileDocs(random);
Document doc = null;
Field field = null, currentField = null;
StringReader bogus = new StringReader("");
if (iw != null)
{
doc = new Document();
FieldType ft = new FieldType(TextField.TYPE_NOT_STORED);
if (random.NextBoolean())
{
ft.StoreTermVectors = true;
ft.StoreTermVectorOffsets = random.NextBoolean();
ft.StoreTermVectorPositions = random.NextBoolean();
if (ft.StoreTermVectorPositions && !OLD_FORMAT_IMPERSONATION_IS_ACTIVE)
{
ft.StoreTermVectorPayloads = random.NextBoolean();
}
}
if (random.NextBoolean())
{
ft.OmitNorms = true;
}
string pf = TestUtil.GetPostingsFormat("dummy");
bool supportsOffsets = !DoesntSupportOffsets.Contains(pf);
switch (random.Next(4))
{
case 0:
ft.IndexOptions = FieldInfo.IndexOptions.DOCS_ONLY;
break;
case 1:
ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS;
break;
case 2:
ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS;
break;
default:
if (supportsOffsets && offsetsAreCorrect)
{
ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS_AND_OFFSETS;
}
else
{
ft.IndexOptions = FieldInfo.IndexOptions.DOCS_AND_FREQS_AND_POSITIONS;
}
break;
}
currentField = field = new Field("dummy", bogus, ft);
doc.Add(currentField);
}
try
{
for (int i = 0; i < iterations; i++)
{
string text;
if (random.Next(10) == 7)
{
// real data from linedocs
text = docs.NextDoc().Get("body");
if (text.Length > maxWordLength)
{
// Take a random slice from the text...:
int startPos = random.Next(text.Length - maxWordLength);
if (startPos > 0 && char.IsLowSurrogate(text[startPos]))
{
// Take care not to split up a surrogate pair:
startPos--;
Assert.True(char.IsHighSurrogate(text[startPos]));
}
int endPos = startPos + maxWordLength - 1;
if (char.IsHighSurrogate(text[endPos]))
{
// Take care not to split up a surrogate pair:
endPos--;
}
text = text.Substring(startPos, 1 + endPos - startPos);
}
}
else
{
// synthetic
text = TestUtil.RandomAnalysisString(random, maxWordLength, simple);
}
try
{
CheckAnalysisConsistency(random, a, useCharFilter, text, offsetsAreCorrect, currentField);
if (iw != null)
{
if (random.Next(7) == 0)
{
// pile up a multivalued field
var ft = (FieldType)field.FieldType();
currentField = new Field("dummy", bogus, ft);
doc.Add(currentField);
}
else
{
iw.AddDocument(doc);
if (doc.Fields.Count > 1)
{
// back to 1 field
currentField = field;
doc.RemoveFields("dummy");
doc.Add(currentField);
}
}
}
}
catch (Exception t)
{
// TODO: really we should pass a random seed to
// checkAnalysisConsistency then print it here too:
Console.Error.WriteLine("TEST FAIL: useCharFilter=" + useCharFilter + " text='" + Escape(text) + "'");
throw;
}
}
}
finally
{
IOUtils.CloseWhileHandlingException(docs);
}
}
public static string Escape(string s)
{
int charUpto = 0;
StringBuilder sb = new StringBuilder();
while (charUpto < s.Length)
{
int c = s[charUpto];
if (c == 0xa)
{
// Strangely, you cannot put \ u000A into Java
// sources (not in a comment nor a string
// constant)...:
sb.Append("\\n");
}
else if (c == 0xd)
{
// ... nor \ u000D:
sb.Append("\\r");
}
else if (c == '"')
{
sb.Append("\\\"");
}
else if (c == '\\')
{
sb.Append("\\\\");
}
else if (c >= 0x20 && c < 0x80)
{
sb.Append((char)c);
}
else
{
// TODO: we can make ascii easier to read if we
// don't escape...
sb.Append(string.Format(CultureInfo.InvariantCulture, "\\u%04x", c));
}
charUpto++;
}
return sb.ToString();
}
public static void CheckAnalysisConsistency(Random random, Analyzer a, bool useCharFilter, string text)
{
CheckAnalysisConsistency(random, a, useCharFilter, text, true);
}
public static void CheckAnalysisConsistency(Random random, Analyzer a, bool useCharFilter, string text, bool offsetsAreCorrect)
{
CheckAnalysisConsistency(random, a, useCharFilter, text, offsetsAreCorrect, null);
}
private static void CheckAnalysisConsistency(Random random, Analyzer a, bool useCharFilter, string text, bool offsetsAreCorrect, Field field)
{
if (VERBOSE)
{
Console.WriteLine(Thread.CurrentThread.Name + ": NOTE: baseTokenStreamTestCase: get first token stream now text=" + text);
}
ICharTermAttribute termAtt;
IOffsetAttribute offsetAtt;
IPositionIncrementAttribute posIncAtt;
IPositionLengthAttribute posLengthAtt;
ITypeAttribute typeAtt;
IList<string> tokens = new List<string>();
IList<string> types = new List<string>();
IList<int> positions = new List<int>();
IList<int> positionLengths = new List<int>();
IList<int> startOffsets = new List<int>();
IList<int> endOffsets = new List<int>();
int remainder = random.Next(10);
StringReader reader = new StringReader(text);
TokenStream ts;
using (ts = a.TokenStream("dummy", useCharFilter ? (TextReader) new MockCharFilter(reader, remainder) : reader))
{
termAtt = ts.HasAttribute<ICharTermAttribute>()
? ts.GetAttribute<ICharTermAttribute>()
: null;
offsetAtt = ts.HasAttribute<IOffsetAttribute>()
? ts.GetAttribute<IOffsetAttribute>()
: null;
posIncAtt = ts.HasAttribute<IPositionIncrementAttribute>()
? ts.GetAttribute<IPositionIncrementAttribute>()
: null;
posLengthAtt = ts.HasAttribute<IPositionLengthAttribute>()
? ts.GetAttribute<IPositionLengthAttribute>()
: null;
typeAtt = ts.HasAttribute<ITypeAttribute>() ? ts.GetAttribute<ITypeAttribute>() : null;
ts.Reset();
// First pass: save away "correct" tokens
while (ts.IncrementToken())
{
Assert.IsNotNull(termAtt, "has no CharTermAttribute");
tokens.Add(termAtt.ToString());
if (typeAtt != null)
{
types.Add(typeAtt.Type);
}
if (posIncAtt != null)
{
positions.Add(posIncAtt.PositionIncrement);
}
if (posLengthAtt != null)
{
positionLengths.Add(posLengthAtt.PositionLength);
}
if (offsetAtt != null)
{
startOffsets.Add(offsetAtt.StartOffset());
endOffsets.Add(offsetAtt.EndOffset());
}
}
ts.End();
}
// verify reusing is "reproducable" and also get the normal tokenstream sanity checks
if (tokens.Count > 0)
{
// KWTokenizer (for example) can produce a token
// even when input is length 0:
if (text.Length != 0)
{
// (Optional) second pass: do something evil:
int evilness = random.Next(50);
if (evilness == 17)
{
if (VERBOSE)
{
Console.WriteLine(Thread.CurrentThread.Name + ": NOTE: baseTokenStreamTestCase: re-run analysis w/ exception");
}
// Throw an errant exception from the Reader:
MockReaderWrapper evilReader = new MockReaderWrapper(random, text);
evilReader.ThrowExcAfterChar(random.Next(text.Length));
reader = evilReader;
try
{
// NOTE: some Tokenizers go and read characters
// when you call .setReader(Reader), eg
// PatternTokenizer. this is a bit
// iffy... (really, they should only
// pull from the Reader when you call
// .incremenToken(), I think?), but we
// currently allow it, so, we must call
// a.TokenStream inside the try since we may
// hit the exc on init:
ts = a.TokenStream("dummy", useCharFilter ? (TextReader)new MockCharFilter(evilReader, remainder) : evilReader);
ts.Reset();
while (ts.IncrementToken()) ;
Assert.Fail("did not hit exception");
}
catch (Exception re)
{
Assert.IsTrue(MockReaderWrapper.IsMyEvilException(re));
}
try
{
ts.End();
}
catch (InvalidOperationException ae)
{
// Catch & ignore MockTokenizer's
// anger...
if ("End() called before IncrementToken() returned false!".Equals(ae.Message))
{
// OK
}
else
{
throw ae;
}
}
finally
{
ts.Dispose();
}
}
else if (evilness == 7)
{
// Only consume a subset of the tokens:
int numTokensToRead = random.Next(tokens.Count);
if (VERBOSE)
{
Console.WriteLine(Thread.CurrentThread.Name + ": NOTE: baseTokenStreamTestCase: re-run analysis, only consuming " + numTokensToRead + " of " + tokens.Count + " tokens");
}
reader = new StringReader(text);
ts = a.TokenStream("dummy", useCharFilter ? (TextReader)new MockCharFilter(reader, remainder) : reader);
ts.Reset();
for (int tokenCount = 0; tokenCount < numTokensToRead; tokenCount++)
{
Assert.IsTrue(ts.IncrementToken());
}
try
{
ts.End();
}
catch (InvalidOperationException ae)
{
// Catch & ignore MockTokenizer's
// anger...
if ("End() called before IncrementToken() returned false!".Equals(ae.Message))
{
// OK
}
else
{
throw ae;
}
}
finally
{
ts.Dispose();
}
}
}
}
// Final pass: verify clean tokenization matches
// results from first pass:
if (VERBOSE)
{
Console.WriteLine(Thread.CurrentThread.Name + ": NOTE: baseTokenStreamTestCase: re-run analysis; " + tokens.Count + " tokens");
}
reader = new StringReader(text);
long seed = random.Next();
random = new Random((int)seed);
if (random.Next(30) == 7)
{
if (VERBOSE)
{
Console.WriteLine(Thread.CurrentThread.Name + ": NOTE: baseTokenStreamTestCase: using spoon-feed reader");
}
reader = new MockReaderWrapper(random, text);
}
ts = a.TokenStream("dummy", useCharFilter ? (TextReader)new MockCharFilter(reader, remainder) : reader);
if (typeAtt != null && posIncAtt != null && posLengthAtt != null && offsetAtt != null)
{
// offset + pos + posLength + type
AssertTokenStreamContents(ts, tokens.ToArray(), ToIntArray(startOffsets), ToIntArray(endOffsets), types.ToArray(), ToIntArray(positions), ToIntArray(positionLengths), text.Length, offsetsAreCorrect);
}
else if (typeAtt != null && posIncAtt != null && offsetAtt != null)
{
// offset + pos + type
AssertTokenStreamContents(ts, tokens.ToArray(), ToIntArray(startOffsets), ToIntArray(endOffsets), types.ToArray(), ToIntArray(positions), null, text.Length, offsetsAreCorrect);
}
else if (posIncAtt != null && posLengthAtt != null && offsetAtt != null)
{
// offset + pos + posLength
AssertTokenStreamContents(ts, tokens.ToArray(), ToIntArray(startOffsets), ToIntArray(endOffsets), null, ToIntArray(positions), ToIntArray(positionLengths), text.Length, offsetsAreCorrect);
}
else if (posIncAtt != null && offsetAtt != null)
{
// offset + pos
AssertTokenStreamContents(ts, tokens.ToArray(), ToIntArray(startOffsets), ToIntArray(endOffsets), null, ToIntArray(positions), null, text.Length, offsetsAreCorrect);
}
else if (offsetAtt != null)
{
// offset
AssertTokenStreamContents(ts, tokens.ToArray(), ToIntArray(startOffsets), ToIntArray(endOffsets), null, null, null, text.Length, offsetsAreCorrect);
}
else
{
// terms only
AssertTokenStreamContents(ts, tokens.ToArray());
}
if (field != null)
{
reader = new StringReader(text);
random = new Random((int)seed);
if (random.Next(30) == 7)
{
if (VERBOSE)
{
Console.WriteLine(Thread.CurrentThread.Name + ": NOTE: baseTokenStreamTestCase: indexing using spoon-feed reader");
}
reader = new MockReaderWrapper(random, text);
}
field.ReaderValue = useCharFilter ? (TextReader)new MockCharFilter(reader, remainder) : reader;
}
}
protected internal virtual string ToDot(Analyzer a, string inputText)
{
StringWriter sw = new StringWriter();
TokenStream ts = a.TokenStream("field", new StringReader(inputText));
ts.Reset();
(new TokenStreamToDot(inputText, ts, /*new StreamWriter(*/(TextWriter)sw/*)*/)).ToDot();
return sw.ToString();
}
protected internal virtual void ToDotFile(Analyzer a, string inputText, string localFileName)
{
StreamWriter w = new StreamWriter(new FileStream(localFileName, FileMode.Open), IOUtils.CHARSET_UTF_8);
TokenStream ts = a.TokenStream("field", new StreamReader(inputText));
ts.Reset();
(new TokenStreamToDot(inputText, ts,/* new PrintWriter(*/w/*)*/)).ToDot();
w.Close();
}
internal static int[] ToIntArray(IList<int> list)
{
int[] ret = new int[list.Count];
int offset = 0;
foreach (int i in list)
{
ret[offset++] = i;
}
return ret;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using V2.PaidTimeOffDAL.Framework;
using V2.PaidTimeOffDAL;
namespace V2.PaidTimeOffBLL.Framework
{
#region ENTWFStateEO
[Serializable()]
public class ENTWFStateEO : ENTBaseEO
{
#region Constructor
public ENTWFStateEO()
{
ENTWFStateProperties = new ENTWFStatePropertyEOList();
}
#endregion Constructor
#region Properties
public int ENTWorkflowId { get; set; }
public string StateName { get; set; }
public string Description { get; set; }
public Nullable<int> ENTWFOwnerGroupId { get; set; }
public bool IsOwnerSubmitter { get; set; }
public ENTWFStatePropertyEOList ENTWFStateProperties { get; private set; }
#endregion Properties
#region Overrides
public override bool Load(int id)
{
//Get the entity object from the DAL.
ENTWFState eNTWFState = new ENTWFStateData().Select(id);
MapEntityToProperties(eNTWFState);
return eNTWFState != null;
}
protected override void MapEntityToCustomProperties(IENTBaseEntity entity)
{
ENTWFState eNTWFState = (ENTWFState)entity;
ID = eNTWFState.ENTWFStateId;
ENTWorkflowId = eNTWFState.ENTWorkflowId;
StateName = eNTWFState.StateName;
Description = eNTWFState.Description;
IsOwnerSubmitter = eNTWFState.IsOwnerSubmitter;
ENTWFOwnerGroupId = eNTWFState.ENTWFOwnerGroupId;
ENTWFStateProperties.Load(ID);
}
public override bool Save(HRPaidTimeOffDataContext db, ref ENTValidationErrors validationErrors, int userAccountId)
{
if (DBAction == DBActionEnum.Save)
{
//Validate the object
Validate(db, ref validationErrors);
//Check if there were any validation errors
if (validationErrors.Count == 0)
{
if (IsNewRecord())
{
//Add
ID = new ENTWFStateData().Insert(db, ENTWorkflowId, StateName, Description, ENTWFOwnerGroupId, IsOwnerSubmitter, userAccountId);
//Update the ID on all the ENTWFStateProperty objects
foreach (ENTWFStatePropertyEO stateProperty in ENTWFStateProperties)
{
stateProperty.ENTWFStateId = ID;
}
}
else
{
//Update
if (!new ENTWFStateData().Update(db, ID, ENTWorkflowId, StateName, Description, ENTWFOwnerGroupId, IsOwnerSubmitter, userAccountId, Version))
{
UpdateFailed(ref validationErrors);
return false;
}
}
//Delete all the existing ENTWFStateProperty records
ENTWFStateProperties.Delete(db, ID);
//Add the records that were chosen on the screen.
if (ENTWFStateProperties.Save(db, ref validationErrors, userAccountId))
{
return true;
}
else
{
return false;
}
}
else
{
//Didn't pass validation.
return false;
}
}
else
{
throw new Exception("DBAction not Save.");
}
}
protected override void Validate(HRPaidTimeOffDataContext db, ref ENTValidationErrors validationErrors)
{
if (StateName.Trim() == "")
{
validationErrors.Add("The state name is required.");
}
else
{
////The windows account name must be unique.
if (new ENTWFStateData().IsDuplicateStateName(db, ID, StateName))
{
validationErrors.Add("The state name must be unique.");
}
}
if (ENTWorkflowId == 0)
{
validationErrors.Add("Please select a workflow to associate with this state.");
}
if ((ENTWFOwnerGroupId == 0) && (IsOwnerSubmitter == false))
{
validationErrors.Add("Please select the group that owns the issue while in this state.");
}
}
protected override void DeleteForReal(HRPaidTimeOffDataContext db)
{
if (DBAction == DBActionEnum.Delete)
{
new ENTWFStateData().Delete(db, ID);
}
else
{
throw new Exception("DBAction not delete.");
}
}
protected override void ValidateDelete(HRPaidTimeOffDataContext db, ref ENTValidationErrors validationErrors)
{
//throw new NotImplementedException();
//Check if associates with a transition
}
public override void Init()
{
//Nothing to default
}
protected override string GetDisplayText()
{
return StateName;
}
#endregion Overrides
}
#endregion ENTWFStateEO
#region ENTWFStateEOList
[Serializable()]
public class ENTWFStateEOList : ENTBaseEOList<ENTWFStateEO>
{
#region Overrides
public override void Load()
{
LoadFromList(new ENTWFStateData().Select());
}
#endregion Overrides
#region Private Methods
private void LoadFromList(List<ENTWFState> eNTWFStates)
{
if (eNTWFStates.Count > 0)
{
foreach (ENTWFState eNTWFState in eNTWFStates)
{
ENTWFStateEO newENTWFStateEO = new ENTWFStateEO();
newENTWFStateEO.MapEntityToProperties(eNTWFState);
this.Add(newENTWFStateEO);
}
}
}
#endregion Private Methods
#region Internal Methods
#endregion Internal Methods
public void Load(int entWorkflowId)
{
LoadFromList(new ENTWFStateData().SelectByENTWorkflowId(entWorkflowId));
}
}
#endregion ENTWFStateEOList
}
| |
#if NET461
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.OAuth;
using Microsoft.Owin.Testing;
using Newtonsoft.Json;
using Owin;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using Xunit;
namespace RimDev.Stuntman.Core.Tests
{
public class IAppBuilderExtensionsTests
{
public class UseStuntmanExtensionMethod
{
[Fact]
public async Task SignInUri_Returns200Ok()
{
var options = new StuntmanOptions();
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var response = await server.HttpClient.GetAsync(
$"{options.SignInUri}?{Constants.StuntmanOptions.ReturnUrlQueryStringKey}=https://app");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
[Fact]
public async Task SignInUri_IfOverrideNotSpecified_ShowsLoginUI()
{
var options = new StuntmanOptions();
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var response = await server.HttpClient.GetAsync(
$"{options.SignInUri}?{Constants.StuntmanOptions.ReturnUrlQueryStringKey}=https://app");
Assert.Contains(
"Please select a user to continue authentication.",
await response.Content.ReadAsStringAsync());
}
}
[Fact]
public async Task SignInUri_OverrideSpecified_ThrowsIfNoMatchingUser()
{
var options = new StuntmanOptions();
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var response = await server.HttpClient.GetAsync(
$"{options.SignInUri}?{Constants.StuntmanOptions.OverrideQueryStringKey}=user-1");
Assert.False(response.IsSuccessStatusCode);
}
}
[Fact]
public async Task SignInUri_OverrideSpecified_SetsExpectedCookieName()
{
var options = new StuntmanOptions()
.AddUser(new StuntmanUser("user-1", "User 1"));
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var response = await server.HttpClient.GetAsync(
$"{options.SignInUri}?{Constants.StuntmanOptions.OverrideQueryStringKey}=user-1&{Constants.StuntmanOptions.ReturnUrlQueryStringKey}=https://app");
var setCookie = response.Headers.GetValues("Set-Cookie").SingleOrDefault();
Assert.StartsWith(
$".AspNet.{Constants.StuntmanAuthenticationType}=",
setCookie);
}
}
[Fact]
public async Task SignInUri_ReturnsExpectedLocationHeader_UsingReferer()
{
const string RedirectUri = "https://redirect-uri/";
var options = new StuntmanOptions();
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var request = new HttpRequestMessage
{
RequestUri = new Uri(new Uri("https://app"), $"{options.SignInUri}"),
Method = HttpMethod.Get
};
request.Headers.Referrer = new Uri(RedirectUri);
var response = await server.HttpClient.SendAsync(request);
Assert.Equal(RedirectUri, response.Headers.Location.AbsoluteUri);
}
}
[Fact]
public async Task SignInUri_ReturnsExpectedLocationHeader_WhenQueryStringUsed()
{
const string RedirectUri = "https://redirect-uri/";
var options = new StuntmanOptions();
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var response = await server.HttpClient.GetAsync(
$"{options.SignInUri}?{Constants.StuntmanOptions.ReturnUrlQueryStringKey}={RedirectUri}");
Assert.Equal(RedirectUri, response.Headers.Location.AbsoluteUri);
}
}
[Theory,
InlineData("Bearer 123 456"),
InlineData("Bearer 123 456 789")]
public async Task AuthorizationBearerToken_400IfNoCorrectFormat(string bearerToken)
{
var options = new StuntmanOptions();
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
app.Map("", root =>
{
root.Run(context =>
{
return Task.FromResult(true);
});
});
}))
{
var request = server.CreateRequest("");
request.AddHeader("Authorization", bearerToken);
var response = await request.GetAsync();
Assert.Equal(400, (int)response.StatusCode);
}
}
[Fact]
public async Task AuthorizationBearerToken_ThrowsIfNoMatchingUser()
{
var options = new StuntmanOptions();
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
app.Map("", root =>
{
root.Run(context =>
{
return Task.FromResult(true);
});
});
}))
{
var request = server.CreateRequest("");
request.AddHeader("Authorization", "Bearer 123");
var response = await request.GetAsync();
Assert.Equal(403, (int)response.StatusCode);
}
}
[Fact]
public async Task AuthorizationBearerToken_AddsTokenClaim()
{
var options = new StuntmanOptions()
.AddUser(
new StuntmanUser("user-1", "User 1")
.SetAccessToken("123"));
IEnumerable<Claim> claims = null;
options.AfterBearerValidateIdentity = (context) =>
{
claims = context
.OwinContext
.Authentication
.AuthenticationResponseGrant
.Identity
.Claims;
};
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var request = server.CreateRequest("");
request.AddHeader("Authorization", "Bearer 123");
await request.GetAsync();
Assert.NotNull(claims);
var accessToken = claims.FirstOrDefault(x => x.Type == "access_token");
Assert.NotNull(accessToken);
Assert.Equal("123", accessToken.Value);
}
}
[Fact]
public async Task SignOutUri_Returns302Redirect()
{
var options = new StuntmanOptions();
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var response = await server.HttpClient.GetAsync(
$"{options.SignOutUri}?{Constants.StuntmanOptions.ReturnUrlQueryStringKey}=https://app");
Assert.Equal(HttpStatusCode.Redirect, response.StatusCode);
}
}
[Fact]
public async Task SignOutUri_RemovesExpectedCookieName()
{
var options = new StuntmanOptions();
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var response = await server.HttpClient.GetAsync(
$"{options.SignOutUri}?{Constants.StuntmanOptions.ReturnUrlQueryStringKey}=https://app");
var setCookie = response.Headers.GetValues("Set-Cookie").SingleOrDefault();
Assert.Equal(
$".AspNet.{Constants.StuntmanAuthenticationType}=; path=/; expires=Thu, 01-Jan-1970 00:00:00 GMT",
setCookie);
}
}
[Fact]
public async Task SignOutUri_ReturnsExpectedLocationHeader_UsingReferer()
{
const string RedirectUri = "https://redirect-uri/";
var options = new StuntmanOptions();
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var request = new HttpRequestMessage
{
RequestUri = new Uri(new Uri("https://app"), $"{options.SignOutUri}"),
Method = HttpMethod.Get
};
request.Headers.Referrer = new Uri(RedirectUri);
var response = await server.HttpClient.SendAsync(request);
Assert.Equal(RedirectUri, response.Headers.Location.AbsoluteUri);
}
}
[Fact]
public async Task SignOutUri_ReturnsExpectedLocationHeader_WhenQueryStringUsed()
{
const string RedirectUri = "https://redirect-uri/";
var options = new StuntmanOptions();
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var response = await server.HttpClient.GetAsync(
$"{options.SignOutUri}?{Constants.StuntmanOptions.ReturnUrlQueryStringKey}={RedirectUri}");
Assert.Equal(RedirectUri, response.Headers.Location.AbsoluteUri);
}
}
[Fact]
public async Task ServerEndpoint_ReturnsExpectedResponse_WhenEnabled()
{
var options = new StuntmanOptions()
.EnableServer();
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var response = await server.HttpClient.GetAsync(
options.ServerUri);
response.EnsureSuccessStatusCode();
var stuntmanServerResponse = JsonConvert.DeserializeObject<StuntmanServerResponse>(
await response.Content.ReadAsStringAsync());
Assert.NotNull(stuntmanServerResponse);
}
}
[Fact]
public async Task ServerEndpoint_ReturnsExpectedResponse_WhenEnabledWithUsers()
{
const string UserId = "user-1";
var options = new StuntmanOptions()
.AddUser(new StuntmanUser(UserId, "User 1"))
.EnableServer();
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var response = await server.HttpClient.GetAsync(
options.ServerUri);
response.EnsureSuccessStatusCode();
var stuntmanServerResponse = JsonConvert.DeserializeObject<StuntmanServerResponse>(
await response.Content.ReadAsStringAsync());
Assert.Equal(UserId, stuntmanServerResponse.Users.Single().Id);
}
}
[Fact]
public async Task ServerEndpoint_Returns404_WhenNotEnabled()
{
var options = new StuntmanOptions();
Assert.False(options.ServerEnabled);
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var response = await server.HttpClient.GetAsync(
options.ServerUri);
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}
}
[Fact]
public async Task DoesNotMapSignInUri_WhenCookieAuthenticationIsDiabled()
{
var options = new StuntmanOptions();
options.AllowCookieAuthentication = false;
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
}))
{
var response = await server.HttpClient.GetAsync(options.SignInUri);
Assert.Equal(404, (int)response.StatusCode);
}
}
[Fact]
public async Task DoesNotRedirectChallenge_WhenCookieAuthenticationIsDiabled()
{
var options = new StuntmanOptions();
options.AllowCookieAuthentication = false;
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
app.Map("/test", root =>
{
root.Run(context =>
{
/**
* Issuing a challenge for a non-existent authentication type
* will result in a 401.
*
* Normal behavior results in a 302 to redirect to the login UI.
*/
context.Authentication.Challenge(Constants.StuntmanAuthenticationType);
return Task.FromResult(true);
});
});
}))
{
var response = await server.HttpClient.GetAsync("test");
Assert.Equal(401, (int)response.StatusCode);
}
}
[Fact]
public async Task DoesNotHydrateIdentity_WhenBearerTokenAuthenticationIsDiabled()
{
var options = new StuntmanOptions()
.AddUser(
new StuntmanUser("user-1", "User 1")
.SetAccessToken("123"));
options.AllowBearerTokenAuthentication = false;
var authenticateResult = new AuthenticateResult(null, new AuthenticationProperties(), new AuthenticationDescription());
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
app.Map("/test", root =>
{
root.Run(async context =>
{
/**
* This result of `AuthenticateAsync` should be `null` since
* nothing is handling the `Authorization` header during the request.
*/
authenticateResult = await context.Authentication.AuthenticateAsync(Constants.StuntmanAuthenticationType);
});
});
}))
{
var request = server.CreateRequest("test");
request.AddHeader("Authorization", "Bearer 123");
var response = await request.GetAsync();
Assert.Null(authenticateResult);
}
}
[Fact]
public async Task DoesNotImmediatelyIssue403_WhenBearerTokenPassthroughIsEnabled()
{
var options = new StuntmanOptions()
.AddUser(
new StuntmanUser("user-1", "User 1")
.SetAccessToken("123"));
options.AllowBearerTokenPassthrough = true;
options.AllowCookieAuthentication = false;
using (var server = TestServer.Create(app =>
{
app.UseStuntman(options);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
{
Challenge = "Bearer StuntmanTest",
AuthenticationMode = AuthenticationMode.Active,
AuthenticationType = Constants.StuntmanAuthenticationType
});
app.Use((context, next) =>
{
if (context.Authentication.User != null &&
context.Authentication.User.Identity != null &&
context.Authentication.User.Identity.IsAuthenticated)
{
return next();
}
else
{
context.Authentication.Challenge(Constants.StuntmanAuthenticationType);
return Task.FromResult(false);
}
});
app.Map("/test", root =>
{
root.Run(context =>
{
return Task.FromResult(true);
});
});
}))
{
var request = server.CreateRequest("test");
request.AddHeader("Authorization", "Bearer 1234");
var response = await request.GetAsync();
Assert.Equal(401, (int)response.StatusCode);
Assert.Contains("StuntmanTest", response.Headers.WwwAuthenticate.Select(x => x.Parameter));
}
}
}
}
}
#endif
| |
// 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.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeFixes.Suppression;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.UnitTests.CodeActions;
using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics.GenerateType;
using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces;
using Microsoft.CodeAnalysis.GenerateType;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Text;
using Microsoft.CodeAnalysis.UnitTests;
using Microsoft.CodeAnalysis.UnitTests.Diagnostics;
using Microsoft.VisualStudio.Text.Differencing;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics
{
public abstract class AbstractUserDiagnosticTest : AbstractCodeActionOrUserDiagnosticTest
{
internal abstract IEnumerable<Tuple<Diagnostic, CodeFixCollection>> GetDiagnosticAndFixes(TestWorkspace workspace, string fixAllActionEquivalenceKey);
internal abstract IEnumerable<Diagnostic> GetDiagnostics(TestWorkspace workspace);
protected override IList<CodeAction> GetCodeActionsWorker(TestWorkspace workspace, string fixAllActionEquivalenceKey)
{
var diagnostics = GetDiagnosticAndFix(workspace, fixAllActionEquivalenceKey);
return diagnostics?.Item2?.Fixes.Select(f => f.Action).ToList();
}
internal Tuple<Diagnostic, CodeFixCollection> GetDiagnosticAndFix(TestWorkspace workspace, string fixAllActionEquivalenceKey = null)
{
return GetDiagnosticAndFixes(workspace, fixAllActionEquivalenceKey).FirstOrDefault();
}
protected Document GetDocumentAndSelectSpan(TestWorkspace workspace, out TextSpan span)
{
var hostDocument = workspace.Documents.Single(d => d.SelectedSpans.Any());
span = hostDocument.SelectedSpans.Single();
return workspace.CurrentSolution.GetDocument(hostDocument.Id);
}
protected bool TryGetDocumentAndSelectSpan(TestWorkspace workspace, out Document document, out TextSpan span)
{
var hostDocument = workspace.Documents.FirstOrDefault(d => d.SelectedSpans.Any());
if (hostDocument == null)
{
document = null;
span = default(TextSpan);
return false;
}
span = hostDocument.SelectedSpans.Single();
document = workspace.CurrentSolution.GetDocument(hostDocument.Id);
return true;
}
protected Document GetDocumentAndAnnotatedSpan(TestWorkspace workspace, out string annotation, out TextSpan span)
{
var hostDocument = workspace.Documents.Single(d => d.AnnotatedSpans.Any());
var annotatedSpan = hostDocument.AnnotatedSpans.Single();
annotation = annotatedSpan.Key;
span = annotatedSpan.Value.Single();
return workspace.CurrentSolution.GetDocument(hostDocument.Id);
}
protected FixAllScope? GetFixAllScope(string annotation)
{
if (annotation == null)
{
return null;
}
switch (annotation)
{
case "FixAllInDocument":
return FixAllScope.Document;
case "FixAllInProject":
return FixAllScope.Project;
case "FixAllInSolution":
return FixAllScope.Solution;
case "FixAllInSelection":
return FixAllScope.Custom;
}
throw new InvalidProgramException("Incorrect FixAll annotation in test");
}
internal IEnumerable<Tuple<Diagnostic, CodeFixCollection>> GetDiagnosticAndFixes(
IEnumerable<Diagnostic> diagnostics,
DiagnosticAnalyzer provider,
CodeFixProvider fixer,
TestDiagnosticAnalyzerDriver testDriver,
Document document,
TextSpan span,
string annotation,
string fixAllActionId)
{
if (diagnostics.IsEmpty())
{
return SpecializedCollections.EmptyEnumerable<Tuple<Diagnostic, CodeFixCollection>>();
}
FixAllScope? scope = GetFixAllScope(annotation);
return GetDiagnosticAndFixes(diagnostics, provider, fixer, testDriver, document, span, scope, fixAllActionId);
}
private IEnumerable<Tuple<Diagnostic, CodeFixCollection>> GetDiagnosticAndFixes(
IEnumerable<Diagnostic> diagnostics,
DiagnosticAnalyzer provider,
CodeFixProvider fixer,
TestDiagnosticAnalyzerDriver testDriver,
Document document,
TextSpan span,
FixAllScope? scope,
string fixAllActionId)
{
Assert.NotEmpty(diagnostics);
if (scope == null)
{
// Simple code fix.
foreach (var diagnostic in diagnostics)
{
var fixes = new List<CodeFix>();
var context = new CodeFixContext(document, diagnostic, (a, d) => fixes.Add(new CodeFix(document.Project, a, d)), CancellationToken.None);
fixer.RegisterCodeFixesAsync(context).Wait();
if (fixes.Any())
{
var codeFix = new CodeFixCollection(fixer, diagnostic.Location.SourceSpan, fixes);
yield return Tuple.Create(diagnostic, codeFix);
}
}
}
else
{
// Fix all fix.
var fixAllProvider = fixer.GetFixAllProvider();
Assert.NotNull(fixAllProvider);
var fixAllContext = GetFixAllContext(diagnostics, provider, fixer, testDriver, document, scope.Value, fixAllActionId);
var fixAllFix = fixAllProvider.GetFixAsync(fixAllContext).WaitAndGetResult(CancellationToken.None);
if (fixAllFix != null)
{
// Same fix applies to each diagnostic in scope.
foreach (var diagnostic in diagnostics)
{
var diagnosticSpan = diagnostic.Location.IsInSource ? diagnostic.Location.SourceSpan : default(TextSpan);
var codeFix = new CodeFixCollection(fixAllProvider, diagnosticSpan, ImmutableArray.Create(new CodeFix(document.Project, fixAllFix, diagnostic)));
yield return Tuple.Create(diagnostic, codeFix);
}
}
}
}
private static FixAllContext GetFixAllContext(
IEnumerable<Diagnostic> diagnostics,
DiagnosticAnalyzer provider,
CodeFixProvider fixer,
TestDiagnosticAnalyzerDriver testDriver,
Document document,
FixAllScope scope,
string fixAllActionId)
{
Assert.NotEmpty(diagnostics);
if (scope == FixAllScope.Custom)
{
// Bulk fixing diagnostics in selected scope.
var diagnosticsToFix = ImmutableDictionary.CreateRange(SpecializedCollections.SingletonEnumerable(KeyValuePair.Create(document, diagnostics.ToImmutableArray())));
return FixMultipleContext.Create(diagnosticsToFix, fixer, fixAllActionId, CancellationToken.None);
}
var diagnostic = diagnostics.First();
Func<Document, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getDocumentDiagnosticsAsync =
(d, diagIds, c) =>
{
var root = d.GetSyntaxRootAsync().Result;
var diags = testDriver.GetDocumentDiagnostics(provider, d, root.FullSpan);
diags = diags.Where(diag => diagIds.Contains(diag.Id));
return Task.FromResult(diags);
};
Func<Project, bool, ImmutableHashSet<string>, CancellationToken, Task<IEnumerable<Diagnostic>>> getProjectDiagnosticsAsync =
(p, includeAllDocumentDiagnostics, diagIds, c) =>
{
var diags = includeAllDocumentDiagnostics ?
testDriver.GetAllDiagnostics(provider, p) :
testDriver.GetProjectDiagnostics(provider, p);
diags = diags.Where(diag => diagIds.Contains(diag.Id));
return Task.FromResult(diags);
};
var diagnosticIds = ImmutableHashSet.Create(diagnostic.Id);
var fixAllDiagnosticProvider = new FixAllCodeActionContext.FixAllDiagnosticProvider(diagnosticIds, getDocumentDiagnosticsAsync, getProjectDiagnosticsAsync);
return diagnostic.Location.IsInSource ?
new FixAllContext(document, fixer, scope, fixAllActionId, diagnosticIds, fixAllDiagnosticProvider, CancellationToken.None) :
new FixAllContext(document.Project, fixer, scope, fixAllActionId, diagnosticIds, fixAllDiagnosticProvider, CancellationToken.None);
}
protected void TestEquivalenceKey(string initialMarkup, string equivalenceKey)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions: null, compilationOptions: null))
{
var diagnosticAndFix = GetDiagnosticAndFix(workspace);
Assert.Equal(equivalenceKey, diagnosticAndFix.Item2.Fixes.ElementAt(index: 0).Action.EquivalenceKey);
}
}
protected void TestActionCountInAllFixes(
string initialMarkup,
int count,
ParseOptions parseOptions = null, CompilationOptions compilationOptions = null)
{
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
var diagnosticAndFix = GetDiagnosticAndFixes(workspace, null);
var diagnosticCount = diagnosticAndFix.Select(x => x.Item2.Fixes.Count()).Sum();
Assert.Equal(count, diagnosticCount);
}
}
protected void TestSpans(
string initialMarkup, string expectedMarkup,
int index = 0,
ParseOptions parseOptions = null, CompilationOptions compilationOptions = null,
string diagnosticId = null, string fixAllActionEquivalenceId = null)
{
IList<TextSpan> spansList;
string unused;
MarkupTestFile.GetSpans(expectedMarkup, out unused, out spansList);
var expectedTextSpans = spansList.ToSet();
using (var workspace = CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions))
{
ISet<TextSpan> actualTextSpans;
if (diagnosticId == null)
{
var diagnosticsAndFixes = GetDiagnosticAndFixes(workspace, fixAllActionEquivalenceId);
var diagnostics = diagnosticsAndFixes.Select(t => t.Item1);
actualTextSpans = diagnostics.Select(d => d.Location.SourceSpan).ToSet();
}
else
{
var diagnostics = GetDiagnostics(workspace);
actualTextSpans = diagnostics.Where(d => d.Id == diagnosticId).Select(d => d.Location.SourceSpan).ToSet();
}
Assert.True(expectedTextSpans.SetEquals(actualTextSpans));
}
}
protected async Task TestAddDocument(
string initialMarkup, string expectedMarkup,
IList<string> expectedContainers,
string expectedDocumentName,
int index = 0,
bool compareTokens = true, bool isLine = true)
{
await TestAddDocument(initialMarkup, expectedMarkup, index, expectedContainers, expectedDocumentName, null, null, compareTokens, isLine).ConfigureAwait(true);
await TestAddDocument(initialMarkup, expectedMarkup, index, expectedContainers, expectedDocumentName, GetScriptOptions(), null, compareTokens, isLine).ConfigureAwait(true);
}
private async Task TestAddDocument(
string initialMarkup, string expectedMarkup,
int index,
IList<string> expectedContainers,
string expectedDocumentName,
ParseOptions parseOptions, CompilationOptions compilationOptions,
bool compareTokens, bool isLine)
{
using (var workspace = isLine ? CreateWorkspaceFromFile(initialMarkup, parseOptions, compilationOptions) : TestWorkspaceFactory.CreateWorkspace(initialMarkup))
{
var codeActions = GetCodeActions(workspace, fixAllActionEquivalenceKey: null);
await TestAddDocument(workspace, expectedMarkup, index, expectedContainers, expectedDocumentName,
codeActions, compareTokens).ConfigureAwait(true);
}
}
private async Task TestAddDocument(
TestWorkspace workspace,
string expectedMarkup,
int index,
IList<string> expectedFolders,
string expectedDocumentName,
IList<CodeAction> actions,
bool compareTokens)
{
var operations = VerifyInputsAndGetOperations(index, actions);
await TestAddDocument(
workspace,
expectedMarkup,
operations,
hasProjectChange: false,
modifiedProjectId: null,
expectedFolders: expectedFolders,
expectedDocumentName: expectedDocumentName,
compareTokens: compareTokens).ConfigureAwait(true);
}
private async Task<Tuple<Solution, Solution>> TestAddDocument(
TestWorkspace workspace,
string expected,
IEnumerable<CodeActionOperation> operations,
bool hasProjectChange,
ProjectId modifiedProjectId,
IList<string> expectedFolders,
string expectedDocumentName,
bool compareTokens)
{
var appliedChanges = ApplyOperationsAndGetSolution(workspace, operations);
var oldSolution = appliedChanges.Item1;
var newSolution = appliedChanges.Item2;
Document addedDocument = null;
if (!hasProjectChange)
{
addedDocument = SolutionUtilities.GetSingleAddedDocument(oldSolution, newSolution);
}
else
{
Assert.NotNull(modifiedProjectId);
addedDocument = newSolution.GetProject(modifiedProjectId).Documents.SingleOrDefault(doc => doc.Name == expectedDocumentName);
}
Assert.NotNull(addedDocument);
AssertEx.Equal(expectedFolders, addedDocument.Folders);
Assert.Equal(expectedDocumentName, addedDocument.Name);
if (compareTokens)
{
TokenUtilities.AssertTokensEqual(
expected, addedDocument.GetTextAsync().Result.ToString(), GetLanguage());
}
else
{
Assert.Equal(expected, addedDocument.GetTextAsync().Result.ToString());
}
var editHandler = workspace.ExportProvider.GetExportedValue<ICodeActionEditHandlerService>();
if (!hasProjectChange)
{
// If there is just one document change then we expect the preview to be a WpfTextView
var content = await editHandler.GetPreviews(workspace, operations, CancellationToken.None).TakeNextPreviewAsync().ConfigureAwait(true);
var diffView = content as IWpfDifferenceViewer;
Assert.NotNull(diffView);
diffView.Close();
}
else
{
// If there are more changes than just the document we need to browse all the changes and get the document change
var contents = editHandler.GetPreviews(workspace, operations, CancellationToken.None);
bool hasPreview = false;
object preview;
while ((preview = await contents.TakeNextPreviewAsync().ConfigureAwait(true)) != null)
{
var diffView = preview as IWpfDifferenceViewer;
if (diffView != null)
{
hasPreview = true;
diffView.Close();
break;
}
}
Assert.True(hasPreview);
}
return Tuple.Create(oldSolution, newSolution);
}
internal async Task TestWithMockedGenerateTypeDialog(
string initial,
string languageName,
string typeName,
string expected = null,
bool isLine = true,
bool isMissing = false,
Accessibility accessibility = Accessibility.NotApplicable,
TypeKind typeKind = TypeKind.Class,
string projectName = null,
bool isNewFile = false,
string existingFilename = null,
IList<string> newFileFolderContainers = null,
string fullFilePath = null,
string newFileName = null,
string assertClassName = null,
bool checkIfUsingsIncluded = false,
bool checkIfUsingsNotIncluded = false,
string expectedTextWithUsings = null,
string defaultNamespace = "",
bool areFoldersValidIdentifiers = true,
GenerateTypeDialogOptions assertGenerateTypeDialogOptions = null,
IList<TypeKindOptions> assertTypeKindPresent = null,
IList<TypeKindOptions> assertTypeKindAbsent = null,
bool isCancelled = false)
{
using (var testState = new GenerateTypeTestState(initial, isLine, projectName, typeName, existingFilename, languageName))
{
// Initialize the viewModel values
testState.TestGenerateTypeOptionsService.SetGenerateTypeOptions(
accessibility: accessibility,
typeKind: typeKind,
typeName: testState.TypeName,
project: testState.ProjectToBeModified,
isNewFile: isNewFile,
newFileName: newFileName,
folders: newFileFolderContainers,
fullFilePath: fullFilePath,
existingDocument: testState.ExistingDocument,
areFoldersValidIdentifiers: areFoldersValidIdentifiers,
isCancelled: isCancelled);
testState.TestProjectManagementService.SetDefaultNamespace(
defaultNamespace: defaultNamespace);
var diagnosticsAndFixes = GetDiagnosticAndFixes(testState.Workspace, null);
var generateTypeDiagFixes = diagnosticsAndFixes.SingleOrDefault(df => GenerateTypeTestState.FixIds.Contains(df.Item1.Id));
if (isMissing)
{
Assert.Null(generateTypeDiagFixes);
return;
}
var fixes = generateTypeDiagFixes.Item2.Fixes;
Assert.NotNull(fixes);
var fixActions = MassageActions(fixes.Select(f => f.Action).ToList());
Assert.NotNull(fixActions);
// Since the dialog option is always fed as the last CodeAction
var index = fixActions.Count() - 1;
var action = fixActions.ElementAt(index);
Assert.Equal(action.Title, FeaturesResources.GenerateNewType);
var operations = action.GetOperationsAsync(CancellationToken.None).Result;
Tuple<Solution, Solution> oldSolutionAndNewSolution = null;
if (!isNewFile)
{
oldSolutionAndNewSolution = TestOperations(
testState.Workspace, expected, operations,
conflictSpans: null, renameSpans: null, warningSpans: null,
compareTokens: false, expectedChangedDocumentId: testState.ExistingDocument.Id);
}
else
{
oldSolutionAndNewSolution = await TestAddDocument(
testState.Workspace,
expected,
operations,
projectName != null,
testState.ProjectToBeModified.Id,
newFileFolderContainers,
newFileName,
compareTokens: false).ConfigureAwait(true);
}
if (checkIfUsingsIncluded)
{
Assert.NotNull(expectedTextWithUsings);
TestOperations(testState.Workspace, expectedTextWithUsings, operations,
conflictSpans: null, renameSpans: null, warningSpans: null, compareTokens: false,
expectedChangedDocumentId: testState.InvocationDocument.Id);
}
if (checkIfUsingsNotIncluded)
{
var oldSolution = oldSolutionAndNewSolution.Item1;
var newSolution = oldSolutionAndNewSolution.Item2;
var changedDocumentIds = SolutionUtilities.GetChangedDocuments(oldSolution, newSolution);
Assert.False(changedDocumentIds.Contains(testState.InvocationDocument.Id));
}
// Added into a different project than the triggering project
if (projectName != null)
{
var appliedChanges = ApplyOperationsAndGetSolution(testState.Workspace, operations);
var newSolution = appliedChanges.Item2;
var triggeredProject = newSolution.GetProject(testState.TriggeredProject.Id);
// Make sure the Project reference is present
Assert.True(triggeredProject.ProjectReferences.Any(pr => pr.ProjectId == testState.ProjectToBeModified.Id));
}
// Assert Option Calculation
if (assertClassName != null)
{
Assert.True(assertClassName == testState.TestGenerateTypeOptionsService.ClassName);
}
if (assertGenerateTypeDialogOptions != null || assertTypeKindPresent != null || assertTypeKindAbsent != null)
{
var generateTypeDialogOptions = testState.TestGenerateTypeOptionsService.GenerateTypeDialogOptions;
if (assertGenerateTypeDialogOptions != null)
{
Assert.True(assertGenerateTypeDialogOptions.IsPublicOnlyAccessibility == generateTypeDialogOptions.IsPublicOnlyAccessibility);
Assert.True(assertGenerateTypeDialogOptions.TypeKindOptions == generateTypeDialogOptions.TypeKindOptions);
Assert.True(assertGenerateTypeDialogOptions.IsAttribute == generateTypeDialogOptions.IsAttribute);
}
if (assertTypeKindPresent != null)
{
foreach (var typeKindPresentEach in assertTypeKindPresent)
{
Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) != 0);
}
}
if (assertTypeKindAbsent != null)
{
foreach (var typeKindPresentEach in assertTypeKindAbsent)
{
Assert.True((typeKindPresentEach & generateTypeDialogOptions.TypeKindOptions) == 0);
}
}
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.