context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
/***************************************************************************
* Folder.cs
*
* Copyright (C) 2006-2007 Alan McGovern
* Authors:
* Alan McGovern (alan.mcgovern@gmail.com)
****************************************************************************/
/* THIS FILE IS LICENSED UNDER THE MIT LICENSE AS OUTLINED IMMEDIATELY BELOW:
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Mtp
{
public class Folder
{
private MtpDevice device;
private uint folderId;
private uint parentId;
private string name;
internal uint FolderId
{
get { return folderId; }
}
public string Name
{
get { return name; }
}
internal uint ParentId
{
get { return parentId; }
}
internal Folder (uint folderId, uint parentId, string name, MtpDevice device)
{
this.device = device;
this.folderId = folderId;
this.parentId = parentId;
this.name = name;
}
internal Folder (FolderStruct folder, MtpDevice device)
: this (folder.folder_id, folder.parent_id, folder.name, device)
{
}
public Folder AddChild(string name)
{
if (string.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
// First create the folder on the device and check for error
uint id = CreateFolder (device.Handle, name, FolderId);
FolderStruct f = new FolderStruct();
f.folder_id = id;
f.parent_id = FolderId;
f.name = name;
return new Folder(f, device);
}
public List<Folder> GetChildren ()
{
using (FolderHandle handle = GetFolderList(device.Handle))
{
// Find the pointer to the folderstruct representing this folder
IntPtr ptr = handle.DangerousGetHandle();
ptr = Find (ptr, folderId);
FolderStruct f = (FolderStruct)Marshal.PtrToStructure(ptr, typeof(FolderStruct));
ptr = f.child;
List<Folder> folders = new List<Folder>();
while (ptr != IntPtr.Zero)
{
FolderStruct folder = (FolderStruct)Marshal.PtrToStructure(ptr, typeof(FolderStruct));
folders.Add(new Folder(folder, device));
ptr = folder.sibling;
}
return folders;
}
}
public void Remove()
{
MtpDevice.DeleteObject(device.Handle, FolderId);
}
public override string ToString ()
{
return String.Format ("{0} (id {1}, parent id {2})", Name, FolderId, ParentId);
}
internal static List<Folder> GetRootFolders (MtpDevice device)
{
List<Folder> folders = new List<Folder>();
using (FolderHandle handle = GetFolderList (device.Handle))
{
for (IntPtr ptr = handle.DangerousGetHandle(); ptr != IntPtr.Zero;)
{
FolderStruct folder = (FolderStruct)Marshal.PtrToStructure(ptr, typeof(FolderStruct));
folders.Add(new Folder (folder, device));
ptr = folder.sibling;
}
return folders;
}
}
internal static uint CreateFolder (MtpDeviceHandle handle, string name, uint parentId)
{
#if LIBMTP8
uint result = LIBMTP_Create_Folder (handle, name, parentId, 0);
#else
uint result = LIBMTP_Create_Folder (handle, name, parentId);
#endif
if (result == 0)
{
LibMtpException.CheckErrorStack(handle);
throw new LibMtpException(ErrorCode.General, "Could not create folder on the device");
}
return result;
}
internal static void DestroyFolder (IntPtr folder)
{
LIBMTP_destroy_folder_t (folder);
}
internal static IntPtr Find (IntPtr folderList, uint folderId )
{
return LIBMTP_Find_Folder (folderList, folderId);
}
internal static FolderHandle GetFolderList (MtpDeviceHandle handle)
{
IntPtr ptr = LIBMTP_Get_Folder_List (handle);
return new FolderHandle(ptr);
}
// Folder Management
//[DllImport("libmtp.dll")]
//private static extern IntPtr LIBMTP_new_folder_t (); // LIBMTP_folder_t*
[DllImport("libmtp.dll")]
private static extern void LIBMTP_destroy_folder_t (IntPtr folder);
[DllImport("libmtp.dll")]
private static extern IntPtr LIBMTP_Get_Folder_List (MtpDeviceHandle handle); // LIBMTP_folder_t*
[DllImport("libmtp.dll")]
private static extern IntPtr LIBMTP_Find_Folder (IntPtr folderList, uint folderId); // LIBMTP_folder_t*
#if LIBMTP8
[DllImport("libmtp.dll")]
private static extern uint LIBMTP_Create_Folder (MtpDeviceHandle handle, string name, uint parentId, uint storageId);
#else
[DllImport("libmtp.dll")]
private static extern uint LIBMTP_Create_Folder (MtpDeviceHandle handle, string name, uint parentId);
#endif
}
internal class FolderHandle : SafeHandle
{
private FolderHandle()
: base(IntPtr.Zero, true)
{
}
internal FolderHandle(IntPtr ptr)
: this(ptr, true)
{
}
internal FolderHandle(IntPtr ptr, bool ownsHandle)
: base (IntPtr.Zero, ownsHandle)
{
SetHandle (ptr);
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override bool ReleaseHandle ()
{
Folder.DestroyFolder (handle);
return true;
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct FolderStruct
{
public uint folder_id;
public uint parent_id;
#if LIBMTP8
public uint storage_id;
#endif
[MarshalAs(UnmanagedType.LPStr)] public string name;
public IntPtr sibling; // LIBMTP_folder_t*
public IntPtr child; // LIBMTP_folder_t*
/*
public object NextSibling
{
get
{
if(sibling == IntPtr.Zero)
return null;
return (FolderStruct)Marshal.PtrToStructure(sibling, typeof(Folder));
}
}
public object NextChild
{
get
{
if(child == IntPtr.Zero)
return null;
return (FolderStruct)Marshal.PtrToStructure(child, typeof(Folder));
}
}
public Folder? Sibling
{
get
{
if (sibling == IntPtr.Zero)
return null;
return (Folder)Marshal.PtrToStructure(sibling, typeof(Folder));
}
}
public Folder? Child
{
get
{
if (child == IntPtr.Zero)
return null;
return (Folder)Marshal.PtrToStructure(child, typeof(Folder));
}
}*/
/*public IEnumerable<Folder> Children()
{
Folder? current = Child;
while(current.HasValue)
{
yield return current.Value;
current = current.Value.Child;
}
}*/
/*public IEnumerable<Folder> Siblings()
{
Folder? current = Sibling;
while(current.HasValue)
{
yield return current.Value;
current = current.Value.Sibling;
}
}*/
}
}
| |
// 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.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Internal;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging.Testing;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
using Xunit;
namespace Microsoft.AspNetCore.Session
{
public class SessionTests
{
[Fact]
public async Task ReadingEmptySessionDoesNotCreateCookie()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(context =>
{
Assert.Null(context.Session.GetString("NotFound"));
return Task.FromResult(0);
});
})
.ConfigureServices(services =>
{
services.AddDistributedMemoryCache();
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
Assert.False(response.Headers.TryGetValues("Set-Cookie", out var _));
}
}
[Fact]
public async Task SettingAValueCausesTheCookieToBeCreated()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(context =>
{
Assert.Null(context.Session.GetString("Key"));
context.Session.SetString("Key", "Value");
Assert.Equal("Value", context.Session.GetString("Key"));
return Task.FromResult(0);
});
})
.ConfigureServices(services =>
{
services.AddDistributedMemoryCache();
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
Assert.True(response.Headers.TryGetValues("Set-Cookie", out var values));
Assert.Single(values);
Assert.True(!string.IsNullOrWhiteSpace(values.First()));
}
}
[Theory]
[InlineData(CookieSecurePolicy.Always, "http://example.com/testpath", true)]
[InlineData(CookieSecurePolicy.Always, "https://example.com/testpath", true)]
[InlineData(CookieSecurePolicy.None, "http://example.com/testpath", false)]
[InlineData(CookieSecurePolicy.None, "https://example.com/testpath", false)]
[InlineData(CookieSecurePolicy.SameAsRequest, "http://example.com/testpath", false)]
[InlineData(CookieSecurePolicy.SameAsRequest, "https://example.com/testpath", true)]
public async Task SecureSessionBasedOnHttpsAndSecurePolicy(
CookieSecurePolicy cookieSecurePolicy,
string requestUri,
bool shouldBeSecureOnly)
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession(new SessionOptions
{
Cookie =
{
Name = "TestCookie",
SecurePolicy = cookieSecurePolicy
}
});
app.Run(context =>
{
Assert.Null(context.Session.GetString("Key"));
context.Session.SetString("Key", "Value");
Assert.Equal("Value", context.Session.GetString("Key"));
return Task.FromResult(0);
});
})
.ConfigureServices(services =>
{
services.AddDistributedMemoryCache();
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(requestUri);
response.EnsureSuccessStatusCode();
Assert.True(response.Headers.TryGetValues("Set-Cookie", out var values));
Assert.Single(values);
if (shouldBeSecureOnly)
{
Assert.Contains("; secure", values.First());
}
else
{
Assert.DoesNotContain("; secure", values.First());
}
}
}
[Fact]
public async Task SessionCanBeAccessedOnTheNextRequest()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(context =>
{
int? value = context.Session.GetInt32("Key");
if (context.Request.Path == new PathString("/first"))
{
Assert.False(value.HasValue);
value = 0;
}
Assert.True(value.HasValue);
context.Session.SetInt32("Key", value.Value + 1);
return context.Response.WriteAsync(value.Value.ToString(CultureInfo.InvariantCulture));
});
})
.ConfigureServices(services =>
{
services.AddDistributedMemoryCache();
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync("first");
response.EnsureSuccessStatusCode();
Assert.Equal("0", await response.Content.ReadAsStringAsync());
client = server.CreateClient();
var cookie = SetCookieHeaderValue.ParseList(response.Headers.GetValues("Set-Cookie").ToList()).First();
client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
Assert.Equal("1", await client.GetStringAsync("/"));
Assert.Equal("2", await client.GetStringAsync("/"));
Assert.Equal("3", await client.GetStringAsync("/"));
}
}
[Fact]
public async Task RemovedItemCannotBeAccessedAgain()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(context =>
{
int? value = context.Session.GetInt32("Key");
if (context.Request.Path == new PathString("/first"))
{
Assert.False(value.HasValue);
value = 0;
context.Session.SetInt32("Key", 1);
}
else if (context.Request.Path == new PathString("/second"))
{
Assert.True(value.HasValue);
Assert.Equal(1, value);
context.Session.Remove("Key");
}
else if (context.Request.Path == new PathString("/third"))
{
Assert.False(value.HasValue);
value = 2;
}
return context.Response.WriteAsync(value.Value.ToString(CultureInfo.InvariantCulture));
});
})
.ConfigureServices(
services =>
{
services.AddDistributedMemoryCache();
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync("first");
response.EnsureSuccessStatusCode();
Assert.Equal("0", await response.Content.ReadAsStringAsync());
client = server.CreateClient();
var cookie = SetCookieHeaderValue.ParseList(response.Headers.GetValues("Set-Cookie").ToList()).First();
client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
Assert.Equal("1", await client.GetStringAsync("/second"));
Assert.Equal("2", await client.GetStringAsync("/third"));
}
}
[Fact]
public async Task ClearedItemsCannotBeAccessedAgain()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(context =>
{
int? value = context.Session.GetInt32("Key");
if (context.Request.Path == new PathString("/first"))
{
Assert.False(value.HasValue);
value = 0;
context.Session.SetInt32("Key", 1);
}
else if (context.Request.Path == new PathString("/second"))
{
Assert.True(value.HasValue);
Assert.Equal(1, value);
context.Session.Clear();
}
else if (context.Request.Path == new PathString("/third"))
{
Assert.False(value.HasValue);
value = 2;
}
return context.Response.WriteAsync(value.Value.ToString(CultureInfo.InvariantCulture));
});
})
.ConfigureServices(services =>
{
services.AddDistributedMemoryCache();
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync("first");
response.EnsureSuccessStatusCode();
Assert.Equal("0", await response.Content.ReadAsStringAsync());
client = server.CreateClient();
var cookie = SetCookieHeaderValue.ParseList(response.Headers.GetValues("Set-Cookie").ToList()).First();
client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
Assert.Equal("1", await client.GetStringAsync("/second"));
Assert.Equal("2", await client.GetStringAsync("/third"));
}
}
[Fact]
public async Task SessionStart_LogsInformation()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<DistributedSession>,
TestSink.EnableWithTypeName<DistributedSession>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(context =>
{
context.Session.SetString("Key", "Value");
return Task.FromResult(0);
});
})
.ConfigureServices(services =>
{
services.AddSingleton(typeof(ILoggerFactory), loggerFactory);
services.AddDistributedMemoryCache();
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
}
var sessionLogMessages = sink.Writes.ToList();
Assert.Equal(2, sessionLogMessages.Count);
Assert.Contains("started", sessionLogMessages[0].State.ToString());
Assert.Equal(LogLevel.Information, sessionLogMessages[0].LogLevel);
Assert.Contains("stored", sessionLogMessages[1].State.ToString());
Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel);
}
[Fact]
public async Task ExpiredSession_LogsInfo()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<DistributedSession>,
TestSink.EnableWithTypeName<DistributedSession>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(context =>
{
int? value = context.Session.GetInt32("Key");
if (context.Request.Path == new PathString("/first"))
{
Assert.False(value.HasValue);
value = 1;
context.Session.SetInt32("Key", 1);
}
else if (context.Request.Path == new PathString("/second"))
{
Assert.False(value.HasValue);
value = 2;
}
return context.Response.WriteAsync(value.Value.ToString(CultureInfo.InvariantCulture));
});
})
.ConfigureServices(services =>
{
services.AddSingleton(typeof(ILoggerFactory), loggerFactory);
services.AddDistributedMemoryCache();
services.AddSession(o => o.IdleTimeout = TimeSpan.FromMilliseconds(30));
});
}).Build();
await host.StartAsync();
string result;
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync("first");
response.EnsureSuccessStatusCode();
client = server.CreateClient();
var cookie = SetCookieHeaderValue.ParseList(response.Headers.GetValues("Set-Cookie").ToList()).First();
client.DefaultRequestHeaders.Add("Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
Thread.Sleep(50);
result = await client.GetStringAsync("/second");
}
var sessionLogMessages = sink.Writes.ToList();
Assert.Equal("2", result);
Assert.Equal(3, sessionLogMessages.Count);
Assert.Contains("started", sessionLogMessages[0].State.ToString());
Assert.Contains("stored", sessionLogMessages[1].State.ToString());
Assert.Contains("expired", sessionLogMessages[2].State.ToString());
Assert.Equal(LogLevel.Information, sessionLogMessages[0].LogLevel);
Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel);
Assert.Equal(LogLevel.Information, sessionLogMessages[2].LogLevel);
}
[Fact]
public async Task RefreshesSession_WhenSessionData_IsNotModified()
{
var clock = new TestClock();
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(context =>
{
string responseData = string.Empty;
if (context.Request.Path == new PathString("/AddDataToSession"))
{
context.Session.SetInt32("Key", 10);
responseData = "added data to session";
}
else if (context.Request.Path == new PathString("/AccessSessionData"))
{
var value = context.Session.GetInt32("Key");
responseData = (value == null) ? "No value found in session." : value.ToString();
}
else if (context.Request.Path == new PathString("/DoNotAccessSessionData"))
{
responseData = "did not access session data";
}
return context.Response.WriteAsync(responseData);
});
})
.ConfigureServices(services =>
{
services.AddSingleton(typeof(ILoggerFactory), NullLoggerFactory.Instance);
services.AddDistributedMemoryCache();
services.AddSession(o => o.IdleTimeout = TimeSpan.FromMinutes(20));
services.Configure<MemoryCacheOptions>(o => o.Clock = clock);
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync("AddDataToSession");
response.EnsureSuccessStatusCode();
client = server.CreateClient();
var cookie = SetCookieHeaderValue.ParseList(response.Headers.GetValues("Set-Cookie").ToList()).First();
client.DefaultRequestHeaders.Add(
"Cookie", new CookieHeaderValue(cookie.Name, cookie.Value).ToString());
for (var i = 0; i < 5; i++)
{
clock.Add(TimeSpan.FromMinutes(10));
await client.GetStringAsync("/DoNotAccessSessionData");
}
var data = await client.GetStringAsync("/AccessSessionData");
Assert.Equal("10", data);
}
}
[Fact]
public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.Use(async (httpContext, next) =>
{
await next(httpContext);
Assert.Null(httpContext.Features.Get<ISessionFeature>());
});
app.UseSession();
app.Run(context =>
{
context.Session.SetString("key", "value");
return Task.FromResult(0);
});
})
.ConfigureServices(services =>
{
services.AddDistributedMemoryCache();
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
}
}
[Fact]
public async Task SessionFeature_IsUnregistered_WhenResponseGoingOut_AndAnUnhandledExcetionIsThrown()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.Use(async (httpContext, next) =>
{
var exceptionThrown = false;
try
{
await next(httpContext);
}
catch
{
exceptionThrown = true;
}
Assert.True(exceptionThrown);
Assert.Null(httpContext.Features.Get<ISessionFeature>());
});
app.UseSession();
app.Run(context =>
{
throw new InvalidOperationException("An error occurred.");
});
})
.ConfigureServices(services =>
{
services.AddDistributedMemoryCache();
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
}
}
[Fact]
public async Task SessionKeys_AreCaseSensitive()
{
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(context =>
{
context.Session.SetString("KEY", "VALUE");
context.Session.SetString("key", "value");
Assert.Equal("VALUE", context.Session.GetString("KEY"));
Assert.Equal("value", context.Session.GetString("key"));
return Task.FromResult(0);
});
})
.ConfigureServices(services =>
{
services.AddDistributedMemoryCache();
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
}
}
[Fact]
public async Task SessionLogsCacheReadException()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<DistributedSession>,
TestSink.EnableWithTypeName<DistributedSession>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(context =>
{
Assert.False(context.Session.TryGetValue("key", out var value));
Assert.Null(value);
Assert.Equal(string.Empty, context.Session.Id);
Assert.False(context.Session.Keys.Any());
return Task.FromResult(0);
});
})
.ConfigureServices(services =>
{
services.AddSingleton(typeof(ILoggerFactory), loggerFactory);
services.AddSingleton<IDistributedCache>(new UnreliableCache(new MemoryCache(new MemoryCacheOptions()))
{
DisableGet = true
});
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
}
Assert.NotEmpty(sink.Writes);
var message = sink.Writes.First();
Assert.Contains("Session cache read exception", message.State.ToString());
Assert.Equal(LogLevel.Error, message.LogLevel);
}
[Fact]
public async Task SessionLogsCacheLoadAsyncException()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<DistributedSession>,
TestSink.EnableWithTypeName<DistributedSession>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(async context =>
{
await Assert.ThrowsAsync<InvalidOperationException>(() => context.Session.LoadAsync());
Assert.False(context.Session.IsAvailable);
Assert.Equal(string.Empty, context.Session.Id);
Assert.False(context.Session.Keys.Any());
});
})
.ConfigureServices(services =>
{
services.AddSingleton(typeof(ILoggerFactory), loggerFactory);
services.AddSingleton<IDistributedCache>(new UnreliableCache(new MemoryCache(new MemoryCacheOptions()))
{
DisableGet = true
});
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
}
Assert.NotEmpty(sink.Writes);
var message = sink.Writes.First();
Assert.Contains("Session cache read exception", message.State.ToString());
Assert.Equal(LogLevel.Error, message.LogLevel);
}
[Fact]
public async Task SessionLogsCacheLoadAsyncTimeoutException()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<DistributedSession>,
TestSink.EnableWithTypeName<DistributedSession>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession(new SessionOptions()
{
IOTimeout = TimeSpan.FromSeconds(0.5)
});
app.Run(async context =>
{
await Assert.ThrowsAsync<OperationCanceledException>(() => context.Session.LoadAsync());
});
})
.ConfigureServices(services =>
{
services.AddSingleton(typeof(ILoggerFactory), loggerFactory);
services.AddSingleton<IDistributedCache>(new UnreliableCache(new MemoryCache(new MemoryCacheOptions()))
{
DelayGetAsync = true
});
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
}
var message = Assert.Single(sink.Writes);
Assert.Contains("Loading the session timed out.", message.State.ToString());
Assert.Equal(LogLevel.Warning, message.LogLevel);
}
[Fact]
public async Task SessionLoadAsyncCanceledException()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<DistributedSession>,
TestSink.EnableWithTypeName<DistributedSession>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(async context =>
{
var cts = new CancellationTokenSource();
var token = cts.Token;
cts.Cancel();
await Assert.ThrowsAsync<OperationCanceledException>(() => context.Session.LoadAsync(token));
});
})
.ConfigureServices(services =>
{
services.AddSingleton(typeof(ILoggerFactory), loggerFactory);
services.AddSingleton<IDistributedCache>(new UnreliableCache(new MemoryCache(new MemoryCacheOptions()))
{
DelayGetAsync = true
});
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
}
Assert.Empty(sink.Writes);
}
[Fact]
public async Task SessionLogsCacheCommitException()
{
var sink = new TestSink(
writeContext =>
{
return writeContext.LoggerName.Equals(typeof(SessionMiddleware).FullName)
|| writeContext.LoggerName.Equals(typeof(DistributedSession).FullName);
},
beginScopeContext =>
{
return beginScopeContext.LoggerName.Equals(typeof(SessionMiddleware).FullName)
|| beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName);
});
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(context =>
{
context.Session.SetInt32("key", 0);
return Task.FromResult(0);
});
})
.ConfigureServices(services =>
{
services.AddSingleton(typeof(ILoggerFactory), loggerFactory);
services.AddSingleton<IDistributedCache>(new UnreliableCache(new MemoryCache(new MemoryCacheOptions()))
{
DisableSetAsync = true
});
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
}
var sessionLogMessage = sink.Writes.Where(message => message.LoggerName.Equals(typeof(DistributedSession).FullName, StringComparison.Ordinal)).Single();
Assert.Contains("Session started", sessionLogMessage.State.ToString());
Assert.Equal(LogLevel.Information, sessionLogMessage.LogLevel);
var sessionMiddlewareLogMessage = sink.Writes.Where(message => message.LoggerName.Equals(typeof(SessionMiddleware).FullName, StringComparison.Ordinal)).Single();
Assert.Contains("Error closing the session.", sessionMiddlewareLogMessage.State.ToString());
Assert.Equal(LogLevel.Error, sessionMiddlewareLogMessage.LogLevel);
}
[Fact]
public async Task SessionLogsCacheCommitTimeoutException()
{
var sink = new TestSink(
writeContext =>
{
return writeContext.LoggerName.Equals(typeof(SessionMiddleware).FullName)
|| writeContext.LoggerName.Equals(typeof(DistributedSession).FullName);
},
beginScopeContext =>
{
return beginScopeContext.LoggerName.Equals(typeof(SessionMiddleware).FullName)
|| beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName);
});
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession(new SessionOptions()
{
IOTimeout = TimeSpan.FromSeconds(0.5)
});
app.Run(context =>
{
context.Session.SetInt32("key", 0);
return Task.FromResult(0);
});
})
.ConfigureServices(services =>
{
services.AddSingleton(typeof(ILoggerFactory), loggerFactory);
services.AddSingleton<IDistributedCache>(new UnreliableCache(new MemoryCache(new MemoryCacheOptions()))
{
DelaySetAsync = true
});
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
}
var sessionLogMessages = sink.Writes.Where(message => message.LoggerName.Equals(typeof(DistributedSession).FullName, StringComparison.Ordinal)).ToList();
Assert.Contains("Session started", sessionLogMessages[0].State.ToString());
Assert.Equal(LogLevel.Information, sessionLogMessages[0].LogLevel);
Assert.Contains("Committing the session timed out.", sessionLogMessages[1].State.ToString());
Assert.Equal(LogLevel.Warning, sessionLogMessages[1].LogLevel);
var sessionMiddlewareLogs = sink.Writes.Where(message => message.LoggerName.Equals(typeof(SessionMiddleware).FullName, StringComparison.Ordinal)).ToList();
Assert.Contains("Committing the session was canceled.", sessionMiddlewareLogs[0].State.ToString());
Assert.Equal(LogLevel.Information, sessionMiddlewareLogs[0].LogLevel);
}
[Fact]
public async Task SessionLogsCacheCommitCanceledException()
{
var sink = new TestSink(
writeContext =>
{
return writeContext.LoggerName.Equals(typeof(SessionMiddleware).FullName)
|| writeContext.LoggerName.Equals(typeof(DistributedSession).FullName);
},
beginScopeContext =>
{
return beginScopeContext.LoggerName.Equals(typeof(SessionMiddleware).FullName)
|| beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName);
});
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(async context =>
{
context.Session.SetInt32("key", 0);
var cts = new CancellationTokenSource();
var token = cts.Token;
cts.Cancel();
await Assert.ThrowsAsync<OperationCanceledException>(() => context.Session.CommitAsync(token));
});
})
.ConfigureServices(services =>
{
services.AddSingleton(typeof(ILoggerFactory), loggerFactory);
services.AddSingleton<IDistributedCache>(new UnreliableCache(new MemoryCache(new MemoryCacheOptions()))
{
DelaySetAsync = true
});
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
}
// The session is automatically committed on unwind even after the manual commit was canceled.
var sessionLogMessages = sink.Writes.Where(message => message.LoggerName.Equals(typeof(DistributedSession).FullName, StringComparison.Ordinal)).ToList();
Assert.Contains("Session started", sessionLogMessages[0].State.ToString());
Assert.Equal(LogLevel.Information, sessionLogMessages[0].LogLevel);
Assert.Contains("Session stored", sessionLogMessages[1].State.ToString());
Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel);
Assert.Empty(sink.Writes.Where(message => message.LoggerName.Equals(typeof(SessionMiddleware).FullName, StringComparison.Ordinal)));
}
[Fact]
public async Task RequestAbortedIgnored()
{
var sink = new TestSink(
writeContext =>
{
return writeContext.LoggerName.Equals(typeof(SessionMiddleware).FullName)
|| writeContext.LoggerName.Equals(typeof(DistributedSession).FullName);
},
beginScopeContext =>
{
return beginScopeContext.LoggerName.Equals(typeof(SessionMiddleware).FullName)
|| beginScopeContext.LoggerName.Equals(typeof(DistributedSession).FullName);
});
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(context =>
{
context.Session.SetInt32("key", 0);
var cts = new CancellationTokenSource();
var token = cts.Token;
cts.Cancel();
context.RequestAborted = token;
return Task.CompletedTask;
});
})
.ConfigureServices(services =>
{
services.AddSingleton(typeof(ILoggerFactory), loggerFactory);
services.AddSingleton<IDistributedCache>(new UnreliableCache(new MemoryCache(new MemoryCacheOptions()))
{
DelaySetAsync = true
});
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
}
var sessionLogMessages = sink.Writes.Where(message => message.LoggerName.Equals(typeof(DistributedSession).FullName, StringComparison.Ordinal)).ToList();
Assert.Contains("Session started", sessionLogMessages[0].State.ToString());
Assert.Equal(LogLevel.Information, sessionLogMessages[0].LogLevel);
Assert.Contains("Session stored", sessionLogMessages[1].State.ToString());
Assert.Equal(LogLevel.Debug, sessionLogMessages[1].LogLevel);
Assert.Empty(sink.Writes.Where(message => message.LoggerName.Equals(typeof(SessionMiddleware).FullName, StringComparison.Ordinal)));
}
[Fact]
public async Task SessionLogsCacheRefreshException()
{
var sink = new TestSink(
TestSink.EnableWithTypeName<SessionMiddleware>,
TestSink.EnableWithTypeName<SessionMiddleware>);
var loggerFactory = new TestLoggerFactory(sink, enabled: true);
using var host = new HostBuilder()
.ConfigureWebHost(webHostBuilder =>
{
webHostBuilder
.UseTestServer()
.Configure(app =>
{
app.UseSession();
app.Run(context =>
{
// The middleware calls context.Session.CommitAsync() once per request
return Task.FromResult(0);
});
})
.ConfigureServices(services =>
{
services.AddSingleton(typeof(ILoggerFactory), loggerFactory);
services.AddSingleton<IDistributedCache>(new UnreliableCache(new MemoryCache(new MemoryCacheOptions()))
{
DisableRefreshAsync = true
});
services.AddSession();
});
}).Build();
await host.StartAsync();
using (var server = host.GetTestServer())
{
var client = server.CreateClient();
var response = await client.GetAsync(string.Empty);
response.EnsureSuccessStatusCode();
}
var message = Assert.Single(sink.Writes);
Assert.Contains("Error closing the session.", message.State.ToString());
Assert.Equal(LogLevel.Error, message.LogLevel);
}
private class TestClock : ISystemClock
{
public TestClock()
{
UtcNow = new DateTimeOffset(2013, 1, 1, 1, 0, 0, TimeSpan.Zero);
}
public DateTimeOffset UtcNow { get; private set; }
public void Add(TimeSpan timespan)
{
UtcNow = UtcNow.Add(timespan);
}
}
private class UnreliableCache : IDistributedCache
{
private readonly MemoryDistributedCache _cache;
public bool DisableGet { get; set; }
public bool DisableSetAsync { get; set; }
public bool DisableRefreshAsync { get; set; }
public bool DelayGetAsync { get; set; }
public bool DelaySetAsync { get; set; }
public bool DelayRefreshAsync { get; set; }
public UnreliableCache(IMemoryCache memoryCache)
{
_cache = new MemoryDistributedCache(Options.Create(new MemoryDistributedCacheOptions()));
}
public byte[] Get(string key)
{
if (DisableGet)
{
throw new InvalidOperationException();
}
return _cache.Get(key);
}
public Task<byte[]> GetAsync(string key, CancellationToken token = default)
{
if (DisableGet)
{
throw new InvalidOperationException();
}
if (DelayGetAsync)
{
token.WaitHandle.WaitOne(TimeSpan.FromSeconds(10));
token.ThrowIfCancellationRequested();
}
return _cache.GetAsync(key, token);
}
public void Refresh(string key) => _cache.Refresh(key);
public Task RefreshAsync(string key, CancellationToken token = default)
{
if (DisableRefreshAsync)
{
throw new InvalidOperationException();
}
if (DelayRefreshAsync)
{
token.WaitHandle.WaitOne(TimeSpan.FromSeconds(10));
token.ThrowIfCancellationRequested();
}
return _cache.RefreshAsync(key);
}
public void Remove(string key) => _cache.Remove(key);
public Task RemoveAsync(string key, CancellationToken token = default) => _cache.RemoveAsync(key);
public void Set(string key, byte[] value, DistributedCacheEntryOptions options) => _cache.Set(key, value, options);
public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default)
{
if (DisableSetAsync)
{
throw new InvalidOperationException();
}
if (DelaySetAsync)
{
token.WaitHandle.WaitOne(TimeSpan.FromSeconds(10));
token.ThrowIfCancellationRequested();
}
return _cache.SetAsync(key, value, options);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Script.Serialization;
using ILPathways.Business;
using ILPathways.Common;
using ILPathways.Utilities;
//using Isle.DataContracts;
using LearningRegistry;
using LearningRegistry.RDDD;
using LRWarehouse.Business;
using LRWarehouse.DAL;
using AcctManager = Isle.BizServices.AccountServices;
using DBM = ILPathways.DAL.DatabaseManager;
using DocManager = ILPathways.DAL.DocumentStoreManager;
using EFDAL = IoerContentBusinessEntities;
using EFManager = IoerContentBusinessEntities.EFContentManager;
using GroupManager = Isle.BizServices.GroupServices;
using MyManager = Isle.BizServices.ContentServices;
//using MyManager = ILPathways.DAL.ContentManager;
using OrgManager = Isle.BizServices.OrganizationBizService;
using ResourceManager = LRWarehouse.DAL.ResourceManager;
using ThisUser = LRWarehouse.Business.Patron;
//using Thumbnailer = LRWarehouse.DAL.ResourceThumbnailManager;
namespace Isle.BizServices
{
public class PublishingServices : ServiceHelper
{
static string thisClassName = "PublishingServices";
MyManager myMgr = new MyManager();
//static ServiceHelper helper = new ServiceHelper();
public PublishingServices()
{ }//
#region --- content approvals ---
/// <summary>
/// Handle request to approve a content record
/// </summary>
/// <param name="resource"></param>
/// <param name="contentId"></param>
/// <param name="user"></param>
/// /// <param name="hasApproval">return true if approval was required</param>
/// <param name="statusMessage"></param>
/// <returns>true if ok, false if errors</returns>
public static bool HandleContentApproval( Resource resource, int contentId, ThisUser author, ref bool hasApproval, ref string statusMessage )
{
// - get record, check if on behalf is org
// if not, set to published?
// -
bool isValid = true;
hasApproval = false;
MyManager mgr = new MyManager();
ContentItem entity = mgr.Get( contentId );
if ( entity == null || entity.Id == 0 )
{
//invalid, return, log error?
statusMessage = "Invalid request, record was not found.";
return false;
}
//entity.ResourceVersionId = resource.Version.Id;
entity.ResourceIntId = resource.Id;
if ( entity.IsOrgContent() == false )
{
entity.StatusId = ContentItem.PUBLISHED_STATUS;
mgr.Update( entity );
//TODO - anything else??
return true;
}
hasApproval = true;
//get approvers for org
SubmitApprovalRequest( entity );
//update status
entity.StatusId = ContentItem.SUBMITTED_STATUS;
mgr.Update( entity );
//set resource to inactive
string status = new ResourceManager().SetResourceActiveState( resource.Id, false );
//add record to audit table
string msg = string.Format( "Request by {0} for approval of resource id: {1}", author.FullName(), entity.Id );
mgr.ContentHistory_Create( contentId, "Approval Request - new", msg, author.Id, ref statusMessage );
return isValid;
}//
/// <summary>
/// Request approval for a content item
/// - resource tagging, and LR publishing (or caching) would have already occured
/// - typically used where a previous submission was denied or author has made updates to an previously approved content item
/// </summary>
/// <param name="contentId"></param>
/// <param name="author"></param>
/// <param name="statusMessage"></param>
/// <returns></returns>
public static bool RequestApproval( int contentId, ThisUser author, ref string statusMessage )
{
//TODO - should resource be set inactive
bool isValid = true;
MyManager mgr = new MyManager();
try
{
ContentItem entity = mgr.Get( contentId );
if ( entity == null || entity.Id == 0 )
{
//invalid, return, log error?
statusMessage = "Invalid request, record was not found.";
return false;
}
//get approvers for org
SubmitApprovalRequest( entity );
//update status
entity.StatusId = ContentItem.SUBMITTED_STATUS;
mgr.Update( entity );
//set resource to inactive
string status = new ResourceManager().SetResourceActiveState( entity.ResourceIntId, false );
//add record to audit table
string msg = string.Format( "Request by {0} for approval of resource id: {1}", author.FullName(), entity.Id );
mgr.ContentHistory_Create( entity.Id, "Approval Request - existing", msg, author.Id, ref statusMessage );
}
catch ( Exception ex )
{
LoggingHelper.LogError( ex, thisClassName + string.Format( ".RequestApproval(contentId: {0}, author: {1})", contentId, author.FullName() ) );
isValid = false;
statusMessage = ex.Message;
}
return isValid;
}
public static void SubmitApprovalRequest( ContentItem entity )
{
//get administrators for org, and parent
//format and send emails
string statusMessage = "";
AcctManager mgr = new AcctManager();
ThisUser author = mgr.Get( entity.CreatedById );
string note = "";
string toEmail = "";
string bccEmail = "";
//if valid
Organization org = OrgManager.GetOrganization( author, ref statusMessage );
if ( org != null && org.Id > 0 )
{
//get list of administrators
List<GroupMember> list = GroupManager.OrgApproversSelect( org.Id );
if ( list != null && list.Count > 0 )
{
foreach ( GroupMember item in list )
{
if ( item.UserEmail.Length > 5 )
toEmail += item.UserEmail + ",";
}
}
else
{
//if no approvers, send to info
toEmail = UtilityManager.GetAppKeyValue( "contactUsMailTo", "DoNotReply@ilsharedlearning.org" );
note = "<br/>NOTE: no organization approvers were found for this organization: " + org.Name;
}
string url = ContentServices.FormatContentFriendlyUrl( entity );
string urlTitle = string.Format( "<a href='{0}'>{1}</a>", url, entity.Title );
if ( System.DateTime.Now < new System.DateTime( 2013, 7, 1 ) )
bccEmail = UtilityManager.GetAppKeyValue( "appAdminEmail", "DoNotReply@ilsharedlearning.org" );
string subject = string.Format( "Isle request to approve an education resource from: {0}", author.FullName() );
string body = string.Format( "<p>{0} from {1} is requesting approval on an education resource.</p>", author.FullName(), org.Name );
//could include the override parm in the link, and just go to the display?
//or, approver will need to see all content, even private?
body += "<br/>url: " + urlTitle;
body += "<br/><br/>From: " + author.EmailSignature();
string from = author.Email;
EmailManager.SendEmail( toEmail, from, subject, body, author.Email, bccEmail );
}
}
/// <summary>
/// Handle action of content approved
/// </summary>
/// <param name="contentId"></param>
/// <param name="approver"></param>
/// <param name="statusMessage"></param>
public static bool HandleApprovedAction( int contentId, ThisUser approver, ref string statusMessage )
{
string errorMessage = "";
ContentItem entity = new MyManager().Get( contentId );
if ( entity != null && entity.Id > 0 )
return HandleApprovedAction( entity, approver, ref statusMessage, ref errorMessage );
else
{
statusMessage = "Error - unable to retrieve the requested resource";
return false;
}
}
/// <summary>
/// Handle action of content approved
/// </summary>
/// <param name="entity"></param>
/// <param name="approver"></param>
/// <param name="statusMessage"></param>
public static bool HandleApprovedAction( ContentItem entity, ThisUser approver
, ref string statusMessage
, ref string errorMessage )
{
bool isValid = true;
string bccEmail = "";
statusMessage = string.Empty;
MyManager mgr = new MyManager();
entity.StatusId = ContentItem.PUBLISHED_STATUS;
entity.ApprovedById = approver.Id;
entity.Approved = System.DateTime.Now;
mgr.Update( entity );
//set resource to active
string status = new ResourceManager().SetResourceActiveState( entity.ResourceIntId, true );
//======= published cached LR data
if ( entity.PrivilegeTypeId == ContentItem.PUBLIC_PRIVILEGE )
{
//new BaseUserControl().SetConsoleInfoMessage( "WARNING - HAVE NOT IMPLEMENTED CODE TO READ CACHED LR DATA AND DO ACTUAL LR PUBLISH" );
if ( PublishSavedEnvelope( entity.ResourceIntId, ref statusMessage ) == false )
{
errorMessage = "WARNING - the publish to the learning registry failed. System administration has been notified.";
EmailManager.NotifyAdmin( "Publish of pending resource failed", string.Format( "The attempt to publish a saved resource was unsuccessful. Content id: {0}, Res IntId: {1}, Message: {2}", entity.Id, entity.ResourceIntId, statusMessage ) );
}
}
//add record to audit table
string msg = string.Format( "Resource: {0}, author: {1}, was approved by {2}", entity.Title, entity.Author, approver.FullName() );
mgr.ContentHistory_Create( entity.Id, "Content Approved", msg, approver.Id, ref statusMessage );
//send email
AcctManager amgr = new AcctManager();
ThisUser author = amgr.Get( entity.CreatedById );
string url = ContentServices.FormatContentFriendlyUrl( entity );
string urlTitle = string.Format( "<a href='{0}'>{1}</a>", url, entity.Title );
string toEmail = author.Email;
if ( System.DateTime.Now < new System.DateTime( 2013, 7, 1 ) )
bccEmail = UtilityManager.GetAppKeyValue( "appAdminEmail", "info@illinoisworknet.com" );
string subject = "Isle: APPROVED education resource";
string body = string.Format( "<p>{0} has approved your education resource. It is now available on the website (based on the defined privilege settings).</p>", approver.FullName() );
body += "<br/>url: " + urlTitle;
body += "<br/>From: " + approver.EmailSignature();
string from = approver.Email;
EmailManager.SendEmail( toEmail, from, subject, body, approver.Email, bccEmail );
return isValid;
}
public static bool PublishSavedEnvelope( int resourceIntId, ref string statusMessage )
{
bool isValid = true;
string LRDocID = "";
ResourceManager manager = new ResourceManager();
try
{
PublishPending entity = manager.PublishPending_GetByResId( resourceIntId );
if ( entity != null && entity.Id > 0 )
{
//Publish to LR
lr_Envelope envelope = new JavaScriptSerializer().Deserialize<lr_Envelope>( entity.LREnvelope );
PublishLREnvelope( envelope, ref statusMessage, ref LRDocID );
//Publish to ElasticSearch
ResourceJSONFlat flat = new ResourceJSONManager().GetJSONFlatByIntID( resourceIntId )[ 0 ];
//new ElasticSearchManager().CreateOrReplaceRecord( flat );
//new ElasticSearchManager().RefreshResource( flat.intID ); //Kludge - need to get ID more efficiently
new Isle.BizServices.ResourceV2Services().RefreshResource( flat.intID );
//Set status messages
SetConsoleSuccessMessage( "Successful Publish of saved resource" );
LoggingHelper.DoTrace( 5, "Successful Publish of saved resource - LR Document ID:<br />" + LRDocID );
//Update entity
entity.IsPublished = true;
entity.PublishedDate = DateTime.Now;
manager.PublishPending_Update( entity );
ResourceVersionManager rvManager = new ResourceVersionManager();
ResourceVersion version = rvManager.Get( entity.ResourceVersionId );
if ( version != null && version.Id > 0 )
{
version.LRDocId = LRDocID;
rvManager.Update_LrDocId( version );
}
else
{
isValid = false;
statusMessage = string.Format( "Error - unable to retrieve the resource version record (in order to update the LR docId: {0}).", LRDocID );
SetConsoleErrorMessage( statusMessage );
}
}
else
{
statusMessage = "Error - unable to retrieve the requested publish-pending resource";
SetConsoleErrorMessage( statusMessage );
isValid = false;
}
}
catch ( Exception ex )
{
SetConsoleErrorMessage( "Error Publishing to Learning Registry: " + ex.Message );
statusMessage = statusMessage + "Publish of saved resource Failed: " + ex.ToString();
isValid = false;
}
return isValid;
}
public static void PublishLREnvelope( lr_Envelope envelope, ref string statusMessage, ref string lrDocID )
{
string node = UtilityManager.GetAppKeyValue( "learningRegistryNodePublish" );
string clientID = UtilityManager.GetAppKeyValue( "learningRegistryUserId" );
string clientPassword = UtilityManager.GetAppKeyValue( "learningRegistryPassword" );
LRClient client = new LRClient( node, clientID, clientPassword );
try
{
PublishResponse response = client.Publish( envelope );
SetConsoleSuccessMessage( "Successful Publish!<br />Learning Registry Document ID:<br />" + response.document_results.ElementAt( 0 ).doc_ID );
statusMessage = statusMessage + "Successful Publish!";
lrDocID = response.document_results.ElementAt( 0 ).doc_ID;
}
catch ( Exception ex )
{
SetConsoleErrorMessage( "Publish Failed: " + ex.Message.ToString() );
}
}
#endregion
/// <summary>
/// publishing
/// 15-04-15 mparsons - explictly passing , rather than getting from Resource object to identify where called from, and ensure set as needed. Then MAYBE will just use in object?
/// </summary>
/// <param name="input"></param>
/// <param name="isSuccessful"></param>
/// <param name="status"></param>
/// <param name="versionID"></param>
/// <param name="intID"></param>
/// <param name="sortTitle"></param>
/// <param name="updatingElasticSearch"></param>
/// <param name="skipLRPublish"></param>
/// <param name="user"></param>
/// <param name="publishForOrgId">Optional will be a valid OrgId if user is publishing for an org</param>
[Obsolete]
public static void PublishToAll_OLD( Resource input,
ref bool isSuccessful,
ref string status,
ref int versionID,
ref int intID,
ref string sortTitle,
bool updatingElasticSearch,
bool skipLRPublish,
Patron user,
int publishForOrgId )
{
bool success = true;
string tempStatus = "";
string lrDocID = "";
string continueOnPublishError = UtilityManager.GetAppKeyValue( "continueOnPublishError", "yes" );
//Publish to LR. This will give us an LR Doc ID
if ( !skipLRPublish )
{
PublishToLearningRegistry2( input,
ref success,
ref tempStatus,
ref lrDocID );
if ( !success && !IsLocalHost() )
{
if ( continueOnPublishError == "no" )
{
isSuccessful = false;
SetConsoleErrorMessage( "Error: " + tempStatus );
status = status + " " + tempStatus + " ";
versionID = 0;
return;
}
else
{
EmailManager.NotifyAdmin( "Error during LR Publish", "Error: " + tempStatus + "<p>The error was encountered during the LR publish. The system continued with saving to the database and elastic search. </p>" );
}
}
}
input.Version.LRDocId = lrDocID;
//If successful, publish to Database. This will give us a Resource Version ID
PublishToDatabase( input, publishForOrgId, ref success, ref tempStatus, ref versionID, ref intID, ref sortTitle );
if ( !success )
{
isSuccessful = false;
SetConsoleErrorMessage( "Error: " + tempStatus );
status = status + " " + tempStatus + " ";
versionID = 0;
return;
}
input.Version.Id = versionID;
input.Version.ResourceIntId = intID;
input.Id = intID;
//If successful, publish to ElasticSearch
if ( updatingElasticSearch )
{
PublishToElasticSearch( input.Id, ref success, ref tempStatus );
if ( !success )
{
isSuccessful = false;
SetConsoleErrorMessage( "Error: " + tempStatus );
status = status + " " + tempStatus + " ";
versionID = 0;
return;
}
}
new ActivityBizServices().PublishActivity( input, user );
isSuccessful = true;
status = "okay";
SetConsoleSuccessMessage( "Successfully published the Resource" );
//new ResourceThumbnailManager().CreateThumbnailAsynchronously( input.Id, input.ResourceUrl, false );
//new Thumbnailer().CreateThumbnail( input.Id, input.ResourceUrl );
ThumbnailServices.CreateThumbnail( input.Id.ToString(), input.ResourceUrl, false );
SendPublishNotification( user, input );
}
public static void PublishToLearningRegistry2( Resource input,
ref bool successful,
ref string status,
ref string lrDocID )
{
//Create payload
var payload = new ResourceJSONManager().GetJSONLRMIFromResource( input );
PublishToLearningRegistry(
new JavaScriptSerializer().Serialize( payload ),
input.ResourceUrl,
input.Version.Submitter,
input.Keyword.Select( m => m.OriginalValue.Trim() ).ToList(),
ref successful,
ref status,
ref lrDocID
);
}
/// <summary>
/// Publish resource to LR
/// NOTE: keep code for filling envelop in sync (better to merge!) with CreateLREnvelope AND BuildDocument
/// </summary>
/// <param name="payload"></param>
/// <param name="url"></param>
/// <param name="submitter"></param>
/// <param name="keywords"></param>
/// <param name="successful"></param>
/// <param name="status"></param>
/// <param name="lrDocID"></param>
public static void PublishToLearningRegistry( string payload,
string url,
string submitter,
List<string> keywords,
ref bool successful,
ref string status,
ref string lrDocID )
{
//Create document
lr_document doc = new lr_document();
LoggingHelper.DoTrace( 8, " %%%%% PublishingServices.PublishToLearningRegistry - New Publish %%%%%%" );
try
{
doc.resource_data_type = "metadata";
doc.payload_placement = "inline";
doc.doc_version = UtilityManager.GetAppKeyValue( "lr_doc_version", "0.51.0" );
doc.payload_schema = new List<string> { "LRMI" };
doc.resource_data = payload;
doc.resource_locator = url;
//keywords
doc.keys = keywords;
if ( !string.IsNullOrWhiteSpace( lrDocID ) )
{
//doing replace
doc.replaces = new List<string> { lrDocID };
LoggingHelper.DoTrace( 3, " %%%%% PublishingServices.PublishToLearningRegistry - doing registry update of LrDoc: " + lrDocID );
}
//Sign the document
SignDocument( submitter, ref doc );
//Build the envelope
lr_Envelope envelope = new lr_Envelope();
envelope.documents.Add( doc );
//Do publish
string node = UtilityManager.GetAppKeyValue( "learningRegistryNodePublish" );
string clientID = UtilityManager.GetAppKeyValue( "learningRegistryUserId" );
string clientPassword = UtilityManager.GetAppKeyValue( "learningRegistryPassword" );
LRClient client = new LRClient( node, clientID, clientPassword );
//LoggingHelper.DoTrace( 4, " %%%%% PublishingServices.PublishToLearningRegistry - doing Publish ");
PublishResponse response = client.Publish( envelope );
lrDocID = response.document_results.ElementAt( 0 ).doc_ID;
if ( !string.IsNullOrWhiteSpace( lrDocID ) && lrDocID.Length > 10 )
{
status = "Successfully published. LR Doc ID: " + lrDocID;
LoggingHelper.DoTrace( 4, " %%%%% PublishingServices.PublishToLearningRegistry - Successfully published. LR Doc ID: " + lrDocID);
//quick read to trace document
if ( System.DateTime.Now.Day == 10 )
{
//lr_document lrDoc = client.ObtainDocByID( lrDocID );
}
}
else
{
//need to get a message from the response, or update Publish
successful = false;
lrDocID = "";
if ( response != null && response.document_results != null && response.document_results.Count > 0 )
status = "Failed to Publish: " + response.document_results[0].error;
else
status = "Failed to Publish: - contact system administration" ;
LoggingHelper.DoTrace( 2, " %%%%% PublishingServices.PublishToLearningRegistry - Error. " + status );
}
}
catch ( Exception ex )
{
LoggingHelper.LogError( ex, "PublishingServices.PublishToLearningRegistry()" );
successful = false;
lrDocID = "";
status = "Failed to Publish: " + ex.Message;
}
}
/// <summary>
/// Delete a document from the registry (asynchronously)
/// </summary>
/// <param name="lrDocID"></param>
/// <param name="submitter"></param>
/// <param name="deletedDocId">If successful contains docId of the document with the delete/replacement</param>
/// <param name="successful"></param>
/// <param name="status"></param>
public static void DeleteFromRegistry( string lrDocID,
Patron user )
{
//,
// ref string deletedDocId,
// ref bool successful,
// ref string status
//do async, as no need for end user to be notified
System.Threading.ThreadPool.QueueUserWorkItem( delegate
{
DeleteFromRegistryAsync( lrDocID, user );
} );
}
/// <summary>
/// Delete a document from the registry
/// </summary>
/// <param name="lrDocID"></param>
/// <param name="submitter"></param>
/// <param name="deletedDocId">If successful contains docId of the document with the delete/replacement</param>
/// <param name="successful"></param>
/// <param name="status"></param>
private static void DeleteFromRegistryAsync( string lrDocID,
Patron user )
{
bool successful = true;
string status = "";
string deletedDocId = "";
string submitter = user.FullName();
if ( string.IsNullOrWhiteSpace( lrDocID ) )
{
successful = false;
status = "An valid LR DOC ID was was not provided";
return;
}
//Create document
lr_document doc = new lr_document();
try
{
doc.replaces = new List<string> { lrDocID };
doc.payload_placement = "none";
doc.resource_data_type = "metadata";
doc.doc_version = UtilityManager.GetAppKeyValue( "lr_doc_version", "0.51.0" );
//Sign the document
SignDocument( submitter, ref doc );
//Build the envelope
lr_Envelope envelope = new lr_Envelope();
envelope.documents.Add( doc );
//Do publish
string node = UtilityManager.GetAppKeyValue( "learningRegistryNodePublish" );
string clientID = UtilityManager.GetAppKeyValue( "learningRegistryUserId" );
string clientPassword = UtilityManager.GetAppKeyValue( "learningRegistryPassword" );
LRClient client = new LRClient( node, clientID, clientPassword );
//trace
LoggingHelper.DoTrace( 3, "Delete document \r\r" + new JavaScriptSerializer().Serialize( envelope ) );
PublishResponse response = client.Publish( envelope );
//Set return values
successful = true;
deletedDocId = response.document_results.ElementAt( 0 ).doc_ID;
if ( !string.IsNullOrWhiteSpace( deletedDocId ) && deletedDocId.Length > 10 )
{
status = submitter + " successfully deleted document from the Credential Registry. Related Doc ID: " + deletedDocId;
new ActivityBizServices().AddActivity( "Learning Registry", "Document Delete", status, user == null ? 0 : user.Id, 0 );
LoggingHelper.DoTrace( 3, status );
}
else
{
//need to get a message from the response
successful = false;
deletedDocId = "";
if ( response != null && response.document_results != null && response.document_results.Count > 0 )
status = "Failed to delete the registry document: " + response.document_results[ 0 ].error;
else
status = "Failed to delete the registry document: - contact system administration";
}
}
catch ( Exception ex )
{
successful = false;
status = "Failed to delete document: " + ex.Message;
}
if ( !successful )
{
EmailManager.NotifyAdmin( "Error encountered while attempting to delete LR document", status );
status = status.Replace( "<br/>", "\\r\\n" );
LoggingHelper.DoTrace( 3, status );
}
}
public static void PublishToDatabase( LRWarehouse.Business.ResourceV2.ResourceDTO input
, int publishForOrgId
, int updatedById
, List<int> selectedTags
, ref bool successful
, ref string status
, ref int versionID
, ref int intID
, ref string sortTitle )
{
ResourceManager resMgr = new ResourceManager();
bool creatingSystemResource = false;
try
{
//Resource
if ( input.ResourceId == 0 )
{
var resource = new Resource()
{
ResourceUrl = input.Url,
CreatedById = input.CreatedById,
};
intID = resMgr.Create( resource, ref status );
if ( intID == 0 )
{
successful = false;
return;
}
else
{
input.ResourceId = intID;
creatingSystemResource = true;
}
}
//Version
//Access Rights
var finalAccessRightsValue = "";
var finalAccessRightsId = 2;
var targetAccessRights = input.Fields.Where( m => m.Schema == "accessRights" ).FirstOrDefault().Tags.Where( t => t.Selected ).FirstOrDefault();
if ( targetAccessRights != null )
{
//Convert new access rights ID to old access rights ID for storage in version table
var accessRightsDBField = new ResourceV2Services().GetFieldAndTagCodeData(false).Where( m => m.Schema == "accessRights" ).FirstOrDefault();
if ( accessRightsDBField != null )
{
var matchedAccessRightsDB = accessRightsDBField.Tags.Where( m => m.Id == targetAccessRights.Id ).FirstOrDefault();
if ( matchedAccessRightsDB != null )
{
finalAccessRightsId = matchedAccessRightsDB.OldCodeId;
finalAccessRightsValue = matchedAccessRightsDB.Title;
}
}
//var accessRights = targetAccessRights.Tags.Where(t => t.Selected).FirstOrDefault() ?? targetAccessRights.Tags.First();
}
var versionManager = new ResourceVersionManager();
var version = new ResourceVersion()
{
Id = versionID,
LRDocId = input.LrDocId,
Title = input.Title,
Description = input.Description,
Publisher = input.Publisher,
Creator = input.Creator,
Rights = input.UsageRights.Url,
UsageRightsId = input.UsageRights.CodeId,
AccessRights = finalAccessRightsValue,
Modified = DateTime.Now,
Submitter = input.Submitter,
Created = DateTime.Now, //Still not sure if this means "resource creation" or "table record creation" date. Going with the safer of the two
TypicalLearningTime = "", //No longer used
IsSkeletonFromParadata = false,
Schema = "LRMI",
AccessRightsId = finalAccessRightsId,
InteractivityTypeId = 0, //No longer used
ResourceIntId = intID,
Requirements = input.Requirements
};
if ( versionID == 0 )
{
versionID = versionManager.Create( version, ref status );
}
else
{
versionManager.UpdateById( version );
}
//Keywords
var keywordManager = new ResourceKeywordManager();
foreach ( var item in input.Keywords )
{
keywordManager.Create( new ResourceChildItem()
{
ResourceIntId = intID,
OriginalValue = item,
CreatedById = updatedById //input.CreatedById
}, ref status );
}
//Standards
//note: AlignmentDegreeId is actually the usage now as in Major, Supporting, Additional
var standardManager = new ResourceStandardManager();
foreach ( var item in input.Standards )
{
standardManager.Create( new ResourceStandard()
{
ResourceIntId = intID,
StandardId = item.StandardId,
AlignmentTypeCodeId = item.AlignmentTypeId,
UsageTypeId = item.UsageTypeId,
AlignmentTypeValue = item.AlignmentType,
UsageType = item.UsageType,
CreatedById = updatedById, //input.CreatedById,
AlignedById = updatedById, //input.CreatedById,
StandardDescription = item.Description,
StandardNotationCode = item.NotationCode
}, ref status );
}
//Tags
//SelectMany condenses resulting lists into a single list--here it condenses the lists of selected tags into a single list
//from which the IDs are selected
//List<int> tags = input.Fields.SelectMany( t => t.Tags.Where( s => s.Selected ) ).ToList().Select( t => t.Id ).ToList();
//Actually, we just want to add the new tags, because EF doesn't do a duplicate check
try
{
if ( selectedTags != null && selectedTags.Count > 0 )
{
new IOERBusinessEntities.EFResourceManager().Resource_CreateTags( selectedTags, input.ResourceId, updatedById );
}
}
catch ( Exception ex )
{
//ServiceHelper.DoTrace(4, "********PublishingServices.PublishToDatabase. EXCEPTION ENCOUNTERED");
//skip throw, to allow continuing!!!
ServiceHelper.LogError( ex, "PublishingServices.PublishToDatabase. " + "Entity Framework Error: " + ex.Message + ";<br />InnerException: " + ex.InnerException.Message + ";<br />" + ex.InnerException.ToString() + ";" );
//throw new Exception("Entity Framework Error: " + ex.Message + ";<br />InnerException: " + ex.InnerException.Message + ";<br />" + ex.InnerException.ToString() + ";");
}
sortTitle = versionManager.Get( versionID ).SortTitle.Replace( " ", "_" );
successful = true;
status = "okay";
if ( creatingSystemResource )
{
}
}
catch ( Exception ex )
{
successful = false;
status = ex.Message;
}
}
[Obsolete]
private static void PublishToDatabase( Resource input
, int publishForOrgId
, ref bool successful
, ref string status
, ref int versionID
, ref int intID
, ref string sortTitle )
{
try
{
string statusMessage = "";
ResourceDataManager dataManager = new ResourceDataManager();
ResourceManager resMgr = new ResourceManager();
input.PublishedForOrgId = publishForOrgId;
//Resource. Use method that just uses url. Published by will be handled here
//intID = resMgr.Create( input, ref status );
intID = resMgr.CreateByUrl( input.ResourceUrl, ref status );
input.Id = intID;
input.Version.ResourceIntId = intID;
//published by. Probably better to do here, rather than burying it?
if ( input.CreatedById > 0 )
{
resMgr.Create_ResourcePublishedBy( intID, input.CreatedById, publishForOrgId, ref statusMessage );
}
//Version
var versionManager = new ResourceVersionManager();
versionID = versionManager.Create( input.Version, ref status );
input.Version.Id = versionID;
//Tags
var tags = new Dictionary<List<ResourceChildItem>, string>
{
{ input.ClusterMap, "careerCluster" },
{ input.EducationalUse, "educationalUse" },
{ input.ResourceFormat, "mediaType" },
{ input.Gradelevel, "gradeLevel" },
{ input.GroupType, "groupType" },
{ input.Audience, "endUser" },
{ input.ItemType, "itemType" },
{ input.Language, "language" },
{ input.ResourceType, "resourceType" },
{ input.SubjectMap, "subject" },
{ input.relatedURL, "originalVersionURL" }
};
foreach ( KeyValuePair<List<ResourceChildItem>, string> entry in tags )
{
CreateMVFs( dataManager, entry.Key, findClass( entry.Value ), intID, input.CreatedById );
}
//Keywords
var keywordManager = new ResourceKeywordManager();
foreach ( ResourceChildItem word in input.Keyword )
{
word.ResourceIntId = intID;
keywordManager.Create( word, ref status );
}
//Standards
var standardManager = new ResourceStandardManager();
foreach ( ResourceStandard standard in input.Standard )
{
standard.ResourceIntId = intID;
standardManager.Create( standard, ref status );
}
sortTitle = versionManager.Get( versionID ).SortTitle.Replace( " ", "_" );
successful = true;
status = "okay";
}
catch ( Exception ex )
{
successful = false;
status = ex.Message;
return;
}
}
#region Helper Methods
public static void SendPublishNotification( Patron user, Resource resource )
{
string toEmail = UtilityManager.GetAppKeyValue( "contactUsMailTo", "info@ilsharedlearning.org" );
string cc = UtilityManager.GetAppKeyValue( "onPublishCC", "" );
string bcc = UtilityManager.GetAppKeyValue( "appAdminEmail", "mparsons@siuccwd.com" );
string fromEmail = user.Email;
string subject = string.Format( "IOER - New publish notification from: {0}", user.FullName() );
string body = string.Format( "<p>{0} published a new resource to IOER. </p>", user.FullName() );
if ( resource.Version != null )
{
body += "<br/>Resource: " + resource.Version.Title;
body += "<br/>" + resource.Version.Description;
}
//body += "<br/>Target Url: <span>" + resource.ResourceUrl + "</span> ";
body += "<br/><br/>Target Url: " + string.Format( "<a href='{0}'>{1}</a>", resource.ResourceUrl, resource.ResourceUrl );
//string url = UtilityManager.FormatAbsoluteUrl( string.Format( "/ResourceDetail.aspx?vid={0}", resource.Version.Id ), true );
//string title = FormatFriendlyTitle( resource.Version.Title );
string url2 = ResourceBizService.FormatFriendlyResourceUrl( resource.Version );
body += "<br/><br/>Detail Url: " + string.Format( "<a href='{0}'>View published resource</a>", url2 );
body += "<br/>From: " + user.EmailSignature();
//string from = applicant.Email;
EmailManager.SendEmail( toEmail, fromEmail, subject, body, cc, bcc );
}
private static void CreateMVFs( ResourceDataManager dataManager, List<ResourceChildItem> input, ResourceDataManager.IResourceDataSubclass className, int intID, int createdByID )
{
foreach ( ResourceChildItem item in input )
{
dataManager.Create( className, intID, item.CodeId, item.OriginalValue, createdByID );
}
}
private static ResourceDataManager.IResourceDataSubclass findClass( string tableName )
{
return ResourceDataManager.ResourceDataSubclassFinder.getSubclassByName( tableName );
}
#endregion
#region Obsolete LR Document methods
/// <summary>
/// ===> NOT USED
/// </summary>
/// <param name="resourceEntity"></param>
/// <returns></returns>
//[Obsolete]
//private static lr_document BuildDocumentXXX( ref Resource resourceEntity )
//{
// lr_document doc = new lr_document();
// //string resourceData = BuildPayloadLRMI_JSON( resourceEntity );
// //OR?
// var resourceData = new ResourceJSONManager().GetJSONLRMIFromResource(resourceEntity);
// //Required Fields
// doc.resource_data_type = "metadata";
// doc.payload_placement = "inline";
// doc.doc_version = UtilityManager.GetAppKeyValue("lr_doc_version", "0.51.0");
// doc.payload_schema = new List<string>( new string[] { "LRMI" } );
// //Most of the data is in here:
// doc.resource_data = resourceData;
// //Resource Locator
// doc.resource_locator = resourceEntity.ResourceUrl;
// //Submitter Informaton
// lr_identity identity = new lr_identity();
// identity.submitter_type = "agent";
// identity.signer = UtilityManager.GetAppKeyValue("lrIdentitySigner", "error");
// string defaultSubmitter = UtilityManager.GetAppKeyValue("defaultSubmitter", "IOER");
// if ( resourceEntity.Version.Submitter.ToLower().IndexOf( defaultSubmitter.ToLower() ) == -1 )
// resourceEntity.Version.Submitter = defaultSubmitter + resourceEntity.Version.Submitter;
// identity.submitter = resourceEntity.Version.Submitter;
// doc.identity = identity;
// //Keywords
// foreach ( ResourceChildItem keyword in resourceEntity.Keyword )
// {
// doc.keys.Add( keyword.OriginalValue.Trim() );
// }
// return doc;
//}
[Obsolete]
private static string BuildPayloadLRMI_JSONXXX( Resource entity )
{
ResourceJSONManager jsonManager = new ResourceJSONManager();
ResourceJSONLRMI resource = jsonManager.GetJSONLRMIFromResource( entity );
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize( resource );
}
[Obsolete]
private static lr_Envelope BuildEnvelope( lr_document doc )
{
lr_Envelope envelope = new lr_Envelope();
envelope.documents.Add( doc );
return envelope;
}
#endregion
public static void PublishToElasticSearchAsynchronously( int resourceId )
{
System.Threading.ThreadPool.QueueUserWorkItem( delegate
{
var successful = true;
var status = "okay";
PublishToElasticSearch( resourceId, ref successful, ref status );
} );
}
public static void PublishToElasticSearch( int resourceId, ref bool successful, ref string status )
{
//Do create
try
{
//new ElasticSearchManager().CreateOrReplaceRecord( resourceId );
//new ElasticSearchManager().RefreshResource( resourceId );
new Isle.BizServices.ResourceV2Services().RefreshResource( resourceId );
successful = true;
status = "okay";
}
catch ( Exception ex )
{
successful = false;
status = ex.Message;
}
}
public static void BuildSaveLRDocument( Resource input,
ref bool successful,
ref string status )
{
var envelope = CreateLREnvelope( input, ref successful, ref status );
var pending = new PublishPending()
{
ResourceId = input.Id,
ResourceVersionId = input.Version.Id,
Reason = "Resource requires approval.",
CreatedById = input.CreatedById,
LREnvelope = new JavaScriptSerializer().Serialize( envelope )
};
new ResourceManager().PublishPending_Create( pending, ref status );
}
/// <summary>
/// Fill an LR Envelope
/// NOTE: keep filling code in sync with PublishToLearningRegistry
/// </summary>
/// <param name="input"></param>
/// <param name="successful"></param>
/// <param name="status"></param>
/// <returns></returns>
public static lr_Envelope CreateLREnvelope(Resource input, ref bool successful, ref string status)
{
//Create payload
var payload = new ResourceJSONManager().GetJSONLRMIFromResource(input);
//keywords
List<string> keywords = new List<string>();
foreach (ResourceChildItem word in input.Keyword)
{
keywords.Add(word.OriginalValue.Trim());
}
return CreateLREnvelope(new JavaScriptSerializer().Serialize(payload), input.ResourceUrl, input.Version.Submitter, keywords, ref successful, ref status);
}
/// <summary>
/// Fill an LR Envelope
/// NOTE: keep filling code in sync with PublishToLearningRegistry and BuildDocument
/// </summary>
/// <param name="payload"></param>
/// <param name="resourceUrl"></param>
/// <param name="submitter"></param>
/// <param name="keywords"></param>
/// <param name="successful"></param>
/// <param name="status"></param>
/// <returns></returns>
public static lr_Envelope CreateLREnvelope( string payload,
string resourceUrl,
string submitter,
List<string> keywords,
ref bool successful,
ref string status )
{
//Create payload
//var payload = new ResourceJSONManager().GetJSONLRMIFromResource( input );
//Create document
lr_document doc = new lr_document();
doc.resource_data_type = "metadata";
doc.payload_placement = "inline";
doc.doc_version = UtilityManager.GetAppKeyValue("lr_doc_version", "0.51.0");
doc.payload_schema = new List<string> { "LRMI" };
doc.resource_data = payload;
doc.resource_locator = resourceUrl;
//keywords
doc.keys = keywords;
//Identity info
//lr_identity identity = new lr_identity();
//identity.submitter_type = "agent";
//identity.signer = UtilityManager.GetAppKeyValue("lrIdentitySigner", "error");
//string defaultSubmitter = UtilityManager.GetAppKeyValue("defaultSubmitter", "IOER");
////check if default submitter already included
//if ( submitter.ToLower().IndexOf( defaultSubmitter.ToLower() ) == -1 )
// submitter = defaultSubmitter + submitter;
//identity.submitter = submitter;
//doc.identity = identity;
//foreach ( ResourceChildItem word in input.Keyword )
//{
// doc.keys.Add( word.OriginalValue.Trim() );
//}
SignDocument( submitter, ref doc );
//Build the envelope
lr_Envelope envelope = new lr_Envelope();
envelope.documents.Add( doc );
return envelope;
}
private static void SignDocument( string submitter, ref lr_document doc )
{
//LoggingHelper.DoTrace( 3, " %%%%% PublishingServices.SignDocument for " + submitter );
string signingKeyLocation = UtilityManager.GetAppKeyValue( "signingKeyLocation", "" );
if ( string.IsNullOrWhiteSpace( signingKeyLocation ) )
{
//produce error?
return;
}
//Identity info
lr_identity identity = new lr_identity();
identity.submitter_type = "agent";
identity.signer = UtilityManager.GetAppKeyValue( "lrIdentitySigner", "error" );
string defaultSubmitter = UtilityManager.GetAppKeyValue( "defaultSubmitter", "IOER" );
//check if default submitter already included
if ( submitter.ToLower().IndexOf( defaultSubmitter.ToLower() ) == -1 )
submitter = defaultSubmitter + submitter;
identity.submitter = submitter;
doc.identity = identity;
string publicKeyLocationId = UtilityManager.GetAppKeyValue( "publicKeyLocationId", "" );
//try
//{
string PgpKeyringLocation = Path.Combine( HttpRuntime.AppDomainAppPath, signingKeyLocation );
string keyData = File.ReadAllText( PgpKeyringLocation );
string[] PublicKeyLocations = new string[] { string.Format("http://pgp.mit.edu:11371/pks/lookup?op=get&search={0}",publicKeyLocationId) };
string UserID = UtilityManager.GetAppKeyValue( "signingUserId", "error" );
string password = UtilityManager.GetAppKeyValue( "signingPassword", "error" );
PgpSigner signer = new PgpSigner( PublicKeyLocations, keyData, UserID, password );
doc = signer.Sign( doc );
//}
//catch ( Exception ex )
//{
// //maybe do not want to catch, let it fail?
//}
}
public static void GenerateThumbnail( int resourceID, string url )
{
//new Thumbnailer().CreateThumbnail( resourceID, url );
ThumbnailServices.CreateThumbnail( resourceID.ToString(), url, false );
}
public static lr_document LR_GetByDocID( string lrDocID )
{
string node = UtilityManager.GetAppKeyValue( "learningRegistryNodePublish" );
string clientID = UtilityManager.GetAppKeyValue( "learningRegistryUserId" );
string clientPassword = UtilityManager.GetAppKeyValue( "learningRegistryPassword" );
LRClient client = new LRClient( node, clientID, clientPassword );
lr_document lrDoc = client.ObtainDocByID( lrDocID );
//add trace code
LoggingHelper.DoTrace( 5, "lrDoc \r\r" + new JavaScriptSerializer().Serialize( lrDoc ) );
return lrDoc;
}
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#if !WINDOWS_UWP
// When the .NET scripting backend is enabled and C# projects are built
// The assembly that this file is part of is still built for the player,
// even though the assembly itself is marked as a test assembly (this is not
// expected because test assemblies should not be included in player builds).
// Because the .NET backend is deprecated in 2018 and removed in 2019 and this
// issue will likely persist for 2018, this issue is worked around by wrapping all
// play mode tests in this check.
using Microsoft.MixedReality.Toolkit.Input;
using Microsoft.MixedReality.Toolkit.UI;
using Microsoft.MixedReality.Toolkit.Utilities;
using System.Collections;
using System.Linq;
using UnityEngine;
using UnityEngine.TestTools;
using Assert = UnityEngine.Assertions.Assert;
namespace Microsoft.MixedReality.Toolkit.Tests
{
public class BoundingBoxTests : BasePlayModeTests
{
#region Utilities
private readonly Vector3 boundingBoxStartCenter = Vector3.forward * 1.5f;
private readonly Vector3 boundingBoxStartScale = Vector3.one * 0.5f;
/// <summary>
/// Instantiates a bounding box at 0, 0, -1.5f
/// box is at scale .5, .5, .5
/// Target is set to its child if targetIsChild is true
/// </summary>
private BoundingBox InstantiateSceneAndDefaultBbox(GameObject target = null)
{
GameObject bboxGameObject;
if (target != null)
{
bboxGameObject = new GameObject();
}
else
{
bboxGameObject = GameObject.CreatePrimitive(PrimitiveType.Cube);
}
bboxGameObject.transform.position = boundingBoxStartCenter;
bboxGameObject.transform.localScale = boundingBoxStartScale;
BoundingBox bbox = bboxGameObject.AddComponent<BoundingBox>();
if (target != null)
{
target.transform.parent = bboxGameObject.transform;
target.transform.localScale = Vector3.one;
target.transform.localPosition = Vector3.zero;
bbox.Target = target;
}
MixedRealityPlayspace.PerformTransformation(
p =>
{
p.position = Vector3.zero;
p.LookAt(bboxGameObject.transform.position);
});
bbox.Active = true;
return bbox;
}
#endregion
/// <summary>
/// Verify that we can instantiate bounding box at runtime
/// </summary>
[UnityTest]
public IEnumerator BBoxInstantiate()
{
var bbox = InstantiateSceneAndDefaultBbox();
yield return null;
Assert.IsNotNull(bbox);
Object.Destroy(bbox.gameObject);
// Wait for a frame to give Unity a change to actually destroy the object
yield return null;
}
/// <summary>
/// Test that if we update the bounds of a box collider, that the corners will move correctly
/// </summary>
[UnityTest]
public IEnumerator BBoxOverride()
{
var bbox = InstantiateSceneAndDefaultBbox();
yield return null;
bbox.BoundingBoxActivation = BoundingBox.BoundingBoxActivationType.ActivateOnStart;
bbox.HideElementsInInspector = false;
yield return null;
var newObject = new GameObject();
var bc = newObject.AddComponent<BoxCollider>();
bc.center = new Vector3(.25f, 0, 0);
bc.size = new Vector3(0.162f, 0.1f, 1);
bbox.BoundsOverride = bc;
yield return null;
Bounds b = GetBoundingBoxRigBounds(bbox);
Debug.Assert(b.center == bc.center, $"bounds center should be {bc.center} but they are {b.center}");
Debug.Assert(b.size == bc.size, $"bounds size should be {bc.size} but they are {b.size}");
Object.Destroy(bbox.gameObject);
Object.Destroy(newObject);
// Wait for a frame to give Unity a change to actually destroy the object
yield return null;
}
/// <summary>
/// Test that if we toggle the bounding box's active status,
/// that the size of the boundsOverride is consistent, even
/// when BoxPadding is set.
/// </summary>
[UnityTest]
public IEnumerator BBoxOverridePaddingReset()
{
var bbox = InstantiateSceneAndDefaultBbox();
yield return null;
bbox.BoundingBoxActivation = BoundingBox.BoundingBoxActivationType.ActivateOnStart;
bbox.HideElementsInInspector = false;
// Set the bounding box to have a large padding.
bbox.BoxPadding = Vector3.one;
yield return null;
var newObject = new GameObject();
var bc = newObject.AddComponent<BoxCollider>();
bc.center = new Vector3(1, 2, 3);
var backupSize = bc.size = new Vector3(1, 2, 3);
bbox.BoundsOverride = bc;
yield return null;
// Toggles the bounding box and verifies
// integrity of the measurements.
VerifyBoundingBox();
// Change the center and size of the boundsOverride
// in the middle of execution, to ensure
// these changes will be correctly reflected
// in the BoundingBox after toggling.
bc.center = new Vector3(0.1776f, 0.42f, 0.0f);
backupSize = bc.size = new Vector3(0.1776f, 0.42f, 1.0f);
bbox.BoundsOverride = bc;
yield return null;
// Toggles the bounding box and verifies
// integrity of the measurements.
VerifyBoundingBox();
// Private helper function to prevent code copypasta.
IEnumerator VerifyBoundingBox()
{
// Toggle the bounding box active status to check that the boundsOverride
// will persist, and will not be destructively resized
bbox.gameObject.SetActive(false);
yield return null;
Debug.Log($"bc.size = {bc.size}");
bbox.gameObject.SetActive(true);
yield return null;
Debug.Log($"bc.size = {bc.size}");
Bounds b = GetBoundingBoxRigBounds(bbox);
var expectedSize = backupSize + Vector3.Scale(bbox.BoxPadding, newObject.transform.lossyScale);
Debug.Assert(b.center == bc.center, $"bounds center should be {bc.center} but they are {b.center}");
Debug.Assert(b.size == expectedSize, $"bounds size should be {expectedSize} but they are {b.size}");
Debug.Assert(bc.size == expectedSize, $"boundsOverride's size was corrupted.");
}
Object.Destroy(bbox.gameObject);
Object.Destroy(newObject);
// Wait for a frame to give Unity a change to actually destroy the object
yield return null;
}
/// <summary>
/// Tests to see that the handlers grow in size when a pointer is near them
/// </summary>
[UnityTest]
public IEnumerator BBoxHandlerUI()
{
const int numSteps = 2;
var bbox = InstantiateSceneAndDefaultBbox();
bbox.ShowRotationHandleForX = true;
bbox.ShowRotationHandleForY = true;
bbox.ShowRotationHandleForZ = true;
bbox.ShowScaleHandles = true;
bbox.ProximityEffectActive = true;
bbox.ScaleHandleSize = 0.1f;
bbox.RotationHandleSize = 0.1f;
bbox.FarScale = 1.0f;
bbox.MediumScale = 1.5f;
bbox.CloseScale = 1.5f;
yield return null;
var bounds = bbox.GetComponent<BoxCollider>().bounds;
Assert.AreEqual(new Vector3(0, 0, 1.5f), bounds.center);
Assert.AreEqual(new Vector3(.5f, .5f, .5f), bounds.size);
// Defining the edge and corner handlers that will be used
Debug.Log(bbox.transform.Find("rigRoot/midpoint_0").GetChild(0));
var originalCornerHandlerScale = bbox.transform.Find("rigRoot/corner_1/visualsScale/visuals").transform.localScale;
var cornerHandlerPosition = bbox.transform.Find("rigRoot/corner_1").transform.position;
var originalEdgeHandlerScale = bbox.transform.Find("rigRoot/midpoint_0/Sphere").transform.localScale;
var edgeHandlerPosition = bbox.transform.Find("rigRoot/midpoint_0").transform.position;
// Wait for the scaling/unscaling animation to finish
yield return new WaitForSeconds(0.2f);
// Move the hand to a handler on the corner
TestHand rightHand = new TestHand(Handedness.Right);
yield return rightHand.Show(new Vector3(0, 0, 0.5f));
yield return rightHand.MoveTo(cornerHandlerPosition, numSteps);
// Wait for the scaling/unscaling animation to finish
yield return new WaitForSeconds(0.4f);
TestUtilities.AssertAboutEqual(bbox.transform.Find("rigRoot/midpoint_0/Sphere").transform.localScale, originalEdgeHandlerScale, "The edge handler changed mistakingly");
TestUtilities.AssertAboutEqual(bbox.transform.Find("rigRoot/corner_1/visualsScale/visuals").transform.localScale.normalized, originalCornerHandlerScale.normalized, "The corner handler scale has changed");
Assert.AreApproximatelyEqual(bbox.transform.Find("rigRoot/corner_1/visualsScale/visuals").transform.localScale.x / originalCornerHandlerScale.x, bbox.MediumScale, 0.1f, "The corner handler did not grow when a pointer was near it");
// Move the hand to a handler on the edge
yield return rightHand.MoveTo(edgeHandlerPosition, numSteps);
// Wait for the scaling/unscaling animation to finish
yield return new WaitForSeconds(0.4f);
TestUtilities.AssertAboutEqual(bbox.transform.Find("rigRoot/corner_1/visualsScale/visuals").transform.localScale, originalCornerHandlerScale, "The corner handler changed mistakingly");
TestUtilities.AssertAboutEqual(bbox.transform.Find("rigRoot/midpoint_0/Sphere").transform.localScale.normalized, originalEdgeHandlerScale.normalized, "The edge handler scale has changed");
Assert.AreApproximatelyEqual(bbox.transform.Find("rigRoot/midpoint_0/Sphere").transform.localScale.x / originalEdgeHandlerScale.x, bbox.MediumScale, 0.1f, "The edge handler did not grow when a pointer was near it");
Object.Destroy(bbox.gameObject);
// Wait for a frame to give Unity a change to actually destroy the object
yield return null;
}
/// <summary>
/// Uses near interaction to scale the bounding box by directly grabbing corner
/// </summary>
[UnityTest]
public IEnumerator ScaleViaNearInteration()
{
const int numSteps = 2;
var bbox = InstantiateSceneAndDefaultBbox();
bbox.ScaleHandleSize = 0.1f;
yield return null;
var bounds = bbox.GetComponent<BoxCollider>().bounds;
Assert.AreEqual(new Vector3(0, 0, 1.5f), bounds.center);
Assert.AreEqual(new Vector3(.5f, .5f, .5f), bounds.size);
// front right corner is corner 3
var frontRightCornerPos = bbox.ScaleCorners[3].transform.position;
TestHand rightHand = new TestHand(Handedness.Right);
yield return rightHand.Show(new Vector3(0, 0, 0.5f));
var delta = new Vector3(0.1f, 0.1f, 0f);
yield return rightHand.MoveTo(frontRightCornerPos, numSteps);
yield return rightHand.SetGesture(ArticulatedHandPose.GestureId.Pinch);
yield return rightHand.Move(delta, numSteps);
var endBounds = bbox.GetComponent<BoxCollider>().bounds;
TestUtilities.AssertAboutEqual(endBounds.center, new Vector3(0.033f, 0.033f, 1.467f), "endBounds incorrect center");
TestUtilities.AssertAboutEqual(endBounds.size, Vector3.one * .567f, "endBounds incorrect size");
Object.Destroy(bbox.gameObject);
// Wait for a frame to give Unity a change to actually destroy the object
yield return null;
}
/// <summary>
/// This tests the minimum and maximum scaling for the bounding box.
/// </summary>
[UnityTest]
public IEnumerator ScaleMinMax()
{
float minScale = 0.5f;
float maxScale = 2f;
var bbox = InstantiateSceneAndDefaultBbox();
var scaleHandler = bbox.EnsureComponent<MinMaxScaleConstraint>();
scaleHandler.ScaleMinimum = minScale;
scaleHandler.ScaleMaximum = maxScale;
yield return null;
Vector3 initialScale = bbox.transform.localScale;
const int numHandSteps = 1;
Vector3 initialHandPosition = new Vector3(0, 0, 0.5f);
var frontRightCornerPos = bbox.ScaleCorners[3].transform.position; // front right corner is corner 3
TestHand hand = new TestHand(Handedness.Right);
// Hands grab object at initial position
yield return hand.Show(initialHandPosition);
yield return hand.SetGesture(ArticulatedHandPose.GestureId.OpenSteadyGrabPoint);
yield return hand.MoveTo(frontRightCornerPos, numHandSteps);
yield return hand.SetGesture(ArticulatedHandPose.GestureId.Pinch);
// No change to scale yet
Assert.AreEqual(initialScale, bbox.transform.localScale);
// Move hands beyond max scale limit
yield return hand.MoveTo(new Vector3(scaleHandler.ScaleMaximum * 2, scaleHandler.ScaleMaximum * 2, 0) + frontRightCornerPos, numHandSteps);
// Assert scale at max
Assert.AreEqual(Vector3.one * scaleHandler.ScaleMaximum, bbox.transform.localScale);
// Move hands beyond min scale limit
yield return hand.MoveTo(new Vector3(-scaleHandler.ScaleMinimum * 2, -scaleHandler.ScaleMinimum * 2, 0) + frontRightCornerPos, numHandSteps);
// Assert scale at min
Assert.AreEqual(Vector3.one * scaleHandler.ScaleMinimum, bbox.transform.localScale);
Object.Destroy(bbox.gameObject);
// Wait for a frame to give Unity a change to actually destroy the object
yield return null;
}
/// <summary>
/// This tests the minimum and maximum scaling for the bounding box when target is a child of the box.
/// </summary>
[UnityTest]
public IEnumerator ScaleChildTargetMinMax()
{
float minScale = 0.5f;
float maxScale = 2f;
var target = GameObject.CreatePrimitive(PrimitiveType.Cube);
var bbox = InstantiateSceneAndDefaultBbox(target);
var scaleHandler = bbox.EnsureComponent<MinMaxScaleConstraint>();
scaleHandler.ScaleMinimum = minScale;
scaleHandler.ScaleMaximum = maxScale;
yield return null;
Vector3 initialScale = bbox.Target.transform.localScale;
const int numHandSteps = 1;
Vector3 initialHandPosition = new Vector3(0, 0, 0.5f);
var frontRightCornerPos = bbox.ScaleCorners[3].transform.position; // front right corner is corner 3
TestHand hand = new TestHand(Handedness.Right);
// Hands grab object at initial position
yield return hand.Show(initialHandPosition);
yield return hand.SetGesture(ArticulatedHandPose.GestureId.OpenSteadyGrabPoint);
yield return hand.MoveTo(frontRightCornerPos, numHandSteps);
yield return hand.SetGesture(ArticulatedHandPose.GestureId.Pinch);
// No change to scale yet
Assert.AreEqual(initialScale, bbox.Target.transform.localScale);
// Move hands beyond max scale limit
yield return hand.MoveTo(new Vector3(scaleHandler.ScaleMaximum * 2, scaleHandler.ScaleMaximum * 2, 0) + frontRightCornerPos, numHandSteps);
// Assert scale at max
Assert.AreEqual(Vector3.one * scaleHandler.ScaleMaximum, bbox.Target.transform.localScale);
// Move hands beyond min scale limit
yield return hand.MoveTo(new Vector3(-scaleHandler.ScaleMinimum * 2, -scaleHandler.ScaleMinimum * 2, 0) + frontRightCornerPos, numHandSteps);
// Assert scale at min
Assert.AreEqual(Vector3.one * scaleHandler.ScaleMinimum, bbox.Target.transform.localScale);
}
/// <summary>
/// Uses far interaction (HoloLens 1 style) to scale the bounding box
/// </summary>
[UnityTest]
public IEnumerator ScaleViaHoloLens1Interaction()
{
var bbox = InstantiateSceneAndDefaultBbox();
yield return null;
yield return null;
var bounds = bbox.GetComponent<BoxCollider>().bounds;
var startCenter = new Vector3(0, 0, 1.5f);
var startSize = new Vector3(.5f, .5f, .5f);
TestUtilities.AssertAboutEqual(bounds.center, startCenter, "bbox incorrect center at start");
TestUtilities.AssertAboutEqual(bounds.size, startSize, "bbox incorrect size at start");
// Switch to hand gestures
var iss = PlayModeTestUtilities.GetInputSimulationService();
var oldSimMode = iss.ControllerSimulationMode;
iss.ControllerSimulationMode = ControllerSimulationMode.HandGestures;
CameraCache.Main.transform.LookAt(bbox.ScaleCorners[3].transform);
var startHandPos = CameraCache.Main.transform.TransformPoint(new Vector3(0.1f, 0f, 1.5f));
TestHand rightHand = new TestHand(Handedness.Right);
yield return rightHand.Show(startHandPos);
yield return rightHand.SetGesture(ArticulatedHandPose.GestureId.Pinch);
// After pinching, center should remain the same
var afterPinchbounds = bbox.GetComponent<BoxCollider>().bounds;
TestUtilities.AssertAboutEqual(afterPinchbounds.center, startCenter, "bbox incorrect center after pinch");
TestUtilities.AssertAboutEqual(afterPinchbounds.size, startSize, "bbox incorrect size after pinch");
var delta = new Vector3(0.1f, 0.1f, 0f);
yield return rightHand.Move(delta);
var endBounds = bbox.GetComponent<BoxCollider>().bounds;
TestUtilities.AssertAboutEqual(endBounds.center, new Vector3(0.033f, 0.033f, 1.467f), "endBounds incorrect center", 0.02f);
TestUtilities.AssertAboutEqual(endBounds.size, Vector3.one * .561f, "endBounds incorrect size", 0.02f);
Object.Destroy(bbox.gameObject);
// Wait for a frame to give Unity a change to actually destroy the object
yield return null;
// Restore the input simulation profile
iss.ControllerSimulationMode = oldSimMode;
yield return null;
}
/// <summary>
/// Uses motion controller to scale the bounding box
/// </summary>
[UnityTest]
public IEnumerator ScaleViaMotionControllerInteraction()
{
var bbox = InstantiateSceneAndDefaultBbox();
yield return null;
yield return null;
var bounds = bbox.GetComponent<BoxCollider>().bounds;
var startCenter = new Vector3(0, 0, 1.5f);
var startSize = new Vector3(.5f, .5f, .5f);
TestUtilities.AssertAboutEqual(bounds.center, startCenter, "bbox incorrect center at start");
TestUtilities.AssertAboutEqual(bounds.size, startSize, "bbox incorrect size at start");
// Switch to motion controller
var iss = PlayModeTestUtilities.GetInputSimulationService();
var oldSimMode = iss.ControllerSimulationMode;
iss.ControllerSimulationMode = ControllerSimulationMode.MotionController;
CameraCache.Main.transform.LookAt(bbox.ScaleCorners[3].transform);
var startPos = CameraCache.Main.transform.TransformPoint(new Vector3(0.21f, -0.35f, 0f));
TestMotionController rightMotionController = new TestMotionController(Handedness.Right);
yield return rightMotionController.Show(startPos);
SimulatedMotionControllerButtonState selectButtonState = new SimulatedMotionControllerButtonState
{
IsSelecting = true
};
yield return rightMotionController.SetState(selectButtonState);
yield return null;
var delta = new Vector3(0.1f, 0.1f, 0f);
yield return rightMotionController.Move(delta);
yield return null;
SimulatedMotionControllerButtonState defaultButtonState = new SimulatedMotionControllerButtonState();
yield return rightMotionController.SetState(defaultButtonState);
yield return null;
var endBounds = bbox.GetComponent<BoxCollider>().bounds;
TestUtilities.AssertAboutEqual(endBounds.center, new Vector3(0.033f, 0.033f, 1.467f), "endBounds incorrect center", 0.02f);
TestUtilities.AssertAboutEqual(endBounds.size, Vector3.one * .561f, "endBounds incorrect size", 0.02f);
Object.Destroy(bbox.gameObject);
// Wait for a frame to give Unity a change to actually destroy the object
yield return null;
// Restore the input simulation profile
iss.ControllerSimulationMode = oldSimMode;
yield return null;
}
/// <summary>
/// Test that changing the transform of the bounding box target (rotation, scale, translation)
/// updates the rig bounds
/// </summary>
[UnityTest]
public IEnumerator UpdateTransformUpdatesBounds()
{
var bbox = InstantiateSceneAndDefaultBbox();
bbox.HideElementsInInspector = false;
yield return null;
var startBounds = GetBoundingBoxRigBounds(bbox);
var startCenter = new Vector3(0, 0, 1.5f);
var startSize = new Vector3(.5f, .5f, .5f);
TestUtilities.AssertAboutEqual(startBounds.center, startCenter, "bbox incorrect center at start");
TestUtilities.AssertAboutEqual(startBounds.size, startSize, "bbox incorrect size at start");
bbox.gameObject.transform.localScale *= 2;
yield return null;
var afterScaleBounds = GetBoundingBoxRigBounds(bbox);
var scaledSize = startSize * 2;
TestUtilities.AssertAboutEqual(afterScaleBounds.center, startCenter, "bbox incorrect center after scale");
TestUtilities.AssertAboutEqual(afterScaleBounds.size, scaledSize, "bbox incorrect size after scale");
bbox.gameObject.transform.position += Vector3.one;
yield return null;
var afterTranslateBounds = GetBoundingBoxRigBounds(bbox);
var afterTranslateCenter = Vector3.one + startCenter;
TestUtilities.AssertAboutEqual(afterTranslateBounds.center, afterTranslateCenter, "bbox incorrect center after translate");
TestUtilities.AssertAboutEqual(afterTranslateBounds.size, scaledSize, "bbox incorrect size after translate");
var c0 = bbox.ScaleCorners[0];
var bboxBottomCenter = afterTranslateBounds.center - Vector3.up * afterTranslateBounds.extents.y;
Vector3 cc0 = c0.transform.position - bboxBottomCenter;
float rotateAmount = 30;
bbox.gameObject.transform.Rotate(new Vector3(0, rotateAmount, 0));
yield return null;
Vector3 cc0_rotated = c0.transform.position - bboxBottomCenter;
Assert.AreApproximatelyEqual(Vector3.Angle(cc0, cc0_rotated), 30, $"rotated angle is not correct. expected {rotateAmount} but got {Vector3.Angle(cc0, cc0_rotated)}");
Object.Destroy(bbox.gameObject);
}
/// <summary>
/// Ensure that while using BoundingBox, if that object gets
/// deactivated, that BoundingBox no longer transforms that object.
/// </summary>
[UnityTest]
public IEnumerator DisableObject()
{
float minScale = 0.5f;
float maxScale = 2f;
var bbox = InstantiateSceneAndDefaultBbox();
var scaleHandler = bbox.EnsureComponent<MinMaxScaleConstraint>();
scaleHandler.ScaleMinimum = minScale;
scaleHandler.ScaleMaximum = maxScale;
yield return null;
Vector3 initialScale = bbox.transform.localScale;
const int numHandSteps = 1;
Vector3 initialHandPosition = new Vector3(0, 0, 0.5f);
var frontRightCornerPos = bbox.ScaleCorners[3].transform.position; // front right corner is corner 3
TestHand hand = new TestHand(Handedness.Right);
// Hands grab object at initial position
yield return hand.Show(initialHandPosition);
yield return hand.SetGesture(ArticulatedHandPose.GestureId.OpenSteadyGrabPoint);
yield return hand.MoveTo(frontRightCornerPos, numHandSteps);
yield return hand.SetGesture(ArticulatedHandPose.GestureId.Pinch);
// Verify that scale works before deactivating
yield return hand.Move(Vector3.right * 0.2f, numHandSteps);
Vector3 afterTransformScale = bbox.transform.localScale;
Assert.AreNotEqual(initialScale, afterTransformScale);
// Deactivate object and ensure that we don't scale
bbox.gameObject.SetActive(false);
yield return null;
bbox.gameObject.SetActive(true);
yield return hand.Move(Vector3.right * 0.2f, numHandSteps);
Assert.AreEqual(afterTransformScale, bbox.transform.localScale);
}
/// <summary>
/// Tests setting a target in code that is a different gameobject than the gameobject the boundingbox component is attached to
/// </summary>
[UnityTest]
public IEnumerator SetTarget()
{
// create cube without control
var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube.transform.position = boundingBoxStartCenter;
MixedRealityPlayspace.PerformTransformation(
p =>
{
p.position = Vector3.zero;
p.LookAt(cube.transform.position);
});
cube.transform.localScale = boundingBoxStartScale;
// create another gameobject with boundscontrol attached
var emptyGameObject = new GameObject("empty");
BoundingBox bbox = emptyGameObject.AddComponent<BoundingBox>();
// set target to cube
bbox.Target = cube;
bbox.Active = true;
// front right corner is corner 3
var frontRightCornerPos = cube.transform.Find("rigRoot/corner_3").position;
// grab corner and scale object
Vector3 initialHandPosition = new Vector3(0, 0, 0.5f);
int numSteps = 30;
var delta = new Vector3(0.1f, 0.1f, 0f);
TestHand hand = new TestHand(Handedness.Right);
yield return hand.Show(initialHandPosition);
yield return hand.SetGesture(ArticulatedHandPose.GestureId.OpenSteadyGrabPoint);
yield return hand.MoveTo(frontRightCornerPos, numSteps);
yield return hand.SetGesture(ArticulatedHandPose.GestureId.Pinch);
yield return hand.MoveTo(frontRightCornerPos + delta, numSteps);
var endBounds = cube.GetComponent<BoxCollider>().bounds;
Vector3 expectedCenter = new Vector3(0.033f, 0.033f, 1.467f);
Vector3 expectedSize = Vector3.one * .567f;
TestUtilities.AssertAboutEqual(endBounds.center, expectedCenter, "endBounds incorrect center");
TestUtilities.AssertAboutEqual(endBounds.size, expectedSize, "endBounds incorrect size");
Object.Destroy(emptyGameObject);
Object.Destroy(cube);
// Wait for a frame to give Unity a change to actually destroy the object
yield return null;
}
/// <summary>
/// Returns the AABB of the bounding box rig (corners, edges)
/// that make up the bounding box by using the positions of the corners
/// </summary>
private Bounds GetBoundingBoxRigBounds(BoundingBox bbox)
{
var corners = bbox.ScaleCorners;
Bounds b = new Bounds();
b.center = corners[0].position;
foreach (var c in corners.Skip(1))
{
b.Encapsulate(c.transform.position);
}
return b;
}
}
}
#endif
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
namespace MbUnit.Forms
{
using MbUnit.Core;
using MbUnit.Core.Remoting;
using MbUnit.Core.Reports.Serialization;
public enum ConsoleStream
{
Out,
Error
}
public sealed class ConsoleTextBox : System.Windows.Forms.UserControl
{
private System.Windows.Forms.RichTextBox textBox;
private System.Windows.Forms.ContextMenu contextMenu1;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
private ConsoleStream consoleStream=ConsoleStream.Out;
private ReflectorTreeView tree = null;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
public ConsoleTextBox()
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// TODO: Add any initialization after the InitializeComponent call
}
public override String Text
{
get
{
return this.textBox.Text;
}
set
{
this.textBox.Text = value;
}
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.textBox = new System.Windows.Forms.RichTextBox();
this.contextMenu1 = new System.Windows.Forms.ContextMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.SuspendLayout();
//
// textBox
//
this.textBox.BackColor = System.Drawing.Color.White;
this.textBox.ContextMenu = this.contextMenu1;
this.textBox.Dock = System.Windows.Forms.DockStyle.Fill;
this.textBox.Location = new System.Drawing.Point(0, 0);
this.textBox.Name = "textBox";
this.textBox.ReadOnly = true;
this.textBox.Size = new System.Drawing.Size(440, 368);
this.textBox.TabIndex = 2;
this.textBox.Text = "";
//
// contextMenu1
//
this.contextMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1,
this.menuItem2});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.Text = "Save";
this.menuItem1.Click += new System.EventHandler(this.menuItem1_Click);
//
// menuItem2
//
this.menuItem2.Index = 1;
this.menuItem2.Text = "Copy To Clipboard";
this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
//
// XmlTextBox
//
this.ContextMenu = this.contextMenu1;
this.Controls.Add(this.textBox);
this.Name = "XmlTextBox";
this.Size = new System.Drawing.Size(440, 368);
this.ResumeLayout(false);
}
#endregion
[Browsable(false)]
public ReflectorTreeView Tree
{
get
{
return this.tree;
}
set
{
if (this.tree != null && value != this.tree)
{
this.tree.AfterSelect -= new TreeViewEventHandler(treeView_AfterSelect);
this.tree.FinishTests -= new EventHandler(treeView_FinishTests);
}
this.tree = value;
if (this.tree != null)
{
this.tree.AfterSelect += new TreeViewEventHandler(treeView_AfterSelect);
this.tree.FinishTests += new EventHandler(treeView_FinishTests);
}
}
}
[Category("Data")]
public ConsoleStream ConsoleStream
{
get
{
return this.consoleStream;
}
set
{
this.consoleStream = value;
}
}
private void treeView_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
SafelyDisplaySelectedNodeResult();
}
private void treeView_FinishTests( object sender, EventArgs e )
{
SafelyDisplaySelectedNodeResult();
}
private void SafelyDisplaySelectedNodeResult()
{
try
{
if (this.InvokeRequired)
{
this.Invoke(new MethodInvoker(this.DisplaySelectedNodeResult));
}
else
{
DisplaySelectedNodeResult();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void DisplaySelectedNodeResult()
{
this.textBox.Text = "";
UnitTreeNode node = this.tree.TypeTree.SelectedNode as UnitTreeNode;
if (node == null)
return;
ReportRun result = this.tree.TestDomains.GetResult(node);
if (result != null)
{
switch (this.consoleStream)
{
case ConsoleStream.Out:
this.textBox.Text = result.ConsoleOut;
break;
case ConsoleStream.Error:
this.textBox.Text = result.ConsoleError;
break;
}
}
this.Refresh();
}
private void menuItem1_Click(object sender, System.EventArgs e)
{
SaveFileDialog dlg = new SaveFileDialog();
if(dlg.ShowDialog() != DialogResult.OK)
return;
using (StreamWriter sw = new StreamWriter(dlg.FileName))
{
sw.Write(this.textBox.Text);
}
}
private void menuItem2_Click(object sender, System.EventArgs e)
{
Clipboard.SetDataObject( this.textBox.Text );
}
public void Clear()
{
this.textBox.Text = "";
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void XorUInt16()
{
var test = new SimpleBinaryOpTest__XorUInt16();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleBinaryOpTest__XorUInt16
{
private const int VectorSize = 16;
private const int ElementCount = VectorSize / sizeof(UInt16);
private static UInt16[] _data1 = new UInt16[ElementCount];
private static UInt16[] _data2 = new UInt16[ElementCount];
private static Vector128<UInt16> _clsVar1;
private static Vector128<UInt16> _clsVar2;
private Vector128<UInt16> _fld1;
private Vector128<UInt16> _fld2;
private SimpleBinaryOpTest__DataTable<UInt16> _dataTable;
static SimpleBinaryOpTest__XorUInt16()
{
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar1), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar2), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
}
public SimpleBinaryOpTest__XorUInt16()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld1), ref Unsafe.As<UInt16, byte>(ref _data1[0]), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld2), ref Unsafe.As<UInt16, byte>(ref _data2[0]), VectorSize);
for (var i = 0; i < ElementCount; i++) { _data1[i] = (ushort)(random.Next(0, ushort.MaxValue)); _data2[i] = (ushort)(random.Next(0, ushort.MaxValue)); }
_dataTable = new SimpleBinaryOpTest__DataTable<UInt16>(_data1, _data2, new UInt16[ElementCount], VectorSize);
}
public bool IsSupported => Sse2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Sse2.Xor(
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Sse2.Xor(
Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Sse2.Xor(
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr))
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr),
Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr)
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Sse2).GetMethod(nameof(Sse2.Xor), new Type[] { typeof(Vector128<UInt16>), typeof(Vector128<UInt16>) })
.Invoke(null, new object[] {
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr)),
Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr))
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector128<UInt16>)(result));
ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Sse2.Xor(
_clsVar1,
_clsVar2
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var left = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray1Ptr);
var right = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArray2Ptr);
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var left = Sse2.LoadVector128((UInt16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadVector128((UInt16*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var left = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray1Ptr));
var right = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArray2Ptr));
var result = Sse2.Xor(left, right);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(left, right, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleBinaryOpTest__XorUInt16();
var result = Sse2.Xor(test._fld1, test._fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Sse2.Xor(_fld1, _fld2);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector128<UInt16> left, Vector128<UInt16> right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[ElementCount];
UInt16[] inArray2 = new UInt16[ElementCount];
UInt16[] outArray = new UInt16[ElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left);
Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "")
{
UInt16[] inArray1 = new UInt16[ElementCount];
UInt16[] inArray2 = new UInt16[ElementCount];
UInt16[] outArray = new UInt16[ElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray1, inArray2, outArray, method);
}
private void ValidateResult(UInt16[] left, UInt16[] right, UInt16[] result, [CallerMemberName] string method = "")
{
if ((ushort)(left[0] ^ right[0]) != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < left.Length; i++)
{
if ((ushort)(left[i] ^ right[i]) != result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Xor)}<UInt16>: {method} failed:");
Console.WriteLine($" left: ({string.Join(", ", left)})");
Console.WriteLine($" right: ({string.Join(", ", right)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
// 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.Text;
using System.Xml;
using Microsoft.Build.Framework;
using Microsoft.Build.BuildEngine.Shared;
namespace Microsoft.Build.BuildEngine
{
// internal delegates to make unit testing the TaskRegistry support easier
internal delegate string[] GetFiles(string path, string pattern);
internal delegate XmlDocument LoadXmlFromPath(string path);
/// <summary>
/// Encapsulates all the state associated with a tools version. Each ToolsetState
/// aggregates a Toolset, which contains that part of the state that is externally visible.
/// </summary>
internal class ToolsetState
{
#region Constructors
/// <summary>
/// Internal constructor
/// </summary>
/// <param name="engine"></param>
/// <param name="toolset"></param>
internal ToolsetState(Engine engine, Toolset toolset)
: this(engine,
toolset,
new GetFiles(Directory.GetFiles),
new LoadXmlFromPath(ToolsetState.LoadXmlDocumentFromPath)
)
{
}
/// <summary>
/// Additional constructor to make unit testing the TaskRegistry support easier
/// </summary>
/// <remarks>
/// Internal for unit test purposes only.
/// </remarks>
/// <param name="engine"></param>
/// <param name="toolset"></param>
/// <param name="getFiles"></param>
/// <param name="loadXmlFromPath"></param>
internal ToolsetState(Engine engine,
Toolset toolset,
GetFiles getFiles,
LoadXmlFromPath loadXmlFromPath
)
{
this.parentEngine = engine;
this.loggingServices = engine.LoggingServices;
ErrorUtilities.VerifyThrowArgumentNull(toolset, "toolset");
this.toolset = toolset;
this.getFiles = getFiles;
this.loadXmlFromPath = loadXmlFromPath;
}
#endregion
#region Properties
/// <summary>
/// Associated Toolset (version name, toolset path, optional associated properties)
/// </summary>
internal Toolset Toolset
{
get
{
return this.toolset;
}
}
/// <summary>
/// Tools version for this toolset
/// </summary>
internal string ToolsVersion
{
get
{
return this.toolset.ToolsVersion;
}
}
/// <summary>
/// Tools path for this toolset
/// </summary>
internal string ToolsPath
{
get
{
return this.toolset.ToolsPath;
}
}
/// <summary>
/// Wrapper for the Toolset property group
/// </summary>
internal BuildPropertyGroup BuildProperties
{
get
{
return this.toolset.BuildProperties;
}
}
#endregion
#region Methods
/// <summary>
/// Used for validating the project (file) and its imported files against a designated schema.
///
/// PERF NOTE: this property helps to delay creation of the ProjectSchemaValidationHandler object
/// </summary>
internal ProjectSchemaValidationHandler SchemaValidator(BuildEventContext buildEventContext)
{
if (schemaValidator == null)
{
schemaValidator = new ProjectSchemaValidationHandler(buildEventContext, loggingServices, toolset.ToolsPath);
}
return schemaValidator;
}
/// <summary>
/// Return a task registry stub for the tasks in the *.tasks file for this toolset
/// </summary>
/// <param name="buildEventContext"></param>
/// <returns></returns>
internal ITaskRegistry GetTaskRegistry(BuildEventContext buildEventContext)
{
RegisterDefaultTasks(buildEventContext);
return defaultTaskRegistry;
}
/// <summary>
/// Sets the default task registry to the provided value.
/// </summary>
/// <param name="taskRegistry"></param>
internal void SetTaskRegistry(ITaskRegistry taskRegistry)
{
ErrorUtilities.VerifyThrowArgumentNull(taskRegistry, "taskRegistry");
defaultTasksRegistrationAttempted = true;
defaultTaskRegistry = taskRegistry;
}
/// <summary>
/// Method extracted strictly to make unit testing easier.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private static XmlDocument LoadXmlDocumentFromPath(string path)
{
XmlDocument xmlDocumentFromPath = new XmlDocument();
xmlDocumentFromPath.Load(path);
return xmlDocumentFromPath;
}
/// <summary>
/// Used to load information about default MSBuild tasks i.e. tasks that do not need to be explicitly declared in projects
/// with the <UsingTask> element. Default task information is read from special files, which are located in the same
/// directory as the MSBuild binaries.
/// </summary>
/// <remarks>
/// 1) a default tasks file needs the <Project> root tag in order to be well-formed
/// 2) the XML declaration tag <?xml ...> is ignored
/// 3) comment tags are always ignored regardless of their placement
/// 4) the rest of the tags are expected to be <UsingTask> tags
/// </remarks>
private void RegisterDefaultTasks(BuildEventContext buildEventContext)
{
if (!defaultTasksRegistrationAttempted)
{
try
{
this.defaultTaskRegistry = new TaskRegistry();
string[] defaultTasksFiles = { };
try
{
defaultTasksFiles = getFiles(toolset.ToolsPath, defaultTasksFilePattern);
if (defaultTasksFiles.Length == 0)
{
loggingServices.LogWarning( buildEventContext, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty),
"DefaultTasksFileLoadFailureWarning",
defaultTasksFilePattern, toolset.ToolsPath, String.Empty);
}
}
// handle security problems when finding the default tasks files
catch (UnauthorizedAccessException e)
{
loggingServices.LogWarning( buildEventContext, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty),
"DefaultTasksFileLoadFailureWarning",
defaultTasksFilePattern, toolset.ToolsPath, e.Message);
}
// handle problems when reading the default tasks files
catch (Exception e) // Catching Exception, but rethrowing unless it's an IO related exception.
{
if (ExceptionHandling.NotExpectedException(e))
throw;
loggingServices.LogWarning( buildEventContext, new BuildEventFileInfo(/* this warning truly does not involve any file */ String.Empty),
"DefaultTasksFileLoadFailureWarning",
defaultTasksFilePattern, toolset.ToolsPath, e.Message);
}
BuildPropertyGroup propertyBag = null;
foreach (string defaultTasksFile in defaultTasksFiles)
{
try
{
XmlDocument defaultTasks = loadXmlFromPath(defaultTasksFile);
// look for the first root tag that is not a comment or an XML declaration -- this should be the <Project> tag
// NOTE: the XML parser will guarantee there is only one real root element in the file
// but we need to find it amongst the other types of XmlNode at the root.
foreach (XmlNode topLevelNode in defaultTasks.ChildNodes)
{
if (XmlUtilities.IsXmlRootElement(topLevelNode))
{
ProjectErrorUtilities.VerifyThrowInvalidProject(topLevelNode.LocalName == XMakeElements.project,
topLevelNode, "UnrecognizedElement", topLevelNode.Name);
ProjectErrorUtilities.VerifyThrowInvalidProject((topLevelNode.Prefix.Length == 0) && (String.Compare(topLevelNode.NamespaceURI, XMakeAttributes.defaultXmlNamespace, StringComparison.OrdinalIgnoreCase) == 0),
topLevelNode, "ProjectMustBeInMSBuildXmlNamespace", XMakeAttributes.defaultXmlNamespace);
// the <Project> tag can only the XML namespace -- no other attributes
foreach (XmlAttribute projectAttribute in topLevelNode.Attributes)
{
ProjectXmlUtilities.VerifyThrowProjectInvalidAttribute(projectAttribute.Name == XMakeAttributes.xmlns, projectAttribute);
}
// look at all the child tags of the <Project> root tag we found
foreach (XmlNode usingTaskNode in topLevelNode.ChildNodes)
{
if (usingTaskNode.NodeType != XmlNodeType.Comment)
{
ProjectErrorUtilities.VerifyThrowInvalidProject(usingTaskNode.Name == XMakeElements.usingTask,
usingTaskNode, "UnrecognizedElement", usingTaskNode.Name);
// Initialize the property bag if it hasn't been already.
if (propertyBag == null)
{
// Set the value of the MSBuildBinPath/ToolsPath properties.
BuildPropertyGroup reservedPropertyBag = new BuildPropertyGroup();
reservedPropertyBag.SetProperty(
new BuildProperty(ReservedPropertyNames.binPath, EscapingUtilities.Escape(toolset.ToolsPath),
PropertyType.ReservedProperty));
reservedPropertyBag.SetProperty(
new BuildProperty(ReservedPropertyNames.toolsPath, EscapingUtilities.Escape(toolset.ToolsPath),
PropertyType.ReservedProperty));
// Also set MSBuildAssemblyVersion so that the tasks file can tell between v4 and v12 MSBuild
reservedPropertyBag.SetProperty(
new BuildProperty(ReservedPropertyNames.assemblyVersion, Constants.AssemblyVersion,
PropertyType.ReservedProperty));
propertyBag = new BuildPropertyGroup();
propertyBag.ImportInitialProperties(parentEngine.EnvironmentProperties, reservedPropertyBag, BuildProperties, parentEngine.GlobalProperties);
}
defaultTaskRegistry.RegisterTask(new UsingTask((XmlElement)usingTaskNode, true), new Expander(propertyBag), loggingServices, buildEventContext);
}
}
break;
}
}
}
// handle security problems when loading the default tasks file
catch (UnauthorizedAccessException e)
{
loggingServices.LogError(buildEventContext, new BuildEventFileInfo(defaultTasksFile), "DefaultTasksFileFailure", e.Message);
break;
}
// handle problems when loading the default tasks file
catch (IOException e)
{
loggingServices.LogError(buildEventContext, new BuildEventFileInfo(defaultTasksFile), "DefaultTasksFileFailure", e.Message);
break;
}
// handle XML errors in the default tasks file
catch (XmlException e)
{
ProjectFileErrorUtilities.VerifyThrowInvalidProjectFile(false, new BuildEventFileInfo(e),
"DefaultTasksFileFailure", e.Message);
}
}
}
finally
{
defaultTasksRegistrationAttempted = true;
}
}
}
#endregion
#region Data
// The parent Engine object used for logging
private Engine parentEngine;
// Logging service for posting messages
private EngineLoggingServices loggingServices;
// The settings for this toolset (version name, path, and properties)
private Toolset toolset;
// these files list all default tasks and task assemblies that do not need to be explicitly declared by projects
private const string defaultTasksFilePattern = "*.tasks";
// indicates if the default tasks file has already been scanned
private bool defaultTasksRegistrationAttempted = false;
// holds all the default tasks we know about and the assemblies they exist in
private ITaskRegistry defaultTaskRegistry = null;
// used for validating the project (file) and its imported files against a designated schema
private ProjectSchemaValidationHandler schemaValidator;
// private delegates to make unit testing the TaskRegistry support easier
private GetFiles getFiles = null;
private LoadXmlFromPath loadXmlFromPath = null;
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.Collections
{
// A vector of bits. Use this to store bits efficiently, without having to do bit
// shifting yourself.
[Serializable]
[System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public sealed class BitArray : ICollection, ICloneable
{
private int[] m_array; // Do not rename (binary serialization)
private int m_length; // Do not rename (binary serialization)
private int _version; // Do not rename (binary serialization)
[NonSerialized]
private object _syncRoot;
private const int _ShrinkThreshold = 256;
/*=========================================================================
** Allocates space to hold length bit values. All of the values in the bit
** array are set to false.
**
** Exceptions: ArgumentException if length < 0.
=========================================================================*/
public BitArray(int length)
: this(length, false)
{
}
/*=========================================================================
** Allocates space to hold length bit values. All of the values in the bit
** array are set to defaultValue.
**
** Exceptions: ArgumentOutOfRangeException if length < 0.
=========================================================================*/
public BitArray(int length, bool defaultValue)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length), length, SR.ArgumentOutOfRange_NeedNonNegNum);
}
m_array = new int[GetArrayLength(length, BitsPerInt32)];
m_length = length;
int fillValue = defaultValue ? unchecked(((int)0xffffffff)) : 0;
for (int i = 0; i < m_array.Length; i++)
{
m_array[i] = fillValue;
}
_version = 0;
}
/*=========================================================================
** Allocates space to hold the bit values in bytes. bytes[0] represents
** bits 0 - 7, bytes[1] represents bits 8 - 15, etc. The LSB of each byte
** represents the lowest index value; bytes[0] & 1 represents bit 0,
** bytes[0] & 2 represents bit 1, bytes[0] & 4 represents bit 2, etc.
**
** Exceptions: ArgumentException if bytes == null.
=========================================================================*/
public BitArray(byte[] bytes)
{
if (bytes == null)
{
throw new ArgumentNullException(nameof(bytes));
}
// this value is chosen to prevent overflow when computing m_length.
// m_length is of type int32 and is exposed as a property, so
// type of m_length can't be changed to accommodate.
if (bytes.Length > int.MaxValue / BitsPerByte)
{
throw new ArgumentException(SR.Format(SR.Argument_ArrayTooLarge, BitsPerByte), nameof(bytes));
}
m_array = new int[GetArrayLength(bytes.Length, BytesPerInt32)];
m_length = bytes.Length * BitsPerByte;
int i = 0;
int j = 0;
while (bytes.Length - j >= 4)
{
m_array[i++] = (bytes[j] & 0xff) |
((bytes[j + 1] & 0xff) << 8) |
((bytes[j + 2] & 0xff) << 16) |
((bytes[j + 3] & 0xff) << 24);
j += 4;
}
Debug.Assert(bytes.Length - j >= 0, "BitArray byteLength problem");
Debug.Assert(bytes.Length - j < 4, "BitArray byteLength problem #2");
switch (bytes.Length - j)
{
case 3:
m_array[i] = ((bytes[j + 2] & 0xff) << 16);
goto case 2;
// fall through
case 2:
m_array[i] |= ((bytes[j + 1] & 0xff) << 8);
goto case 1;
// fall through
case 1:
m_array[i] |= (bytes[j] & 0xff);
break;
}
_version = 0;
}
public BitArray(bool[] values)
{
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
m_array = new int[GetArrayLength(values.Length, BitsPerInt32)];
m_length = values.Length;
for (int i = 0; i < values.Length; i++)
{
if (values[i])
m_array[i / 32] |= (1 << (i % 32));
}
_version = 0;
}
/*=========================================================================
** Allocates space to hold the bit values in values. values[0] represents
** bits 0 - 31, values[1] represents bits 32 - 63, etc. The LSB of each
** integer represents the lowest index value; values[0] & 1 represents bit
** 0, values[0] & 2 represents bit 1, values[0] & 4 represents bit 2, etc.
**
** Exceptions: ArgumentException if values == null.
=========================================================================*/
public BitArray(int[] values)
{
if (values == null)
{
throw new ArgumentNullException(nameof(values));
}
// this value is chosen to prevent overflow when computing m_length
if (values.Length > int.MaxValue / BitsPerInt32)
{
throw new ArgumentException(SR.Format(SR.Argument_ArrayTooLarge, BitsPerInt32), nameof(values));
}
m_array = new int[values.Length];
Array.Copy(values, 0, m_array, 0, values.Length);
m_length = values.Length * BitsPerInt32;
_version = 0;
}
/*=========================================================================
** Allocates a new BitArray with the same length and bit values as bits.
**
** Exceptions: ArgumentException if bits == null.
=========================================================================*/
public BitArray(BitArray bits)
{
if (bits == null)
{
throw new ArgumentNullException(nameof(bits));
}
int arrayLength = GetArrayLength(bits.m_length, BitsPerInt32);
m_array = new int[arrayLength];
Array.Copy(bits.m_array, 0, m_array, 0, arrayLength);
m_length = bits.m_length;
_version = bits._version;
}
public bool this[int index]
{
get
{
return Get(index);
}
set
{
Set(index, value);
}
}
/*=========================================================================
** Returns the bit value at position index.
**
** Exceptions: ArgumentOutOfRangeException if index < 0 or
** index >= GetLength().
=========================================================================*/
public bool Get(int index)
{
if (index < 0 || index >= Length)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
return (m_array[index / 32] & (1 << (index % 32))) != 0;
}
/*=========================================================================
** Sets the bit value at position index to value.
**
** Exceptions: ArgumentOutOfRangeException if index < 0 or
** index >= GetLength().
=========================================================================*/
public void Set(int index, bool value)
{
if (index < 0 || index >= Length)
{
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_Index);
}
if (value)
{
m_array[index / 32] |= (1 << (index % 32));
}
else
{
m_array[index / 32] &= ~(1 << (index % 32));
}
_version++;
}
/*=========================================================================
** Sets all the bit values to value.
=========================================================================*/
public void SetAll(bool value)
{
int fillValue = value ? unchecked(((int)0xffffffff)) : 0;
int ints = GetArrayLength(m_length, BitsPerInt32);
for (int i = 0; i < ints; i++)
{
m_array[i] = fillValue;
}
_version++;
}
/*=========================================================================
** Returns a reference to the current instance ANDed with value.
**
** Exceptions: ArgumentException if value == null or
** value.Length != this.Length.
=========================================================================*/
public BitArray And(BitArray value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (Length != value.Length)
throw new ArgumentException(SR.Arg_ArrayLengthsDiffer);
int ints = GetArrayLength(m_length, BitsPerInt32);
for (int i = 0; i < ints; i++)
{
m_array[i] &= value.m_array[i];
}
_version++;
return this;
}
/*=========================================================================
** Returns a reference to the current instance ORed with value.
**
** Exceptions: ArgumentException if value == null or
** value.Length != this.Length.
=========================================================================*/
public BitArray Or(BitArray value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (Length != value.Length)
throw new ArgumentException(SR.Arg_ArrayLengthsDiffer);
int ints = GetArrayLength(m_length, BitsPerInt32);
for (int i = 0; i < ints; i++)
{
m_array[i] |= value.m_array[i];
}
_version++;
return this;
}
/*=========================================================================
** Returns a reference to the current instance XORed with value.
**
** Exceptions: ArgumentException if value == null or
** value.Length != this.Length.
=========================================================================*/
public BitArray Xor(BitArray value)
{
if (value == null)
throw new ArgumentNullException(nameof(value));
if (Length != value.Length)
throw new ArgumentException(SR.Arg_ArrayLengthsDiffer);
int ints = GetArrayLength(m_length, BitsPerInt32);
for (int i = 0; i < ints; i++)
{
m_array[i] ^= value.m_array[i];
}
_version++;
return this;
}
/*=========================================================================
** Inverts all the bit values. On/true bit values are converted to
** off/false. Off/false bit values are turned on/true. The current instance
** is updated and returned.
=========================================================================*/
public BitArray Not()
{
int ints = GetArrayLength(m_length, BitsPerInt32);
for (int i = 0; i < ints; i++)
{
m_array[i] = ~m_array[i];
}
_version++;
return this;
}
/*=========================================================================
** Shift all the bit values to right on count bits. The current instance is
** updated and returned.
*
** Exceptions: ArgumentOutOfRangeException if count < 0
=========================================================================*/
public BitArray RightShift(int count)
{
if (count <= 0)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum);
}
_version++;
return this;
}
int toIndex = 0;
int ints = GetArrayLength(m_length, BitsPerInt32);
if (count < m_length)
{
int shiftCount;
// We can not use Math.DivRem without taking a dependency on System.Runtime.Extensions
int fromIndex = count / BitsPerInt32;
shiftCount = count - fromIndex * BitsPerInt32; // Optimized Rem
if (shiftCount == 0)
{
unchecked
{
uint mask = uint.MaxValue >> (BitsPerInt32 - m_length % BitsPerInt32);
m_array[ints - 1] &= (int)mask;
}
Array.Copy(m_array, fromIndex, m_array, 0, ints - fromIndex);
toIndex = ints - fromIndex;
}
else
{
int lastIndex = ints - 1;
unchecked
{
while (fromIndex < lastIndex)
{
uint right = (uint)m_array[fromIndex] >> shiftCount;
int left = m_array[++fromIndex] << (BitsPerInt32 - shiftCount);
m_array[toIndex++] = left | (int)right;
}
uint mask = uint.MaxValue >> (BitsPerInt32 - m_length % BitsPerInt32);
mask &= (uint)m_array[fromIndex];
m_array[toIndex++] = (int)(mask >> shiftCount);
}
}
}
Array.Clear(m_array, toIndex, ints - toIndex);
_version++;
return this;
}
/*=========================================================================
** Shift all the bit values to left on count bits. The current instance is
** updated and returned.
*
** Exceptions: ArgumentOutOfRangeException if count < 0
=========================================================================*/
public BitArray LeftShift(int count)
{
if (count <= 0)
{
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), count, SR.ArgumentOutOfRange_NeedNonNegNum);
}
_version++;
return this;
}
int lengthToClear;
if (count < m_length)
{
int lastIndex = (m_length - 1) / BitsPerInt32;
int shiftCount;
// We can not use Math.DivRem without taking a dependency on System.Runtime.Extensions
lengthToClear = count / BitsPerInt32;
shiftCount = count - lengthToClear * BitsPerInt32; // Optimized Rem
if (shiftCount == 0)
{
Array.Copy(m_array, 0, m_array, lengthToClear, lastIndex + 1 - lengthToClear);
}
else
{
int fromindex = lastIndex - lengthToClear;
unchecked
{
while (fromindex > 0)
{
int left = m_array[fromindex] << shiftCount;
uint right = (uint)m_array[--fromindex] >> (BitsPerInt32 - shiftCount);
m_array[lastIndex] = left | (int)right;
lastIndex--;
}
m_array[lastIndex] = m_array[fromindex] << shiftCount;
}
}
}
else
{
lengthToClear = GetArrayLength(m_length, BitsPerInt32); // Clear all
}
Array.Clear(m_array, 0, lengthToClear);
_version++;
return this;
}
public int Length
{
get
{
return m_length;
}
set
{
if (value < 0)
{
throw new ArgumentOutOfRangeException(nameof(value), value, SR.ArgumentOutOfRange_NeedNonNegNum);
}
int newints = GetArrayLength(value, BitsPerInt32);
if (newints > m_array.Length || newints + _ShrinkThreshold < m_array.Length)
{
// grow or shrink (if wasting more than _ShrinkThreshold ints)
Array.Resize(ref m_array, newints);
}
if (value > m_length)
{
// clear high bit values in the last int
int last = GetArrayLength(m_length, BitsPerInt32) - 1;
int bits = m_length % 32;
if (bits > 0)
{
m_array[last] &= (1 << bits) - 1;
}
// clear remaining int values
Array.Clear(m_array, last + 1, newints - last - 1);
}
m_length = value;
_version++;
}
}
public void CopyTo(Array array, int index)
{
if (array == null)
throw new ArgumentNullException(nameof(array));
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), index, SR.ArgumentOutOfRange_NeedNonNegNum);
if (array.Rank != 1)
throw new ArgumentException(SR.Arg_RankMultiDimNotSupported, nameof(array));
int[] intArray = array as int[];
if (intArray != null)
{
int last = GetArrayLength(m_length, BitsPerInt32) - 1;
int extraBits = m_length % BitsPerInt32;
if (extraBits == 0)
{
// we have perfect bit alignment, no need to sanitize, just copy
Array.Copy(m_array, 0, intArray, index, GetArrayLength(m_length, BitsPerInt32));
}
else
{
// do not copy the last int, as it is not completely used
Array.Copy(m_array, 0, intArray, index, GetArrayLength(m_length, BitsPerInt32) - 1);
// the last int needs to be masked
intArray[index + last] = m_array[last] & unchecked((1 << extraBits) - 1);
}
}
else if (array is byte[])
{
int extraBits = m_length % BitsPerByte;
int arrayLength = GetArrayLength(m_length, BitsPerByte);
if ((array.Length - index) < arrayLength)
throw new ArgumentException(SR.Argument_InvalidOffLen);
if (extraBits > 0)
{
// last byte is not aligned, we will directly copy one less byte
arrayLength -= 1;
}
byte[] b = (byte[])array;
// copy all the perfectly-aligned bytes
for (int i = 0; i < arrayLength; i++)
b[index + i] = (byte)((m_array[i / 4] >> ((i % 4) * 8)) & 0x000000FF); // Shift to bring the required byte to LSB, then mask
if (extraBits > 0)
{
// mask the final byte
int i = arrayLength;
b[index + i] = (byte)((m_array[i / 4] >> ((i % 4) * 8)) & ((1 << extraBits) - 1));
}
}
else if (array is bool[])
{
if (array.Length - index < m_length)
throw new ArgumentException(SR.Argument_InvalidOffLen);
bool[] b = (bool[])array;
for (int i = 0; i < m_length; i++)
b[index + i] = ((m_array[i / 32] >> (i % 32)) & 0x00000001) != 0;
}
else
throw new ArgumentException(SR.Arg_BitArrayTypeUnsupported, nameof(array));
}
public int Count
{
get
{
return m_length;
}
}
public Object SyncRoot
{
get
{
if (_syncRoot == null)
{
System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new object(), null);
}
return _syncRoot;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public object Clone()
{
return new BitArray(this);
}
public IEnumerator GetEnumerator()
{
return new BitArrayEnumeratorSimple(this);
}
// XPerY=n means that n Xs can be stored in 1 Y.
private const int BitsPerInt32 = 32;
private const int BytesPerInt32 = 4;
private const int BitsPerByte = 8;
/// <summary>
/// Used for conversion between different representations of bit array.
/// Returns (n+(div-1))/div, rearranged to avoid arithmetic overflow.
/// For example, in the bit to int case, the straightforward calc would
/// be (n+31)/32, but that would cause overflow. So instead it's
/// rearranged to ((n-1)/32) + 1, with special casing for 0.
///
/// Usage:
/// GetArrayLength(77, BitsPerInt32): returns how many ints must be
/// allocated to store 77 bits.
/// </summary>
/// <param name="n"></param>
/// <param name="div">use a conversion constant, e.g. BytesPerInt32 to get
/// how many ints are required to store n bytes</param>
/// <returns></returns>
private static int GetArrayLength(int n, int div)
{
Debug.Assert(div > 0, "GetArrayLength: div arg must be greater than 0");
return n > 0 ? (((n - 1) / div) + 1) : 0;
}
private class BitArrayEnumeratorSimple : IEnumerator, ICloneable
{
private BitArray bitarray;
private int index;
private int version;
private bool currentElement;
internal BitArrayEnumeratorSimple(BitArray bitarray)
{
this.bitarray = bitarray;
this.index = -1;
version = bitarray._version;
}
public object Clone()
{
return MemberwiseClone();
}
public virtual bool MoveNext()
{
ICollection bitarrayAsICollection = bitarray;
if (version != bitarray._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
if (index < (bitarrayAsICollection.Count - 1))
{
index++;
currentElement = bitarray.Get(index);
return true;
}
else
index = bitarrayAsICollection.Count;
return false;
}
public virtual object Current
{
get
{
if (index == -1)
throw new InvalidOperationException(SR.InvalidOperation_EnumNotStarted);
if (index >= ((ICollection)bitarray).Count)
throw new InvalidOperationException(SR.InvalidOperation_EnumEnded);
return currentElement;
}
}
public void Reset()
{
if (version != bitarray._version) throw new InvalidOperationException(SR.InvalidOperation_EnumFailedVersion);
index = -1;
}
}
}
}
| |
using System;
using Gtk;
using System.Diagnostics;
namespace FirefoxCleaner
{
public partial class MainWindow: Gtk.Window
{
Cleaner cleaner = new Cleaner ();
public MainWindow () : base (Gtk.WindowType.Toplevel)
{
Build ();
if (cleaner.FirefoxAppPath == string.Empty) {
Additional.GetMessageBox(this,
"FirefoxClearing error",
"Mozilla is not installed in your computer",
"",
DialogFlags.Modal,
MessageType.Warning,
ButtonsType.Ok);
MainPanel.Sensitive = false;
return;
}
if (Cleaner.osPlatform == PlatformID.Unix) {
FFUpdateLogs.Sensitive = false;
MZUpdates.Sensitive = false;
MaintenServLogs.Sensitive = false;
GetUserPassword usPassDlg = new GetUserPassword();
if(usPassDlg.IsPushedOK)
{
Cleaner.UserPasswd = usPassDlg.UserPassword;
}
else
{
this.Sensitive = false;
}
usPassDlg.Destroy();
}
ClearBtn.IsFocus = true;
}
protected void OnDeleteEvent (object sender, DeleteEventArgs a)
{
Application.Quit ();
a.RetVal = true;
}
protected void OnClearBtnClicked (object sender, EventArgs e)
{
try
{
// Check is Firefox running
Additional.IsFirefoxRunning ();
// Run cleaning
cleaner.Run ();
}
catch(ApplicationException appex) {
Additional.GetMessageBox (null,
"FirefoxClearing error",
appex.Message,
"",
DialogFlags.Modal,
MessageType.Error,
ButtonsType.Ok);
}
catch(Exception ex) {
Additional.GetMessageBox (null,
"FirefoxClearing error",
"ERROR MESSAGE: " + ex.Message,
"",
DialogFlags.Modal,
MessageType.Error,
ButtonsType.Ok);
}
}
#region checkboxes
protected void OnInetHistoryClicked (object sender, EventArgs e)
{
if (InetHistory.Active == true)
cleaner.SelectInternetHistory (true);
else
cleaner.SelectInternetHistory();
}
protected void OnInetCacheClicked (object sender, EventArgs e)
{
if (InetCache.Active == true)
cleaner.SelectInternetCache (true);
else
cleaner.SelectInternetCache();
}
protected void OnCookiesClicked (object sender, EventArgs e)
{
if (Cookies.Active == true)
cleaner.SelectCookies (true);
else
cleaner.SelectCookies();
}
protected void OnAdblockBackupsClicked (object sender, EventArgs e)
{
if (AdblockBackups.Active == true)
cleaner.SelectAdblockBackups (true);
else
cleaner.SelectAdblockBackups();
}
protected void OnBookmarkBackupsClicked (object sender, EventArgs e)
{
if (BookmarkBackups.Active == true)
cleaner.SelectBookmarkBackups (true);
else
cleaner.SelectBookmarkBackups();
}
protected void OnCrashReportsClicked (object sender, EventArgs e)
{
if (CrashReports.Active == true)
cleaner.SelectCrashReports (true);
else
cleaner.SelectCrashReports();
}
protected void OnDownloadHistoryClicked (object sender, EventArgs e)
{
if (DownloadHistory.Active == true)
cleaner.SelectDownloadHistory (true);
else
cleaner.SelectDownloadHistory();
}
protected void OnFFCorruptSQLClicked (object sender, EventArgs e)
{
if (FFCorruptSQL.Active == true)
cleaner.SelectFirefoxCorruptSQLites (true);
else
cleaner.SelectFirefoxCorruptSQLites();
}
protected void OnFFExtLogClicked (object sender, EventArgs e)
{
if (FFExtLog.Active == true)
cleaner.SelectFirefoxExtensionsLogs (true);
else
cleaner.SelectFirefoxExtensionsLogs();
}
protected void OnFFLogsClicked (object sender, EventArgs e)
{
if (FFLogs.Active == true)
cleaner.SelectFirefoxLogs (true);
else
cleaner.SelectFirefoxLogs();
}
protected void OnFFMinidumpsClicked (object sender, EventArgs e)
{
if (FFMinidumps.Active == true)
cleaner.SelectFirefoxMinidumps (true);
else
cleaner.SelectFirefoxMinidumps();
}
protected void OnFFStartupCacheClicked (object sender, EventArgs e)
{
if (FFStartupCache.Active == true)
cleaner.SelectFirefoxStartupCache (true);
else
cleaner.SelectFirefoxStartupCache();
}
protected void OnFFTelemetryClicked (object sender, EventArgs e)
{
if (FFTelemetry.Active == true)
cleaner.SelectFirefoxTelemetry (true);
else
cleaner.SelectFirefoxTelemetry();
}
protected void OnFFTestPilotErrorLogsClicked (object sender, EventArgs e)
{
if (FFTestPilotErrorLogs.Active == true)
cleaner.SelectFirefoxTestPilotErrorLogs (true);
else
cleaner.SelectFirefoxTestPilotErrorLogs();
}
protected void OnFFUpdateLogsClicked (object sender, EventArgs e)
{
if (FFUpdateLogs.Active == true)
cleaner.SelectFirefoxUpdateLogs (true);
else
cleaner.SelectFirefoxUpdateLogs();
}
protected void OnFFurlclassifier3Clicked (object sender, EventArgs e)
{
if (FFurlclassifier3.Active == true)
cleaner.SelectFirefoxUrlclassifier (true);
else
cleaner.SelectFirefoxUrlclassifier();
}
protected void OnFFwebappsstoreClicked (object sender, EventArgs e)
{
if (FFwebappsstore.Active == true)
cleaner.SelectFirefoxWebappstore (true);
else
cleaner.SelectFirefoxWebappstore();
}
protected void OnFlashGotClicked (object sender, EventArgs e)
{
if (FlashGot.Active == true)
cleaner.SelectFlashGot (true);
else
cleaner.SelectFlashGot();
}
protected void OnLockFilesClicked (object sender, EventArgs e)
{
if (LockFiles.Active == true)
cleaner.SelectLockFiles (true);
else
cleaner.SelectLockFiles();
}
protected void OnMaintenServLogsClicked (object sender, EventArgs e)
{
if (MaintenServLogs.Active == true)
cleaner.SelectMaintananceServiceLogs (true);
else
cleaner.SelectMaintananceServiceLogs();
}
protected void OnMZUpdatesClicked (object sender, EventArgs e)
{
if (MZUpdates.Active == true)
cleaner.SelectMozillaUpdates (true);
else
cleaner.SelectMozillaUpdates();
}
protected void OnRecovFileFragmentsClicked (object sender, EventArgs e)
{
if (RecovFileFragments.Active == true)
cleaner.SelectRecoveredFileFragments (true);
else
cleaner.SelectRecoveredFileFragments();
}
protected void OnStylishSyncBackupsClicked (object sender, EventArgs e)
{
if (StylishSyncBackups.Active == true)
cleaner.SelectStylishSyncBackups (true);
else
cleaner.SelectStylishSyncBackups();
}
protected void OnSyncLogsClicked (object sender, EventArgs e)
{
if (SyncLogs.Active == true)
cleaner.SelectSyncLogs (true);
else
cleaner.SelectSyncLogs();
}
protected void OnThumbnailsClicked (object sender, EventArgs e)
{
if (Thumbnails.Active == true)
cleaner.SelectThumbnails (true);
else
cleaner.SelectThumbnails();
}
protected void OnCompactDBClicked (object sender, EventArgs e)
{
if (CompactDB.Active == true)
cleaner.SelectCompactDatabases (true);
else
cleaner.SelectCompactDatabases();
}
protected void OnDumpFilesClicked (object sender, EventArgs e)
{
if (CompactDB.Active == true)
cleaner.SelectDumpFiles (true);
else
cleaner.SelectDumpFiles();
}
#endregion
protected void OnUninstallFirefoxBtnClicked (object sender, EventArgs e)
{
int response = Additional.GetMessageBox(this,
"Uninstalling Mozilla Firefox",
"If you continue Mozilla Firefox will removed from your computer",
"",
DialogFlags.Modal,
MessageType.Warning,
ButtonsType.OkCancel);
if (response != -5)
return;
try
{
bool isFirefoxWasDefaultBrowser = cleaner.UninstallFirefox ();
if(Cleaner.osPlatform == PlatformID.Unix)
{
Additional.GetMessageBox(this,
"Uninstalling Mozilla Firefox",
"Mosilla Firefox uninstalled successfully",
"",
DialogFlags.Modal,
MessageType.Info,
ButtonsType.Ok);
}
else
{
string secondaryText = string.Empty;
if (isFirefoxWasDefaultBrowser) secondaryText = "Internet Explorer is default browser now.\n\n";
secondaryText += "For correct unistalling need reboot computer.\nReboot computer now?";
response = Additional.GetMessageBox(this,
"Uninstalling Mozilla Firefox",
"Mosilla Firefox uninstalled successfully",
secondaryText,
DialogFlags.Modal,
MessageType.Info,
ButtonsType.YesNo);
if (response == -8)
{
Process.Start("shutdown", "-r -f");
}
}
MainPanel.Sensitive = false;
}
catch(Exception ex) {
Additional.GetMessageBox (null,
"FirefoxCleaner exception",
"Uninstalling error",
ex.Message,
DialogFlags.Modal,
MessageType.Error,
ButtonsType.Ok);
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Text;
using Microsoft.Diagnostics.Tracing;
using Address = System.UInt64;
#pragma warning disable 1591 // disable warnings on XML comments not being present
// This code was automatically generated by the TraceParserGen tool, which converts
// an ETW event manifest into strongly typed C# classes.
namespace Microsoft.Diagnostics.Tracing.Parsers
{
using Microsoft.Diagnostics.Tracing.Parsers.MicrosoftWindowsRPC;
[System.CodeDom.Compiler.GeneratedCode("traceparsergen", "2.0")]
public sealed class MicrosoftWindowsRPCTraceEventParser : TraceEventParser
{
public static string ProviderName = "Microsoft-Windows-RPC";
public static Guid ProviderGuid = new Guid(unchecked((int) 0x6ad52b32), unchecked((short) 0xd609), unchecked((short) 0x4be9), 0xae, 0x07, 0xce, 0x8d, 0xae, 0x93, 0x7e, 0x39);
public MicrosoftWindowsRPCTraceEventParser(TraceEventSource source) : base(source) {}
public event Action<RpcClientCallStartArgs> RpcClientCallStart
{
add
{
source.RegisterEventTemplate(RpcClientCallStartTemplate(value));
}
remove
{
source.UnregisterEventTemplate(value, 5, ProviderGuid);
}
}
public event Action<RpcClientCallErrorArgs> RpcClientCallError
{
add
{
source.RegisterEventTemplate(RpcClientCallErrorTemplate(value));
}
remove
{
source.UnregisterEventTemplate(value, 1, ProviderGuid);
}
}
public event Action<RpcCallStopArgs> RpcClientCallStop
{
add
{
source.RegisterEventTemplate(RpcClientCallStopTemplate(value));
}
remove
{
source.UnregisterEventTemplate(value, 7, ProviderGuid);
}
}
public event Action<RpcServerCallBlockedArgs> RpcServerCall
{
add
{
source.RegisterEventTemplate(RpcServerCallBlockedTemplate(value));
}
remove
{
source.UnregisterEventTemplate(value, 2, ProviderGuid);
}
}
public event Action<RpcServerCallStartArgs> RpcServerCallStart
{
add
{
source.RegisterEventTemplate(RpcServerCallStartTemplate(value));
}
remove
{
source.UnregisterEventTemplate(value, 6, ProviderGuid);
}
}
public event Action<RpcCallStopArgs> RpcServerCallStop
{
add
{
source.RegisterEventTemplate(RpcServerCallStopTemplate(value));
}
remove
{
source.UnregisterEventTemplate(value, 8, ProviderGuid);
}
}
public event Action<RpcCallStopArgs> RpcException
{
add
{
source.RegisterEventTemplate(RpcCallException(value));
}
remove
{
source.UnregisterEventTemplate(value, 9, ProviderGuid);
}
}
#region private
protected override string GetProviderName() { return ProviderName; }
static private EmptyTraceData NotUsed4(Action<EmptyTraceData> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new EmptyTraceData(action, 4, 3, "Debug", Guid.Empty, 0, "", ProviderGuid, ProviderName );
}
static private EmptyTraceData NotUsed10(Action<EmptyTraceData> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new EmptyTraceData(action, 10, 3, "Debug", Guid.Empty, 0, "", ProviderGuid, ProviderName );
}
static private EmptyTraceData NotUsed11(Action<EmptyTraceData> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new EmptyTraceData(action, 11, 3, "Debug", Guid.Empty, 0, "", ProviderGuid, ProviderName );
}
static private EmptyTraceData NotUsed12(Action<EmptyTraceData> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new EmptyTraceData(action, 12, 3, "Debug", Guid.Empty, 1, "Start", ProviderGuid, ProviderName );
}
static private EmptyTraceData NotUsed13(Action<EmptyTraceData> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new EmptyTraceData(action, 13, 3, "Debug", Guid.Empty, 2, "Stop", ProviderGuid, ProviderName );
}
static private EmptyTraceData NotUsed14(Action<EmptyTraceData> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new EmptyTraceData(action, 14, 4, "FunctionTrace", Guid.Empty, 1, "Start", ProviderGuid, ProviderName );
}
static private EmptyTraceData NotUsed16(Action<EmptyTraceData> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new EmptyTraceData(action, 16, 4, "FunctionTrace", Guid.Empty, 1, "Start", ProviderGuid, ProviderName );
}
static private EmptyTraceData NotUsed15(Action<EmptyTraceData> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new EmptyTraceData(action, 15, 4, "FunctionTrace", Guid.Empty, 2, "Stop", ProviderGuid, ProviderName );
}
static private RpcClientCallStartArgs RpcClientCallStartTemplate(Action<RpcClientCallStartArgs> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new RpcClientCallStartArgs(action, 5, 1, "RpcClientCall", Guid.Empty, 1, "Start", ProviderGuid, ProviderName );
}
static private RpcClientCallErrorArgs RpcClientCallErrorTemplate(Action<RpcClientCallErrorArgs> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new RpcClientCallErrorArgs(action, 1, 1, "RpcClientCall", Guid.Empty, 2, "Stop", ProviderGuid, ProviderName );
}
static private RpcCallStopArgs RpcClientCallStopTemplate(Action<RpcCallStopArgs> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new RpcCallStopArgs(action, 7, 1, "RpcClientCall", Guid.Empty, 2, "Stop", ProviderGuid, ProviderName );
}
static private RpcServerCallBlockedArgs RpcServerCallBlockedTemplate(Action<RpcServerCallBlockedArgs> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new RpcServerCallBlockedArgs(action, 2, 2, "RpcServerCall", Guid.Empty, 0, "", ProviderGuid, ProviderName );
}
static private RpcServerCallStartArgs RpcServerCallStartTemplate(Action<RpcServerCallStartArgs> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new RpcServerCallStartArgs(action, 6, 2, "RpcServerCall", Guid.Empty, 1, "Start", ProviderGuid, ProviderName );
}
static private RpcCallStopArgs RpcServerCallStopTemplate(Action<RpcCallStopArgs> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new RpcCallStopArgs(action, 8, 2, "RpcServerCall", Guid.Empty, 2, "Stop", ProviderGuid, ProviderName );
}
static private EmptyTraceData NotUsed0(Action<EmptyTraceData> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new EmptyTraceData(action, 3, 0, "task_0", Guid.Empty, 0, "", ProviderGuid, ProviderName );
}
static private RpcCallStopArgs RpcCallException(Action<RpcCallStopArgs> action)
{ // action, eventid, taskid, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName
return new RpcCallStopArgs(action, 9, 0, "task_0", Guid.Empty, 0, "", ProviderGuid, ProviderName );
}
static private volatile TraceEvent[] s_templates;
protected override void EnumerateTemplates(Func<string, string, EventFilterResponse> eventsToObserve, Action<TraceEvent> callback)
{
if (s_templates == null)
{
var templates = new TraceEvent[16];
templates[0] = RpcClientCallErrorTemplate(null);
templates[1] = RpcServerCallBlockedTemplate(null);
templates[2] = NotUsed0(null);
templates[3] = NotUsed4(null);
templates[4] = RpcClientCallStartTemplate(null);
templates[5] = RpcServerCallStartTemplate(null);
templates[6] = RpcClientCallErrorTemplate(null);
templates[7] = RpcServerCallStopTemplate(null);
templates[8] = NotUsed0(null);
templates[9] = NotUsed4(null);
templates[10] = NotUsed4(null);
templates[11] = NotUsed12(null);
templates[12] = NotUsed13(null);
templates[13] = NotUsed14(null);
templates[14] = NotUsed15(null);
templates[15] = NotUsed14(null);
s_templates = templates;
}
foreach (var template in s_templates)
if (eventsToObserve == null || eventsToObserve(template.ProviderName, template.EventName) == EventFilterResponse.AcceptEvent)
callback(template);
}
#endregion
}
}
namespace Microsoft.Diagnostics.Tracing.Parsers.MicrosoftWindowsRPC
{
public sealed class RpcClientCallStartArgs : TraceEvent
{
public Guid InterfaceUuid { get { return GetGuidAt(0); } }
public int ProcNum { get { return GetInt32At(16); } }
public ProtocolSequences Protocol { get { return (ProtocolSequences)GetInt32At(20); } }
public string NetworkAddress { get { return GetUnicodeStringAt(24); } }
public string Endpoint { get { return GetUnicodeStringAt(SkipUnicodeString(24)); } }
public string Options { get { return GetUnicodeStringAt(SkipUnicodeString(SkipUnicodeString(24))); } }
public int AuthenticationLevel { get { return GetInt32At(SkipUnicodeString(SkipUnicodeString(SkipUnicodeString(24)))); } }
public AuthenticationServices AuthenticationService { get { return (AuthenticationServices)GetInt32At(SkipUnicodeString(SkipUnicodeString(SkipUnicodeString(24)))+4); } }
public ImpersonationLevels ImpersonationLevel { get { return (ImpersonationLevels)GetInt32At(SkipUnicodeString(SkipUnicodeString(SkipUnicodeString(24)))+8); } }
#region Private
internal RpcClientCallStartArgs(Action<RpcClientCallStartArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName)
: base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName)
{
this.m_target = target;
}
protected override void Dispatch()
{
m_target(this);
}
protected override void Validate()
{
Debug.Assert(!(Version == 1 && EventDataLength != SkipUnicodeString(SkipUnicodeString(SkipUnicodeString(24)))+12));
Debug.Assert(!(Version > 1 && EventDataLength < SkipUnicodeString(SkipUnicodeString(SkipUnicodeString(24)))+12));
}
protected override Delegate Target
{
get { return m_target; }
set { m_target = (Action<RpcClientCallStartArgs>) value; }
}
public override StringBuilder ToXml(StringBuilder sb)
{
Prefix(sb);
XmlAttrib(sb, "InterfaceUuid", InterfaceUuid);
XmlAttrib(sb, "ProcNum", ProcNum);
XmlAttrib(sb, "Protocol", Protocol);
XmlAttrib(sb, "NetworkAddress", NetworkAddress);
XmlAttrib(sb, "Endpoint", Endpoint);
XmlAttrib(sb, "Options", Options);
XmlAttrib(sb, "AuthenticationLevel", AuthenticationLevel);
XmlAttrib(sb, "AuthenticationService", AuthenticationService);
XmlAttrib(sb, "ImpersonationLevel", ImpersonationLevel);
sb.Append("/>");
return sb;
}
public override string[] PayloadNames
{
get
{
if (payloadNames == null)
payloadNames = new string[] { "InterfaceUuid", "ProcNum", "Protocol", "NetworkAddress", "Endpoint", "Options", "AuthenticationLevel", "AuthenticationService", "ImpersonationLevel"};
return payloadNames;
}
}
public override object PayloadValue(int index)
{
switch (index)
{
case 0:
return InterfaceUuid;
case 1:
return ProcNum;
case 2:
return Protocol;
case 3:
return NetworkAddress;
case 4:
return Endpoint;
case 5:
return Options;
case 6:
return AuthenticationLevel;
case 7:
return AuthenticationService;
case 8:
return ImpersonationLevel;
default:
Debug.Assert(false, "Bad field index");
return null;
}
}
private event Action<RpcClientCallStartArgs> m_target;
#endregion
}
public sealed class RpcClientCallErrorArgs : TraceEvent
{
public string ImageName { get { return GetUnicodeStringAt(0); } }
public string ComputerName { get { return GetUnicodeStringAt(SkipUnicodeString(0)); } }
public int PID { get { return GetInt32At(SkipUnicodeString(SkipUnicodeString(0))); } }
// Skipping TimeStamp
public int GeneratingComponent { get { return GetInt32At(SkipUnicodeString(SkipUnicodeString(0))+4); } }
public int Status { get { return GetInt32At(SkipUnicodeString(SkipUnicodeString(0))+8); } }
public int DetectionLocation { get { return GetInt16At(SkipUnicodeString(SkipUnicodeString(0))+12); } }
public int Flags { get { return GetInt16At(SkipUnicodeString(SkipUnicodeString(0))+14); } }
public int NumberOfParameters { get { return GetInt16At(SkipUnicodeString(SkipUnicodeString(0))+16); } }
public long Params(int arrayIndex) { return GetInt64At(SkipUnicodeString(SkipUnicodeString(0))+18 + (arrayIndex * HostOffset(8, 0))); }
#region Private
internal RpcClientCallErrorArgs(Action<RpcClientCallErrorArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName)
: base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName)
{
this.m_target = target;
}
protected override void Dispatch()
{
m_target(this);
}
protected override void Validate()
{
Debug.Assert(!(Version == 1 && EventDataLength != SkipUnicodeString(SkipUnicodeString(0))+18));
Debug.Assert(!(Version > 1 && EventDataLength < SkipUnicodeString(SkipUnicodeString(0))+18));
}
protected override Delegate Target
{
get { return m_target; }
set { m_target = (Action<RpcClientCallErrorArgs>) value; }
}
public override StringBuilder ToXml(StringBuilder sb)
{
Prefix(sb);
XmlAttrib(sb, "ImageName", ImageName);
XmlAttrib(sb, "ComputerName", ComputerName);
XmlAttrib(sb, "PID", PID);
XmlAttrib(sb, "GeneratingComponent", GeneratingComponent);
XmlAttrib(sb, "Status", Status);
XmlAttrib(sb, "DetectionLocation", DetectionLocation);
XmlAttrib(sb, "Flags", Flags);
XmlAttrib(sb, "NumberOfParameters", NumberOfParameters);
sb.Append("/>");
return sb;
}
public override string[] PayloadNames
{
get
{
if (payloadNames == null)
payloadNames = new string[] { "ImageName", "ComputerName", "PID", "GeneratingComponent", "Status", "DetectionLocation", "Flags", "NumberOfParameters", "Params"};
return payloadNames;
}
}
public override object PayloadValue(int index)
{
switch (index)
{
case 0:
return ImageName;
case 1:
return ComputerName;
case 2:
return PID;
case 3:
return GeneratingComponent;
case 4:
return Status;
case 5:
return DetectionLocation;
case 6:
return Flags;
case 7:
return NumberOfParameters;
default:
Debug.Assert(false, "Bad field index");
return null;
}
}
private event Action<RpcClientCallErrorArgs> m_target;
#endregion
}
public sealed class RpcCallStopArgs : TraceEvent
{
public int Status { get { return GetInt32At(0); } }
#region Private
internal RpcCallStopArgs(Action<RpcCallStopArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName)
: base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName)
{
this.m_target = target;
}
protected override void Dispatch()
{
m_target(this);
}
protected override void Validate()
{
Debug.Assert(!(Version == 1 && EventDataLength != 4));
Debug.Assert(!(Version > 1 && EventDataLength < 4));
}
protected override Delegate Target
{
get { return m_target; }
set { m_target = (Action<RpcCallStopArgs>) value; }
}
public override StringBuilder ToXml(StringBuilder sb)
{
Prefix(sb);
XmlAttrib(sb, "Status", Status);
sb.Append("/>");
return sb;
}
public override string[] PayloadNames
{
get
{
if (payloadNames == null)
payloadNames = new string[] { "Status"};
return payloadNames;
}
}
public override object PayloadValue(int index)
{
switch (index)
{
case 0:
return Status;
default:
Debug.Assert(false, "Bad field index");
return null;
}
}
private event Action<RpcCallStopArgs> m_target;
#endregion
}
public sealed class RpcServerCallBlockedArgs : TraceEvent
{
public string ImangeName { get { return GetUnicodeStringAt(0); } }
public Guid InterfaceUuid { get { return GetGuidAt(SkipUnicodeString(0)); } }
public Guid FilterKey { get { return GetGuidAt(SkipUnicodeString(0)+16); } }
#region Private
internal RpcServerCallBlockedArgs(Action<RpcServerCallBlockedArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName)
: base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName)
{
this.m_target = target;
}
protected override void Dispatch()
{
m_target(this);
}
protected override void Validate()
{
Debug.Assert(!(Version == 1 && EventDataLength != SkipUnicodeString(0)+32));
Debug.Assert(!(Version > 1 && EventDataLength < SkipUnicodeString(0)+32));
}
protected override Delegate Target
{
get { return m_target; }
set { m_target = (Action<RpcServerCallBlockedArgs>) value; }
}
public override StringBuilder ToXml(StringBuilder sb)
{
Prefix(sb);
XmlAttrib(sb, "ImangeName", ImangeName);
XmlAttrib(sb, "InterfaceUuid", InterfaceUuid);
XmlAttrib(sb, "FilterKey", FilterKey);
sb.Append("/>");
return sb;
}
public override string[] PayloadNames
{
get
{
if (payloadNames == null)
payloadNames = new string[] { "ImangeName", "InterfaceUuid", "FilterKey"};
return payloadNames;
}
}
public override object PayloadValue(int index)
{
switch (index)
{
case 0:
return ImangeName;
case 1:
return InterfaceUuid;
case 2:
return FilterKey;
default:
Debug.Assert(false, "Bad field index");
return null;
}
}
private event Action<RpcServerCallBlockedArgs> m_target;
#endregion
}
public sealed class RpcServerCallStartArgs : TraceEvent
{
public Guid InterfaceUuid { get { return GetGuidAt(0); } }
public int ProcNum { get { return GetInt32At(16); } }
public ProtocolSequences Protocol { get { return (ProtocolSequences)GetInt32At(20); } }
public string NetworkAddress { get { return GetUnicodeStringAt(24); } }
public string Endpoint { get { return GetUnicodeStringAt(SkipUnicodeString(24)); } }
public string Options { get { return GetUnicodeStringAt(SkipUnicodeString(SkipUnicodeString(24))); } }
public int AuthenticationLevel { get { return GetInt32At(SkipUnicodeString(SkipUnicodeString(SkipUnicodeString(24)))); } }
public AuthenticationServices AuthenticationService { get { return (AuthenticationServices)GetInt32At(SkipUnicodeString(SkipUnicodeString(SkipUnicodeString(24)))+4); } }
public ImpersonationLevels ImpersonationLevel { get { return (ImpersonationLevels)GetInt32At(SkipUnicodeString(SkipUnicodeString(SkipUnicodeString(24)))+8); } }
#region Private
internal RpcServerCallStartArgs(Action<RpcServerCallStartArgs> target, int eventID, int task, string taskName, Guid taskGuid, int opcode, string opcodeName, Guid providerGuid, string providerName)
: base(eventID, task, taskName, taskGuid, opcode, opcodeName, providerGuid, providerName)
{
this.m_target = target;
}
protected override void Dispatch()
{
m_target(this);
}
protected override void Validate()
{
Debug.Assert(!(Version == 1 && EventDataLength != SkipUnicodeString(SkipUnicodeString(SkipUnicodeString(24)))+12));
Debug.Assert(!(Version > 1 && EventDataLength < SkipUnicodeString(SkipUnicodeString(SkipUnicodeString(24)))+12));
}
protected override Delegate Target
{
get { return m_target; }
set { m_target = (Action<RpcServerCallStartArgs>) value; }
}
public override StringBuilder ToXml(StringBuilder sb)
{
Prefix(sb);
XmlAttrib(sb, "InterfaceUuid", InterfaceUuid);
XmlAttrib(sb, "ProcNum", ProcNum);
XmlAttrib(sb, "Protocol", Protocol);
XmlAttrib(sb, "NetworkAddress", NetworkAddress);
XmlAttrib(sb, "Endpoint", Endpoint);
XmlAttrib(sb, "Options", Options);
XmlAttrib(sb, "AuthenticationLevel", AuthenticationLevel);
XmlAttrib(sb, "AuthenticationService", AuthenticationService);
XmlAttrib(sb, "ImpersonationLevel", ImpersonationLevel);
sb.Append("/>");
return sb;
}
public override string[] PayloadNames
{
get
{
if (payloadNames == null)
payloadNames = new string[] { "InterfaceUuid", "ProcNum", "Protocol", "NetworkAddress", "Endpoint", "Options", "AuthenticationLevel", "AuthenticationService", "ImpersonationLevel"};
return payloadNames;
}
}
public override object PayloadValue(int index)
{
switch (index)
{
case 0:
return InterfaceUuid;
case 1:
return ProcNum;
case 2:
return Protocol;
case 3:
return NetworkAddress;
case 4:
return Endpoint;
case 5:
return Options;
case 6:
return AuthenticationLevel;
case 7:
return AuthenticationService;
case 8:
return ImpersonationLevel;
default:
Debug.Assert(false, "Bad field index");
return null;
}
}
private event Action<RpcServerCallStartArgs> m_target;
#endregion
}
public enum AuthenticationServices
{
Negotiate = 0x9,
NTLM = 0xa,
SChannel = 0xe,
Kerberos = 0x10,
Kernel = 0x14,
}
public enum ImpersonationLevels
{
Default = 0x0,
Anonymous = 0x1,
Identify = 0x2,
Impersonate = 0x3,
Delegate = 0x4,
}
public enum ProtocolSequences
{
TCP = 0x1,
NamedPipes = 0x2,
LRPC = 0x3,
RPCHTTP = 0x4,
}
public enum RpcHttp2ObjectTypes
{
SOCKET_CHANNEL = 0x1,
PROXY_SOCKET_CHANNEL = 0x2,
CHANNEL = 0x3,
BOTTOM_CHANNEL = 0x4,
IIS_CHANNEL = 0x5,
RAW_CONNECTION = 0x6,
INITIAL_RAW_CONNECTION = 0x7,
IIS_SENDER_CHANNEL = 0x8,
ENDPOINT_RECEIVER = 0x9,
PLUG_CHANNEL = 0xa,
CLIENT_VC = 0xb,
SERVER_VC = 0xc,
INPROXY_VC = 0xd,
OUTPROXY_VC = 0xe,
PROXY_VC = 0xf,
CDATA_ORIGINATOR = 0x10,
CLIENT_CHANNEL = 0x11,
CALLBACK = 0x12,
FLOW_CONTROL_SENDER = 0x13,
WINHTTP_CALLBACK = 0x14,
WINHTTP_CHANNEL = 0x15,
WINHTTP_RAW = 0x16,
PROXY_RECEIVER = 0x17,
SERVER_CHANNEL = 0x18,
FRAGMENT_RECEIVER = 0x19,
}
public enum SubjectTypes
{
ASSOC = 0x2e,
HTTPv2 = 0x32,
SASSOC = 0x41,
BCACHE2 = 0x42,
SCALL = 0x43,
ADDRESS = 0x44,
ENGINE = 0x45,
CAUSAL_F = 0x46,
GC = 0x47,
HEAP = 0x48,
EEINFO = 0x49,
ALPC = 0x4c,
RESERVED_MEM = 0x4d,
SCONN = 0x4e,
CORRUPT = 0x4f,
PROVIDER = 0x50,
SECCRED = 0x53,
STABLE = 0x54,
PROTOCOL = 0x57,
CASSOC = 0x61,
BCACHE = 0x62,
CCALL = 0x63,
TP_ALPC = 0x64,
CENDPOINT = 0x65,
TP_CALLBACK = 0x66,
HANDLE = 0x68,
IF = 0x69,
TP_IO = 0x6a,
TP_WORK = 0x6b,
CTXHANDLE = 0x6c,
MUTEX = 0x6d,
CCONN = 0x6e,
TRANS_CONN = 0x6f,
PACKET = 0x70,
REFOBJ = 0x72,
SSECCTX = 0x73,
THREAD = 0x74,
TP_TIMER = 0x75,
EVENT = 0x76,
TP_WAIT = 0x77,
EXCEPT = 0x78,
}
}
| |
#if !XAMARIN && !WINDOWS_UWP
//-----------------------------------------------------------------------
// <copyright file="ObjectStatus.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>Container for other UI controls that exposes</summary>
//-----------------------------------------------------------------------
using System;
using System.Windows;
using System.ComponentModel;
using Csla.Core;
namespace Csla.Xaml
{
/// <summary>
/// Container for other UI controls that exposes
/// various status values from the CSLA .NET
/// business object acting as DataContext.
/// </summary>
/// <remarks>
/// This control provides access to the IsDirty,
/// IsNew, IsDeleted, IsValid and IsSavable properties
/// of a business object. The purpose behind this
/// control is to expose those properties in a way
/// that supports WFP data binding against those
/// values.
/// </remarks>
public class ObjectStatus : DataDecoratorBase
{
#region Per-Type Dependency Properties
private static readonly DependencyProperty CanCreateProperty =
DependencyProperty.Register("CanCreateObject", typeof(bool), typeof(ObjectStatus), new FrameworkPropertyMetadata(false), null);
private static readonly DependencyProperty CanGetProperty =
DependencyProperty.Register("CanGetObject", typeof(bool), typeof(ObjectStatus), new FrameworkPropertyMetadata(false), null);
private static readonly DependencyProperty CanEditProperty =
DependencyProperty.Register("CanEditObject", typeof(bool), typeof(ObjectStatus), new FrameworkPropertyMetadata(false), null);
private static readonly DependencyProperty CanDeleteProperty =
DependencyProperty.Register("CanDeleteObject", typeof(bool), typeof(ObjectStatus), new FrameworkPropertyMetadata(false), null);
/// <summary>
/// Exposes the CanCreateObject property of the
/// DataContext business object.
/// </summary>
public bool CanCreateObject
{
get { return (bool)base.GetValue(CanCreateProperty); }
protected set
{
bool old = CanCreateObject;
base.SetValue(CanCreateProperty, value);
if (old != value)
OnPropertyChanged(
new DependencyPropertyChangedEventArgs(CanCreateProperty, old, value));
}
}
/// <summary>
/// Exposes the CanGetObject property of the
/// DataContext business object.
/// </summary>
public bool CanGetObject
{
get { return (bool)base.GetValue(CanGetProperty); }
protected set
{
bool old = CanGetObject;
base.SetValue(CanGetProperty, value);
if (old != value)
OnPropertyChanged(
new DependencyPropertyChangedEventArgs(CanGetProperty, old, value));
}
}
/// <summary>
/// Exposes the CanEditObject property of the
/// DataContext business object.
/// </summary>
public bool CanEditObject
{
get { return (bool)base.GetValue(CanEditProperty); }
protected set
{
bool old = CanEditObject;
base.SetValue(CanEditProperty, value);
if (old != value)
OnPropertyChanged(
new DependencyPropertyChangedEventArgs(CanEditProperty, old, value));
}
}
/// <summary>
/// Exposes the CanDeleteObject property of the
/// DataContext business object.
/// </summary>
public bool CanDeleteObject
{
get { return (bool)base.GetValue(CanDeleteProperty); }
protected set
{
bool old = CanDeleteObject;
base.SetValue(CanDeleteProperty, value);
if (old != value)
OnPropertyChanged(
new DependencyPropertyChangedEventArgs(CanDeleteProperty, old, value));
}
}
#endregion
#region Per-Instance Dependency Properties
private static readonly DependencyProperty IsDeletedProperty =
DependencyProperty.Register("IsDeleted", typeof(bool), typeof(ObjectStatus), new FrameworkPropertyMetadata(false), null);
private static readonly DependencyProperty IsDirtyProperty =
DependencyProperty.Register("IsDirty", typeof(bool), typeof(ObjectStatus), new FrameworkPropertyMetadata(false), null);
private static readonly DependencyProperty IsNewProperty =
DependencyProperty.Register("IsNew", typeof(bool), typeof(ObjectStatus), new FrameworkPropertyMetadata(false), null);
private static readonly DependencyProperty IsSavableProperty =
DependencyProperty.Register("IsSavable", typeof(bool), typeof(ObjectStatus), new FrameworkPropertyMetadata(false), null);
private static readonly DependencyProperty IsValidProperty =
DependencyProperty.Register("IsValid", typeof(bool), typeof(ObjectStatus), new FrameworkPropertyMetadata(false), null);
/// <summary>
/// Exposes the IsDeleted property of the
/// DataContext business object.
/// </summary>
public bool IsDeleted
{
get { return (bool)base.GetValue(IsDeletedProperty); }
protected set
{
bool old = IsDeleted;
base.SetValue(IsDeletedProperty, value);
OnPropertyChanged(
new DependencyPropertyChangedEventArgs(IsDeletedProperty, old, value));
}
}
/// <summary>
/// Exposes the IsDirty property of the
/// DataContext business object.
/// </summary>
public bool IsDirty
{
get { return (bool)base.GetValue(IsDirtyProperty); }
protected set
{
bool old = IsDirty;
base.SetValue(IsDirtyProperty, value);
if (old != value)
OnPropertyChanged(
new DependencyPropertyChangedEventArgs(IsDirtyProperty, old, value));
}
}
/// <summary>
/// Exposes the IsNew property of the
/// DataContext business object.
/// </summary>
public bool IsNew
{
get { return (bool)base.GetValue(IsNewProperty); }
protected set
{
bool old = IsNew;
base.SetValue(IsNewProperty, value);
if (old != value)
OnPropertyChanged(
new DependencyPropertyChangedEventArgs(IsNewProperty, old, value));
}
}
/// <summary>
/// Exposes the IsSavable property of the
/// DataContext business object.
/// </summary>
public bool IsSavable
{
get { return (bool)base.GetValue(IsSavableProperty); }
protected set
{
bool old = IsSavable;
base.SetValue(IsSavableProperty, value);
if (old != value)
OnPropertyChanged(
new DependencyPropertyChangedEventArgs(IsSavableProperty, old, value));
}
}
/// <summary>
/// Exposes the IsValid property of the
/// DataContext business object.
/// </summary>
public bool IsValid
{
get { return (bool)base.GetValue(IsValidProperty); }
protected set
{
bool old = IsValid;
base.SetValue(IsValidProperty, value);
if (old != value)
OnPropertyChanged(
new DependencyPropertyChangedEventArgs(IsValidProperty, old, value));
}
}
#endregion
#region Base Overrides
/// <summary>
/// This method is called when the data
/// object to which the control is bound
/// has changed.
/// </summary>
protected override void DataObjectChanged()
{
Refresh();
}
/// <summary>
/// This method is called when a property
/// of the data object to which the
/// control is bound has changed.
/// </summary>
protected override void DataPropertyChanged(PropertyChangedEventArgs e)
{
Refresh();
}
/// <summary>
/// This method is called if the data
/// object is an IBindingList, and the
/// ListChanged event was raised by
/// the data object.
/// </summary>
protected override void DataBindingListChanged(ListChangedEventArgs e)
{
Refresh();
}
/// <summary>
/// This method is called if the data
/// object is an INotifyCollectionChanged,
/// and the CollectionChanged event was
/// raised by the data object.
/// </summary>
protected override void DataObservableCollectionChanged(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
Refresh();
}
/// <summary>
/// Refreshes the control's property
/// values to reflect the values of
/// the underlying business object.
/// </summary>
public void Refresh()
{
// per-type rules
if (DataObject != null)
{
var sourceType = DataObject.GetType();
var newValue = Csla.Rules.BusinessRules.HasPermission(ApplicationContextManager.GetApplicationContext(), Rules.AuthorizationActions.CreateObject, DataObject);
if (CanCreateObject != newValue)
CanCreateObject = newValue;
newValue = Csla.Rules.BusinessRules.HasPermission(ApplicationContextManager.GetApplicationContext(), Rules.AuthorizationActions.GetObject, DataObject);
if (CanGetObject != newValue)
CanGetObject = newValue;
newValue = Csla.Rules.BusinessRules.HasPermission(ApplicationContextManager.GetApplicationContext(), Rules.AuthorizationActions.EditObject, DataObject);
if (CanEditObject != newValue)
CanEditObject = newValue;
newValue = Csla.Rules.BusinessRules.HasPermission(ApplicationContextManager.GetApplicationContext(), Rules.AuthorizationActions.DeleteObject, DataObject);
if (CanDeleteObject != newValue)
CanDeleteObject = newValue;
}
else
{
CanCreateObject = false;
CanGetObject = false;
CanEditObject = false;
CanDeleteObject = false;
}
IEditableBusinessObject source = DataObject as IEditableBusinessObject;
if (source != null)
{
if (IsDeleted != source.IsDeleted)
IsDeleted = source.IsDeleted;
if (IsDirty != source.IsDirty)
IsDirty = source.IsDirty;
if (IsNew != source.IsNew)
IsNew = source.IsNew;
if (IsSavable != source.IsSavable)
IsSavable = source.IsSavable;
if (IsValid != source.IsValid)
IsValid = source.IsValid;
}
else
{
IEditableCollection sourceList = DataObject as IEditableCollection;
if (sourceList != null)
{
if (IsDirty != sourceList.IsDirty)
IsDirty = sourceList.IsDirty;
if (IsValid != sourceList.IsValid)
IsValid = sourceList.IsValid;
if (IsSavable != sourceList.IsSavable)
IsSavable = sourceList.IsSavable;
IsDeleted = false;
IsNew = false;
}
}
}
#endregion
}
}
#endif
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.Insights
{
using System.Linq;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// AlertRuleIncidentsOperations operations.
/// </summary>
internal partial class AlertRuleIncidentsOperations : Microsoft.Rest.IServiceOperations<InsightsManagementClient>, IAlertRuleIncidentsOperations
{
/// <summary>
/// Initializes a new instance of the AlertRuleIncidentsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal AlertRuleIncidentsOperations(InsightsManagementClient client)
{
if (client == null)
{
throw new System.ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the InsightsManagementClient
/// </summary>
public InsightsManagementClient Client { get; private set; }
/// <summary>
/// Gets an incident associated to an alert rule
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='ruleName'>
/// The name of the rule.
/// </param>
/// <param name='incidentName'>
/// The name of the incident to retrieve.
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async System.Threading.Tasks.Task<Microsoft.Rest.Azure.AzureOperationResponse<Incident>> GetWithHttpMessagesAsync(string resourceGroupName, string ruleName, string incidentName, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
if (resourceGroupName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "resourceGroupName");
}
if (ruleName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "ruleName");
}
if (incidentName == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "incidentName");
}
if (this.Client.SubscriptionId == null)
{
throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
string apiVersion = "2016-03-01";
// Tracing
bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString();
System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("ruleName", ruleName);
tracingParameters.Add("incidentName", incidentName);
tracingParameters.Add("apiVersion", apiVersion);
tracingParameters.Add("cancellationToken", cancellationToken);
Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/alertrules/{ruleName}/incidents/{incidentName}").ToString();
_url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{ruleName}", System.Uri.EscapeDataString(ruleName));
_url = _url.Replace("{incidentName}", System.Uri.EscapeDataString(incidentName));
_url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(this.Client.SubscriptionId));
System.Collections.Generic.List<string> _queryParameters = new System.Collections.Generic.List<string>();
if (apiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage();
System.Net.Http.HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new System.Net.Http.HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new Microsoft.Rest.Azure.CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new Microsoft.Rest.Azure.CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (Newtonsoft.Json.JsonException)
{
// Ignore the exception
}
ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new Microsoft.Rest.Azure.AzureOperationResponse<Incident>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Incident>(_responseContent, this.Client.DeserializationSettings);
}
catch (Newtonsoft.Json.JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit;
using Autodesk.Revit.ApplicationServices;
using Autodesk.Revit.DB.Plumbing;
using Autodesk.Revit.DB.Mechanical;
using System.Diagnostics;
using Element = Autodesk.Revit.DB.Element;
using System.Collections;
namespace Revit.SDK.Samples.AvoidObstruction.CS
{
/// <summary>
/// This class implement the algorithm to detect the obstruction and resolve it.
/// </summary>
class Resolver
{
/// <summary>
/// Revit Document.
/// </summary>
private Document m_rvtDoc;
/// <summary>
/// Revit Application.
/// </summary>
private Application m_rvtApp;
/// <summary>
/// Detector to detect the obstructions.
/// </summary>
private Detector m_detector;
/// <summary>
/// Constructor, initialize all the fields of this class.
/// </summary>
/// <param name="data">Revit ExternalCommandData from external command entrance</param>
public Resolver(ExternalCommandData data)
{
m_rvtDoc = data.Application.ActiveUIDocument.Document;
m_rvtApp = data.Application.Application;
m_detector = new Detector(m_rvtDoc);
}
/// <summary>
/// Detect and resolve the obstructions of all Pipes.
/// </summary>
public void Resolve()
{
List<Autodesk.Revit.DB.Element> pipes = new List<Autodesk.Revit.DB.Element>();
FilteredElementCollector collector = new FilteredElementCollector(m_rvtDoc);
pipes.AddRange(collector.OfClass(typeof(Pipe)).ToElements());
foreach (Element pipe in pipes)
{
Resolve(pipe as Pipe);
}
}
/// <summary>
/// Calculate the uniform perpendicular directions with inputting direction "dir".
/// </summary>
/// <param name="dir">Direction to calculate</param>
/// <param name="count">How many perpendicular directions will be calculated</param>
/// <returns>The calculated perpendicular directions with dir</returns>
private List<Autodesk.Revit.DB.XYZ > PerpendicularDirs(Autodesk.Revit.DB.XYZ dir, int count)
{
List<Autodesk.Revit.DB.XYZ > dirs = new List<Autodesk.Revit.DB.XYZ >();
Plane plane = m_rvtApp.Create.NewPlane(dir, Autodesk.Revit.DB.XYZ.Zero);
Arc arc = m_rvtApp.Create.NewArc(plane, 1.0, 0, 6.28);
double delta = 1.0 / (double)count;
for (int i = 1; i <= count; i++)
{
Autodesk.Revit.DB.XYZ pt = arc.Evaluate(delta * i, true);
dirs.Add(pt);
}
return dirs;
}
/// <summary>
/// Detect the obstructions of pipe and resolve them.
/// </summary>
/// <param name="pipe">Pipe to resolve</param>
private void Resolve(Pipe pipe)
{
// Get the centerline of pipe.
Line pipeLine = (pipe.Location as LocationCurve).Curve as Line;
// Calculate the intersection references with pipe's centerline.
List<ReferenceWithContext> obstructionRefArr = m_detector.Obstructions(pipeLine);
// Filter out the references, just allow Pipe, Beam, and Duct.
Filter(pipe, obstructionRefArr);
if (obstructionRefArr.Count == 0)
{
// There are no intersection found.
return;
}
// Calculate the direction of pipe's centerline.
Autodesk.Revit.DB.XYZ dir = pipeLine.get_EndPoint(1) - pipeLine.get_EndPoint(0);
// Build the sections from the intersection references.
List<Section> sections = Section.BuildSections(obstructionRefArr, dir.Normalize());
// Merge the neighbor sections if the distance of them is too close.
for (int i = sections.Count - 2; i >= 0; i--)
{
Autodesk.Revit.DB.XYZ detal = sections[i].End - sections[i + 1].Start;
if (detal.GetLength() < pipe.Diameter * 3)
{
sections[i].Refs.AddRange(sections[i + 1].Refs);
sections.RemoveAt(i + 1);
}
}
// Resolve the obstructions one by one.
foreach (Section sec in sections)
{
Resolve(pipe, sec);
}
// Connect the neighbor sections with pipe and elbow fittings.
//
for (int i = 1; i < sections.Count; i++)
{
// Get the end point from the previous section.
Autodesk.Revit.DB.XYZ start = sections[i - 1].End;
// Get the start point from the current section.
Autodesk.Revit.DB.XYZ end = sections[i].Start;
// Create a pipe between two neighbor section.
Pipe tmpPipe = m_rvtDoc.Create.NewPipe(start, end, pipe.PipeType);
// Copy pipe's parameters values to tmpPipe.
CopyParameters(pipe, tmpPipe);
// Create elbow fitting to connect previous section with tmpPipe.
Connector conn1 = FindConnector(sections[i - 1].Pipes[2], start);
Connector conn2 = FindConnector(tmpPipe, start);
FamilyInstance fi = m_rvtDoc.Create.NewElbowFitting(conn1, conn2);
// Create elbow fitting to connect current section with tmpPipe.
Connector conn3 = FindConnector(sections[i].Pipes[0], end);
Connector conn4 = FindConnector(tmpPipe, end);
FamilyInstance f2 = m_rvtDoc.Create.NewElbowFitting(conn3, conn4);
}
// Find two connectors which pipe's two ends connector connected to.
Connector startConn = FindConnectedTo(pipe, pipeLine.get_EndPoint(0));
Connector endConn = FindConnectedTo(pipe, pipeLine.get_EndPoint(1));
Pipe startPipe = null;
if (null != startConn)
{
// Create a pipe between pipe's start connector and pipe's start section.
startPipe = m_rvtDoc.Create.NewPipe(sections[0].Start, startConn, pipe.PipeType);
}
else
{
// Create a pipe between pipe's start point and pipe's start section.
startPipe = m_rvtDoc.Create.NewPipe(sections[0].Start, pipeLine.get_EndPoint(0), pipe.PipeType);
}
// Copy parameters from pipe to startPipe.
CopyParameters(pipe, startPipe);
// Connect the startPipe and first section with elbow fitting.
Connector connStart1 = FindConnector(startPipe, sections[0].Start);
Connector connStart2 = FindConnector(sections[0].Pipes[0], sections[0].Start);
FamilyInstance fii = m_rvtDoc.Create.NewElbowFitting(connStart1, connStart2);
Pipe endPipe = null;
int count = sections.Count;
if (null != endConn)
{
// Create a pipe between pipe's end connector and pipe's end section.
endPipe = m_rvtDoc.Create.NewPipe(sections[count - 1].End, endConn, pipe.PipeType);
}
else
{
// Create a pipe between pipe's end point and pipe's end section.
endPipe = m_rvtDoc.Create.NewPipe(sections[count - 1].End, pipeLine.get_EndPoint(1), pipe.PipeType);
}
// Copy parameters from pipe to endPipe.
CopyParameters(pipe, endPipe);
// Connect the endPipe and last section with elbow fitting.
Connector connEnd1 = FindConnector(endPipe, sections[count - 1].End);
Connector connEnd2 = FindConnector(sections[count - 1].Pipes[2], sections[count - 1].End);
FamilyInstance fiii = m_rvtDoc.Create.NewElbowFitting(connEnd1, connEnd2);
// Delete the pipe after resolved.
m_rvtDoc.Delete(pipe);
}
/// <summary>
/// Filter the inputting References, just allow Pipe, Duct and Beam References.
/// </summary>
/// <param name="pipe">Pipe</param>
/// <param name="refs">References to filter</param>
private void Filter(Pipe pipe, List<ReferenceWithContext> refs)
{
for (int i = refs.Count - 1; i >= 0; i--)
{
Reference cur = refs[i].GetReference();
Element curElem = m_rvtDoc.GetElement(cur);
if (curElem.Id == pipe.Id ||
(!(curElem is Pipe) && !(curElem is Duct) &&
curElem.Category.Id.IntegerValue != (int)BuiltInCategory.OST_StructuralFraming))
{
refs.RemoveAt(i);
}
}
}
/// <summary>
/// This method will find out a route to avoid the obstruction.
/// </summary>
/// <param name="pipe">Pipe to resolve</param>
/// <param name="section">Pipe's one obstruction</param>
/// <returns>A route which can avoid the obstruction</returns>
private Line FindRoute(Pipe pipe, Section section)
{
// Perpendicular direction minimal length.
double minLength = pipe.Diameter * 2;
// Parallel direction jump step.
double jumpStep = pipe.Diameter;
// Calculate the directions in which to find the solution.
List<Autodesk.Revit.DB.XYZ > dirs = new List<Autodesk.Revit.DB.XYZ >();
Autodesk.Revit.DB.XYZ crossDir = null;
foreach (ReferenceWithContext gref in section.Refs)
{
Element elem = m_rvtDoc.GetElement(gref.GetReference());
Line locationLine = (elem.Location as LocationCurve).Curve as Line;
Autodesk.Revit.DB.XYZ refDir = locationLine.get_EndPoint(1) - locationLine.get_EndPoint(0);
refDir = refDir.Normalize();
if (refDir.IsAlmostEqualTo(section.PipeCenterLineDirection) || refDir.IsAlmostEqualTo(-section.PipeCenterLineDirection))
{
continue;
}
crossDir = refDir.CrossProduct(section.PipeCenterLineDirection);
dirs.Add(crossDir.Normalize());
break;
}
// When all the obstruction are parallel with the centerline of the pipe,
// We can't calculate the direction from the vector.Cross method.
if (dirs.Count == 0)
{
// Calculate perpendicular directions with dir in four directions.
List<Autodesk.Revit.DB.XYZ > perDirs = PerpendicularDirs(section.PipeCenterLineDirection, 4);
dirs.Add(perDirs[0]);
dirs.Add(perDirs[1]);
}
Line foundLine = null;
while (null == foundLine)
{
// Extend the section interval by jumpStep.
section.Inflate(0, jumpStep);
section.Inflate(1, jumpStep);
// Find solution in the given directions.
for (int i = 0; null == foundLine && i < dirs.Count; i++)
{
// Calculate the intersections.
List<ReferenceWithContext> obs1 = m_detector.Obstructions(section.Start, dirs[i]);
List<ReferenceWithContext> obs2 = m_detector.Obstructions(section.End, dirs[i]);
// Filter out the intersection result.
Filter(pipe, obs1);
Filter(pipe, obs2);
// Find out the minimal intersections in two opposite direction.
ReferenceWithContext[] mins1 = GetClosestSectionsToOrigin(obs1);
ReferenceWithContext[] mins2 = GetClosestSectionsToOrigin(obs2);
// Find solution in the given direction and its opposite direction.
for (int j = 0; null == foundLine && j < 2; j++)
{
if (mins1[j] != null && Math.Abs(mins1[j].Proximity) < minLength ||
mins2[j] != null && Math.Abs(mins2[j].Proximity) < minLength)
{
continue;
}
// Calculate the maximal height that the parallel line can be reached.
double maxHight = 1000 * pipe.Diameter;
if (mins1[j] != null && mins2[j] != null)
{
maxHight = Math.Min(Math.Abs(mins1[j].Proximity), Math.Abs(mins2[j].Proximity));
}
else if(mins1[j] != null)
{
maxHight = Math.Abs(mins1[j].Proximity);
}
else if (mins2[j] != null)
{
maxHight = Math.Abs(mins2[j].Proximity);
}
Autodesk.Revit.DB.XYZ dir = (j == 1) ? dirs[i] : -dirs[i];
// Calculate the parallel line which can avoid obstructions.
foundLine = FindParallelLine(pipe, section, dir, maxHight);
}
}
}
return foundLine;
}
/// <summary>
/// Find a line Parallel to pipe's centerline to avoid the obstruction.
/// </summary>
/// <param name="pipe">Pipe who has obstructions</param>
/// <param name="section">Pipe's one obstruction</param>
/// <param name="dir">Offset Direction of the parallel line</param>
/// <param name="maxLength">Maximum offset distance</param>
/// <returns>Parallel line which can avoid the obstruction</returns>
private Line FindParallelLine(Pipe pipe, Section section, Autodesk.Revit.DB.XYZ dir, double maxLength)
{
double step = pipe.Diameter;
double hight = 2 * pipe.Diameter;
while (hight <= maxLength)
{
Autodesk.Revit.DB.XYZ detal = dir * hight;
Line line = Line.get_Bound(section.Start + detal, section.End + detal);
List<ReferenceWithContext> refs = m_detector.Obstructions(line);
Filter(pipe, refs);
if (refs.Count == 0)
{
return line;
}
hight += step;
}
return null;
}
/// <summary>
/// Find out two References, whose ProximityParameter is negative or positive,
/// And Get the minimal value from all positive reference, and get the maximal value
/// from the negative reference. if there are no such reference, using null instead.
/// </summary>
/// <param name="refs">References</param>
/// <returns>Reference array</returns>
private ReferenceWithContext[] GetClosestSectionsToOrigin(List<ReferenceWithContext> refs)
{
ReferenceWithContext[] mins = new ReferenceWithContext[2];
if (refs.Count == 0)
{
return mins;
}
if (refs[0].Proximity > 0)
{
mins[1] = refs[0];
return mins;
}
for (int i = 0; i < refs.Count - 1; i++)
{
if (refs[i].Proximity < 0 && refs[i + 1].Proximity > 0)
{
mins[0] = refs[i];
mins[1] = refs[i + 1];
return mins;
}
}
mins[0] = refs[refs.Count - 1];
return mins;
}
/// <summary>
/// Resolve one obstruction of Pipe.
/// </summary>
/// <param name="pipe">Pipe to resolve</param>
/// <param name="section">One pipe's obstruction</param>
private void Resolve(Pipe pipe, Section section)
{
// Find out a parallel line of pipe centerline, which can avoid the obstruction.
Line offset = FindRoute(pipe, section);
// Construct a section line according to the given section.
Line sectionLine = Line.get_Bound(section.Start, section.End);
// Construct two side lines, which can avoid the obstruction too.
Line side1 = Line.get_Bound(sectionLine.get_EndPoint(0), offset.get_EndPoint(0));
Line side2 = Line.get_Bound(offset.get_EndPoint(1), sectionLine.get_EndPoint(1));
//
// Create an "U" shape, which connected with three pipes and two elbows, to round the obstruction.
//
PipeType pipeType = pipe.PipeType;
Autodesk.Revit.DB.XYZ start = side1.get_EndPoint(0);
Autodesk.Revit.DB.XYZ startOffset = offset.get_EndPoint(0);
Autodesk.Revit.DB.XYZ endOffset = offset.get_EndPoint(1);
Autodesk.Revit.DB.XYZ end = side2.get_EndPoint(1);
// Create three side pipes of "U" shape.
Pipe pipe1 = m_rvtDoc.Create.NewPipe(start, startOffset, pipeType);
Pipe pipe2 = m_rvtDoc.Create.NewPipe(startOffset, endOffset, pipeType);
Pipe pipe3 = m_rvtDoc.Create.NewPipe(endOffset, end, pipeType);
// Copy parameters from pipe to other three created pipes.
CopyParameters(pipe, pipe1);
CopyParameters(pipe, pipe2);
CopyParameters(pipe, pipe3);
// Add the created three pipes to current section.
section.Pipes.Add(pipe1);
section.Pipes.Add(pipe2);
section.Pipes.Add(pipe3);
// Create the first elbow to connect two neighbor pipes of "U" shape.
Connector conn1 = FindConnector(pipe1, startOffset);
Connector conn2 = FindConnector(pipe2, startOffset);
m_rvtDoc.Create.NewElbowFitting(conn1, conn2);
// Create the second elbow to connect another two neighbor pipes of "U" shape.
Connector conn3 = FindConnector(pipe2, endOffset);
Connector conn4 = FindConnector(pipe3, endOffset);
m_rvtDoc.Create.NewElbowFitting(conn3, conn4);
}
/// <summary>
/// Copy parameters from source pipe to target pipe.
/// </summary>
/// <param name="source">Coping source</param>
/// <param name="target">Coping target</param>
private void CopyParameters(Pipe source, Pipe target)
{
double diameter = source.get_Parameter(BuiltInParameter.RBS_PIPE_DIAMETER_PARAM).AsDouble();
target.get_Parameter(BuiltInParameter.RBS_PIPE_DIAMETER_PARAM).Set(diameter);
}
/// <summary>
/// Find out a connector from pipe with a specified point.
/// </summary>
/// <param name="pipe">Pipe to find the connector</param>
/// <param name="conXYZ">Specified point</param>
/// <returns>Connector whose origin is conXYZ</returns>
private Connector FindConnector(Pipe pipe, Autodesk.Revit.DB.XYZ conXYZ)
{
ConnectorSet conns = pipe.ConnectorManager.Connectors;
foreach (Connector conn in conns)
{
if (conn.Origin.IsAlmostEqualTo(conXYZ))
{
return conn;
}
}
return null;
}
/// <summary>
/// Find out the connector which the pipe's specified connector connected to.
/// The pipe's specified connector is given by point conxyz.
/// </summary>
/// <param name="pipe">Pipe to find the connector</param>
/// <param name="conXYZ">Specified point</param>
/// <returns>Connector whose origin is conXYZ</returns>
private Connector FindConnectedTo(Pipe pipe, Autodesk.Revit.DB.XYZ conXYZ)
{
Connector connItself = FindConnector(pipe, conXYZ);
ConnectorSet connSet = connItself.AllRefs;
foreach (Connector conn in connSet)
{
if (conn.Owner.Id.IntegerValue != pipe.Id.IntegerValue &&
conn.ConnectorType == ConnectorType.End)
{
return conn;
}
}
return null;
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.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.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetGroupMembersSpectraS3Request : Ds3Request
{
private string _groupId;
public string GroupId
{
get { return _groupId; }
set { WithGroupId(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private string _memberGroupId;
public string MemberGroupId
{
get { return _memberGroupId; }
set { WithMemberGroupId(value); }
}
private string _memberUserId;
public string MemberUserId
{
get { return _memberUserId; }
set { WithMemberUserId(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
public GetGroupMembersSpectraS3Request WithGroupId(Guid? groupId)
{
this._groupId = groupId.ToString();
if (groupId != null)
{
this.QueryParams.Add("group_id", groupId.ToString());
}
else
{
this.QueryParams.Remove("group_id");
}
return this;
}
public GetGroupMembersSpectraS3Request WithGroupId(string groupId)
{
this._groupId = groupId;
if (groupId != null)
{
this.QueryParams.Add("group_id", groupId);
}
else
{
this.QueryParams.Remove("group_id");
}
return this;
}
public GetGroupMembersSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetGroupMembersSpectraS3Request WithMemberGroupId(Guid? memberGroupId)
{
this._memberGroupId = memberGroupId.ToString();
if (memberGroupId != null)
{
this.QueryParams.Add("member_group_id", memberGroupId.ToString());
}
else
{
this.QueryParams.Remove("member_group_id");
}
return this;
}
public GetGroupMembersSpectraS3Request WithMemberGroupId(string memberGroupId)
{
this._memberGroupId = memberGroupId;
if (memberGroupId != null)
{
this.QueryParams.Add("member_group_id", memberGroupId);
}
else
{
this.QueryParams.Remove("member_group_id");
}
return this;
}
public GetGroupMembersSpectraS3Request WithMemberUserId(Guid? memberUserId)
{
this._memberUserId = memberUserId.ToString();
if (memberUserId != null)
{
this.QueryParams.Add("member_user_id", memberUserId.ToString());
}
else
{
this.QueryParams.Remove("member_user_id");
}
return this;
}
public GetGroupMembersSpectraS3Request WithMemberUserId(string memberUserId)
{
this._memberUserId = memberUserId;
if (memberUserId != null)
{
this.QueryParams.Add("member_user_id", memberUserId);
}
else
{
this.QueryParams.Remove("member_user_id");
}
return this;
}
public GetGroupMembersSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetGroupMembersSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetGroupMembersSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetGroupMembersSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetGroupMembersSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/group_member";
}
}
}
}
| |
namespace LeagueSeason5CountersService.Migrations
{
using System;
using System.Collections.Generic;
using System.Data.Entity.Infrastructure.Annotations;
using System.Data.Entity.Migrations;
public partial class Initial : DbMigration
{
public override void Up()
{
CreateTable(
"LeagueSeason5Counters.ChampionFeedbacks",
c => new
{
Id = c.String(nullable: false, maxLength: 128,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Id")
},
}),
Name = c.String(),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion",
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Version")
},
}),
CreatedAt = c.DateTimeOffset(nullable: true, precision: 7, defaultValue: DateTimeOffset.Now,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "CreatedAt")
},
}),
UpdatedAt = c.DateTimeOffset(precision: 7,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "UpdatedAt")
},
}),
Deleted = c.Boolean(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Deleted")
},
}),
})
.PrimaryKey(t => t.Id)
.Index(t => t.CreatedAt, clustered: true);
CreateTable(
"LeagueSeason5Counters.Comments",
c => new
{
Id = c.String(nullable: false, maxLength: 128,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Id")
},
}),
Text = c.String(),
User = c.String(),
Score = c.Int(nullable: false),
ChampionFeedbackId = c.String(maxLength: 128),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion",
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Version")
},
}),
CreatedAt = c.DateTimeOffset(nullable: true, precision: 7, defaultValue: DateTimeOffset.Now,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "CreatedAt")
},
}),
UpdatedAt = c.DateTimeOffset(precision: 7,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "UpdatedAt")
},
}),
Deleted = c.Boolean(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Deleted")
},
}),
})
.PrimaryKey(t => t.Id)
.ForeignKey("LeagueSeason5Counters.ChampionFeedbacks", t => t.ChampionFeedbackId)
.Index(t => t.ChampionFeedbackId)
.Index(t => t.CreatedAt, clustered: true);
CreateTable(
"LeagueSeason5Counters.UserRatings",
c => new
{
Id = c.String(nullable: false, maxLength: 128,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Id")
},
}),
UniqueUser = c.String(),
Score = c.Int(nullable: false),
CommentId = c.String(maxLength: 128),
Version = c.Binary(nullable: false, fixedLength: true, timestamp: true, storeType: "rowversion",
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Version")
},
}),
CreatedAt = c.DateTimeOffset(nullable: true, precision: 7, defaultValue: DateTimeOffset.Now,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "CreatedAt")
},
}),
UpdatedAt = c.DateTimeOffset(precision: 7,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "UpdatedAt")
},
}),
Deleted = c.Boolean(nullable: false,
annotations: new Dictionary<string, AnnotationValues>
{
{
"ServiceTableColumn",
new AnnotationValues(oldValue: null, newValue: "Deleted")
},
}),
})
.PrimaryKey(t => t.Id)
.ForeignKey("LeagueSeason5Counters.Comments", t => t.CommentId)
.Index(t => t.CommentId)
.Index(t => t.CreatedAt, clustered: true);
}
public override void Down()
{
DropForeignKey("LeagueSeason5Counters.UserRatings", "CommentId", "LeagueSeason5Counters.Comments");
DropForeignKey("LeagueSeason5Counters.Comments", "ChampionFeedbackId", "LeagueSeason5Counters.ChampionFeedbacks");
DropIndex("LeagueSeason5Counters.UserRatings", new[] { "CreatedAt" });
DropIndex("LeagueSeason5Counters.UserRatings", new[] { "CommentId" });
DropIndex("LeagueSeason5Counters.Comments", new[] { "CreatedAt" });
DropIndex("LeagueSeason5Counters.Comments", new[] { "ChampionFeedbackId" });
DropIndex("LeagueSeason5Counters.ChampionFeedbacks", new[] { "CreatedAt" });
DropTable("LeagueSeason5Counters.UserRatings",
removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>>
{
{
"CreatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "CreatedAt" },
}
},
{
"Deleted",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Deleted" },
}
},
{
"Id",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Id" },
}
},
{
"UpdatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "UpdatedAt" },
}
},
{
"Version",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Version" },
}
},
});
DropTable("LeagueSeason5Counters.Comments",
removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>>
{
{
"CreatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "CreatedAt" },
}
},
{
"Deleted",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Deleted" },
}
},
{
"Id",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Id" },
}
},
{
"UpdatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "UpdatedAt" },
}
},
{
"Version",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Version" },
}
},
});
DropTable("LeagueSeason5Counters.ChampionFeedbacks",
removedColumnAnnotations: new Dictionary<string, IDictionary<string, object>>
{
{
"CreatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "CreatedAt" },
}
},
{
"Deleted",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Deleted" },
}
},
{
"Id",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Id" },
}
},
{
"UpdatedAt",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "UpdatedAt" },
}
},
{
"Version",
new Dictionary<string, object>
{
{ "ServiceTableColumn", "Version" },
}
},
});
}
}
}
| |
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using AzureCards.ConsoleClient;
using AzureCards.ConsoleClient.Models;
using Microsoft.Rest;
using Newtonsoft.Json.Linq;
namespace AzureCards.ConsoleClient
{
internal partial class Deck : IServiceOperations<AzureCardsClient>, IDeck
{
/// <summary>
/// Initializes a new instance of the Deck class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal Deck(AzureCardsClient client)
{
this._client = client;
}
private AzureCardsClient _client;
/// <summary>
/// Gets a reference to the AzureCards.ConsoleClient.AzureCardsClient.
/// </summary>
public AzureCardsClient Client
{
get { return this._client; }
}
/// <param name='deckId'>
/// Required.
/// </param>
/// <param name='cardCount'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<DealResponseMessage>> DealWithOperationResponseAsync(string deckId, int cardCount, CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Validate
if (deckId == null)
{
throw new ArgumentNullException("deckId");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deckId", deckId);
tracingParameters.Add("cardCount", cardCount);
ServiceClientTracing.Enter(invocationId, this, "DealAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/deck/";
url = url + Uri.EscapeDataString(deckId);
url = url + "/deal/";
url = url + Uri.EscapeDataString(cardCount.ToString());
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (statusCode != HttpStatusCode.OK)
{
HttpOperationException<object> ex = new HttpOperationException<object>();
ex.Request = httpRequest;
ex.Response = httpResponse;
ex.Body = null;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HttpOperationResponse<DealResponseMessage> result = new HttpOperationResponse<DealResponseMessage>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
DealResponseMessage resultModel = new DealResponseMessage();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null)
{
resultModel.DeserializeJson(responseDoc);
}
result.Body = resultModel;
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<string>> NewWithOperationResponseAsync(CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
ServiceClientTracing.Enter(invocationId, this, "NewAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/deck/new";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (statusCode != HttpStatusCode.OK)
{
HttpOperationException<object> ex = new HttpOperationException<object>();
ex.Request = httpRequest;
ex.Response = httpResponse;
ex.Body = null;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HttpOperationResponse<string> result = new HttpOperationResponse<string>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
string resultModel = default(string);
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null)
{
resultModel = ((string)responseDoc);
}
result.Body = resultModel;
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
/// <param name='deckId'>
/// Required.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
public async Task<HttpOperationResponse<bool>> ShuffleWithOperationResponseAsync(string deckId, CancellationToken cancellationToken = default(System.Threading.CancellationToken))
{
// Validate
if (deckId == null)
{
throw new ArgumentNullException("deckId");
}
// Tracing
bool shouldTrace = ServiceClientTracing.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("deckId", deckId);
ServiceClientTracing.Enter(invocationId, this, "ShuffleAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/deck/";
url = url + Uri.EscapeDataString(deckId);
url = url + "/shuffle";
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (shouldTrace)
{
ServiceClientTracing.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
ServiceClientTracing.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
if (statusCode != HttpStatusCode.OK)
{
HttpOperationException<object> ex = new HttpOperationException<object>();
ex.Request = httpRequest;
ex.Response = httpResponse;
ex.Body = null;
if (shouldTrace)
{
ServiceClientTracing.Error(invocationId, ex);
}
throw ex;
}
// Create Result
HttpOperationResponse<bool> result = new HttpOperationResponse<bool>();
result.Request = httpRequest;
result.Response = httpResponse;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
bool resultModel = default(bool);
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null)
{
resultModel = ((bool)responseDoc);
}
result.Body = resultModel;
}
if (shouldTrace)
{
ServiceClientTracing.Exit(invocationId, result);
}
return result;
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Catalog.cs" company="Sitecore Corporation">
// Copyright (c) Sitecore Corporation 1999-2015
// </copyright>
// <summary>
// Represents catalog configuration. By default stored in /system/modules/Ecommerce/Catalogs/[Catalog Name] item.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
// Copyright 2015 Sitecore Corporation A/S
// 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.
// -------------------------------------------------------------------------------------------
namespace Sitecore.Ecommerce.Shell.Applications.Catalogs.Models
{
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using Data;
using Globalization;
using Search;
using Sitecore.Data;
using Sitecore.Data.Items;
using Text;
/// <summary>
/// Represents catalog configuration. By default stored in /system/modules/Ecommerce/Catalogs/[Catalog Name] item.
/// </summary>
public class Catalog
{
/// <summary>
/// The catalog data source field name.
/// </summary>
public const string CatalogDataSourceFieldName = "Catalog Data Source";
/// <summary>
/// The data mapper.
/// </summary>
private readonly IDataMapper dataMapper;
/// <summary>
/// The catalog item.
/// </summary>
private Item catalogItem;
/// <summary>
/// Initializes a new instance of the <see cref="Catalog"/> class.
/// </summary>
public Catalog()
: this(Context.Entity.Resolve<DataMapper>())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Catalog"/> class.
/// </summary>
/// <param name="dataMapper">The data mapper.</param>
public Catalog(IDataMapper dataMapper)
{
this.dataMapper = dataMapper;
}
/// <summary>
/// Gets or sets the item URI.
/// </summary>
/// <value>The item URI.</value>
public ItemUri ItemUri { get; set; }
/// <summary>
/// Gets or sets the database.
/// </summary>
/// <value>
/// The database.
/// </value>
public Database Database { get; set; }
/// <summary>
/// Gets or sets Language.
/// </summary>
public Language Language { get; set; }
/// <summary>
/// Gets the search provider.
/// </summary>
/// <value>The search provider.</value>
public virtual CatalogBaseSource CatalogSource
{
get
{
if (this.CatalogItem != null && !string.IsNullOrEmpty(this.CatalogItem[CatalogDataSourceFieldName]))
{
CatalogBaseSource source = this.CreateCatalogSource();
if (source != null)
{
source.Database = this.Database;
source.Language = this.Language;
return source;
}
}
return null;
}
}
/// <summary>
/// Gets the row editor fields.
/// </summary>
/// <value>The row editor fields.</value>
public virtual StringCollection EditorFields
{
get
{
ListString editorFields = this.GetFieldValueList("Editor Fields");
return editorFields != null ? this.GetFieldValueList("Editor Fields").ToStringCollection() : null;
}
}
/// <summary>
/// Gets the data mapper.
/// </summary>
[NotNull]
protected IDataMapper DataMapper
{
get { return this.dataMapper; }
}
/// <summary>
/// Gets the catalog item.
/// </summary>
/// <value>The catalog item.</value>
protected Item CatalogItem
{
get
{
if (this.catalogItem != null)
{
return this.catalogItem;
}
if (this.ItemUri == null)
{
return null;
}
this.catalogItem = Database.GetItem(this.ItemUri);
return this.catalogItem;
}
}
/// <summary>
/// Gets the ribbon URI.
/// </summary>
/// <returns>The ribbon URI.</returns>
public virtual ItemUri GetRibbonSourceUri()
{
string uri = this.CatalogItem["Ribbon Source Uri"];
return string.IsNullOrEmpty(uri) ? null : new ItemUri(uri);
}
/// <summary>
/// Gets the textbox definitions.
/// </summary>
/// <returns>The textbox definitions.</returns>
public virtual List<TextBoxDefinition> GetTextBoxDefinitions()
{
List<TextBoxDefinition> list = new List<TextBoxDefinition>();
if (this.CatalogItem == null)
{
return list;
}
Item searchFieldsRoot = this.CatalogItem.Children["Search Text Fields"];
if (searchFieldsRoot != null && searchFieldsRoot.Children.Count > 0)
{
foreach (Item searchTextField in searchFieldsRoot.Children)
{
list.Add(this.dataMapper.GetEntity<TextBoxDefinition>(searchTextField));
}
}
return list;
}
/// <summary>
/// Gets the search templates.
/// </summary>
/// <returns>The search templates</returns>
public virtual ListString GetSearchTemplates()
{
return this.GetFieldValueList("Templates");
}
/// <summary>
/// Gets the checklists.
/// </summary>
/// <returns>Gets the checklist definitions.</returns>
public virtual List<ChecklistDefinition> GetChecklistDefinitions()
{
ChecklistCollection checklists = new ChecklistCollection();
if (this.CatalogItem == null)
{
return checklists;
}
Item checklistsRoot = this.CatalogItem.Children["Checklists"];
if (checklistsRoot != null && checklistsRoot.Children.Count > 0)
{
foreach (Item checklistItem in checklistsRoot.Children)
{
Collection<ChecklistItem> checkboxes = new Collection<ChecklistItem>();
Item checkboxesRoot = this.Database.GetItem(checklistItem["Root"]);
if (checkboxesRoot != null)
{
foreach (Item item in checkboxesRoot.Children)
{
checkboxes.Add(new ChecklistItem { Text = item["Title"], Value = item.ID.ToString() });
}
}
ChecklistDefinition checklist = new ChecklistDefinition { Header = checklistItem["Title"], Field = checklistItem["Field"], Checkboxes = checkboxes };
checklists.Add(checklist);
}
}
return checklists;
}
/// <summary>
/// Gets the catalog grid column definitions. Used to construct a grid in catalog view.
/// </summary>
/// <returns>The catalog grid column definitions.</returns>
[NotNull]
public virtual List<GridColumn> GetGridColumns()
{
List<GridColumn> columns = new List<GridColumn>();
if (this.CatalogItem == null)
{
return columns;
}
Item row = this.CatalogItem.Children["Grid"];
if (row != null && row.Children.Count > 0)
{
foreach (Item columnItem in row.Children)
{
columns.Add(this.dataMapper.GetEntity<GridColumn>(columnItem));
}
}
return columns;
}
/// <summary>
/// Creates the catalog source.
/// </summary>
/// <returns>The catalog source.</returns>
[CanBeNull]
protected virtual CatalogBaseSource CreateCatalogSource()
{
return Reflection.ReflectionUtil.CreateObject(this.CatalogItem[CatalogDataSourceFieldName]) as CatalogBaseSource;
}
/// <summary>
/// Gets the field value list.
/// </summary>
/// <param name="fieldName">Name of the field.</param>
/// <returns>The field value list</returns>
[NotNull]
private ListString GetFieldValueList([NotNull] string fieldName)
{
return this.CatalogItem == null ? new ListString() : new ListString(this.CatalogItem[fieldName]);
}
}
}
| |
/************************************************************************************
Copyright : Copyright 2014 Oculus VR, LLC. All Rights reserved.
Licensed under the Oculus VR Rift SDK License Version 3.2 (the "License");
you may not use the Oculus VR Rift SDK except in compliance with the License,
which is provided at the time of installation or download, or which
otherwise accompanies this software in either electronic or hard copy form.
You may obtain a copy of the License at
http://www.oculusvr.com/licenses/LICENSE-3.2
Unless required by applicable law or agreed to in writing, the Oculus VR SDK
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.Runtime.InteropServices;
using UnityEngine;
using Ovr;
/// <summary>
/// Manages an Oculus Rift head-mounted display (HMD).
/// </summary>
public class OVRDisplay
{
/// <summary>
/// Specifies the size and field-of-view for one eye texture.
/// </summary>
public struct EyeRenderDesc
{
/// <summary>
/// The horizontal and vertical size of the texture.
/// </summary>
public Vector2 resolution;
/// <summary>
/// The angle of the horizontal and vertical field of view in degrees.
/// </summary>
public Vector2 fov;
}
/// <summary>
/// Contains latency measurements for a single frame of rendering.
/// </summary>
public struct LatencyData
{
/// <summary>
/// The time it took to render both eyes in seconds.
/// </summary>
public float render;
/// <summary>
/// The time it took to perform TimeWarp in seconds.
/// </summary>
public float timeWarp;
/// <summary>
/// The time between the end of TimeWarp and scan-out in seconds.
/// </summary>
public float postPresent;
public float renderError;
public float timeWarpError;
}
/// <summary>
/// If true, a physical HMD is attached to the system.
/// </summary>
/// <value><c>true</c> if is present; otherwise, <c>false</c>.</value>
public bool isPresent
{
get {
#if !UNITY_ANDROID || UNITY_EDITOR
return (OVRManager.capiHmd.GetTrackingState().StatusFlags & (uint)StatusBits.HmdConnected) != 0;
#else
return OVR_IsHMDPresent();
#endif
}
}
private int prevAntiAliasing;
private int prevScreenWidth;
private int prevScreenHeight;
private bool needsConfigureTexture;
private bool needsSetTexture;
private bool needsSetDistortionCaps;
private bool prevFullScreen;
private OVRPose[] eyePoses = new OVRPose[(int)OVREye.Count];
private EyeRenderDesc[] eyeDescs = new EyeRenderDesc[(int)OVREye.Count];
private RenderTexture[] eyeTextures = new RenderTexture[eyeTextureCount];
private int[] eyeTextureIds = new int[eyeTextureCount];
private int currEyeTextureIdx = 0;
private static int frameCount = 0;
#if !UNITY_ANDROID && !UNITY_EDITOR
private bool needsSetViewport;
#endif
#if UNITY_ANDROID && !UNITY_EDITOR
private const int eyeTextureCount = 3 * (int)OVREye.Count; // triple buffer
#else
private const int eyeTextureCount = 1 * (int)OVREye.Count;
#endif
#if UNITY_ANDROID && !UNITY_EDITOR
private int nextEyeTextureIdx = 0;
#endif
/// <summary>
/// Creates an instance of OVRDisplay. Called by OVRManager.
/// </summary>
public OVRDisplay()
{
#if !UNITY_ANDROID || UNITY_EDITOR
needsConfigureTexture = false;
needsSetTexture = true;
needsSetDistortionCaps = true;
prevFullScreen = Screen.fullScreen;
#elif !UNITY_ANDROID && !UNITY_EDITOR
needsSetViewport = true;
#endif
ConfigureEyeDesc(OVREye.Left);
ConfigureEyeDesc(OVREye.Right);
for (int i = 0; i < eyeTextureCount; i += 2)
{
ConfigureEyeTexture(i, OVREye.Left);
ConfigureEyeTexture(i, OVREye.Right);
}
OVRManager.NativeTextureScaleModified += (prev, current) => { needsConfigureTexture = true; };
OVRManager.EyeTextureAntiAliasingModified += (prev, current) => { needsConfigureTexture = true; };
OVRManager.EyeTextureDepthModified += (prev, current) => { needsConfigureTexture = true; };
OVRManager.EyeTextureFormatModified += (prev, current) => { needsConfigureTexture = true; };
OVRManager.VirtualTextureScaleModified += (prev, current) => { needsSetTexture = true; };
OVRManager.MonoscopicModified += (prev, current) => { needsSetTexture = true; };
OVRManager.HdrModified += (prev, current) => { needsSetDistortionCaps = true; };
}
/// <summary>
/// Updates the internal state of the OVRDisplay. Called by OVRManager.
/// </summary>
public void Update()
{
UpdateDistortionCaps();
UpdateViewport();
UpdateTextures();
}
/// <summary>
/// Marks the beginning of all rendering.
/// </summary>
public void BeginFrame()
{
bool updateFrameCount = !(OVRManager.instance.timeWarp && OVRManager.instance.freezeTimeWarp);
if (updateFrameCount)
{
frameCount++;
}
OVRPluginEvent.IssueWithData(RenderEventType.BeginFrame, frameCount);
}
/// <summary>
/// Marks the end of all rendering.
/// </summary>
public void EndFrame()
{
OVRPluginEvent.Issue(RenderEventType.EndFrame);
}
/// <summary>
/// Gets the head pose at the current time or predicted at the given time.
/// </summary>
public OVRPose GetHeadPose(double predictionTime = 0d)
{
#if !UNITY_ANDROID || UNITY_EDITOR
double abs_time_plus_pred = Hmd.GetTimeInSeconds() + predictionTime;
TrackingState state = OVRManager.capiHmd.GetTrackingState(abs_time_plus_pred);
return state.HeadPose.ThePose.ToPose();
#else
float px = 0, py = 0, pz = 0, ow = 0, ox = 0, oy = 0, oz = 0;
double atTime = Time.time + predictionTime;
OVR_GetCameraPositionOrientation(ref px, ref py, ref pz,
ref ox, ref oy, ref oz, ref ow, atTime);
return new OVRPose
{
position = new Vector3(px, py, -pz),
orientation = new Quaternion(-ox, -oy, oz, ow),
};
#endif
}
#if UNITY_ANDROID && !UNITY_EDITOR
private float w = 0, x = 0, y = 0, z = 0, fov = 90f;
#endif
/// <summary>
/// Gets the pose of the given eye, predicted for the time when the current frame will scan out.
/// </summary>
public OVRPose GetEyePose(OVREye eye)
{
#if !UNITY_ANDROID || UNITY_EDITOR
bool updateEyePose = !(OVRManager.instance.timeWarp && OVRManager.instance.freezeTimeWarp);
if (updateEyePose)
{
eyePoses[(int)eye] = OVR_GetRenderPose(frameCount, (int)eye).ToPose();
}
return eyePoses[(int)eye];
#else
if (eye == OVREye.Left)
OVR_GetSensorState(
OVRManager.instance.monoscopic,
ref w,
ref x,
ref y,
ref z,
ref fov,
ref OVRManager.timeWarpViewNumber);
Quaternion rot = new Quaternion(-x, -y, z, w);
float eyeOffsetX = 0.5f * OVRManager.profile.ipd;
eyeOffsetX = (eye == OVREye.Left) ? -eyeOffsetX : eyeOffsetX;
Vector3 pos = rot * new Vector3(eyeOffsetX, 0.0f, 0.0f);
return new OVRPose
{
position = pos,
orientation = rot,
};
#endif
}
/// <summary>
/// Gets the given eye's projection matrix.
/// </summary>
/// <param name="eyeId">Specifies the eye.</param>
/// <param name="nearClip">The distance to the near clipping plane.</param>
/// <param name="farClip">The distance to the far clipping plane.</param>
public Matrix4x4 GetProjection(int eyeId, float nearClip, float farClip)
{
#if !UNITY_ANDROID || UNITY_EDITOR
FovPort fov = OVRManager.capiHmd.GetDesc().DefaultEyeFov[eyeId];
uint projectionModFlags = (uint)Hmd.ProjectionModifier.RightHanded;
return Hmd.GetProjection(fov, nearClip, farClip, projectionModFlags).ToMatrix4x4();
#else
return new Matrix4x4();
#endif
}
/// <summary>
/// Occurs when the head pose is reset.
/// </summary>
public event System.Action RecenteredPose;
/// <summary>
/// Recenters the head pose.
/// </summary>
public void RecenterPose()
{
#if !UNITY_ANDROID || UNITY_EDITOR
OVRManager.capiHmd.RecenterPose();
#else
OVR_ResetSensorOrientation();
#endif
if (RecenteredPose != null)
{
RecenteredPose();
}
}
/// <summary>
/// Gets the current acceleration of the head.
/// </summary>
public Vector3 acceleration
{
get {
#if !UNITY_ANDROID || UNITY_EDITOR
return OVRManager.capiHmd.GetTrackingState().HeadPose.LinearAcceleration.ToVector3();
#else
float x = 0.0f, y = 0.0f, z = 0.0f;
OVR_GetAcceleration(ref x, ref y, ref z);
return new Vector3(x, y, z);
#endif
}
}
/// <summary>
/// Gets the current angular velocity of the head.
/// </summary>
public Vector3 angularVelocity
{
get {
#if !UNITY_ANDROID || UNITY_EDITOR
return OVRManager.capiHmd.GetTrackingState().HeadPose.AngularVelocity.ToVector3();
#else
float x = 0.0f, y = 0.0f, z = 0.0f;
OVR_GetAngularVelocity(ref x, ref y, ref z);
return new Vector3(x, y, z);
#endif
}
}
/// <summary>
/// Gets the resolution and field of view for the given eye.
/// </summary>
public EyeRenderDesc GetEyeRenderDesc(OVREye eye)
{
return eyeDescs[(int)eye];
}
/// <summary>
/// Gets the currently active render texture for the given eye.
/// </summary>
public RenderTexture GetEyeTexture(OVREye eye)
{
return eyeTextures[currEyeTextureIdx + (int)eye];
}
/// <summary>
/// Gets the currently active render texture's native ID for the given eye.
/// </summary>
public int GetEyeTextureId(OVREye eye)
{
return eyeTextureIds[currEyeTextureIdx + (int)eye];
}
/// <summary>
/// True if the direct mode display driver is active.
/// </summary>
public bool isDirectMode
{
get
{
#if !UNITY_ANDROID || UNITY_EDITOR
uint caps = OVRManager.capiHmd.GetDesc().HmdCaps;
uint mask = caps & (uint)HmdCaps.ExtendDesktop;
return mask == 0;
#else
return false;
#endif
}
}
/// <summary>
/// If true, direct mode rendering will also show output in the main window.
/// </summary>
public bool mirrorMode
{
get
{
#if !UNITY_ANDROID || UNITY_EDITOR
uint caps = OVRManager.capiHmd.GetEnabledCaps();
return (caps & (uint)HmdCaps.NoMirrorToWindow) == 0;
#else
return false;
#endif
}
set
{
#if !UNITY_ANDROID || UNITY_EDITOR
uint caps = OVRManager.capiHmd.GetEnabledCaps();
if (((caps & (uint)HmdCaps.NoMirrorToWindow) == 0) == value)
return;
if (value)
caps &= ~(uint)HmdCaps.NoMirrorToWindow;
else
caps |= (uint)HmdCaps.NoMirrorToWindow;
OVRManager.capiHmd.SetEnabledCaps(caps);
#endif
}
}
/// <summary>
/// If true, TimeWarp will be used to correct the output of each OVRCameraRig for rotational latency.
/// </summary>
internal bool timeWarp
{
get { return (distortionCaps & (int)DistortionCaps.TimeWarp) != 0; }
set
{
if (value != timeWarp)
distortionCaps ^= (int)DistortionCaps.TimeWarp;
}
}
/// <summary>
/// If true, VR output will be rendered upside-down.
/// </summary>
internal bool flipInput
{
get { return (distortionCaps & (int)DistortionCaps.FlipInput) != 0; }
set
{
if (value != flipInput)
distortionCaps ^= (int)DistortionCaps.FlipInput;
}
}
/// <summary>
/// Enables and disables distortion rendering capabilities from the Ovr.DistortionCaps enum.
/// </summary>
public uint distortionCaps
{
get
{
return _distortionCaps;
}
set
{
if (value == _distortionCaps)
return;
_distortionCaps = value;
#if !UNITY_ANDROID || UNITY_EDITOR
OVR_SetDistortionCaps(value);
#endif
}
}
private uint _distortionCaps =
#if (UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX)
(uint)DistortionCaps.ProfileNoTimewarpSpinWaits |
#endif
(uint)DistortionCaps.Chromatic |
(uint)DistortionCaps.Vignette |
(uint)DistortionCaps.Overdrive;
/// <summary>
/// Gets the current measured latency values.
/// </summary>
public LatencyData latency
{
get {
#if !UNITY_ANDROID || UNITY_EDITOR
float[] values = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f };
float[] latencies = OVRManager.capiHmd.GetFloatArray("DK2Latency", values);
return new LatencyData
{
render = latencies[0] * 1000.0f,
timeWarp = latencies[1] * 1000.0f,
postPresent = latencies[2] * 1000.0f,
renderError = latencies[3] * 1000.0f,
timeWarpError = latencies[4] * 1000.0f,
};
#else
return new LatencyData
{
render = 0.0f,
timeWarp = 0.0f,
postPresent = 0.0f,
renderError = 0.0f,
timeWarpError = 0.0f,
};
#endif
}
}
private void UpdateDistortionCaps()
{
#if !UNITY_ANDROID || UNITY_EDITOR
needsSetDistortionCaps = needsSetDistortionCaps
|| QualitySettings.antiAliasing != prevAntiAliasing;
if (needsSetDistortionCaps)
{
if (QualitySettings.antiAliasing > 0)
{
distortionCaps |= (uint)Ovr.DistortionCaps.HqDistortion;
}
else
{
distortionCaps &= ~(uint)Ovr.DistortionCaps.HqDistortion;
}
if (QualitySettings.activeColorSpace == ColorSpace.Linear && !OVRManager.instance.hdr)
{
distortionCaps |= (uint)Ovr.DistortionCaps.SRGB;
}
else
{
distortionCaps &= ~(uint)Ovr.DistortionCaps.SRGB;
}
prevAntiAliasing = QualitySettings.antiAliasing;
needsSetDistortionCaps = false;
needsSetTexture = true;
}
#endif
}
private void UpdateViewport()
{
#if !UNITY_ANDROID && !UNITY_EDITOR
needsSetViewport = needsSetViewport
|| Screen.width != prevScreenWidth
|| Screen.height != prevScreenHeight;
if (needsSetViewport)
{
SetViewport(0, 0, Screen.width, Screen.height);
prevScreenWidth = Screen.width;
prevScreenHeight = Screen.height;
needsSetViewport = false;
}
#endif
}
private void UpdateTextures()
{
#if !UNITY_ANDROID || UNITY_EDITOR
if (needsConfigureTexture)
{
ConfigureEyeDesc(OVREye.Left);
ConfigureEyeDesc(OVREye.Right);
for (int i = 0; i < eyeTextureCount; i += 2)
{
ConfigureEyeTexture(i, OVREye.Left);
ConfigureEyeTexture(i, OVREye.Right);
}
OVR_UnitySetModeChange(true);
needsConfigureTexture = false;
needsSetTexture = true;
}
#endif
for (int i = 0; i < eyeTextureCount; i++)
{
if (!eyeTextures[i].IsCreated())
{
eyeTextures[i].Create();
eyeTextureIds[i] = eyeTextures[i].GetNativeTextureID();
#if !UNITY_ANDROID || UNITY_EDITOR
needsSetTexture = true;
#endif
}
}
#if !UNITY_ANDROID || UNITY_EDITOR
needsSetTexture = needsSetTexture
|| Screen.fullScreen != prevFullScreen
|| OVR_UnityGetModeChange();
if (needsSetTexture)
{
for (int i = 0; i < eyeTextureCount; i += (int)OVREye.Count)
{
int leftEyeIndex = i + (int)OVREye.Left;
int rightEyeIndex = i + (int)OVREye.Right;
IntPtr leftEyeTexturePtr = eyeTextures[leftEyeIndex].GetNativeTexturePtr();
IntPtr rightEyeTexturePtr = eyeTextures[rightEyeIndex].GetNativeTexturePtr();
if (OVRManager.instance.monoscopic)
rightEyeTexturePtr = leftEyeTexturePtr;
if (leftEyeTexturePtr == System.IntPtr.Zero || rightEyeTexturePtr == System.IntPtr.Zero)
return;
OVR_SetTexture(leftEyeIndex, leftEyeTexturePtr, OVRManager.instance.virtualTextureScale);
OVR_SetTexture(rightEyeIndex, rightEyeTexturePtr, OVRManager.instance.virtualTextureScale);
}
prevFullScreen = Screen.fullScreen;
OVR_UnitySetModeChange(false);
needsSetTexture = false;
}
#else
currEyeTextureIdx = nextEyeTextureIdx;
nextEyeTextureIdx = (nextEyeTextureIdx + 2) % eyeTextureCount;
#endif
}
private void ConfigureEyeDesc(OVREye eye)
{
Vector2 texSize = Vector2.zero;
Vector2 fovSize = Vector2.zero;
#if !UNITY_ANDROID || UNITY_EDITOR
FovPort fovPort = OVRManager.capiHmd.GetDesc().DefaultEyeFov[(int)eye];
fovPort.LeftTan = fovPort.RightTan = Mathf.Max(fovPort.LeftTan, fovPort.RightTan);
fovPort.UpTan = fovPort.DownTan = Mathf.Max(fovPort.UpTan, fovPort.DownTan);
texSize = OVRManager.capiHmd.GetFovTextureSize((Ovr.Eye)eye, fovPort, OVRManager.instance.nativeTextureScale).ToVector2();
fovSize = new Vector2(2f * Mathf.Rad2Deg * Mathf.Atan(fovPort.LeftTan), 2f * Mathf.Rad2Deg * Mathf.Atan(fovPort.UpTan));
#else
texSize = new Vector2(1024, 1024) * OVRManager.instance.nativeTextureScale;
fovSize = new Vector2(90, 90);
#endif
eyeDescs[(int)eye] = new EyeRenderDesc()
{
resolution = texSize,
fov = fovSize
};
}
private void ConfigureEyeTexture(int eyeBufferIndex, OVREye eye)
{
int eyeIndex = eyeBufferIndex + (int)eye;
EyeRenderDesc eyeDesc = eyeDescs[(int)eye];
eyeTextures[eyeIndex] = new RenderTexture(
(int)eyeDesc.resolution.x,
(int)eyeDesc.resolution.y,
(int)OVRManager.instance.eyeTextureDepth,
OVRManager.instance.eyeTextureFormat);
eyeTextures[eyeIndex].antiAliasing = (int)OVRManager.instance.eyeTextureAntiAliasing;
eyeTextures[eyeIndex].Create();
eyeTextureIds[eyeIndex] = eyeTextures[eyeIndex].GetNativeTextureID();
}
public void SetViewport(int x, int y, int w, int h)
{
#if !UNITY_ANDROID || UNITY_EDITOR
OVR_SetViewport(x, y, w, h);
#endif
}
private const string LibOVR = "OculusPlugin";
#if UNITY_ANDROID && !UNITY_EDITOR
//TODO: Get rid of these functions and implement OVR.CAPI.Hmd on Android.
[DllImport(LibOVR)]
private static extern bool OVR_ResetSensorOrientation();
[DllImport(LibOVR)]
private static extern bool OVR_GetAcceleration(ref float x, ref float y, ref float z);
[DllImport(LibOVR)]
private static extern bool OVR_GetAngularVelocity(ref float x, ref float y, ref float z);
[DllImport(LibOVR)]
private static extern bool OVR_IsHMDPresent();
[DllImport(LibOVR)]
private static extern bool OVR_GetCameraPositionOrientation(
ref float px,
ref float py,
ref float pz,
ref float ox,
ref float oy,
ref float oz,
ref float ow,
double atTime);
[DllImport(LibOVR)]
private static extern bool OVR_GetSensorState(
bool monoscopic,
ref float w,
ref float x,
ref float y,
ref float z,
ref float fov,
ref int viewNumber);
#else
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
private static extern void OVR_SetDistortionCaps(uint distortionCaps);
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
private static extern bool OVR_SetViewport(int x, int y, int w, int h);
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
private static extern Posef OVR_GetRenderPose(int frameIndex, int eyeId);
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
private static extern bool OVR_SetTexture(int id, System.IntPtr texture, float scale = 1);
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
private static extern bool OVR_UnityGetModeChange();
[DllImport(LibOVR, CallingConvention = CallingConvention.Cdecl)]
private static extern bool OVR_UnitySetModeChange(bool isChanged);
#endif
}
| |
#region License
//
// Command Line Library: ParserFixture.cs
//
// Author:
// Giacomo Stelluti Scala (gsscoder@gmail.com)
//
// Copyright (C) 2005 - 2013 Giacomo Stelluti Scala
//
// 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 Using Directives
using System;
using System.Globalization;
using System.IO;
using System.Threading;
using CommandLine.Tests.Fakes;
using Xunit;
using FluentAssertions;
#endregion
namespace CommandLine.Tests.Unit.Parser
{
public class ParserFixture : ParserBaseFixture
{
[Fact]
public void Will_throw_exception_if_arguments_array_is_null()
{
Assert.Throws<ArgumentNullException>(
() => new CommandLine.Parser().ParseArguments(null, new SimpleOptions()));
}
[Fact]
public void Will_throw_exception_if_options_instance_is_null()
{
Assert.Throws<ArgumentNullException>(
() => new CommandLine.Parser().ParseArguments(new string[] {}, null));
}
[Fact]
public void Parse_string_option()
{
var options = new SimpleOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-s", "something" }, options);
result.Should().BeTrue();
options.StringValue.Should().Be("something");
Console.WriteLine(options);
}
[Fact]
public void Parse_string_integer_bool_options()
{
var options = new SimpleOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(
new string[] { "-s", "another string", "-i100", "--switch" }, options);
result.Should().BeTrue();
options.StringValue.Should().Be("another string");
options.IntegerValue.Should().Be(100);
options.BooleanValue.Should().BeTrue();
Console.WriteLine(options);
}
[Fact]
public void Parse_short_adjacent_options()
{
var options = new BooleanSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-ca", "-d65" }, options);
result.Should().BeTrue();
options.BooleanThree.Should().BeTrue();
options.BooleanOne.Should().BeTrue();
options.BooleanTwo.Should().BeFalse();
options.NonBooleanValue.Should().Be(65D);
Console.WriteLine(options);
}
[Fact]
public void Parse_short_long_options()
{
var options = new BooleanSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-b", "--double=9" }, options);
result.Should().BeTrue();
options.BooleanTwo.Should().BeTrue();
options.BooleanOne.Should().BeFalse();
options.BooleanThree.Should().BeFalse();
options.NonBooleanValue.Should().Be(9D);
Console.WriteLine(options);
}
[Fact]
public void Parse_option_list()
{
var options = new SimpleOptionsWithOptionList();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] {
"-k", "string1:stringTwo:stringIII", "-s", "test-file.txt" }, options);
result.Should().BeTrue();
options.SearchKeywords[0].Should().Be("string1");
Console.WriteLine(options.SearchKeywords[0]);
options.SearchKeywords[1].Should().Be("stringTwo");
Console.WriteLine(options.SearchKeywords[1]);
options.SearchKeywords[2].Should().Be("stringIII");
Console.WriteLine(options.SearchKeywords[2]);
options.StringValue.Should().Be("test-file.txt");
Console.WriteLine(options.StringValue);
}
#region #BUG0000
[Fact]
public void Short_option_refuses_equal_token()
{
var options = new SimpleOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-i=10" }, options);
result.Should().BeFalse();
Console.WriteLine(options);
}
#endregion
[Fact]
public void Parse_enum_options()
{
var options = new SimpleOptionsWithEnum();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-s", "data.bin", "-a", "ReadWrite" }, options);
result.Should().BeTrue();
options.StringValue.Should().Be("data.bin");
options.FileAccess.Should().Be(FileAccess.ReadWrite);
Console.WriteLine(options);
}
[Fact]
public void Parse_culture_specific_number()
{
//var actualCulture = Thread.CurrentThread.CurrentCulture;
//Thread.CurrentThread.CurrentCulture = new CultureInfo("it-IT");
var options = new NumberSetOptions();
var parser = new CommandLine.Parser(new ParserSettings { ParsingCulture = new CultureInfo("it-IT") });
var result = parser.ParseArguments(new string[] { "-d", "10,986" }, options);
result.Should().BeTrue();
options.DoubleValue.Should().Be(10.986D);
//Thread.CurrentThread.CurrentCulture = actualCulture;
}
[Fact]
public void Parse_culture_specific_nullable_number()
{
var actualCulture = Thread.CurrentThread.CurrentCulture;
Thread.CurrentThread.CurrentCulture = new CultureInfo("it-IT");
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--n-double", "12,32982" }, options);
result.Should().BeTrue();
options.NullableDoubleValue.Should().Be(12.32982D);
Thread.CurrentThread.CurrentCulture = actualCulture;
}
[Fact]
public void Parse_options_with_defaults()
{
var options = new SimpleOptionsWithDefaults();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] {}, options);
result.Should().BeTrue();
options.StringValue.Should().Be("str");
options.IntegerValue.Should().Be(9);
options.BooleanValue.Should().BeTrue();
}
[Fact]
public void Parse_options_with_default_array()
{
var options = new SimpleOptionsWithDefaultArray();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new [] { "-y", "4", "5", "6" }, options);
result.Should().BeTrue();
options.StringArrayValue.Should().Equal(new [] { "a", "b", "c" });
options.IntegerArrayValue.Should().Equal(new [] { 4, 5, 6 });
options.DoubleArrayValue.Should().Equal(new [] { 1.1, 2.2, 3.3 });
}
[Fact]
public void Parse_options_with_bad_defaults()
{
var options = new SimpleOptionsWithBadDefaults();
Assert.Throws<ParserException>(
() => new CommandLine.Parser().ParseArguments(new string[] {}, options));
}
#region #BUG0002
[Fact]
public void Parsing_non_existent_short_option_fails_without_throwing_an_exception()
{
var options = new SimpleOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-x" }, options);
result.Should().BeFalse();
}
[Fact]
public void Parsing_non_existent_long_option_fails_without_throwing_an_exception()
{
var options = new SimpleOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--extend" }, options);
result.Should().BeFalse();
}
#endregion
#region #REQ0000
[Fact]
public void Default_parsing_is_case_sensitive()
{
var parser = new CommandLine.Parser();
var options = new MixedCaseOptions();
var result = parser.ParseArguments(new string[] { "-a", "alfa", "--beta-OPTION", "beta" }, options);
result.Should().BeTrue();
options.AlfaValue.Should().Be("alfa");
options.BetaValue.Should().Be("beta");
}
[Fact]
public void Using_wrong_case_with_default_fails()
{
var parser = new CommandLine.Parser();
var options = new MixedCaseOptions();
var result = parser.ParseArguments(new string[] { "-A", "alfa", "--Beta-Option", "beta" }, options);
result.Should().BeFalse();
}
[Fact]
public void Disabling_case_sensitive()
{
var parser = new CommandLine.Parser(new ParserSettings(false)); //Ref.: #DGN0001
var options = new MixedCaseOptions();
var result = parser.ParseArguments(new string[] { "-A", "alfa", "--Beta-Option", "beta" }, options);
result.Should().BeTrue();
options.AlfaValue.Should().Be("alfa");
options.BetaValue.Should().Be("beta");
}
#endregion
#region #BUG0003
[Fact]
public void Passing_no_value_to_a_string_type_long_option_fails()
{
var options = new SimpleOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--string" }, options);
result.Should().BeFalse();
}
[Fact]
public void Passing_no_value_to_a_byte_type_long_option_fails()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--byte" }, options);
result.Should().BeFalse();
}
[Fact]
public void Passing_no_value_to_a_short_type_long_option_fails()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--short" }, options);
result.Should().BeFalse();
}
[Fact]
public void Passing_no_value_to_an_integer_type_long_option_fails()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--int" }, options);
result.Should().BeFalse();
}
[Fact]
public void Passing_no_value_to_a_long_type_long_option_fails()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--long" }, options);
result.Should().BeFalse();
}
[Fact]
public void Passing_no_value_to_a_float_type_long_option_fails()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--float" }, options);
result.Should().BeFalse();
}
[Fact]
public void Passing_no_value_to_a_double_type_long_option_fails()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--double" }, options);
result.Should().BeFalse();
}
#endregion
#region #REQ0001
[Fact]
public void Allow_single_dash_as_option_input_value()
{
var options = new SimpleOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--string", "-" }, options);
result.Should().BeTrue();
options.StringValue.Should().Be("-");
}
[Fact]
public void Allow_single_dash_as_non_option_value()
{
var options = new SimpleOptionsWithValueList();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-sparser.xml", "-", "--switch" }, options);
result.Should().BeTrue();
options.StringValue.Should().Be("parser.xml");
options.BooleanValue.Should().BeTrue();
options.Items.Count.Should().Be(1);
options.Items[0].Should().Be("-");
}
#endregion
#region #BUG0004
[Fact]
public void Parse_negative_integer_value()
{
var options = new SimpleOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-i", "-4096" }, options);
result.Should().BeTrue();
options.IntegerValue.Should().Be(-4096);
}
public void ParseNegativeIntegerValue_InputStyle2()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-i-4096" }, options);
result.Should().BeTrue();
options.IntegerValue.Should().Be(-4096);
}
public void ParseNegativeIntegerValue_InputStyle3()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--int", "-4096" }, options);
result.Should().BeTrue();
options.IntegerValue.Should().Be(-4096);
}
public void ParseNegativeIntegerValue_InputStyle4()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--int=-4096" }, options);
result.Should().BeTrue();
options.IntegerValue.Should().Be(-4096);
}
[Fact]
public void Parse_negative_floating_point_value()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-d", "-4096.1024" }, options);
result.Should().BeTrue();
options.DoubleValue.Should().Be(-4096.1024D);
}
[Fact]
public void Parse_negative_floating_point_value_input_style2()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-d-4096.1024" }, options);
result.Should().BeTrue();
options.DoubleValue.Should().Be(-4096.1024D);
}
[Fact]
public void Parse_negative_floating_point_value_input_style3()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--double", "-4096.1024" }, options);
result.Should().BeTrue();
options.DoubleValue.Should().Be(-4096.1024D);
}
[Fact]
public void Parse_negative_floating_point_value_input_style4()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "--double=-4096.1024" }, options);
result.Should().BeTrue();
options.DoubleValue.Should().Be(-4096.1024D);
}
#endregion
#region #BUG0005
[Fact]
public void Passing_short_value_to_byte_option_must_fail_gracefully()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-b", short.MaxValue.ToString(CultureInfo.InvariantCulture) }, options);
result.Should().BeFalse();
}
[Fact]
public void Passing_integer_value_to_short_option_must_fail_gracefully()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-s", int.MaxValue.ToString(CultureInfo.InvariantCulture) }, options);
result.Should().BeFalse();
}
[Fact]
public void Passing_long_value_to_integer_option_must_fail_gracefully()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-i", long.MaxValue.ToString(CultureInfo.InvariantCulture) }, options);
result.Should().BeFalse();
}
[Fact]
public void Passing_float_value_to_long_option_must_fail_gracefully()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-l", float.MaxValue.ToString(CultureInfo.InvariantCulture) }, options);
result.Should().BeFalse();
}
[Fact]
public void Passing_double_value_to_float_option_must_fail_gracefully()
{
var options = new NumberSetOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new string[] { "-f", double.MaxValue.ToString(CultureInfo.InvariantCulture) }, options);
result.Should().BeFalse();
}
#endregion
#region ISSUE#15
/// <summary>
/// https://github.com/gsscoder/commandline/issues/15
/// </summary>
[Fact]
public void Parser_should_report_missing_value()
{
var options = new ComplexOptions();
var parser = new CommandLine.Parser();
var result = parser.ParseArguments(new[] { "-i", "-o" }, options);
result.Should().BeFalse();
options.LastParserState.Errors.Count.Should().BeGreaterThan(0);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using NuGet.Resources;
namespace NuGet
{
public static class ProjectSystemExtensions
{
public static void AddFiles(this IProjectSystem project,
IEnumerable<IPackageFile> files,
IDictionary<FileTransformExtensions, IPackageFileTransformer> fileTransformers)
{
// Convert files to a list
List<IPackageFile> fileList = files.ToList();
// See if the project system knows how to sort the files
var fileComparer = project as IComparer<IPackageFile>;
if (fileComparer != null)
{
fileList.Sort(fileComparer);
}
var batchProcessor = project as IBatchProcessor<string>;
try
{
if (batchProcessor != null)
{
var paths = fileList.Select(file => ResolvePath(fileTransformers, fte => fte.InstallExtension, file.EffectivePath));
batchProcessor.BeginProcessing(paths, PackageAction.Install);
}
foreach (IPackageFile file in fileList)
{
if (file.IsEmptyFolder())
{
continue;
}
// Resolve the target path
IPackageFileTransformer installTransformer;
string path = ResolveTargetPath(project, fileTransformers, fte => fte.InstallExtension, file.EffectivePath, out installTransformer);
if (project.IsSupportedFile(path))
{
if (installTransformer != null)
{
installTransformer.TransformFile(file, path, project);
}
else
{
// Ignore uninstall transform file during installation
string truncatedPath;
IPackageFileTransformer uninstallTransformer =
FindFileTransformer(fileTransformers, fte => fte.UninstallExtension, file.EffectivePath, out truncatedPath);
if (uninstallTransformer != null)
{
continue;
}
TryAddFile(project, path, file.GetStream);
}
}
}
}
finally
{
if (batchProcessor != null)
{
batchProcessor.EndProcessing();
}
}
}
/// <summary>
/// Try to add the specified the project with the target path. If there's an existing file in the project with the same name,
/// it will ask the logger for the resolution, which has 4 choices: Overwrite|Ignore|Overwrite All|Ignore All
/// </summary>
internal static void TryAddFile(IProjectSystem project, string path, Func<Stream> content)
{
if (project.FileExists(path) && project.FileExistsInProject(path))
{
// file exists in project, ask user if he wants to overwrite or ignore
string conflictMessage = String.Format(CultureInfo.CurrentCulture, NuGetResources.FileConflictMessage, path, project.ProjectName);
FileConflictResolution resolution = project.Logger.ResolveFileConflict(conflictMessage);
if (resolution == FileConflictResolution.Overwrite || resolution == FileConflictResolution.OverwriteAll)
{
// overwrite
project.Logger.Log(MessageLevel.Info, NuGetResources.Info_OverwriteExistingFile, path);
using (Stream stream = content())
{
project.AddFile(path, stream);
}
}
else
{
// ignore
project.Logger.Log(MessageLevel.Info, NuGetResources.Warning_FileAlreadyExists, path);
}
}
else
{
using (Stream stream = content())
{
project.AddFile(path, stream);
}
}
}
[SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling")]
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "We want delete to be robust, when exceptions occur we log then and move on")]
public static void DeleteFiles(this IProjectSystem project,
IEnumerable<IPackageFile> files,
IEnumerable<IPackage> otherPackages,
IDictionary<FileTransformExtensions, IPackageFileTransformer> fileTransformers)
{
IPackageFileTransformer transformer;
// First get all directories that contain files
var directoryLookup = files.ToLookup(
p => Path.GetDirectoryName(ResolveTargetPath(project, fileTransformers, fte => fte.UninstallExtension, p.EffectivePath, out transformer)));
// Get all directories that this package may have added
var directories = from grouping in directoryLookup
from directory in FileSystemExtensions.GetDirectories(grouping.Key)
orderby directory.Length descending
select directory;
// Remove files from every directory
foreach (var directory in directories)
{
var directoryFiles = directoryLookup.Contains(directory) ? directoryLookup[directory] : Enumerable.Empty<IPackageFile>();
if (!project.DirectoryExists(directory))
{
continue;
}
var batchProcessor = project as IBatchProcessor<string>;
try
{
if (batchProcessor != null)
{
var paths = directoryFiles.Select(file => ResolvePath(fileTransformers, fte => fte.UninstallExtension, file.EffectivePath));
batchProcessor.BeginProcessing(paths, PackageAction.Uninstall);
}
foreach (var file in directoryFiles)
{
if (file.IsEmptyFolder())
{
continue;
}
// Resolve the path
string path = ResolveTargetPath(project,
fileTransformers,
fte => fte.UninstallExtension,
file.EffectivePath,
out transformer);
if (project.IsSupportedFile(path))
{
if (transformer != null)
{
var matchingFiles = from p in otherPackages
from otherFile in project.GetCompatibleItemsCore(p.GetContentFiles())
where otherFile.EffectivePath.Equals(file.EffectivePath, StringComparison.OrdinalIgnoreCase)
select otherFile;
try
{
transformer.RevertFile(file, path, matchingFiles, project);
}
catch (Exception e)
{
// Report a warning and move on
project.Logger.Log(MessageLevel.Warning, e.Message);
}
}
else
{
project.DeleteFileSafe(path, file.GetStream);
}
}
}
// If the directory is empty then delete it
if (!project.GetFilesSafe(directory).Any() &&
!project.GetDirectoriesSafe(directory).Any())
{
project.DeleteDirectorySafe(directory, recursive: false);
}
}
finally
{
if (batchProcessor != null)
{
batchProcessor.EndProcessing();
}
}
}
}
public static bool TryGetCompatibleItems<T>(this IProjectSystem projectSystem, IEnumerable<T> items, out IEnumerable<T> compatibleItems) where T : IFrameworkTargetable
{
if (projectSystem == null)
{
throw new ArgumentNullException("projectSystem");
}
if (items == null)
{
throw new ArgumentNullException("items");
}
return VersionUtility.TryGetCompatibleItems<T>(projectSystem.TargetFramework, items, out compatibleItems);
}
internal static IEnumerable<T> GetCompatibleItemsCore<T>(this IProjectSystem projectSystem, IEnumerable<T> items) where T : IFrameworkTargetable
{
IEnumerable<T> compatibleItems;
if (VersionUtility.TryGetCompatibleItems(projectSystem.TargetFramework, items, out compatibleItems))
{
return compatibleItems;
}
return Enumerable.Empty<T>();
}
private static string ResolvePath(
IDictionary<FileTransformExtensions, IPackageFileTransformer> fileTransformers,
Func<FileTransformExtensions, string> extensionSelector,
string effectivePath)
{
string truncatedPath;
// Remove the transformer extension (e.g. .pp, .transform)
IPackageFileTransformer transformer = FindFileTransformer(
fileTransformers, extensionSelector, effectivePath, out truncatedPath);
if (transformer != null)
{
effectivePath = truncatedPath;
}
return effectivePath;
}
private static string ResolveTargetPath(IProjectSystem projectSystem,
IDictionary<FileTransformExtensions, IPackageFileTransformer> fileTransformers,
Func<FileTransformExtensions, string> extensionSelector,
string effectivePath,
out IPackageFileTransformer transformer)
{
string truncatedPath;
// Remove the transformer extension (e.g. .pp, .transform)
transformer = FindFileTransformer(fileTransformers, extensionSelector, effectivePath, out truncatedPath);
if (transformer != null)
{
effectivePath = truncatedPath;
}
return projectSystem.ResolvePath(effectivePath);
}
private static IPackageFileTransformer FindFileTransformer(
IDictionary<FileTransformExtensions, IPackageFileTransformer> fileTransformers,
Func<FileTransformExtensions, string> extensionSelector,
string effectivePath,
out string truncatedPath)
{
foreach (var transformExtensions in fileTransformers.Keys)
{
string extension = extensionSelector(transformExtensions);
if (effectivePath.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
{
truncatedPath = effectivePath.Substring(0, effectivePath.Length - extension.Length);
// Bug 1686: Don't allow transforming packages.config.transform,
// but we still want to copy packages.config.transform as-is into the project.
string fileName = Path.GetFileName(truncatedPath);
if (!Constants.PackageReferenceFile.Equals(fileName, StringComparison.OrdinalIgnoreCase))
{
return fileTransformers[transformExtensions];
}
}
}
truncatedPath = effectivePath;
return null;
}
}
}
| |
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.SPA.CRM.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;
}
}
}
| |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Q42.HueApi.ColorConverters.Gamut;
using Q42.HueApi.Models.Gamut;
using System;
namespace Q42.HueApi.ColorConverters.Tests
{
[TestClass]
public class ColorConverterTests
{
[TestMethod]
public void ColorConversionWhitePoint()
{
// These light models are capable of Gamuts A, B and C respectively.
// See http://www.developers.meethue.com/documentation/supported-lights
string[] models = new string[] { "LST001", "LCT001", "LST002" };
foreach (string model in models)
{
// Make sure that Philips' white point resolves to #FFFFFF for all lights.
var rgb = HueColorConverter.XYToRgb(CIE1931Point.PhilipsWhite, CIE1931Gamut.ForModel(model));
Assert.AreEqual(rgb.R, 1.0, 0.0001);
Assert.AreEqual(rgb.G, 1.0, 0.0001);
Assert.AreEqual(rgb.B, 1.0, 0.0001);
var xy = HueColorConverter.RgbToXY(new RGBColor(1.0, 1.0, 1.0), CIE1931Gamut.ForModel(model));
AssertAreEqual(CIE1931Point.PhilipsWhite, xy, 0.0001);
}
}
[TestMethod]
public void ColorsOutsideGamutAdjustedToInBeInGamut()
{
// This green is in the gamut of LST001, but not LCT001.
CIE1931Point outsideGreen = new CIE1931Point(0.18, 0.72);
CIE1931Point gamutAGreen = new CIE1931Point(0.2151, 0.7106);
CIE1931Point gamutBGreen = new CIE1931Point(0.409, 0.518);
CIE1931Point gamutCGreen = new CIE1931Point(0.17, 0.7);
AssertAreEqual(gamutAGreen, CIE1931Gamut.ForModel("LST001").NearestContainedPoint(outsideGreen), 0.0001);
AssertAreEqual(gamutBGreen, CIE1931Gamut.ForModel("LCT001").NearestContainedPoint(outsideGreen), 0.0001);
AssertAreEqual(gamutCGreen, CIE1931Gamut.ForModel("LST002").NearestContainedPoint(outsideGreen), 0.0001);
}
[TestMethod]
public void ColorsOutsideGamutAdjustedToInBeInGamutOnConversion()
{
// The green primary of Gamut A.
CIE1931Point gamutGreen = new CIE1931Point(0.2151, 0.7106);
// A color green outside Gamut A.
CIE1931Point greenOutsideGamut = new CIE1931Point(0.21, 0.75);
var a = HueColorConverter.XYToRgb(gamutGreen, CIE1931Gamut.ForModel("LST001"));
var b = HueColorConverter.XYToRgb(greenOutsideGamut, CIE1931Gamut.ForModel("LST001"));
// Points should be equal, since the green outside the gamut should
// be adjusted the the nearest green in-gamut.
Assert.AreEqual(a.R, b.R);
Assert.AreEqual(a.G, b.G);
Assert.AreEqual(a.B, b.B);
}
[TestMethod]
public void CompareColorConversionWithReference()
{
// Use a consistent seed for test reproducability
Random r = new Random(0);
for (int trial = 0; trial < 1000; trial++)
{
double red = r.NextDouble();
double green = r.NextDouble();
double blue = r.NextDouble();
var referenceXy = ReferenceColorConverter.XyFromColor(red, green, blue);
// LCT001 uses Gamut B, which is the gamut used in the reference implementation.
var actualXy = HueColorConverter.RgbToXY(new RGBColor(red, green, blue), CIE1931Gamut.ForModel("LCT001"));
AssertAreEqual(referenceXy, actualXy, 0.0001);
}
}
[TestMethod]
public void GamutContainsWorksCorrectly()
{
Random r = new Random(0);
for (int trial = 0; trial < 1000; trial++)
{
var point = new CIE1931Point(r.NextDouble(), r.NextDouble());
var gamutB = CIE1931Gamut.ForModel("LCT001");
Assert.AreEqual(ReferenceColorConverter.CheckPointInLampsReach(point), gamutB.Contains(point));
}
}
[TestMethod]
public void ColorConversionRoundtripInsideGamut()
{
// Use a consistent seed for test reproducability
Random r = new Random(0);
for (int trial = 0; trial < 1000; trial++)
{
CIE1931Point originalXy;
// Randomly generate a test color that is at a valid CIE1931 coordinate.
do
{
originalXy = new CIE1931Point(r.NextDouble(), r.NextDouble());
}
while (originalXy.x + originalXy.y >= 1.0
|| !ReferenceColorConverter.CheckPointInLampsReach(originalXy)
|| !CIE1931Gamut.PhilipsWideGamut.Contains(originalXy));
RGBColor rgb = HueColorConverter.XYToRgb(originalXy, CIE1931Gamut.ForModel("LCT001"));
var xy = HueColorConverter.RgbToXY(rgb, CIE1931Gamut.ForModel("LCT001"));
AssertAreEqual(originalXy, xy, 0.0001);
}
}
[TestMethod]
public void ColorConversionRoundtripAllPoints()
{
// Use a consistent seed for test reproducability
Random r = new Random(0);
for (int trial = 0; trial < 1000; trial++)
{
CIE1931Point originalXy;
// Randomly generate a test color that is at a valid CIE1931 coordinate.
do
{
originalXy = new CIE1931Point(r.NextDouble(), r.NextDouble());
}
while (originalXy.x + originalXy.y >= 1.0);
RGBColor rgb = HueColorConverter.XYToRgb(originalXy, CIE1931Gamut.ForModel("LCT001"));
var xy = HueColorConverter.RgbToXY(rgb, CIE1931Gamut.ForModel("LCT001"));
// We expect a point that is both inside the lamp's gamut and the "wide gamut"
// used for XYZ->RGB and RGB->XYZ conversion.
// Conversion from XY to RGB
var expectedXy = CIE1931Gamut.ForModel("LCT001").NearestContainedPoint(originalXy);
expectedXy = CIE1931Gamut.PhilipsWideGamut.NearestContainedPoint(expectedXy);
// RGB to XY
expectedXy = CIE1931Gamut.ForModel("LCT001").NearestContainedPoint(expectedXy);
AssertAreEqual(expectedXy, xy, 0.0001);
}
}
private void AssertAreEqual(CIE1931Point expected, CIE1931Point actual, double delta)
{
Assert.AreEqual(expected.x, actual.x, delta);
Assert.AreEqual(expected.y, actual.y, delta);
Assert.AreEqual(expected.z, actual.z, delta);
}
}
/// <summary>
/// A prior implementation of color converter. Assumes all lights have the gamut of
/// the original LCT001 hue lights.
/// N.B. It has been modified to use the philips matrix "Wide Gamut" for mapping from RGB -> XYZ
/// instead of the original matrix, and apply gamma correctly.
/// </summary>
internal static partial class ReferenceColorConverter
{
private static CIE1931Point Red = new CIE1931Point(0.675F, 0.322F);
private static CIE1931Point Lime = new CIE1931Point(0.409F, 0.518F);
private static CIE1931Point Blue = new CIE1931Point(0.167F, 0.04F);
private static float factor = 10000.0f;
private static int maxX = 452;
private static int maxY = 302;
/// <summary>
/// Get XY from red,green,blue ints
/// </summary>
/// <param name="red"></param>
/// <param name="green"></param>
/// <param name="blue"></param>
/// <returns></returns>
public static CIE1931Point XyFromColor(double red, double green, double blue)
{
double r = (red > 0.04045f) ? Math.Pow((red + 0.055f) / (1.0f + 0.055f), 2.4f) : (red / 12.92f);
double g = (green > 0.04045f) ? Math.Pow((green + 0.055f) / (1.0f + 0.055f), 2.4f) : (green / 12.92f);
double b = (blue > 0.04045f) ? Math.Pow((blue + 0.055f) / (1.0f + 0.055f), 2.4f) : (blue / 12.92f);
//double X = r * 0.4360747f + g * 0.3850649f + b * 0.0930804f;
//double Y = r * 0.2225045f + g * 0.7168786f + b * 0.0406169f;
//double Z = r * 0.0139322f + g * 0.0971045f + b * 0.7141733f;
double X = r * 0.664511f + g * 0.154324f + b * 0.162028f;
double Y = r * 0.283881f + g * 0.668433f + b * 0.047685f;
double Z = r * 0.000088f + g * 0.072310f + b * 0.986039f;
double cx = X / (X + Y + Z);
double cy = Y / (X + Y + Z);
if (Double.IsNaN(cx))
{
cx = 0.0f;
}
if (Double.IsNaN(cy))
{
cy = 0.0f;
}
//Check if the given XY value is within the colourreach of our lamps.
CIE1931Point xyPoint = new CIE1931Point(cx, cy);
bool inReachOfLamps = ReferenceColorConverter.CheckPointInLampsReach(xyPoint);
if (!inReachOfLamps)
{
//It seems the colour is out of reach
//let's find the closes colour we can produce with our lamp and send this XY value out.
//Find the closest point on each line in the triangle.
CIE1931Point pAB = ReferenceColorConverter.GetClosestPointToPoint(Red, Lime, xyPoint);
CIE1931Point pAC = ReferenceColorConverter.GetClosestPointToPoint(Blue, Red, xyPoint);
CIE1931Point pBC = ReferenceColorConverter.GetClosestPointToPoint(Lime, Blue, xyPoint);
//Get the distances per point and see which point is closer to our Point.
double dAB = ReferenceColorConverter.GetDistanceBetweenTwoPoints(xyPoint, pAB);
double dAC = ReferenceColorConverter.GetDistanceBetweenTwoPoints(xyPoint, pAC);
double dBC = ReferenceColorConverter.GetDistanceBetweenTwoPoints(xyPoint, pBC);
double lowest = dAB;
CIE1931Point closestPoint = pAB;
if (dAC < lowest)
{
lowest = dAC;
closestPoint = pAC;
}
if (dBC < lowest)
{
lowest = dBC;
closestPoint = pBC;
}
//Change the xy value to a value which is within the reach of the lamp.
cx = closestPoint.x;
cy = closestPoint.y;
}
return new CIE1931Point(cx, cy);
}
/// <summary>
/// Method to see if the given XY value is within the reach of the lamps.
/// </summary>
/// <param name="p">p the point containing the X,Y value</param>
/// <returns>true if within reach, false otherwise.</returns>
public static bool CheckPointInLampsReach(CIE1931Point p)
{
CIE1931Point v1 = new CIE1931Point(Lime.x - Red.x, Lime.y - Red.y);
CIE1931Point v2 = new CIE1931Point(Blue.x - Red.x, Blue.y - Red.y);
CIE1931Point q = new CIE1931Point(p.x - Red.x, p.y - Red.y);
double s = ReferenceColorConverter.CrossProduct(q, v2) / ReferenceColorConverter.CrossProduct(v1, v2);
double t = ReferenceColorConverter.CrossProduct(v1, q) / ReferenceColorConverter.CrossProduct(v1, v2);
if ((s >= 0.0f) && (t >= 0.0f) && (s + t <= 1.0f))
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Calculates crossProduct of two 2D vectors / points.
/// </summary>
/// <param name="p1"> p1 first point used as vector</param>
/// <param name="p2">p2 second point used as vector</param>
/// <returns>crossProduct of vectors</returns>
private static double CrossProduct(CIE1931Point p1, CIE1931Point p2)
{
return (p1.x * p2.y - p1.y * p2.x);
}
/// <summary>
/// Find the closest point on a line.
/// This point will be within reach of the lamp.
/// </summary>
/// <param name="A">A the point where the line starts</param>
/// <param name="B">B the point where the line ends</param>
/// <param name="P">P the point which is close to a line.</param>
/// <returns> the point which is on the line.</returns>
private static CIE1931Point GetClosestPointToPoint(CIE1931Point A, CIE1931Point B, CIE1931Point P)
{
CIE1931Point AP = new CIE1931Point(P.x - A.x, P.y - A.y);
CIE1931Point AB = new CIE1931Point(B.x - A.x, B.y - A.y);
double ab2 = AB.x * AB.x + AB.y * AB.y;
double ap_ab = AP.x * AB.x + AP.y * AB.y;
double t = ap_ab / ab2;
if (t < 0.0f)
t = 0.0f;
else if (t > 1.0f)
t = 1.0f;
CIE1931Point newPoint = new CIE1931Point(A.x + AB.x * t, A.y + AB.y * t);
return newPoint;
}
/// <summary>
/// Find the distance between two points.
/// </summary>
/// <param name="one"></param>
/// <param name="two"></param>
/// <returns>the distance between point one and two</returns>
private static double GetDistanceBetweenTwoPoints(CIE1931Point one, CIE1931Point two)
{
double dx = one.x - two.x; // horizontal difference
double dy = one.y - two.y; // vertical difference
double dist = Math.Sqrt(dx * dx + dy * dy);
return dist;
}
/// <summary>
/// Get the RGB color from an XY value
/// </summary>
/// <param name="xNumber"></param>
/// <param name="yNumber"></param>
/// <returns></returns>
public static RGBColor RgbFromXy(double xNumber, double yNumber)
{
if (xNumber == 0 && yNumber == 0)
{
return new RGBColor(1.0, 1.0, 1.0);
}
int closestValue = Int32.MaxValue;
int closestX = 0, closestY = 0;
double fX = xNumber;
double fY = yNumber;
int intX = (int)(fX * factor);
int intY = (int)(fY * factor);
for (int y = 0; y < maxY; y++)
{
for (int x = 0; x < maxX; x++)
{
int differenceForPixel = 0;
differenceForPixel += Math.Abs(xArray[x, y] - intX);
differenceForPixel += Math.Abs(yArray[x, y] - intY);
if (differenceForPixel < closestValue)
{
closestX = x;
closestY = y;
closestValue = differenceForPixel;
}
}
}
int color = cArray[closestX, closestY];
int red = (color >> 16) & 0xFF;
int green = (color >> 8) & 0xFF;
int blue = color & 0xFF;
return new RGBColor(red / 255.0, green / 255.0, blue / 255.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.Text;
namespace System
{
public class RandomDataGenerator
{
private Random _rand = new Random();
private int? _seed = null;
public int? Seed
{
get { return _seed; }
set
{
if (!_seed.HasValue && value.HasValue)
{
_seed = value;
_rand = new Random(value.Value);
}
}
}
// returns a byte array of random data
public void GetBytes(int newSeed, byte[] buffer)
{
Seed = newSeed;
GetBytes(buffer);
}
public void GetBytes(byte[] buffer)
{
_rand.NextBytes(buffer);
}
// returns a non-negative Int64 between 0 and Int64.MaxValue
public long GetInt64(int newSeed)
{
Seed = newSeed;
return GetInt64();
}
public long GetInt64()
{
byte[] buffer = new byte[8];
GetBytes(buffer);
long result = BitConverter.ToInt64(buffer, 0);
return result != long.MinValue ? Math.Abs(result) : long.MaxValue;
}
// returns a non-negative Int32 between 0 and Int32.MaxValue
public int GetInt32(int new_seed)
{
Seed = new_seed;
return GetInt32();
}
public int GetInt32()
{
return _rand.Next();
}
// returns a non-negative Int16 between 0 and Int16.MaxValue
public short GetInt16(int new_seed)
{
Seed = new_seed;
return GetInt16();
}
public short GetInt16()
{
return (short)_rand.Next(1 + short.MaxValue);
}
// returns a non-negative Byte between 0 and Byte.MaxValue
public byte GetByte(int new_seed)
{
Seed = new_seed;
return GetByte();
}
public byte GetByte()
{
return (byte)_rand.Next(1 + byte.MaxValue);
}
// returns a non-negative Double between 0.0 and 1.0
public double GetDouble(int new_seed)
{
Seed = new_seed;
return GetDouble();
}
public double GetDouble()
{
return _rand.NextDouble();
}
// returns a non-negative Single between 0.0 and 1.0
public float GetSingle(int newSeed)
{
Seed = newSeed;
return GetSingle();
}
public float GetSingle()
{
return (float)_rand.NextDouble();
}
// returns a valid char that is a letter
public char GetCharLetter(int newSeed)
{
Seed = newSeed;
return GetCharLetter();
}
public char GetCharLetter()
{
return GetCharLetter(allowSurrogate: true);
}
// returns a valid char that is a letter
// if allowsurrogate is true then surrogates are valid return values
public char GetCharLetter(int newSeed, bool allowSurrogate)
{
Seed = newSeed;
return GetCharLetter(allowSurrogate);
}
public char GetCharLetter(bool allowSurrogate)
{
return GetCharLetter(allowSurrogate, allowNoWeight: true);
}
// returns a valid char that is a letter
// if allowsurrogate is true then surrogates are valid return values
// if allownoweight is true, then no-weight characters are valid return values
public char GetCharLetter(int newSeed, bool allowSurrogate, bool allowNoWeight)
{
Seed = newSeed;
return GetCharLetter(allowSurrogate, allowNoWeight);
}
public char GetCharLetter(bool allowSurrogate, bool allowNoWeight)
{
short iVal;
char c = 'a';
int counter;
bool loopCondition = true;
// attempt to randomly find a letter
counter = 100;
do
{
counter--;
iVal = GetInt16();
if (false == allowNoWeight)
{
throw new NotSupportedException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES");
}
c = Convert.ToChar(iVal);
loopCondition = allowSurrogate ? (!char.IsLetter(c)) : (!char.IsLetter(c) || char.IsSurrogate(c));
}
while (loopCondition && 0 < counter);
if (!char.IsLetter(c))
{
// we tried and failed to get a letter
// Grab an ASCII letter
c = Convert.ToChar(GetInt16() % 26 + 'A');
}
return c;
}
// returns a valid char that is a number
public char GetCharNumber(int newSeed)
{
Seed = newSeed;
return GetCharNumber();
}
public char GetCharNumber()
{
return GetCharNumber(true);
}
// returns a valid char that is a number
// if allownoweight is true, then no-weight characters are valid return values
public char GetCharNumber(int newSeed, bool allowNoWeight)
{
Seed = newSeed;
return GetCharNumber(allowNoWeight);
}
public char GetCharNumber(bool allowNoWeight)
{
char c = '0';
int counter;
short iVal;
bool loopCondition = true;
// attempt to randomly find a number
counter = 100;
do
{
counter--;
iVal = GetInt16();
if (false == allowNoWeight)
{
throw new InvalidOperationException("allownoweight = false is not supported in TestLibrary with FEATURE_NOPINVOKES");
}
c = Convert.ToChar(iVal);
loopCondition = !char.IsNumber(c);
}
while (loopCondition && 0 < counter);
if (!char.IsNumber(c))
{
// we tried and failed to get a letter
// Grab an ASCII number
c = Convert.ToChar(GetInt16() % 10 + '0');
}
return c;
}
// returns a valid char
public char GetChar(int newSeed)
{
Seed = newSeed;
return GetChar();
}
public char GetChar()
{
return GetChar(allowSurrogate: true);
}
// returns a valid char
// if allowsurrogate is true then surrogates are valid return values
public char GetChar(int newSeed, bool allowSurrogate)
{
Seed = newSeed;
return GetChar(allowSurrogate);
}
public char GetChar(bool allowSurrogate)
{
return GetChar(allowSurrogate, allowNoWeight: true);
}
// returns a valid char
// if allowsurrogate is true then surrogates are valid return values
// if allownoweight characters then noweight characters are valid return values
public char GetChar(int newSeed, bool allowSurrogate, bool allowNoWeight)
{
Seed = newSeed;
return GetChar(allowSurrogate, allowNoWeight);
}
public char GetChar(bool allowSurrogate, bool allowNoWeight)
{
short iVal = GetInt16();
char c = (char)(iVal);
if (!char.IsLetter(c))
{
// we tried and failed to get a letter
// Just grab an ASCII letter
c = (char)(GetInt16() % 26 + 'A');
}
return c;
}
// returns a string. If "validPath" is set, only valid path characters
// will be included
public string GetString(int newSeed, bool validPath, int minLength, int maxLength)
{
Seed = newSeed;
return GetString(validPath, minLength, maxLength);
}
public string GetString(bool validPath, int minLength, int maxLength)
{
return GetString(validPath, true, true, minLength, maxLength);
}
public string GetString(int newSeed, bool validPath, bool allowNulls, int minLength, int maxLength)
{
Seed = newSeed;
return GetString(validPath, allowNulls, minLength, maxLength);
}
public string GetString(bool validPath, bool allowNulls, int minLength, int maxLength)
{
return GetString(validPath, allowNulls, true, minLength, maxLength);
}
public string GetString(int newSeed, bool validPath, bool allowNulls, bool allowNoWeight, int minLength, int maxLength)
{
Seed = newSeed;
return GetString(validPath, allowNulls, allowNoWeight, minLength, maxLength);
}
public string GetString(bool validPath, bool allowNulls, bool allowNoWeight, int minLength, int maxLength)
{
StringBuilder sVal = new StringBuilder();
char c;
int length;
if (0 == minLength && 0 == maxLength) return string.Empty;
if (minLength > maxLength) return null;
length = minLength;
if (minLength != maxLength)
{
length = (GetInt32() % (maxLength - minLength)) + minLength;
}
for (int i = 0; length > i; i++)
{
if (validPath)
{
if (0 == (GetByte() % 2))
{
c = GetCharLetter(true, allowNoWeight);
}
else
{
c = GetCharNumber(allowNoWeight);
}
}
else if (!allowNulls)
{
do
{
c = GetChar(true, allowNoWeight);
} while (c == '\u0000');
}
else
{
c = GetChar(true, allowNoWeight);
}
sVal.Append(c);
}
string s = sVal.ToString();
return s;
}
public string[] GetStrings(int newSeed, bool validPath, int minLength, int maxLength)
{
Seed = newSeed;
return GetStrings(validPath, minLength, maxLength);
}
public string[] GetStrings(bool validPath, int minLength, int maxLength)
{
string validString;
const char c_LATIN_A = '\u0100';
const char c_LOWER_A = 'a';
const char c_UPPER_A = 'A';
const char c_ZERO_WEIGHT = '\uFEFF';
const char c_DOUBLE_WIDE_A = '\uFF21';
const string c_SURROGATE_UPPER = "\uD801\uDC00";
const string c_SURROGATE_LOWER = "\uD801\uDC28";
const char c_LOWER_SIGMA1 = (char)0x03C2;
const char c_LOWER_SIGMA2 = (char)0x03C3;
const char c_UPPER_SIGMA = (char)0x03A3;
const char c_SPACE = ' ';
if (2 >= minLength && 2 >= maxLength || minLength > maxLength)
return null;
validString = GetString(validPath, minLength - 1, maxLength - 1);
string[] retStrings = new string[12];
retStrings[0] = GetString(validPath, minLength, maxLength);
retStrings[1] = validString + c_LATIN_A;
retStrings[2] = validString + c_LOWER_A;
retStrings[3] = validString + c_UPPER_A;
retStrings[4] = validString + c_ZERO_WEIGHT;
retStrings[5] = validString + c_DOUBLE_WIDE_A;
retStrings[6] = GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_UPPER;
retStrings[7] = GetString(validPath, minLength - 2, maxLength - 2) + c_SURROGATE_LOWER;
retStrings[8] = validString + c_LOWER_SIGMA1;
retStrings[9] = validString + c_LOWER_SIGMA2;
retStrings[10] = validString + c_UPPER_SIGMA;
retStrings[11] = validString + c_SPACE;
return retStrings;
}
public static void VerifyRandomDistribution(byte[] random)
{
// Better tests for randomness are available. For now just use a simple
// check that compares the number of 0s and 1s in the bits.
VerifyNeutralParity(random);
}
private static void VerifyNeutralParity(byte[] random)
{
int zeroCount = 0, oneCount = 0;
for (int i = 0; i < random.Length; i++)
{
for (int j = 0; j < 8; j++)
{
if (((random[i] >> j) & 1) == 1)
{
oneCount++;
}
else
{
zeroCount++;
}
}
}
// Over the long run there should be about as many 1s as 0s.
// This isn't a guarantee, just a statistical observation.
// Allow a 7% tolerance band before considering it to have gotten out of hand.
double bitDifference = Math.Abs(zeroCount - oneCount) / (double)(zeroCount + oneCount);
const double AllowedTolerance = 0.07;
if (bitDifference > AllowedTolerance)
{
throw new InvalidOperationException("Expected bitDifference < " + AllowedTolerance + ", got " + bitDifference + ".");
}
}
}
}
| |
using System;
using System.Diagnostics;
using System.Text;
namespace System.Data.SQLite
{
using sqlite3_callback = Sqlite3.dxCallback;
using sqlite3_stmt = Sqlite3.Vdbe;
internal partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** Main file for the SQLite library. The routines in this file
** implement the programmer interface to the library. Routines in
** other files are for internal use by SQLite and should not be
** accessed by users of the library.
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2010-08-23 18:52:01 42537b60566f288167f1b5864a5435986838e3a3
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** Execute SQL code. Return one of the SQLITE_ success/failure
** codes. Also write an error message into memory obtained from
** malloc() and make pzErrMsg point to that message.
**
** If the SQL is a query, then for each row in the query result
** the xCallback() function is called. pArg becomes the first
** argument to xCallback(). If xCallback=NULL then no callback
** is invoked, even for queries.
*/
//C# Alias
static public int exec(sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ int NoCallback, int NoArgs, int NoErrors)
{
string Errors = "";
return sqlite3_exec(db, zSql, null, null, ref Errors);
}
static public int exec(sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ int NoErrors)
{
string Errors = "";
return sqlite3_exec(db, zSql, xCallback, pArg, ref Errors);
}
static public int exec(sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ sqlite3_callback xCallback, /* Invoke this callback routine */ object pArg, /* First argument to xCallback() */ ref string pzErrMsg /* Write error messages here */)
{
return sqlite3_exec(db, zSql, xCallback, pArg, ref pzErrMsg);
}
//OVERLOADS
static public int sqlite3_exec(
sqlite3 db, /* The database on which the SQL executes */
string zSql, /* The SQL to be executed */
int NoCallback, int NoArgs, int NoErrors
)
{
string Errors = "";
return sqlite3_exec(db, zSql, null, null, ref Errors);
}
static public int sqlite3_exec(
sqlite3 db, /* The database on which the SQL executes */
string zSql, /* The SQL to be executed */
sqlite3_callback xCallback, /* Invoke this callback routine */
object pArg, /* First argument to xCallback() */
int NoErrors
)
{
string Errors = "";
return sqlite3_exec(db, zSql, xCallback, pArg, ref Errors);
}
static public int sqlite3_exec(
sqlite3 db, /* The database on which the SQL executes */
string zSql, /* The SQL to be executed */
sqlite3_callback xCallback, /* Invoke this callback routine */
object pArg, /* First argument to xCallback() */
ref string pzErrMsg /* Write error messages here */
)
{
int rc = SQLITE_OK; /* Return code */
string zLeftover = ""; /* Tail of unprocessed SQL */
sqlite3_stmt pStmt = null; /* The current SQL statement */
string[] azCols = null; /* Names of result columns */
int nRetry = 0; /* Number of retry attempts */
int callbackIsInit; /* True if callback data is initialized */
if (!sqlite3SafetyCheckOk(db))
return SQLITE_MISUSE_BKPT();
if (zSql == null)
zSql = "";
sqlite3_mutex_enter(db.mutex);
sqlite3Error(db, SQLITE_OK, 0);
while ((rc == SQLITE_OK || (rc == SQLITE_SCHEMA && (++nRetry) < 2)) && zSql != "")
{
int nCol;
string[] azVals = null;
pStmt = null;
rc = sqlite3_prepare(db, zSql, -1, ref pStmt, ref zLeftover);
Debug.Assert(rc == SQLITE_OK || pStmt == null);
if (rc != SQLITE_OK)
{
continue;
}
if (pStmt == null)
{
/* this happens for a comment or white-space */
zSql = zLeftover;
continue;
}
callbackIsInit = 0;
nCol = sqlite3_column_count(pStmt);
while (true)
{
int i;
rc = sqlite3_step(pStmt);
/* Invoke the callback function if required */
if (xCallback != null &&
(SQLITE_ROW == rc ||
(SQLITE_DONE == rc && callbackIsInit == 0 && (db.flags & SQLITE_NullCallback) != 0)))
{
if (0 == callbackIsInit)
{
azCols = new string[nCol];//sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
//if ( azCols == null )
//{
// goto exec_out;
//}
for (i = 0; i < nCol; i++)
{
azCols[i] = sqlite3_column_name(pStmt, i);
/* sqlite3VdbeSetColName() installs column names as UTF8
** strings so there is no way for sqlite3_column_name() to fail. */
Debug.Assert(azCols[i] != null);
}
callbackIsInit = 1;
}
if (rc == SQLITE_ROW)
{
azVals = new string[nCol];// azCols[nCol];
for (i = 0; i < nCol; i++)
{
azVals[i] = sqlite3_column_text(pStmt, i);
if (azVals[i] == null && sqlite3_column_type(pStmt, i) != SQLITE_NULL)
{
//db.mallocFailed = 1;
//goto exec_out;
}
}
}
if (xCallback(pArg, nCol, azVals, azCols) != 0)
{
rc = SQLITE_ABORT;
sqlite3VdbeFinalize(ref pStmt);
pStmt = null;
sqlite3Error(db, SQLITE_ABORT, 0);
goto exec_out;
}
}
if (rc != SQLITE_ROW)
{
rc = sqlite3VdbeFinalize(ref pStmt);
pStmt = null;
if (rc != SQLITE_SCHEMA)
{
nRetry = 0;
if ((zSql = zLeftover) != "")
{
int zindex = 0;
while (zindex < zSql.Length && sqlite3Isspace(zSql[zindex]))
zindex++;
if (zindex != 0)
zSql = zindex < zSql.Length ? zSql.Substring(zindex) : "";
}
}
break;
}
}
sqlite3DbFree(db, ref azCols);
azCols = null;
}
exec_out:
if (pStmt != null)
sqlite3VdbeFinalize(ref pStmt);
sqlite3DbFree(db, ref azCols);
rc = sqlite3ApiExit(db, rc);
if (rc != SQLITE_OK && ALWAYS(rc == sqlite3_errcode(db)) && pzErrMsg != null)
{
//int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
//pzErrMsg = sqlite3Malloc(nErrMsg);
//if (pzErrMsg)
//{
// memcpy(pzErrMsg, sqlite3_errmsg(db), nErrMsg);
//}else{
//rc = SQLITE_NOMEM;
//sqlite3Error(db, SQLITE_NOMEM, 0);
//}
pzErrMsg = sqlite3_errmsg(db);
}
else if (pzErrMsg != "")
{
pzErrMsg = "";
}
Debug.Assert((rc & db.errMask) == rc);
sqlite3_mutex_leave(db.mutex);
return rc;
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
namespace Microsoft.Practices.Prism
{
/// <summary>
/// A dictionary of lists.
/// </summary>
/// <typeparam name="TKey">The key to use for lists.</typeparam>
/// <typeparam name="TValue">The type of the value held by lists.</typeparam>
public sealed class ListDictionary<TKey, TValue> : IDictionary<TKey, IList<TValue>>
{
Dictionary<TKey, IList<TValue>> innerValues = new Dictionary<TKey, IList<TValue>>();
#region Public Methods
/// <summary>
/// If a list does not already exist, it will be created automatically.
/// </summary>
/// <param name="key">The key of the list that will hold the value.</param>
public void Add(TKey key)
{
if (key == null)
throw new ArgumentNullException("key");
CreateNewList(key);
}
/// <summary>
/// Adds a value to a list with the given key. If a list does not already exist,
/// it will be created automatically.
/// </summary>
/// <param name="key">The key of the list that will hold the value.</param>
/// <param name="value">The value to add to the list under the given key.</param>
public void Add(TKey key, TValue value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
if (innerValues.ContainsKey(key))
{
innerValues[key].Add(value);
}
else
{
List<TValue> values = CreateNewList(key);
values.Add(value);
}
}
private List<TValue> CreateNewList(TKey key)
{
List<TValue> values = new List<TValue>();
innerValues.Add(key, values);
return values;
}
/// <summary>
/// Removes all entries in the dictionary.
/// </summary>
public void Clear()
{
innerValues.Clear();
}
/// <summary>
/// Determines whether the dictionary contains the specified value.
/// </summary>
/// <param name="value">The value to locate.</param>
/// <returns>true if the dictionary contains the value in any list; otherwise, false.</returns>
public bool ContainsValue(TValue value)
{
foreach (KeyValuePair<TKey, IList<TValue>> pair in innerValues)
{
if (pair.Value.Contains(value))
{
return true;
}
}
return false;
}
/// <summary>
/// Determines whether the dictionary contains the given key.
/// </summary>
/// <param name="key">The key to locate.</param>
/// <returns>true if the dictionary contains the given key; otherwise, false.</returns>
public bool ContainsKey(TKey key)
{
if (key == null)
throw new ArgumentNullException("key");
return innerValues.ContainsKey(key);
}
/// <summary>
/// Retrieves the all the elements from the list which have a key that matches the condition
/// defined by the specified predicate.
/// </summary>
/// <param name="keyFilter">The filter with the condition to use to filter lists by their key.</param>
/// <returns>The elements that have a key that matches the condition defined by the specified predicate.</returns>
public IEnumerable<TValue> FindAllValuesByKey(Predicate<TKey> keyFilter)
{
foreach (KeyValuePair<TKey, IList<TValue>> pair in this)
{
if (keyFilter(pair.Key))
{
foreach (TValue value in pair.Value)
{
yield return value;
}
}
}
}
/// <summary>
/// Retrieves all the elements that match the condition defined by the specified predicate.
/// </summary>
/// <param name="valueFilter">The filter with the condition to use to filter values.</param>
/// <returns>The elements that match the condition defined by the specified predicate.</returns>
public IEnumerable<TValue> FindAllValues(Predicate<TValue> valueFilter)
{
foreach (KeyValuePair<TKey, IList<TValue>> pair in this)
{
foreach (TValue value in pair.Value)
{
if (valueFilter(value))
{
yield return value;
}
}
}
}
/// <summary>
/// Removes a list by key.
/// </summary>
/// <param name="key">The key of the list to remove.</param>
/// <returns><see langword="true" /> if the element was removed.</returns>
public bool Remove(TKey key)
{
if (key == null)
throw new ArgumentNullException("key");
return innerValues.Remove(key);
}
/// <summary>
/// Removes a value from the list with the given key.
/// </summary>
/// <param name="key">The key of the list where the value exists.</param>
/// <param name="value">The value to remove.</param>
public void Remove(TKey key, TValue value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
if (innerValues.ContainsKey(key))
{
List<TValue> innerList = (List<TValue>)innerValues[key];
innerList.RemoveAll(delegate(TValue item)
{
return value.Equals(item);
});
}
}
/// <summary>
/// Removes a value from all lists where it may be found.
/// </summary>
/// <param name="value">The value to remove.</param>
public void Remove(TValue value)
{
foreach (KeyValuePair<TKey, IList<TValue>> pair in innerValues)
{
Remove(pair.Key, value);
}
}
#endregion
#region Properties
/// <summary>
/// Gets a shallow copy of all values in all lists.
/// </summary>
/// <value>List of values.</value>
public IList<TValue> Values
{
get
{
List<TValue> values = new List<TValue>();
foreach (IEnumerable<TValue> list in innerValues.Values)
{
values.AddRange(list);
}
return values;
}
}
/// <summary>
/// Gets the list of keys in the dictionary.
/// </summary>
/// <value>Collection of keys.</value>
public ICollection<TKey> Keys
{
get { return innerValues.Keys; }
}
/// <summary>
/// Gets or sets the list associated with the given key. The
/// access always succeeds, eventually returning an empty list.
/// </summary>
/// <param name="key">The key of the list to access.</param>
/// <returns>The list associated with the key.</returns>
public IList<TValue> this[TKey key]
{
get
{
if (innerValues.ContainsKey(key) == false)
{
innerValues.Add(key, new List<TValue>());
}
return innerValues[key];
}
set { innerValues[key] = value; }
}
/// <summary>
/// Gets the number of lists in the dictionary.
/// </summary>
/// <value>Value indicating the values count.</value>
public int Count
{
get { return innerValues.Count; }
}
#endregion
#region IDictionary<TKey,List<TValue>> Members
/// <summary>
/// See <see cref="IDictionary{TKey,TValue}.Add"/> for more information.
/// </summary>
void IDictionary<TKey, IList<TValue>>.Add(TKey key, IList<TValue> value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
innerValues.Add(key, value);
}
/// <summary>
/// See <see cref="IDictionary{TKey,TValue}.TryGetValue"/> for more information.
/// </summary>
bool IDictionary<TKey, IList<TValue>>.TryGetValue(TKey key, out IList<TValue> value)
{
value = this[key];
return true;
}
/// <summary>
/// See <see cref="IDictionary{TKey,TValue}.Values"/> for more information.
/// </summary>
ICollection<IList<TValue>> IDictionary<TKey, IList<TValue>>.Values
{
get { return innerValues.Values; }
}
#endregion
#region ICollection<KeyValuePair<TKey,List<TValue>>> Members
/// <summary>
/// See <see cref="ICollection{TValue}.Add"/> for more information.
/// </summary>
void ICollection<KeyValuePair<TKey, IList<TValue>>>.Add(KeyValuePair<TKey, IList<TValue>> item)
{
((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Add(item);
}
/// <summary>
/// See <see cref="ICollection{TValue}.Contains"/> for more information.
/// </summary>
bool ICollection<KeyValuePair<TKey, IList<TValue>>>.Contains(KeyValuePair<TKey, IList<TValue>> item)
{
return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Contains(item);
}
/// <summary>
/// See <see cref="ICollection{TValue}.CopyTo"/> for more information.
/// </summary>
void ICollection<KeyValuePair<TKey, IList<TValue>>>.CopyTo(KeyValuePair<TKey, IList<TValue>>[] array, int arrayIndex)
{
((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).CopyTo(array, arrayIndex);
}
/// <summary>
/// See <see cref="ICollection{TValue}.IsReadOnly"/> for more information.
/// </summary>
bool ICollection<KeyValuePair<TKey, IList<TValue>>>.IsReadOnly
{
get { return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).IsReadOnly; }
}
/// <summary>
/// See <see cref="ICollection{TValue}.Remove"/> for more information.
/// </summary>
bool ICollection<KeyValuePair<TKey, IList<TValue>>>.Remove(KeyValuePair<TKey, IList<TValue>> item)
{
return ((ICollection<KeyValuePair<TKey, IList<TValue>>>)innerValues).Remove(item);
}
#endregion
#region IEnumerable<KeyValuePair<TKey,List<TValue>>> Members
/// <summary>
/// See <see cref="IEnumerable{TValue}.GetEnumerator"/> for more information.
/// </summary>
IEnumerator<KeyValuePair<TKey, IList<TValue>>> IEnumerable<KeyValuePair<TKey, IList<TValue>>>.GetEnumerator()
{
return innerValues.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// See <see cref="System.Collections.IEnumerable.GetEnumerator"/> for more information.
/// </summary>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return innerValues.GetEnumerator();
}
#endregion
}
}
| |
using System;
using System.Globalization;
using System.Linq;
using NUnit.Framework;
using SIL.Archiving.Generic;
using SIL.Archiving.IMDI;
using SIL.Archiving.IMDI.Lists;
using SIL.Archiving.IMDI.Schema;
namespace SIL.Archiving.Tests
{
[TestFixture]
[Category("Archiving")]
class IMDI30Tests
{
[Test]
public void SessionDate_DateTime_ValidStringProduced()
{
var session = new Session();
var dateIn = DateTime.Today;
session.SetDate(dateIn);
var dateOut = session.Date;
Assert.AreEqual(dateIn.ToString("yyyy-MM-dd"), dateOut, "The date returned was not what was expected.");
}
[Test]
public void SessionDate_YearOnly_ValidStringProduced()
{
var session = new Session();
const int dateIn = 1964;
session.SetDate(dateIn);
var dateOut = session.Date;
Assert.AreEqual(dateIn.ToString(CultureInfo.InvariantCulture), dateOut, "The date returned was not what was expected.");
}
[Test]
public void SessionDate_DateRange_ValidStringProduced()
{
var session = new Session();
const string dateIn = "2013-11-20 to 2013-11-25";
session.SetDate(dateIn);
var dateOut = session.Date;
Assert.AreEqual(dateIn, dateOut, "The date returned was not what was expected.");
}
[Test]
public void ActorType_ArchivingActor_ValidActorType()
{
const string motherTongueIso3 = "spa";
const string primaryLanguageIso3 = "eng";
const string additionalLanguageIso3 = "fra";
var actrIn = new ArchivingActor
{
Code = "123",
Education = "8th grade",
Name = "John Smith",
Age = "50 +- 10",
Gender = "Male",
BirthDate = 1964,
Occupation = "Nerf Herder",
MotherTongueLanguage = new ArchivingLanguage(motherTongueIso3),
PrimaryLanguage = new ArchivingLanguage(primaryLanguageIso3)
};
// additional languages
actrIn.Iso3Languages.Add(new ArchivingLanguage(additionalLanguageIso3));
var actrOut = new ActorType(actrIn);
Assert.AreEqual(actrIn.Name, actrOut.FullName);
Assert.AreEqual(actrIn.Name, actrOut.Name[0]);
Assert.AreEqual(actrIn.Code, actrOut.Code);
Assert.AreEqual(actrIn.Gender, actrOut.Sex.Value);
Assert.AreEqual(actrIn.Occupation, actrOut.Keys.Key.Find(k => k.Name == "Occupation").Value);
Assert.AreEqual(actrIn.GetBirthDate(), actrOut.BirthDate);
Assert.AreEqual(actrIn.Age, actrOut.Age);
// language count
Assert.AreEqual(3, actrOut.Languages.Language.Count);
// mother tongue
string motherTongueCodeFound = null;
foreach (var lang in actrOut.Languages.Language)
{
if (lang.MotherTongue.Value == BooleanEnum.@true)
motherTongueCodeFound = lang.Id;
}
Assert.IsNotNull(motherTongueCodeFound, "Mother tongue not found.");
Assert.AreEqual(motherTongueIso3, motherTongueCodeFound.Substring(motherTongueCodeFound.Length - 3), "Wrong mother tongue returned.");
// primary language
string primaryLanguageCodeFound = null;
foreach (var lang in actrOut.Languages.Language)
{
if (lang.PrimaryLanguage.Value == BooleanEnum.@true)
primaryLanguageCodeFound = lang.Id;
}
Assert.IsNotNull(primaryLanguageCodeFound, "Primary language not found.");
Assert.AreEqual(primaryLanguageIso3, primaryLanguageCodeFound.Substring(primaryLanguageCodeFound.Length - 3), "Wrong primary language returned.");
// additional language
var additionalLanguageFound = false;
foreach (var lang in actrOut.Languages.Language)
{
if (lang.Id.EndsWith(additionalLanguageIso3))
additionalLanguageFound = true;
}
Assert.IsTrue(additionalLanguageFound, "The additional language was not found.");
}
[Test]
public void LocationType_ArchivingLocation_ValidLocationType()
{
var locIn = new ArchivingLocation
{
Continent = "Asia",
Country = "China",
Region = "Great Wall",
Address = "315 N Main St"
};
var locOut = locIn.ToIMDILocationType();
Assert.AreEqual("Asia", locOut.Continent.Value);
Assert.AreEqual("China", locOut.Country.Value);
Assert.AreEqual("Great Wall", locOut.Region[0]);
Assert.AreEqual("315 N Main St", locOut.Address);
}
[Test]
public void SetContinent_InvalidContinent_ReturnsUnspecified()
{
LocationType location = new LocationType();
location.SetContinent("Narnia");
Assert.AreEqual("Unspecified", location.Continent.Value);
}
[Test]
public void AddDescription_Add2ForSameLanguage_AddsOnlyTheFirst()
{
var desc1 = new LanguageString { Iso3LanguageId = "eng", Value = "First description"};
var desc2 = new LanguageString { Iso3LanguageId = "eng", Value = "Second description" };
var obj = new Corpus();
obj.Description.Add(desc1);
obj.Description.Add(desc2);
Assert.AreEqual(1, obj.Description.Count);
Assert.AreEqual("First description", obj.Description.First().Value);
}
[Test]
public void AddSubjectLanguge_AddDuplicate_DuplicateNotAdded()
{
IMDIPackage proj = new IMDIPackage(false, string.Empty);
proj.ContentIso3Languages.Add(new ArchivingLanguage("fra"));
proj.ContentIso3Languages.Add(new ArchivingLanguage("spa"));
proj.ContentIso3Languages.Add(new ArchivingLanguage("spa"));
proj.ContentIso3Languages.Add(new ArchivingLanguage("fra"));
Assert.AreEqual(2, proj.ContentIso3Languages.Count);
Assert.IsTrue(proj.ContentIso3Languages.Contains(new ArchivingLanguage("fra")));
Assert.IsTrue(proj.ContentIso3Languages.Contains(new ArchivingLanguage("spa")));
}
[Test]
public void AddDocumentLanguge_AddDuplicate_DuplicateNotAdded()
{
IMDIPackage proj = new IMDIPackage(false, string.Empty);
proj.MetadataIso3Languages.Add(new ArchivingLanguage("fra"));
proj.MetadataIso3Languages.Add(new ArchivingLanguage("spa"));
proj.MetadataIso3Languages.Add(new ArchivingLanguage("spa"));
proj.MetadataIso3Languages.Add(new ArchivingLanguage("fra"));
Assert.AreEqual(2, proj.MetadataIso3Languages.Count);
Assert.IsTrue(proj.MetadataIso3Languages.Contains(new ArchivingLanguage("fra")));
Assert.IsTrue(proj.MetadataIso3Languages.Contains(new ArchivingLanguage("spa")));
}
[Test]
public void SessionAddActor_Anonymized_ReturnsAnonymizedNames()
{
ArchivingActor actor = new ArchivingActor
{
Name = "Actor Name",
FullName = "Actor Full Name",
Anonymize = true
};
Session session = new Session();
session.AddActor(actor);
var imdiActor = session.MDGroup.Actors.Actor[0];
Assert.AreNotEqual("Actor Name", imdiActor.Name[0]);
Assert.AreNotEqual("Actor Full Name", imdiActor.FullName);
}
[Test]
public void SessionAddActor_Anonymized_RemovesActorFiles()
{
ArchivingActor actor = new ArchivingActor
{
Name = "Actor Name",
FullName = "Actor Full Name",
Anonymize = true
};
actor.Files.Add(new ArchivingFile(System.Reflection.Assembly.GetExecutingAssembly().Location));
Session session = new Session();
session.AddActor(actor);
Assert.AreEqual(0, session.Resources.MediaFile.Count);
Assert.AreEqual(0, session.Resources.WrittenResource.Count);
}
[Test]
public void FindByISO3Code_InvalidIso3Code_MustBeInList_Throws()
{
Assert.Throws<ArgumentException>(() => LanguageList.FindByISO3Code("xyz", true));
}
[Test]
public void FindByISO3Code_InvalidIso3Code_NotMustBeInList_DoesNotThrow()
{
Assert.DoesNotThrow(() => LanguageList.FindByISO3Code("xyz", false));
}
[Test]
[Category("SkipOnTeamCity")]
public void GetList_RemoveNone_ReturnUnknownAndUnspecified()
{
var countries = ListConstructor.GetList(ListType.Countries, true, null, ListConstructor.RemoveUnknown.RemoveNone);
Assert.NotNull(countries.FindByText("Unknown"));
Assert.NotNull(countries.FindByText("Unspecified"));
Assert.NotNull(countries.FindByText("Undefined"));
}
[Test]
[Category("SkipOnTeamCity")]
public void GetList_LeaveUnknown_ReturnUnspecified()
{
var countries = ListConstructor.GetList(ListType.Countries, true, null, ListConstructor.RemoveUnknown.LeaveUnknown);
Assert.NotNull(countries.FindByText("Unknown"));
Assert.IsNull(countries.FindByText("Unspecified"));
Assert.IsNull(countries.FindByText("Undefined"));
}
[Test]
[Category("SkipOnTeamCity")]
public void GetList_RemoveAll_ReturnNone()
{
var countries = ListConstructor.GetList(ListType.Countries, true, null, ListConstructor.RemoveUnknown.RemoveAll);
Assert.IsNull(countries.FindByText("Unknown"));
Assert.IsNull(countries.FindByText("Unspecified"));
Assert.IsNull(countries.FindByText("Undefined"));
}
[Test]
[Category("SkipOnTeamCity")]
public void GetClosedList_RemoveNone_ReturnUnknownAndUnspecified()
{
var countries = ListConstructor.GetClosedList(ListType.Countries, true, ListConstructor.RemoveUnknown.RemoveNone);
Assert.NotNull(countries.FindByText("Unknown"));
Assert.NotNull(countries.FindByText("Unspecified"));
Assert.NotNull(countries.FindByText("Undefined"));
}
[Test]
[Category("SkipOnTeamCity")]
public void GetClosedList_LeaveUnknown_ReturnUnspecified()
{
var countries = ListConstructor.GetClosedList(ListType.Countries, true, ListConstructor.RemoveUnknown.LeaveUnknown);
Assert.NotNull(countries.FindByText("Unknown"));
Assert.IsNull(countries.FindByText("Unspecified"));
Assert.IsNull(countries.FindByText("Undefined"));
}
[Test]
[Category("SkipOnTeamCity")]
public void GetClosedList_RemoveAll_ReturnNone()
{
var countries = ListConstructor.GetClosedList(ListType.Countries, true, ListConstructor.RemoveUnknown.RemoveAll);
Assert.IsNull(countries.FindByText("Unknown"));
Assert.IsNull(countries.FindByText("Unspecified"));
Assert.IsNull(countries.FindByText("Undefined"));
}
[Test]
public void SetSessionGenre_NullValue_Null()
{
var session = new Session();
session.Genre = null;
Assert.AreEqual(null, session.Genre);
}
[Test]
public void SetSessionGenre_ContainsAngleBrackets_LatinOnly()
{
var session = new Session();
session.Genre = "<Unknown>";
Assert.AreEqual("Unknown", session.Genre);
}
[Test]
public void SessionAddKeyValuePair_TwoKeywords_numberUp2()
{
var session = new Session();
var number = session.MDGroup.Content.Keys.Key.Count;
session.AddContentKeyValuePair("keyword", "holiday");
session.AddContentKeyValuePair("keyword", "emotion");
Assert.AreEqual(number + 2, session.MDGroup.Content.Keys.Key.Count);
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Shared.TestHooks;
using Microsoft.CodeAnalysis.Snippets;
using Microsoft.CSharp.RuntimeBinder;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.Snippets
{
/// <summary>
/// This service is created on the UI thread during package initialization, but it must not
/// block the initialization process. If the expansion manager is an IExpansionManager,
/// then we can use the asynchronous population mechanism it provides. Otherwise, getting
/// snippet information from the <see cref="IVsExpansionManager"/> must be done synchronously
/// through on the UI thread, which we do after package initialization at a lower priority.
/// </summary>
/// <remarks>
/// IExpansionManager was introduced in Visual Studio 2015 Update 1, but
/// will be enabled by default for the first time in Visual Studio 2015 Update 2. However,
/// the platform still supports returning the <see cref="IVsExpansionManager"/> if a major
/// problem in the IExpansionManager is discovered, so we must continue
/// supporting the fallback.
/// </remarks>
internal abstract class AbstractSnippetInfoService : ForegroundThreadAffinitizedObject, ISnippetInfoService, IVsExpansionEvents
{
private readonly Guid _languageGuidForSnippets;
private readonly IVsExpansionManager _expansionManager;
/// <summary>
/// Initialize these to empty values. When returning from <see cref="GetSnippetsIfAvailable "/>
/// and <see cref="SnippetShortcutExists_NonBlocking"/>, we return the current set of known
/// snippets rather than waiting for initial results.
/// </summary>
protected ImmutableArray<SnippetInfo> snippets = ImmutableArray.Create<SnippetInfo>();
protected IImmutableSet<string> snippetShortcuts = ImmutableHashSet.Create<string>();
// Guard the snippets and snippetShortcut fields so that returned result sets are always
// complete.
protected object cacheGuard = new object();
private readonly AggregateAsynchronousOperationListener _waiter;
public AbstractSnippetInfoService(
Shell.SVsServiceProvider serviceProvider,
Guid languageGuidForSnippets,
IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> asyncListeners)
{
AssertIsForeground();
if (serviceProvider != null)
{
var textManager = (IVsTextManager2)serviceProvider.GetService(typeof(SVsTextManager));
if (textManager.GetExpansionManager(out _expansionManager) == VSConstants.S_OK)
{
ComEventSink.Advise<IVsExpansionEvents>(_expansionManager, this);
_waiter = new AggregateAsynchronousOperationListener(asyncListeners, FeatureAttribute.Snippets);
_languageGuidForSnippets = languageGuidForSnippets;
PopulateSnippetCaches();
}
}
}
public int OnAfterSnippetsUpdate()
{
AssertIsForeground();
if (_expansionManager != null)
{
PopulateSnippetCaches();
}
return VSConstants.S_OK;
}
public int OnAfterSnippetsKeyBindingChange([ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")]uint dwCmdGuid, [ComAliasName("Microsoft.VisualStudio.OLE.Interop.DWORD")]uint dwCmdId, [ComAliasName("Microsoft.VisualStudio.OLE.Interop.BOOL")]int fBound)
{
return VSConstants.S_OK;
}
public IEnumerable<SnippetInfo> GetSnippetsIfAvailable()
{
// Immediately return the known set of snippets, even if we're still in the process
// of calculating a more up-to-date list.
lock (cacheGuard)
{
return snippets;
}
}
public bool SnippetShortcutExists_NonBlocking(string shortcut)
{
if (shortcut == null)
{
return false;
}
// Check against the known set of snippets, even if we're still in the process of
// calculating a more up-to-date list.
lock (cacheGuard)
{
return snippetShortcuts.Contains(shortcut);
}
}
public virtual bool ShouldFormatSnippet(SnippetInfo snippetInfo)
{
return false;
}
private void PopulateSnippetCaches()
{
Debug.Assert(_expansionManager != null);
// Ideally we'd fork execution here based on whether the expansion manager is an
// IExpansionManager or not. Unfortunately, we cannot mention that type by name until
// the Roslyn build machines are upgraded to Visual Studio 2015 Update 1. We therefore
// need to try using IExpansionManager dynamically, from a background thread. If that
// fails, then we come back to the UI thread for using IVsExpansionManager instead.
var token = _waiter.BeginAsyncOperation(GetType().Name + ".Start");
Task.Factory.StartNew(async () => await PopulateSnippetCacheOnBackgroundWithForegroundFallback().ConfigureAwait(false),
CancellationToken.None,
TaskCreationOptions.None,
TaskScheduler.Default).CompletesAsyncOperation(token);
}
private async Task PopulateSnippetCacheOnBackgroundWithForegroundFallback()
{
AssertIsBackground();
try
{
IVsExpansionEnumeration expansionEnumerator = await ((dynamic)_expansionManager).EnumerateExpansionsAsync(
_languageGuidForSnippets,
0, // shortCutOnly
Array.Empty<string>(), // types
0, // countTypes
1, // includeNULLTypes
1 // includeDulicates: Allows snippets with the same title but different shortcuts
).ConfigureAwait(false);
// The rest of the process requires being on the UI thread, see the explanation on
// PopulateSnippetCacheFromExpansionEnumeration for details
await Task.Factory.StartNew(() => PopulateSnippetCacheFromExpansionEnumeration(expansionEnumerator),
CancellationToken.None,
TaskCreationOptions.None,
ForegroundTaskScheduler).ConfigureAwait(false);
}
catch (RuntimeBinderException)
{
// The IExpansionManager.EnumerateExpansionsAsync could not be found. Use
// IVsExpansionManager.EnumerateExpansions instead, but from the UI thread.
await Task.Factory.StartNew(() => PopulateSnippetCacheOnForeground(),
CancellationToken.None,
TaskCreationOptions.None,
ForegroundTaskScheduler).ConfigureAwait(false);
}
}
/// <remarks>
/// Changes to the <see cref="IVsExpansionManager.EnumerateExpansions"/> invocation
/// should also be made to the IExpansionManager.EnumerateExpansionsAsync
/// invocation in <see cref="PopulateSnippetCacheOnBackgroundWithForegroundFallback"/>.
/// </remarks>
private void PopulateSnippetCacheOnForeground()
{
AssertIsForeground();
IVsExpansionEnumeration expansionEnumerator = null;
_expansionManager.EnumerateExpansions(
_languageGuidForSnippets,
fShortCutOnly: 0,
bstrTypes: null,
iCountTypes: 0,
fIncludeNULLType: 1,
fIncludeDuplicates: 1, // Allows snippets with the same title but different shortcuts
pEnum: out expansionEnumerator);
PopulateSnippetCacheFromExpansionEnumeration(expansionEnumerator);
}
/// <remarks>
/// This method must be called on the UI thread because it eventually calls into
/// IVsExpansionEnumeration.Next, which must be called on the UI thread due to an issue
/// with how the call is marshalled.
///
/// The second parameter for IVsExpansionEnumeration.Next is defined like this:
/// [ComAliasName("Microsoft.VisualStudio.TextManager.Interop.VsExpansion")] IntPtr[] rgelt
///
/// We pass a pointer for rgelt that we expect to be populated as the result. This
/// eventually calls into the native CExpansionEnumeratorShim::Next method, which has the
/// same contract of expecting a non-null rgelt that it can drop expansion data into. When
/// we call from the UI thread, this transition from managed code to the
/// CExpansionEnumeratorShim` goes smoothly and everything works.
///
/// When we call from a background thread, the COM marshaller has to move execution to the
/// UI thread, and as part of this process it uses the interface as defined in the idl to
/// set up the appropriate arguments to pass. The same parameter from the idl is defined as
/// [out, size_is(celt), length_is(*pceltFetched)] VsExpansion **rgelt
///
/// Because rgelt is specified as an `out` parameter, the marshaller is discarding the
/// pointer we passed and substituting the null reference. This then causes a null
/// reference exception in the shim. Calling from the UI thread avoids this marshaller.
/// </remarks>
void PopulateSnippetCacheFromExpansionEnumeration(IVsExpansionEnumeration expansionEnumerator)
{
AssertIsForeground();
var updatedSnippets = ExtractSnippetInfo(expansionEnumerator);
var updatedSnippetShortcuts = GetShortcutsHashFromSnippets(updatedSnippets);
lock (cacheGuard)
{
snippets = updatedSnippets;
snippetShortcuts = updatedSnippetShortcuts;
}
}
private ImmutableArray<SnippetInfo> ExtractSnippetInfo(IVsExpansionEnumeration expansionEnumerator)
{
AssertIsForeground();
var snippetListBuilder = ImmutableArray.CreateBuilder<SnippetInfo>();
uint count = 0;
uint fetched = 0;
VsExpansion snippetInfo = new VsExpansion();
IntPtr[] pSnippetInfo = new IntPtr[1];
try
{
// Allocate enough memory for one VSExpansion structure. This memory is filled in by the Next method.
pSnippetInfo[0] = Marshal.AllocCoTaskMem(Marshal.SizeOf(snippetInfo));
expansionEnumerator.GetCount(out count);
for (uint i = 0; i < count; i++)
{
expansionEnumerator.Next(1, pSnippetInfo, out fetched);
if (fetched > 0)
{
// Convert the returned blob of data into a structure that can be read in managed code.
snippetInfo = ConvertToVsExpansionAndFree(pSnippetInfo[0]);
if (!string.IsNullOrEmpty(snippetInfo.shortcut))
{
snippetListBuilder.Add(new SnippetInfo(snippetInfo.shortcut, snippetInfo.title, snippetInfo.description, snippetInfo.path));
}
}
}
}
finally
{
Marshal.FreeCoTaskMem(pSnippetInfo[0]);
}
return snippetListBuilder.ToImmutable();
}
protected static IImmutableSet<string> GetShortcutsHashFromSnippets(ImmutableArray<SnippetInfo> updatedSnippets)
{
return new HashSet<string>(updatedSnippets.Select(s => s.Shortcut), StringComparer.OrdinalIgnoreCase)
.ToImmutableHashSet(StringComparer.OrdinalIgnoreCase);
}
private static VsExpansion ConvertToVsExpansionAndFree(IntPtr expansionPtr)
{
var buffer = (VsExpansionWithIntPtrs)Marshal.PtrToStructure(expansionPtr, typeof(VsExpansionWithIntPtrs));
var expansion = new VsExpansion();
ConvertToStringAndFree(ref buffer.DescriptionPtr, ref expansion.description);
ConvertToStringAndFree(ref buffer.PathPtr, ref expansion.path);
ConvertToStringAndFree(ref buffer.ShortcutPtr, ref expansion.shortcut);
ConvertToStringAndFree(ref buffer.TitlePtr, ref expansion.title);
return expansion;
}
private static void ConvertToStringAndFree(ref IntPtr ptr, ref string str)
{
if (ptr != IntPtr.Zero)
{
str = Marshal.PtrToStringBSTR(ptr);
Marshal.FreeBSTR(ptr);
ptr = IntPtr.Zero;
}
}
/// <summary>
/// This structure is used to facilitate the interop calls with IVsExpansionEnumeration.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
private struct VsExpansionWithIntPtrs
{
public IntPtr PathPtr;
public IntPtr TitlePtr;
public IntPtr ShortcutPtr;
public IntPtr DescriptionPtr;
}
}
}
| |
// Copyright 2015 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Apis.Http;
using Google.Apis.Upload;
using Google.Cloud.ClientTesting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
using Object = Google.Apis.Storage.v1.Data.Object;
namespace Google.Cloud.Storage.V1.IntegrationTests
{
using static TestHelpers;
[Collection(nameof(StorageFixture))]
public class UploadObjectTest
{
private readonly StorageFixture _fixture;
public UploadObjectTest(StorageFixture fixture)
{
_fixture = fixture;
}
[Fact]
public void SimpleUpload()
{
var name = IdGenerator.FromGuid();
var contentType = "application/octet-stream";
var source = GenerateData(100);
var result = _fixture.Client.UploadObject(_fixture.MultiVersionBucket, name, contentType, source);
Assert.Equal(_fixture.MultiVersionBucket, result.Bucket);
Assert.Equal(name, result.Name);
Assert.Equal(contentType, result.ContentType);
ValidateData(_fixture.MultiVersionBucket, name, source);
}
[Fact]
public void CorsUpload()
{
var name = IdGenerator.FromGuid();
var contentType = "application/octet-stream";
var source = GenerateData(100);
var options = new UploadObjectOptions { Origin = "http://nodatime.org" };
var result = _fixture.Client.UploadObject(_fixture.MultiVersionBucket, name, contentType, source, options);
Assert.Equal(_fixture.MultiVersionBucket, result.Bucket);
Assert.Equal(name, result.Name);
Assert.Equal(contentType, result.ContentType);
ValidateData(_fixture.MultiVersionBucket, name, source);
}
[Fact]
public void UploadWithObject()
{
var destination = new Object
{
Bucket = _fixture.MultiVersionBucket,
Name = IdGenerator.FromGuid(),
ContentType = "test/type",
ContentDisposition = "attachment",
Metadata = new Dictionary<string, string> { { "x", "y" } }
};
var source = GenerateData(100);
var result = _fixture.Client.UploadObject(destination, source);
Assert.NotSame(destination, result);
Assert.Equal(destination.Name, result.Name);
Assert.Equal(destination.Bucket, result.Bucket);
Assert.Equal(destination.ContentType, result.ContentType);
Assert.Equal(destination.ContentDisposition, result.ContentDisposition);
Assert.Equal(destination.Metadata, result.Metadata);
ValidateData(_fixture.MultiVersionBucket, destination.Name, source);
}
[Fact]
public async Task UploadAsyncWithProgress()
{
var chunks = 2;
var name = IdGenerator.FromGuid();
var contentType = "application/octet-stream";
var source = GenerateData(UploadObjectOptions.MinimumChunkSize * chunks);
int progressCount = 0;
var progress = new Progress<IUploadProgress>(p => progressCount++);
var result = await _fixture.Client.UploadObjectAsync(_fixture.MultiVersionBucket, name, contentType, source,
new UploadObjectOptions { ChunkSize = UploadObjectOptions.MinimumChunkSize },
CancellationToken.None, progress);
Assert.Equal(chunks + 1, progressCount); // Should start with a 0 progress
Assert.Equal(name, result.Name); // Assume the rest of the properties are okay...
ValidateData(_fixture.MultiVersionBucket, name, source);
}
[Fact]
public void ReplaceObject()
{
var client = _fixture.Client;
var bucket = _fixture.MultiVersionBucket;
var name = IdGenerator.FromGuid();
var contentType = "application/octet-stream";
var source1 = GenerateData(100);
var firstVersion = client.UploadObject(bucket, name, contentType, source1);
ValidateData(_fixture.MultiVersionBucket, name, source1);
var source2 = GenerateData(50);
firstVersion.ContentType = "application/x-replaced";
// Clear hash and cache information, as we're changing the data.
firstVersion.Crc32c = null;
firstVersion.ETag = null;
firstVersion.Md5Hash = null;
var secondVersion = client.UploadObject(firstVersion, source2);
ValidateData(_fixture.MultiVersionBucket, name, source2);
Assert.NotEqual(firstVersion.Generation, secondVersion.Generation);
Assert.Equal(firstVersion.ContentType, secondVersion.ContentType); // The modified content type should stick
// When we ask for the first generation, we get the original data back.
var firstGenerationData = new MemoryStream();
client.DownloadObject(firstVersion, firstGenerationData, new DownloadObjectOptions { Generation = firstVersion.Generation }, null);
Assert.Equal(source1.ToArray(), firstGenerationData.ToArray());
}
[Fact]
public void UploadObjectIfGenerationMatch_NewFile()
{
var stream = GenerateData(50);
var name = IdGenerator.FromGuid();
var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.UploadObject(
_fixture.MultiVersionBucket, name, "", stream,
new UploadObjectOptions { IfGenerationMatch = 100 }, null));
}
[Fact]
public void UploadObjectIfGenerationMatch_Matching()
{
var existing = GetExistingObject();
var stream = GenerateData(50);
_fixture.Client.UploadObject(existing, stream,
new UploadObjectOptions { IfGenerationMatch = existing.Generation }, null);
}
[Fact]
public void UploadObjectIfGenerationMatch_NotMatching()
{
var existing = GetExistingObject();
var stream = GenerateData(50);
var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.UploadObject(existing, stream,
new UploadObjectOptions { IfGenerationMatch = existing.Generation + 1 }, null));
Assert.Equal(HttpStatusCode.PreconditionFailed, exception.HttpStatusCode);
}
[Fact]
public void UploadObjectIfGenerationNotMatch_Matching()
{
var existing = GetExistingObject();
var stream = GenerateData(50);
var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.UploadObject(existing, stream,
new UploadObjectOptions { IfGenerationNotMatch = existing.Generation }, null));
Assert.Equal(HttpStatusCode.NotModified, exception.HttpStatusCode);
}
[Fact]
public void UploadObjectIfGenerationNotMatch_NotMatching()
{
var existing = GetExistingObject();
var stream = GenerateData(50);
_fixture.Client.UploadObject(existing, stream,
new UploadObjectOptions { IfGenerationNotMatch = existing.Generation + 1 }, null);
}
[Fact]
public void UploadObject_IfGenerationMatchAndNotMatch()
{
Assert.Throws<ArgumentException>(() => _fixture.Client.UploadObject(_fixture.MultiVersionBucket, IdGenerator.FromGuid(), "", new MemoryStream(),
new UploadObjectOptions { IfGenerationMatch = 1, IfGenerationNotMatch = 2 },
null));
}
[Fact]
public void UploadObjectIfMetagenerationMatch_Matching()
{
var existing = GetExistingObject();
var stream = GenerateData(50);
_fixture.Client.UploadObject(existing, stream,
new UploadObjectOptions { IfMetagenerationMatch = existing.Metageneration }, null);
}
[Fact]
public void UploadObjectIfMetagenerationMatch_NotMatching()
{
var existing = GetExistingObject();
var stream = GenerateData(50);
var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.UploadObject(existing, stream,
new UploadObjectOptions { IfMetagenerationMatch = existing.Metageneration + 1 }, null));
Assert.Equal(HttpStatusCode.PreconditionFailed, exception.HttpStatusCode);
}
[Fact]
public void UploadObjectIfMetagenerationNotMatch_Matching()
{
var existing = GetExistingObject();
var stream = GenerateData(50);
var exception = Assert.Throws<GoogleApiException>(() => _fixture.Client.UploadObject(existing, stream,
new UploadObjectOptions { IfMetagenerationNotMatch = existing.Metageneration }, null));
Assert.Equal(HttpStatusCode.NotModified, exception.HttpStatusCode);
}
[Fact]
public void UploadObjectIfMetagenerationNotMatch_NotMatching()
{
var existing = GetExistingObject();
var stream = GenerateData(50);
_fixture.Client.UploadObject(existing, stream,
new UploadObjectOptions { IfMetagenerationNotMatch = existing.Metageneration + 1 }, null);
}
[Fact]
public void UploadObject_IfMetagenerationMatchAndNotMatch()
{
Assert.Throws<ArgumentException>(() => _fixture.Client.UploadObject(_fixture.MultiVersionBucket, IdGenerator.FromGuid(), "", new MemoryStream(),
new UploadObjectOptions { IfMetagenerationMatch = 1, IfMetagenerationNotMatch = 2 },
null));
}
[Fact]
public void UploadObject_NullContentType()
{
_fixture.Client.UploadObject(_fixture.MultiVersionBucket, IdGenerator.FromGuid(), null, new MemoryStream());
}
[Fact]
public void UploadObject_InvalidHash_None()
{
var client = StorageClient.Create();
var interceptor = new BreakUploadInterceptor();
client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor);
var stream = GenerateData(50);
var name = IdGenerator.FromGuid();
var bucket = _fixture.MultiVersionBucket;
var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.None };
// Upload succeeds despite the data being broken.
client.UploadObject(bucket, name, null, stream, options);
// The object should contain our "wrong" bytes.
ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes));
}
[Fact]
public void UploadObject_InvalidHash_ThrowOnly()
{
var client = StorageClient.Create();
var interceptor = new BreakUploadInterceptor();
client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor);
var stream = GenerateData(50);
var name = IdGenerator.FromGuid();
var bucket = _fixture.MultiVersionBucket;
var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.ThrowOnly };
Assert.Throws<UploadValidationException>(() => client.UploadObject(bucket, name, null, stream, options));
// We don't delete the object, so it's still present.
ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes));
}
[Fact]
public void UploadObject_InvalidHash_DeleteAndThrow()
{
var client = StorageClient.Create();
var interceptor = new BreakUploadInterceptor();
client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor);
var stream = GenerateData(50);
var name = IdGenerator.FromGuid();
var bucket = _fixture.MultiVersionBucket;
var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.DeleteAndThrow };
Assert.Throws<UploadValidationException>(() => client.UploadObject(bucket, name, null, stream, options));
var notFound = Assert.Throws<GoogleApiException>(() => _fixture.Client.GetObject(bucket, name));
Assert.Equal(HttpStatusCode.NotFound, notFound.HttpStatusCode);
}
[Fact]
public void UploadObject_InvalidHash_DeleteAndThrow_DeleteFails()
{
var client = StorageClient.Create();
var interceptor = new BreakUploadInterceptor();
client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor);
client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(new BreakDeleteInterceptor());
var stream = GenerateData(50);
var name = IdGenerator.FromGuid();
var bucket = _fixture.MultiVersionBucket;
var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.DeleteAndThrow };
var ex = Assert.Throws<UploadValidationException>(() => client.UploadObject(bucket, name, null, stream, options));
Assert.NotNull(ex.AdditionalFailures);
// The deletion failed, so the uploaded object still exists.
ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes));
}
[Fact]
public async Task UploadObjectAsync_InvalidHash_None()
{
var client = StorageClient.Create();
var interceptor = new BreakUploadInterceptor();
client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor);
var stream = GenerateData(50);
var name = IdGenerator.FromGuid();
var bucket = _fixture.MultiVersionBucket;
var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.None };
// Upload succeeds despite the data being broken.
await client.UploadObjectAsync(bucket, name, null, stream, options);
// The object should contain our "wrong" bytes.
ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes));
}
[Fact]
public async Task UploadObjectAsync_InvalidHash_ThrowOnly()
{
var client = StorageClient.Create();
var interceptor = new BreakUploadInterceptor();
client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor);
var stream = GenerateData(50);
var name = IdGenerator.FromGuid();
var bucket = _fixture.MultiVersionBucket;
var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.ThrowOnly };
await Assert.ThrowsAsync<UploadValidationException>(() => client.UploadObjectAsync(bucket, name, null, stream, options));
// We don't delete the object, so it's still present.
ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes));
}
[Fact]
public async Task UploadObjectAsync_InvalidHash_DeleteAndThrow()
{
var client = StorageClient.Create();
var interceptor = new BreakUploadInterceptor();
client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor);
var stream = GenerateData(50);
var name = IdGenerator.FromGuid();
var bucket = _fixture.MultiVersionBucket;
var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.DeleteAndThrow };
await Assert.ThrowsAsync<UploadValidationException>(() => client.UploadObjectAsync(bucket, name, null, stream, options));
var notFound = await Assert.ThrowsAsync<GoogleApiException>(() => _fixture.Client.GetObjectAsync(bucket, name));
Assert.Equal(HttpStatusCode.NotFound, notFound.HttpStatusCode);
}
[Fact]
public async Task UploadObjectAsync_InvalidHash_DeleteAndThrow_DeleteFails()
{
var client = StorageClient.Create();
var interceptor = new BreakUploadInterceptor();
client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(interceptor);
client.Service.HttpClient.MessageHandler.AddExecuteInterceptor(new BreakDeleteInterceptor());
var stream = GenerateData(50);
var name = IdGenerator.FromGuid();
var bucket = _fixture.MultiVersionBucket;
var options = new UploadObjectOptions { UploadValidationMode = UploadValidationMode.DeleteAndThrow };
var ex = await Assert.ThrowsAsync<UploadValidationException>(() => client.UploadObjectAsync(bucket, name, null, stream, options));
Assert.NotNull(ex.AdditionalFailures);
// The deletion failed, so the uploaded object still exists.
ValidateData(bucket, name, new MemoryStream(interceptor.UploadedBytes));
}
private class BreakUploadInterceptor : IHttpExecuteInterceptor
{
internal byte[] UploadedBytes { get; set; }
public async Task InterceptAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// We only care about Put requests, as that's what upload uses.
if (request.Method != HttpMethod.Put)
{
return;
}
var originalContent = request.Content;
var bytes = await originalContent.ReadAsByteArrayAsync().ConfigureAwait(false);
// Unlikely, but if we get an empty request, just leave it alone.
if (bytes.Length == 0)
{
return;
}
bytes[0]++;
request.Content = new ByteArrayContent(bytes);
UploadedBytes = bytes;
foreach (var header in originalContent.Headers)
{
request.Content.Headers.Add(header.Key, header.Value);
}
}
}
private class BreakDeleteInterceptor : IHttpExecuteInterceptor
{
public Task InterceptAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
// We only care about Delete requests
if (request.Method == HttpMethod.Delete)
{
// Ugly but effective hack: replace the generation URL parameter so that we add a leading 9,
// so the generation we try to delete is the wrong one.
request.RequestUri = new Uri(request.RequestUri.ToString().Replace("generation=", "generation=9"));
}
return Task.FromResult(0);
}
}
private Object GetExistingObject()
{
var obj = _fixture.Client.UploadObject(_fixture.MultiVersionBucket, IdGenerator.FromGuid(), "application/octet-stream", GenerateData(100));
// Clear hash and cache information, ready for a new version.
obj.Crc32c = null;
obj.ETag = null;
obj.Md5Hash = null;
return obj;
}
}
}
| |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.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.
* ****************************************************************************
*/
// This code is auto-generated, do not modify
using Ds3.Models;
using System;
using System.Net;
namespace Ds3.Calls
{
public class GetSuspectBucketsSpectraS3Request : Ds3Request
{
private string _dataPolicyId;
public string DataPolicyId
{
get { return _dataPolicyId; }
set { WithDataPolicyId(value); }
}
private bool? _lastPage;
public bool? LastPage
{
get { return _lastPage; }
set { WithLastPage(value); }
}
private string _name;
public string Name
{
get { return _name; }
set { WithName(value); }
}
private int? _pageLength;
public int? PageLength
{
get { return _pageLength; }
set { WithPageLength(value); }
}
private int? _pageOffset;
public int? PageOffset
{
get { return _pageOffset; }
set { WithPageOffset(value); }
}
private string _pageStartMarker;
public string PageStartMarker
{
get { return _pageStartMarker; }
set { WithPageStartMarker(value); }
}
private string _userId;
public string UserId
{
get { return _userId; }
set { WithUserId(value); }
}
public GetSuspectBucketsSpectraS3Request WithDataPolicyId(Guid? dataPolicyId)
{
this._dataPolicyId = dataPolicyId.ToString();
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId.ToString());
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public GetSuspectBucketsSpectraS3Request WithDataPolicyId(string dataPolicyId)
{
this._dataPolicyId = dataPolicyId;
if (dataPolicyId != null)
{
this.QueryParams.Add("data_policy_id", dataPolicyId);
}
else
{
this.QueryParams.Remove("data_policy_id");
}
return this;
}
public GetSuspectBucketsSpectraS3Request WithLastPage(bool? lastPage)
{
this._lastPage = lastPage;
if (lastPage != null)
{
this.QueryParams.Add("last_page", lastPage.ToString());
}
else
{
this.QueryParams.Remove("last_page");
}
return this;
}
public GetSuspectBucketsSpectraS3Request WithName(string name)
{
this._name = name;
if (name != null)
{
this.QueryParams.Add("name", name);
}
else
{
this.QueryParams.Remove("name");
}
return this;
}
public GetSuspectBucketsSpectraS3Request WithPageLength(int? pageLength)
{
this._pageLength = pageLength;
if (pageLength != null)
{
this.QueryParams.Add("page_length", pageLength.ToString());
}
else
{
this.QueryParams.Remove("page_length");
}
return this;
}
public GetSuspectBucketsSpectraS3Request WithPageOffset(int? pageOffset)
{
this._pageOffset = pageOffset;
if (pageOffset != null)
{
this.QueryParams.Add("page_offset", pageOffset.ToString());
}
else
{
this.QueryParams.Remove("page_offset");
}
return this;
}
public GetSuspectBucketsSpectraS3Request WithPageStartMarker(Guid? pageStartMarker)
{
this._pageStartMarker = pageStartMarker.ToString();
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker.ToString());
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetSuspectBucketsSpectraS3Request WithPageStartMarker(string pageStartMarker)
{
this._pageStartMarker = pageStartMarker;
if (pageStartMarker != null)
{
this.QueryParams.Add("page_start_marker", pageStartMarker);
}
else
{
this.QueryParams.Remove("page_start_marker");
}
return this;
}
public GetSuspectBucketsSpectraS3Request WithUserId(Guid? userId)
{
this._userId = userId.ToString();
if (userId != null)
{
this.QueryParams.Add("user_id", userId.ToString());
}
else
{
this.QueryParams.Remove("user_id");
}
return this;
}
public GetSuspectBucketsSpectraS3Request WithUserId(string userId)
{
this._userId = userId;
if (userId != null)
{
this.QueryParams.Add("user_id", userId);
}
else
{
this.QueryParams.Remove("user_id");
}
return this;
}
public GetSuspectBucketsSpectraS3Request()
{
}
internal override HttpVerb Verb
{
get
{
return HttpVerb.GET;
}
}
internal override string Path
{
get
{
return "/_rest_/suspect_bucket";
}
}
}
}
| |
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.Tokens;
using Microsoft.SharePoint.Client;
using System;
using System.Net;
using System.Security.Principal;
using System.Web;
using System.Web.Configuration;
namespace Diagnostics.LoggingWeb
{
/// <summary>
/// Encapsulates all the information from SharePoint.
/// </summary>
public abstract class SharePointContext
{
public const string SPHostUrlKey = "SPHostUrl";
public const string SPAppWebUrlKey = "SPAppWebUrl";
public const string SPLanguageKey = "SPLanguage";
public const string SPClientTagKey = "SPClientTag";
public const string SPProductNumberKey = "SPProductNumber";
protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0);
private readonly Uri spHostUrl;
private readonly Uri spAppWebUrl;
private readonly string spLanguage;
private readonly string spClientTag;
private readonly string spProductNumber;
// <AccessTokenString, UtcExpiresOn>
protected Tuple<string, DateTime> userAccessTokenForSPHost;
protected Tuple<string, DateTime> userAccessTokenForSPAppWeb;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost;
protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb;
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]);
Uri spHostUrl;
if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) &&
(spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps))
{
return spHostUrl;
}
return null;
}
/// <summary>
/// Gets the SharePoint host url from QueryString of the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The specified HTTP request.</param>
/// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns>
public static Uri GetSPHostUrl(HttpRequest httpRequest)
{
return GetSPHostUrl(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// The SharePoint host url.
/// </summary>
public Uri SPHostUrl
{
get { return this.spHostUrl; }
}
/// <summary>
/// The SharePoint app web url.
/// </summary>
public Uri SPAppWebUrl
{
get { return this.spAppWebUrl; }
}
/// <summary>
/// The SharePoint language.
/// </summary>
public string SPLanguage
{
get { return this.spLanguage; }
}
/// <summary>
/// The SharePoint client tag.
/// </summary>
public string SPClientTag
{
get { return this.spClientTag; }
}
/// <summary>
/// The SharePoint product number.
/// </summary>
public string SPProductNumber
{
get { return this.spProductNumber; }
}
/// <summary>
/// The user access token for the SharePoint host.
/// </summary>
public abstract string UserAccessTokenForSPHost
{
get;
}
/// <summary>
/// The user access token for the SharePoint app web.
/// </summary>
public abstract string UserAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// The app only access token for the SharePoint host.
/// </summary>
public abstract string AppOnlyAccessTokenForSPHost
{
get;
}
/// <summary>
/// The app only access token for the SharePoint app web.
/// </summary>
public abstract string AppOnlyAccessTokenForSPAppWeb
{
get;
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber)
{
if (spHostUrl == null)
{
throw new ArgumentNullException("spHostUrl");
}
if (string.IsNullOrEmpty(spLanguage))
{
throw new ArgumentNullException("spLanguage");
}
if (string.IsNullOrEmpty(spClientTag))
{
throw new ArgumentNullException("spClientTag");
}
if (string.IsNullOrEmpty(spProductNumber))
{
throw new ArgumentNullException("spProductNumber");
}
this.spHostUrl = spHostUrl;
this.spAppWebUrl = spAppWebUrl;
this.spLanguage = spLanguage;
this.spClientTag = spClientTag;
this.spProductNumber = spProductNumber;
}
/// <summary>
/// Creates a user ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost);
}
/// <summary>
/// Creates a user ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateUserClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb);
}
/// <summary>
/// Creates app only ClientContext for the SharePoint host.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPHost()
{
return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost);
}
/// <summary>
/// Creates an app only ClientContext for the SharePoint app web.
/// </summary>
/// <returns>A ClientContext instance.</returns>
public ClientContext CreateAppOnlyClientContextForSPAppWeb()
{
return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb);
}
/// <summary>
/// Gets the database connection string from SharePoint for autohosted app.
/// This method is deprecated because the autohosted option is no longer available.
/// </summary>
[ObsoleteAttribute("This method is deprecated because the autohosted option is no longer available.", true)]
public string GetDatabaseConnectionString()
{
throw new NotSupportedException("This method is deprecated because the autohosted option is no longer available.");
}
/// <summary>
/// Determines if the specified access token is valid.
/// It considers an access token as not valid if it is null, or it has expired.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <returns>True if the access token is valid.</returns>
protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken)
{
return accessToken != null &&
!string.IsNullOrEmpty(accessToken.Item1) &&
accessToken.Item2 > DateTime.UtcNow;
}
/// <summary>
/// Creates a ClientContext with the specified SharePoint site url and the access token.
/// </summary>
/// <param name="spSiteUrl">The site url.</param>
/// <param name="accessToken">The access token.</param>
/// <returns>A ClientContext instance.</returns>
private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken)
{
if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken))
{
return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken);
}
return null;
}
}
/// <summary>
/// Redirection status.
/// </summary>
public enum RedirectionStatus
{
Ok,
ShouldRedirect,
CanNotRedirect
}
/// <summary>
/// Provides SharePointContext instances.
/// </summary>
public abstract class SharePointContextProvider
{
private static SharePointContextProvider current;
/// <summary>
/// The current SharePointContextProvider instance.
/// </summary>
public static SharePointContextProvider Current
{
get { return SharePointContextProvider.current; }
}
/// <summary>
/// Initializes the default SharePointContextProvider instance.
/// </summary>
static SharePointContextProvider()
{
if (!TokenHelper.IsHighTrustApp())
{
SharePointContextProvider.current = new SharePointAcsContextProvider();
}
else
{
SharePointContextProvider.current = new SharePointHighTrustContextProvider();
}
}
/// <summary>
/// Registers the specified SharePointContextProvider instance as current.
/// It should be called by Application_Start() in Global.asax.
/// </summary>
/// <param name="provider">The SharePointContextProvider to be set as current.</param>
public static void Register(SharePointContextProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException("provider");
}
SharePointContextProvider.current = provider;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
redirectUrl = null;
bool contextTokenExpired = false;
try
{
if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null)
{
return RedirectionStatus.Ok;
}
}
catch (SecurityTokenExpiredException)
{
contextTokenExpired = true;
}
const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint";
if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey]) && !contextTokenExpired)
{
return RedirectionStatus.CanNotRedirect;
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return RedirectionStatus.CanNotRedirect;
}
if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST"))
{
return RedirectionStatus.CanNotRedirect;
}
Uri requestUrl = httpContext.Request.Url;
var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query);
// Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string.
queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey);
queryNameValueCollection.Remove(SharePointContext.SPLanguageKey);
queryNameValueCollection.Remove(SharePointContext.SPClientTagKey);
queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey);
// Adds SPHasRedirectedToSharePoint=1.
queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1");
UriBuilder returnUrlBuilder = new UriBuilder(requestUrl);
returnUrlBuilder.Query = queryNameValueCollection.ToString();
// Inserts StandardTokens.
const string StandardTokens = "{StandardTokens}";
string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri;
returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&");
// Constructs redirect url.
string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString));
redirectUrl = new Uri(redirectUrlString, UriKind.Absolute);
return RedirectionStatus.ShouldRedirect;
}
/// <summary>
/// Checks if it is necessary to redirect to SharePoint for user to authenticate.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param>
/// <returns>Redirection status.</returns>
public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl)
{
return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest)
{
if (httpRequest == null)
{
throw new ArgumentNullException("httpRequest");
}
// SPHostUrl
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest);
if (spHostUrl == null)
{
return null;
}
// SPAppWebUrl
string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]);
Uri spAppWebUrl;
if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) ||
!(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps))
{
spAppWebUrl = null;
}
// SPLanguage
string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey];
if (string.IsNullOrEmpty(spLanguage))
{
return null;
}
// SPClientTag
string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey];
if (string.IsNullOrEmpty(spClientTag))
{
return null;
}
// SPProductNumber
string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey];
if (string.IsNullOrEmpty(spProductNumber))
{
return null;
}
return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest);
}
/// <summary>
/// Creates a SharePointContext instance with the specified HTTP request.
/// </summary>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
public SharePointContext CreateSharePointContext(HttpRequest httpRequest)
{
return CreateSharePointContext(new HttpRequestWrapper(httpRequest));
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContextBase httpContext)
{
if (httpContext == null)
{
throw new ArgumentNullException("httpContext");
}
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
if (spHostUrl == null)
{
return null;
}
SharePointContext spContext = LoadSharePointContext(httpContext);
if (spContext == null || !ValidateSharePointContext(spContext, httpContext))
{
spContext = CreateSharePointContext(httpContext.Request);
if (spContext != null)
{
SaveSharePointContext(spContext, httpContext);
}
}
return spContext;
}
/// <summary>
/// Gets a SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns>
public SharePointContext GetSharePointContext(HttpContext httpContext)
{
return GetSharePointContext(new HttpContextWrapper(httpContext));
}
/// <summary>
/// Creates a SharePointContext instance.
/// </summary>
/// <param name="spHostUrl">The SharePoint host url.</param>
/// <param name="spAppWebUrl">The SharePoint app web url.</param>
/// <param name="spLanguage">The SharePoint language.</param>
/// <param name="spClientTag">The SharePoint client tag.</param>
/// <param name="spProductNumber">The SharePoint product number.</param>
/// <param name="httpRequest">The HTTP request.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns>
protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest);
/// <summary>
/// Validates if the given SharePointContext can be used with the specified HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext.</param>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns>
protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
/// <summary>
/// Loads the SharePointContext instance associated with the specified HTTP context.
/// </summary>
/// <param name="httpContext">The HTTP context.</param>
/// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns>
protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext);
/// <summary>
/// Saves the specified SharePointContext instance associated with the specified HTTP context.
/// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context.
/// </summary>
/// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param>
/// <param name="httpContext">The HTTP context.</param>
protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext);
}
#region ACS
/// <summary>
/// Encapsulates all the information from SharePoint in ACS mode.
/// </summary>
public class SharePointAcsContext : SharePointContext
{
private readonly string contextToken;
private readonly SharePointContextToken contextTokenObj;
/// <summary>
/// The context token.
/// </summary>
public string ContextToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; }
}
/// <summary>
/// The context token's "CacheKey" claim.
/// </summary>
public string CacheKey
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; }
}
/// <summary>
/// The context token's "refreshtoken" claim.
/// </summary>
public string RefreshToken
{
get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl)));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl)));
}
}
public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (string.IsNullOrEmpty(contextToken))
{
throw new ArgumentNullException("contextToken");
}
if (contextTokenObj == null)
{
throw new ArgumentNullException("contextTokenObj");
}
this.contextToken = contextToken;
this.contextTokenObj = contextTokenObj;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
try
{
OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler();
DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn;
if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn);
}
catch (WebException)
{
}
}
}
/// <summary>
/// Default provider for SharePointAcsContext.
/// </summary>
public class SharePointAcsContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
private const string SPCacheKeyKey = "SPCacheKey";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest);
if (string.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = null;
try
{
contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority);
}
catch (WebException)
{
return null;
}
catch (AudienceUriValidationFailedException)
{
return null;
}
return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request);
HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey];
string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null;
return spHostUrl == spAcsContext.SPHostUrl &&
!string.IsNullOrEmpty(spAcsContext.CacheKey) &&
spCacheKey == spAcsContext.CacheKey &&
!string.IsNullOrEmpty(spAcsContext.ContextToken) &&
(string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken);
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointAcsContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointAcsContext spAcsContext = spContext as SharePointAcsContext;
if (spAcsContext != null)
{
HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey)
{
Value = spAcsContext.CacheKey,
Secure = true,
HttpOnly = true
};
httpContext.Response.AppendCookie(spCacheKeyCookie);
}
httpContext.Session[SPContextKey] = spAcsContext;
}
}
#endregion ACS
#region HighTrust
/// <summary>
/// Encapsulates all the information from SharePoint in HighTrust mode.
/// </summary>
public class SharePointHighTrustContext : SharePointContext
{
private readonly WindowsIdentity logonUserIdentity;
/// <summary>
/// The Windows identity for the current user.
/// </summary>
public WindowsIdentity LogonUserIdentity
{
get { return this.logonUserIdentity; }
}
public override string UserAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.userAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity));
}
}
public override string UserAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity));
}
}
public override string AppOnlyAccessTokenForSPHost
{
get
{
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null));
}
}
public override string AppOnlyAccessTokenForSPAppWeb
{
get
{
if (this.SPAppWebUrl == null)
{
return null;
}
return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb,
() => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null));
}
}
public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity)
: base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber)
{
if (logonUserIdentity == null)
{
throw new ArgumentNullException("logonUserIdentity");
}
this.logonUserIdentity = logonUserIdentity;
}
/// <summary>
/// Ensures the access token is valid and returns it.
/// </summary>
/// <param name="accessToken">The access token to verify.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
/// <returns>The access token string.</returns>
private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler);
return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null;
}
/// <summary>
/// Renews the access token if it is not valid.
/// </summary>
/// <param name="accessToken">The access token to renew.</param>
/// <param name="tokenRenewalHandler">The token renewal handler.</param>
private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler)
{
if (IsAccessTokenValid(accessToken))
{
return;
}
DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime);
if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance)
{
// Make the access token get renewed a bit earlier than the time when it expires
// so that the calls to SharePoint with it will have enough time to complete successfully.
expiresOn -= AccessTokenLifetimeTolerance;
}
accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn);
}
}
/// <summary>
/// Default provider for SharePointHighTrustContext.
/// </summary>
public class SharePointHighTrustContextProvider : SharePointContextProvider
{
private const string SPContextKey = "SPContext";
protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest)
{
WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity;
if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null)
{
return null;
}
return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity);
}
protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext;
if (spHighTrustContext != null)
{
Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request);
WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity;
return spHostUrl == spHighTrustContext.SPHostUrl &&
logonUserIdentity != null &&
logonUserIdentity.IsAuthenticated &&
!logonUserIdentity.IsGuest &&
logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User;
}
return false;
}
protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext)
{
return httpContext.Session[SPContextKey] as SharePointHighTrustContext;
}
protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext)
{
httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext;
}
}
#endregion HighTrust
}
| |
/*
* daap-sharp
* Copyright (C) 2005 James Willcox <snorp@snorp.net>
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Text;
using System.Net;
using System.Runtime.InteropServices;
using ICSharpCode.SharpZipLib.GZip;
namespace Daap {
internal class ContentFetcher : IDisposable {
private IPAddress address;
private UInt16 port;
private int sessionId;
private int requestId = 10;
private DAAPCredentials creds = new DAAPCredentials ();
private List<WebRequest> requests = new List<WebRequest> ();
public string Username {
get { return creds.Username; }
set { creds.Username = value; }
}
public string Password {
get { return creds.Password; }
set { creds.Password = value; }
}
public int SessionId {
get { return sessionId; }
set { sessionId = value; }
}
public ContentFetcher (IPAddress address, UInt16 port) {
this.address = address;
this.port = port;
}
public void Dispose () {
KillAll ();
}
public void KillAll () {
lock (requests) {
foreach (WebRequest request in requests) {
request.Abort ();
}
requests.Clear ();
}
}
public byte[] Fetch (string path) {
return Fetch (path, null, null, 0);
}
public byte[] Fetch (string path, string query) {
return Fetch (path, query, null, 0);
}
public byte[] Fetch (string path, string query, WebHeaderCollection extraHeaders,
int requestId) {
HttpWebResponse response = FetchResponse (path, -1, query, extraHeaders, requestId, false);
MemoryStream data = new MemoryStream ();
BinaryReader reader = new BinaryReader (GetResponseStream (response));
try {
if (response.ContentLength < 0)
return null;
byte[] buf;
while (true) {
buf = reader.ReadBytes (8192);
if (buf.Length == 0)
break;
data.Write (buf, 0, buf.Length);
}
data.Flush ();
return data.GetBuffer ();
} finally {
data.Close ();
reader.Close ();
response.Close ();
}
}
public HttpWebResponse FetchResponse (string path, string query, WebHeaderCollection headers) {
return FetchResponse (path, -1, query, headers, ++requestId, false);
}
public HttpWebResponse FetchFile (string path, long offset) {
return FetchResponse (path, offset, null, null, ++requestId, true);
}
public HttpWebResponse FetchResponse (string path, long offset, string query,
WebHeaderCollection extraHeaders,
int requestId, bool disableKeepalive) {
UriBuilder builder = new UriBuilder ("http", address.ToString ());
builder.Port = port;
builder.Path = path;
if (sessionId != 0)
query = String.Format ("session-id={0}&", sessionId) + query;
if (query != null)
builder.Query += query;
HttpWebRequest request = (HttpWebRequest) WebRequest.Create (builder.Uri);
request.PreAuthenticate = true;
request.Timeout = System.Threading.Timeout.Infinite;
request.Headers.Add ("Accept-Encoding", "gzip");
if (offset > 0) {
request.AddRange ("bytes", (int) offset);
}
request.ServicePoint.ConnectionLimit = 3;
if (extraHeaders != null)
request.Headers = extraHeaders;
request.Accept = "*/*";
request.KeepAlive = !disableKeepalive;
string hash = Hasher.GenerateHash (3, builder.Uri.PathAndQuery, 2, requestId);
request.UserAgent = "iTunes/4.6 (Windows; N)";
request.Headers.Set ("Client-DAAP-Version", "3.0");
request.Headers.Set ("Client-DAAP-Validation", hash);
request.Headers.Set ("Client-DAAP-Access-Index", "2");
if (requestId >= 0)
request.Headers.Set ("Client-DAAP-Request-ID", requestId.ToString ());
request.Credentials = creds;
request.PreAuthenticate = true;
try {
lock (requests) {
requests.Add (request);
}
HttpWebResponse response = (HttpWebResponse) request.GetResponse ();
return response;
} finally {
lock (requests) {
requests.Remove (request);
}
}
}
public Stream GetResponseStream (HttpWebResponse response) {
if (response.ContentEncoding == "gzip") {
return new GZipInputStream (response.GetResponseStream ());
} else {
return response.GetResponseStream ();
}
}
private class DAAPCredentials : ICredentials {
private string username;
private string password;
public string Username {
get { return username; }
set { username = value; }
}
public string Password {
get { return password; }
set { password = value; }
}
public NetworkCredential GetCredential (Uri uri, string type) {
return new NetworkCredential (username == null ? "none" : username, password);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
using Medo.Configuration;
namespace Tests.Medo.Configuration {
public class ConfigTests {
[Fact(DisplayName = "Config: Null key throws exception")]
public void NullKey() {
var ex = Assert.Throws<ArgumentNullException>(() => {
Config.Read(null, "");
});
Assert.StartsWith("Key cannot be null.", ex.Message);
}
[Fact(DisplayName = "Config: Empty key throws exception")]
public void EmptyKey() {
var ex = Assert.Throws<ArgumentOutOfRangeException>(() => {
Config.Read(" ", "");
});
Assert.StartsWith("Key cannot be empty.", ex.Message);
}
[Fact(DisplayName = "Config: Empty file Load/Save")]
public void EmptySave() {
using var loader = new ConfigLoader("Empty.cfg");
Assert.True(Config.Load(), "File should exist before load.");
Assert.True(Config.Save(), "Save should succeed.");
Assert.Equal(BitConverter.ToString(loader.Bytes), BitConverter.ToString(File.ReadAllBytes(loader.FileName)));
Assert.False(Config.IsAssumedInstalled);
}
[Fact(DisplayName = "Config: Installation status assumption")]
public void AssumeInstalled() {
var executablePath = Assembly.GetEntryAssembly().Location;
var userFileLocation = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? Path.Combine(Environment.GetEnvironmentVariable("AppData"), "", "Microsoft.TestHost", "Microsoft.TestHost.cfg")
: Path.Combine(Environment.GetEnvironmentVariable("HOME") ?? "~", "Microsoft.TestHost.cfg");
var localFileLocation = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? Path.Combine(Path.GetDirectoryName(executablePath), "Microsoft.TestHost.cfg")
: Path.Combine(Path.GetDirectoryName(executablePath), ".Microsoft.TestHost");
var userFileDirectory = Path.GetDirectoryName(userFileLocation);
//clean files
if (Directory.Exists(userFileDirectory)) { Directory.Delete(userFileDirectory, true); }
if (File.Exists(localFileLocation)) { File.Delete(localFileLocation); }
try {
Config.Reset();
Assert.False(Config.IsAssumedInstalled);
Assert.NotNull(Config.FileName);
Assert.Null(Config.OverrideFileName);
} finally { //clean files
if (Directory.Exists(userFileDirectory)) { Directory.Delete(userFileDirectory, true); }
if (File.Exists(localFileLocation)) { File.Delete(localFileLocation); }
}
try { //create empty file in AppData directory and a local file
Config.Reset();
Config.IsAssumedInstalled = true;
if (!Directory.Exists(userFileDirectory)) { Directory.CreateDirectory(userFileDirectory); }
File.WriteAllText(userFileLocation, "");
File.WriteAllText(localFileLocation, "");
Assert.True(Config.IsAssumedInstalled);
Assert.NotNull(Config.FileName);
Assert.NotNull(Config.OverrideFileName);
} finally { //clean files
if (Directory.Exists(userFileDirectory)) { Directory.Delete(userFileDirectory, true); }
if (File.Exists(localFileLocation)) { File.Delete(localFileLocation); }
}
try {
Config.Reset();
Assert.False(Config.IsAssumedInstalled);
Assert.NotNull(Config.FileName);
Assert.Null(Config.OverrideFileName);
} finally { //clean files
if (Directory.Exists(userFileDirectory)) { Directory.Delete(userFileDirectory, true); }
if (File.Exists(localFileLocation)) { File.Delete(localFileLocation); }
}
}
[Fact(DisplayName = "Config: CRLF preserved on Save")]
public void EmptyLinesCRLF() {
using var loader = new ConfigLoader("EmptyLinesCRLF.cfg");
Config.Save();
Assert.Equal(BitConverter.ToString(loader.Bytes), BitConverter.ToString(File.ReadAllBytes(loader.FileName)));
}
[Fact(DisplayName = "Config: LF preserved on Save")]
public void EmptyLinesLF() {
using var loader = new ConfigLoader("EmptyLinesLF.cfg");
Config.Save();
Assert.Equal(BitConverter.ToString(loader.Bytes), BitConverter.ToString(File.ReadAllBytes(loader.FileName)));
}
[Fact(DisplayName = "Config: CR preserved on Save")]
public void EmptyLinesCR() {
using var loader = new ConfigLoader("EmptyLinesCR.cfg");
Config.Save();
Assert.Equal(BitConverter.ToString(loader.Bytes), BitConverter.ToString(File.ReadAllBytes(loader.FileName)));
}
[Fact(DisplayName = "Config: Mixed line ending gets normalized on Save")]
public void EmptyLinesMixed() {
using var loader = new ConfigLoader("EmptyLinesMixed.cfg", "EmptyLinesMixed.Good.cfg");
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
}
[Fact(DisplayName = "Config: Comments are preserved on Save")]
public void CommentsOnly() {
using var loader = new ConfigLoader("CommentsOnly.cfg", "CommentsOnly.Good.cfg");
Config.Save();
Assert.Equal(BitConverter.ToString(loader.GoodBytes), BitConverter.ToString(File.ReadAllBytes(loader.FileName)));
}
[Fact(DisplayName = "Config: Values with comments are preserved on Save")]
public void CommentsWithValues() {
using var loader = new ConfigLoader("CommentsWithValues.cfg");
Config.Save();
Assert.Equal(Encoding.UTF8.GetString(loader.Bytes), Encoding.UTF8.GetString(File.ReadAllBytes(loader.FileName)));
Assert.Equal(BitConverter.ToString(loader.Bytes), BitConverter.ToString(File.ReadAllBytes(loader.FileName)));
}
[Fact(DisplayName = "Config: Leading spaces are preserved on Save")]
public void SpacingEscape() {
using var loader = new ConfigLoader("SpacingEscape.cfg", "SpacingEscape.Good.cfg");
Assert.Equal(" Value 1", Config.Read("Key1"));
Assert.Equal("Value 2 ", Config.Read("Key2"));
Assert.Equal(" Value 3 ", Config.Read("Key3"));
Assert.Equal(" Value 4 ", Config.Read("Key4"));
Assert.Equal("\tValue 5\t", Config.Read("Key5"));
Assert.Equal("\tValue 6", Config.Read("Key6"));
Assert.Equal("\0", Config.Read("Null"));
Config.Save();
Config.Write("Null", "\0Null\0");
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
}
[Fact(DisplayName = "Config: Basic write")]
public void WriteBasic() {
using var loader = new ConfigLoader("Empty.cfg", "WriteBasic.Good.cfg");
Config.Write("Key1", "Value 1");
Config.Write("Key2", "Value 2");
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
}
[Fact(DisplayName = "Config: Basic write (without empty line ending)")]
public void WriteNoEmptyLine() {
using var loader = new ConfigLoader("WriteNoEmptyLine.cfg", "WriteNoEmptyLine.Good.cfg");
Config.Write("Key1", "Value 1");
Config.Write("Key2", "Value 2");
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
}
[Fact(DisplayName = "Config: Separator equals (=) is preserved upon save")]
public void WriteSameSeparatorEquals() {
using var loader = new ConfigLoader("WriteSameSeparatorEquals.cfg", "WriteSameSeparatorEquals.Good.cfg");
Config.Write("Key1", "Value 1");
Config.Write("Key2", "Value 2");
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
}
[Fact(DisplayName = "Config: Separator space ( ) is preserved upon save")]
public void WriteSameSeparatorSpace() {
using var loader = new ConfigLoader("WriteSameSeparatorSpace.cfg", "WriteSameSeparatorSpace.Good.cfg");
Config.Write("Key1", "Value 1");
Config.Write("Key2", "Value 2");
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
}
[Fact(DisplayName = "Config: Write replaces existing entry")]
public void Replace() {
using var loader = new ConfigLoader("Replace.cfg", "Replace.Good.cfg");
Config.Write("Key1", "Value 1a");
Config.Write("Key2", "Value 2a");
Config.Save();
Assert.Equal("Value 1a", Config.Read("Key1"));
Assert.Equal("Value 2a", Config.Read("Key2"));
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
}
[Fact(DisplayName = "Config: Write preserves spacing")]
public void SpacingPreserved() {
using var loader = new ConfigLoader("SpacingPreserved.cfg", "SpacingPreserved.Good.cfg");
Config.Write("KeyOne", "Value 1a");
Config.Write("KeyTwo", "Value 2b");
Config.Write("KeyThree", "Value 3c");
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
}
[Fact(DisplayName = "Config: Write preserves spacing on add")]
public void SpacingPreservedOnAdd() {
using var loader = new ConfigLoader("SpacingPreservedOnAdd.cfg", "SpacingPreservedOnAdd.Good.cfg");
Config.Write("One", "Value 1a");
Config.Write("Two", new string[] { "Value 2a", "Value 2b" });
Config.Write("Three", "Value 3a");
Config.Write("Four", "Value 4a");
Config.Write("Five", new string[] { "Value 5a", "Value 5b", "Value 5c" });
Config.Write("FourtyTwo", 42);
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
}
[Fact(DisplayName = "Config: Write without preexisting file")]
public void WriteToEmpty() {
using var loader = new ConfigLoader(null, "Replace.Good.cfg");
Config.Write("Key1", "Value 1a");
Config.Write("Key2", "Value 2a");
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
}
[Fact(DisplayName = "Config: Write replaces only last instance of same key")]
public void ReplaceOnlyLast() {
using var loader = new ConfigLoader("ReplaceOnlyLast.cfg", "ReplaceOnlyLast.Good.cfg");
Config.Write("Key1", "Value 1a");
Config.Write("Key2", "Value 2a");
Config.Save();
Assert.Equal("Value 1a", Config.Read("Key1"));
Assert.Equal("Value 2a", Config.Read("Key2"));
Assert.Equal("Value 3", Config.Read("Key3"));
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
}
[Fact(DisplayName = "Config: Write creates directory")]
public void SaveInNonexistingDirectory1() {
var propertiesFile = Path.Combine(Path.GetTempPath(), "ConfigDirectory", "Test.cfg");
try {
Directory.Delete(Path.Combine(Path.GetTempPath(), "ConfigDirectory"), true);
} catch (IOException) { }
Config.FileName = propertiesFile;
Assert.False(Config.Load(), "No file present for load.");
var x = Config.Read("Test", "test");
Assert.Equal("test", x);
Assert.True(Config.Save(), "Save should create directory structure and succeed.");
Assert.True(File.Exists(propertiesFile));
Directory.Delete(Path.Combine(Path.GetTempPath(), "ConfigDirectory"), true);
}
[Fact(DisplayName = "Config: Write creates directory (2 levels deep)")]
public void SaveInNonexistingDirectory2() {
var propertiesFile = Path.Combine(Path.GetTempPath(), "ConfigDirectoryOuter", "ConfigDirectoryInner", "Test.cfg");
try {
Directory.Delete(Path.Combine(Path.GetTempPath(), "ConfigDirectoryOuter"), true);
} catch (IOException) { }
Config.FileName = propertiesFile;
Assert.False(Config.Load(), "No file present for load.");
var x = Config.Read("Test", "test");
Assert.Equal("test", x);
Assert.True(Config.Save(), "Save should create directory structure and succeed.");
Assert.True(File.Exists(propertiesFile));
Directory.Delete(Path.Combine(Path.GetTempPath(), "ConfigDirectoryOuter"), true);
}
[Fact(DisplayName = "Config: Write creates directory (3 levels deep)")]
public void SaveInNonexistingDirectory3() {
var propertiesFile = Path.Combine(Path.GetTempPath(), "ConfigDirectoryOuter", "ConfigDirectoryMiddle", "ConfigDirectoryInner", "Test.cfg");
try {
Directory.Delete(Path.Combine(Path.GetTempPath(), "ConfigDirectoryOuter"), true);
} catch (IOException) { }
Config.FileName = propertiesFile;
Assert.False(Config.Load(), "No file present for load.");
var x = Config.Read("Test", "test");
Assert.Equal("test", x);
Assert.True(Config.Save(), "Save should create directory structure and succeed.");
Assert.True(File.Exists(propertiesFile));
Directory.Delete(Path.Combine(Path.GetTempPath(), "ConfigDirectoryOuter"), true);
}
[Fact(DisplayName = "Config: Removing entry")]
public void RemoveSingle() {
using var loader = new ConfigLoader("Remove.cfg", "Remove.Good.cfg");
Config.Delete("Key1");
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
}
[Fact(DisplayName = "Config: Removing multiple entries")]
public void RemoveMulti() {
using var loader = new ConfigLoader("RemoveMulti.cfg", "RemoveMulti.Good.cfg");
Config.Delete("Key2");
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
}
[Fact(DisplayName = "Config: Override is used first")]
public void UseOverrideFirst() {
using var loader = new ConfigLoader("Replace.cfg", resourceOverrideFileName: "Replace.Good.cfg");
Assert.Equal("Value 1a", Config.Read("Key1"));
}
[Fact(DisplayName = "Config: Override is not written")]
public void DontOverwriteOverride() {
using var loader = new ConfigLoader("Replace.cfg", resourceOverrideFileName: "Replace.Good.cfg");
Config.ImmediateSave = true;
Config.Write("Key1", "XXX");
Assert.Equal("Value 1a", Config.Read("Key1"));
Config.OverrideFileName = null;
Assert.Equal("XXX", Config.Read("Key1"));
}
[Fact(DisplayName = "Config: Reading multiple entries")]
public void ReadMulti() {
using var loader = new ConfigLoader("ReplaceOnlyLast.Good.cfg");
var list = new List<string>(Config.ReadAll("Key2"));
Assert.Equal(2, list.Count);
Assert.Equal("Value 2", list[0]);
Assert.Equal("Value 2a", list[1]);
}
[Fact(DisplayName = "Config: Reading multiple entries from override")]
public void ReadMultiFromOverride() {
using var loader = new ConfigLoader("ReplaceOnlyLast.Good.cfg", resourceOverrideFileName: "RemoveMulti.cfg");
var list = new List<string>(Config.ReadAll("Key2"));
Assert.Equal(3, list.Count);
Assert.Equal("Value 2a", list[0]);
Assert.Equal("Value 2b", list[1]);
Assert.Equal("Value 2c", list[2]);
}
[Fact(DisplayName = "Config: Reading multi entries when override is not found")]
public void ReadMultiFromOverrideNotFound() {
using var loader = new ConfigLoader("ReplaceOnlyLast.Good.cfg", resourceOverrideFileName: "RemoveMulti.cfg");
var list = new List<string>(Config.ReadAll("Key3"));
Assert.Single(list);
Assert.Equal("Value 3", list[0]);
}
[Fact(DisplayName = "Config: Multi-value write")]
public void MultiWrite() {
using var loader = new ConfigLoader(null, resourceFileNameGood: "WriteMulti.Good.cfg");
Config.Write("Key1", "Value 1");
Config.Write("Key2", new string[] { "Value 2a", "Value 2b", "Value 2c" });
Config.Write("Key3", "Value 3");
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
Assert.Equal("Value 1", Config.Read("Key1"));
Assert.Equal("Value 3", Config.Read("Key3"));
var list = new List<string>(Config.ReadAll("Key2"));
Assert.Equal(3, list.Count);
Assert.Equal("Value 2a", list[0]);
Assert.Equal("Value 2b", list[1]);
Assert.Equal("Value 2c", list[2]);
}
[Fact(DisplayName = "Config: Multi-value replace")]
public void MultiReplace() {
using var loader = new ConfigLoader("WriteMulti.cfg", resourceFileNameGood: "WriteMulti.Good.cfg");
Config.Write("Key2", new string[] { "Value 2a", "Value 2b", "Value 2c" });
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
Assert.Equal("Value 1", Config.Read("Key1"));
Assert.Equal("Value 3", Config.Read("Key3"));
var list = new List<string>(Config.ReadAll("Key2"));
Assert.Equal(3, list.Count);
Assert.Equal("Value 2a", list[0]);
Assert.Equal("Value 2b", list[1]);
Assert.Equal("Value 2c", list[2]);
}
[Fact(DisplayName = "Config: Multi-value override is not written")]
public void DontOverwriteOverrideMulti() {
using var loader = new ConfigLoader("ReplaceOnlyLast.Good.cfg", resourceOverrideFileName: "RemoveMulti.cfg");
Config.Write("Key2", "Value X");
var list = new List<string>(Config.ReadAll("Key2"));
Assert.Equal(3, list.Count);
Assert.Equal("Value 2a", list[0]);
Assert.Equal("Value 2b", list[1]);
Assert.Equal("Value 2c", list[2]);
}
[Fact(DisplayName = "Config: Test conversion")]
public void TestConversion() {
using var loader = new ConfigLoader(null, resourceFileNameGood: "WriteConverted.Good.cfg");
Config.Write("Integer", 42);
Config.Write("Integer Min", int.MinValue);
Config.Write("Integer Max", int.MaxValue);
Config.Write("Long", 42L);
Config.Write("Long Min", long.MinValue);
Config.Write("Long Max", long.MaxValue);
Config.Write("Boolean", true);
Config.Write("Double", 42.42);
Config.Write("Double Pi", System.Math.PI);
Config.Write("Double Third", 1.0 / 3);
Config.Write("Double Seventh", 1.0 / 7);
Config.Write("Double Min", double.MinValue);
Config.Write("Double Max", double.MaxValue);
Config.Write("Double NaN", double.NaN);
Config.Write("Double Infinity+", double.PositiveInfinity);
Config.Write("Double Infinity-", double.NegativeInfinity);
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
using var loader2 = new ConfigLoader(loader.FileName, resourceFileNameGood: "WriteConverted.Good.cfg");
Assert.Equal(42, Config.Read("Integer", 0));
Assert.Equal(int.MinValue, Config.Read("Integer Min", 0));
Assert.Equal(int.MaxValue, Config.Read("Integer Max", 0));
Assert.Equal(42, Config.Read("Long", 0L));
Assert.Equal(long.MinValue, Config.Read("Long Min", 0L));
Assert.Equal(long.MaxValue, Config.Read("Long Max", 0L));
Assert.True(Config.Read("Boolean", false));
Assert.Equal(42.42, Config.Read("Double", 0.0));
Assert.Equal(System.Math.PI, Config.Read("Double Pi", 0.0));
Assert.Equal(1.0 / 3, Config.Read("Double Third", 0.0));
Assert.Equal(1.0 / 7, Config.Read("Double Seventh", 0.0));
Assert.Equal(double.MinValue, Config.Read("Double Min", 0.0));
Assert.Equal(double.MaxValue, Config.Read("Double Max", 0.0));
Assert.Equal(double.NaN, Config.Read("Double NaN", 0.0));
Assert.Equal(double.PositiveInfinity, Config.Read("Double Infinity+", 0.0));
Assert.Equal(double.NegativeInfinity, Config.Read("Double Infinity-", 0.0));
}
[Fact(DisplayName = "Config: Key whitespace reading and saving")]
public void KeyWhitespace() {
using var loader = new ConfigLoader("KeyWhitespace.cfg", "KeyWhitespace.Good.cfg");
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName));
Assert.Equal("Value 1", Config.Read("Key 1"));
Assert.Equal("Value 3", Config.Read("Key 3"));
var list = new List<string>(Config.ReadAll("Key 2"));
Assert.Equal(3, list.Count);
Assert.Equal("Value 2a", list[0]);
Assert.Equal("Value 2b", list[1]);
Assert.Equal("Value 2c", list[2]);
}
[Fact(DisplayName = "Config: Delete all values")]
public void DeleteAll() {
using var loader = new ConfigLoader("WriteBasic.Good.cfg", "Empty.cfg");
Assert.Equal("Value 1", Config.Read("Key1"));
Assert.Equal("Value 2", Config.Read("Key2"));
Config.DeleteAll();
Assert.Null(Config.Read("Key1"));
Assert.Null(Config.Read("Key2"));
Assert.NotEqual(loader.GoodText, File.ReadAllText(loader.FileName)); //check that changes are not saved
Config.Save();
Assert.Equal(loader.GoodText, File.ReadAllText(loader.FileName)); //check that changes are saved
}
#region Utils
private class ConfigLoader : IDisposable {
public string FileName { get; }
public byte[] Bytes { get; }
public byte[] GoodBytes { get; }
public ConfigLoader(string resourceFileName, string resourceFileNameGood = null, string resourceOverrideFileName = null) {
Config.Reset();
if (File.Exists(resourceFileName)) {
Bytes = File.ReadAllBytes(resourceFileName);
} else {
Bytes = (resourceFileName != null) ? GetResourceStreamBytes(resourceFileName) : null;
}
GoodBytes = (resourceFileNameGood != null) ? GetResourceStreamBytes(resourceFileNameGood) : null;
var overrideBytes = (resourceOverrideFileName != null) ? GetResourceStreamBytes(resourceOverrideFileName) : null;
FileName = Path.GetTempFileName();
if (resourceFileName == null) {
File.Delete(FileName); //to start fresh
} else {
File.WriteAllBytes(FileName, Bytes);
}
Config.FileName = FileName;
var overrideFileName = (resourceOverrideFileName != null) ? Path.GetTempFileName() : null;
if (overrideFileName != null) {
File.WriteAllBytes(overrideFileName, overrideBytes);
Config.OverrideFileName = overrideFileName;
} else {
Config.OverrideFileName = null;
}
Config.ImmediateSave = false;
}
private readonly Encoding Utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false);
public string Text { get => Utf8.GetString(Bytes); }
public string GoodText { get => Utf8.GetString(GoodBytes ?? Array.Empty<byte>()); }
#region IDisposable Support
~ConfigLoader() {
Dispose(false);
}
protected virtual void Dispose(bool disposing) {
try {
File.Delete(FileName);
} catch (IOException) { }
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
}
private static byte[] GetResourceStreamBytes(string fileName) {
var resAssembly = typeof(ConfigTests).GetTypeInfo().Assembly;
var resStream = resAssembly.GetManifestResourceStream("Tests.Medo._Resources.Configuration.Config." + fileName);
var buffer = new byte[(int)resStream.Length];
resStream.Read(buffer, 0, buffer.Length);
return buffer;
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using NUnit.Framework;
using SIL.Xml;
namespace SIL.Tests.Xml
{
[TestFixture]
public class XmlUtilsTests
{
[Test]
public void GetAttributes_DoubleQuotedAttribute_HasValue()
{
const string data = @"<element attr='data' />";
var tmp = data.Replace("'", "\"");
var attrValues = XmlUtils.GetAttributes(Encoding.UTF8.GetBytes(tmp), new HashSet<string> { "attr" });
Assert.IsTrue(attrValues["attr"] == "data");
attrValues = XmlUtils.GetAttributes(tmp, new HashSet<string> { "attr" });
Assert.IsTrue(attrValues["attr"] == "data");
}
[Test]
public void GetAttributes_SingleQuotedAttribute_HasValue()
{
const string data = @"<element attr='data' />";
var attrValues = XmlUtils.GetAttributes(Encoding.UTF8.GetBytes(data), new HashSet<string> { "attr" });
Assert.IsTrue(attrValues["attr"] == "data");
attrValues = XmlUtils.GetAttributes(data, new HashSet<string> { "attr" });
Assert.IsTrue(attrValues["attr"] == "data");
}
[Test]
public void GetAttributes_NonExistentAttribute_IsNull()
{
const string data = @"<element />";
var attrValues = XmlUtils.GetAttributes(Encoding.UTF8.GetBytes(data), new HashSet<string> { "attr" });
Assert.IsNull(attrValues["attr"]);
attrValues = XmlUtils.GetAttributes(data, new HashSet<string> { "attr" });
Assert.IsNull(attrValues["attr"]);
}
[Test]
public void SanitizeString_NullString_ReturnsNull()
{
Assert.IsNull(XmlUtils.SanitizeString(null));
}
[Test]
public void SanitizeString_EmptyString_ReturnsEmptyString()
{
Assert.AreEqual(string.Empty, XmlUtils.SanitizeString(string.Empty));
}
[Test]
public void SanitizeString_ValidString_ReturnsSameString()
{
string s = "Abc\u0009 \u000A\u000D\uD7FF\uE000\uFFFD";
s += char.ConvertFromUtf32(0x10000);
s += char.ConvertFromUtf32(0x10FFFF);
Assert.AreEqual(s, XmlUtils.SanitizeString(s));
}
[Test]
public void SanitizeString_CompletelyInvalidString_ReturnsEmptyString()
{
string s = "\u0000\u0008\u000B\u000C\u000E\u001F\uD800\uD999\uFFFE\uFFFF";
int utf32 = 0x20ffff - 0x10000;
char[] surrogate = new char[2];
surrogate[0] = (char)((utf32 / 0x400) + '\ud800');
surrogate[1] = (char)((utf32 % 0x400) + '\udc00');
s += new string(surrogate);
Assert.AreEqual(string.Empty, XmlUtils.SanitizeString(s));
}
[Test]
public void SanitizeString_StringWithInvalidChars_ReturnsStringWithInvalidCharsRemoved()
{
string s = "A\u0008B\u000B\u000C\u000E\u001F\uD800\uD999\uFFFE\uFFFFC";
int utf32 = 0x20ffff - 0x10000;
char[] surrogate = new char[2];
surrogate[0] = (char)((utf32 / 0x400) + '\ud800');
surrogate[1] = (char)((utf32 % 0x400) + '\udc00');
s += new string(surrogate);
Assert.AreEqual("ABC", XmlUtils.SanitizeString(s));
}
/// <summary>
/// This is a regression test for (FLEx) LT-13962, a problem caused by importing white space introduced by pretty-printing.
/// </summary>
[Test]
public void WriteNode_DoesNotIndentFirstChildOfMixedNode()
{
string input = @"<text><span class='bold'>bt</span> more text</text>";
string expectedOutput =
"<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n"
+ "<root>\r\n"
+ " <text><span\r\n"
+ " class=\"bold\">bt</span> more text</text>\r\n"
+ "</root>";
var output = new StringBuilder();
using (var writer = XmlWriter.Create(output, CanonicalXmlSettings.CreateXmlWriterSettings()))
{
writer.WriteStartDocument();
writer.WriteStartElement("root");
XmlUtils.WriteNode(writer, input, new HashSet<string>());
writer.WriteEndElement();
writer.WriteEndDocument();
}
Assert.That(output.ToString(), Is.EqualTo(expectedOutput));
}
/// <summary>
/// This verifies the special case of (FLEx) LT-13962 where the ONLY child of an element that can contain significant text
/// is an element.
/// </summary>
[Test]
public void WriteNode_DoesNotIndentChildWhenSuppressed()
{
string input = @"<text><span class='bold'>bt</span></text>";
string expectedOutput =
"<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n"
+ "<root>\r\n"
+ " <text><span\r\n"
+ " class=\"bold\">bt</span></text>\r\n"
+ "</root>";
var output = new StringBuilder();
var suppressIndentingChildren = new HashSet<string>();
suppressIndentingChildren.Add("text");
using (var writer = XmlWriter.Create(output, CanonicalXmlSettings.CreateXmlWriterSettings()))
{
writer.WriteStartDocument();
writer.WriteStartElement("root");
XmlUtils.WriteNode(writer, input, suppressIndentingChildren);
writer.WriteEndElement();
writer.WriteEndDocument();
}
Assert.That(output.ToString(), Is.EqualTo(expectedOutput));
}
/// <summary>
/// This verifies that suppressing pretty-printing of children works for spans nested in spans nested in text.
/// </summary>
[Test]
public void WriteNode_DoesNotIndentChildWhenTwoLevelsSuppressed()
{
string input = @"<text><span class='bold'><span class='italic'>bit</span>bt</span></text>";
string expectedOutput =
"<?xml version=\"1.0\" encoding=\"utf-16\"?>\r\n"
+ "<root>\r\n"
+ " <text><span\r\n"
+ " class=\"bold\"><span\r\n"
+ " class=\"italic\">bit</span>bt</span></text>\r\n"
+ "</root>";
var output = new StringBuilder();
var suppressIndentingChildren = new HashSet<string>();
suppressIndentingChildren.Add("text");
using (var writer = XmlWriter.Create(output, CanonicalXmlSettings.CreateXmlWriterSettings()))
{
writer.WriteStartDocument();
writer.WriteStartElement("root");
XmlUtils.WriteNode(writer, input, suppressIndentingChildren);
writer.WriteEndElement();
writer.WriteEndDocument();
}
Assert.That(output.ToString(), Is.EqualTo(expectedOutput));
}
[Test]
public void GetMandatoryIntegerAttributeValue_OfElement_ReturnsInteger()
{
var element = new XElement("element");
var attr = new XAttribute("intAttr", 1);
element.Add(attr);
Assert.AreEqual(1, XmlUtils.GetMandatoryIntegerAttributeValue(element, "intAttr"));
}
[Test]
public void GetMandatoryIntegerAttributeValue_OfElement_Throws_If_Attr_Not_Present()
{
Assert.Throws<ApplicationException>(() => XmlUtils.GetMandatoryIntegerAttributeValue(new XElement("element"), "intAttr"));
}
[Test]
public void GetMandatoryIntegerAttributeValue_OfElement_Throws_If_Not_Integer()
{
Assert.Throws<FormatException>(() => XmlUtils.GetMandatoryIntegerAttributeValue(new XElement("element", new XAttribute("intAttr", "Not_Int")), "intAttr"));
}
[Test]
public void GetOptionalIntegerValue_OfElement_Returns_Default_Value()
{
Assert. AreEqual(1, XmlUtils.GetOptionalIntegerValue(new XElement("element"), "intAttr", 1));
}
[Test]
public void GetOptionalIntegerValue_OfElement_Ignores_Default_Value_When_Attr_Present()
{
Assert.AreEqual(2, XmlUtils.GetOptionalIntegerValue(new XElement("element", new XAttribute("intAttr", "2")), "intAttr", 1));
}
[Test]
public void GetOptionalIntegerValue_OfElement_Throws_If_Not_Integer()
{
Assert.Throws<FormatException>(() => XmlUtils.GetOptionalIntegerValue(new XElement("element", new XAttribute("intAttr", "Not_Int")), "intAttr", 1));
}
[TestCase(null, "Null should return false")]
[TestCase("", "Empty string should return false")]
[TestCase(" ", "Whitespace only string should return false")]
[TestCase("FALSE", "'FALSE' should return false")]
[TestCase("False", "'False' should return false")]
[TestCase("false", "'false' should return false")]
[TestCase("NO", "'NO' should return false")]
[TestCase("No", "'No' should return false")]
[TestCase("no", "'no' should return false")]
public void GetBooleanAttributeValue_Returns_False(string input, string errorMessage)
{
// Test overload that takes just the attribute's value
Assert.IsFalse(XmlUtils.GetBooleanAttributeValue(input), errorMessage);
// Test overload that takes the element and attr name.
var element = new XElement("element");
if (input != null)
{
var attr = new XAttribute("boolAttr", input);
element.Add(attr);
}
Assert.IsFalse(XmlUtils.GetBooleanAttributeValue(element, "boolAttr"), errorMessage);
}
[TestCase("TRUE", "'TRUE' should return true")]
[TestCase("True", "'True' should return true")]
[TestCase("true", "'true' should return true")]
[TestCase("YES", "'YES' should return true")]
[TestCase("Yes", "'Yes' should return true")]
[TestCase("yes", "'yes' should return true")]
public void GetBooleanAttributeValue_Returns_True(string input, string errorMessage)
{
// Test overload that takes just the attribute's value
Assert.IsTrue(XmlUtils.GetBooleanAttributeValue(input), errorMessage);
// Test overload that takes the element and attr name.
var element = new XElement("element", new XAttribute("boolAttr", input));
Assert.IsTrue(XmlUtils.GetBooleanAttributeValue(element, "boolAttr"), errorMessage);
}
[TestCase(false, true /* not used */, true, "No attr should return default of true")]
[TestCase(false, true /* not used */, false, "No attr should return default of false")]
[TestCase(true, true, false, "Has attr should not return default of false")]
[TestCase(true, false, true, "Has attr should not return default of true")]
public void GetOptionalBooleanAttributeValue(bool hasAttr, bool actualValue, bool defaultValue, string errorMessage)
{
bool expectedValue;
var element = new XElement("element");
if (hasAttr)
{
element.Add(new XAttribute("boolAttr", actualValue));
expectedValue = actualValue;
}
else
{
// Don't add attr, but expect the call to use the default value.
expectedValue = defaultValue;
}
Assert.AreEqual(expectedValue, XmlUtils.GetOptionalBooleanAttributeValue(element, "boolAttr", defaultValue), errorMessage);
}
[TestCase(false, "NotUsedValue" /* not used */, "DefaultValue", "No attr should return default of 'DefaultValue'")]
[TestCase(true, "RealValue", "DefaultValue", "Has attr should not return default of 'DefaultValue'")]
public void GetOptionalAttributeValue_Using_Default(bool hasAttr, string actualValue, string defaultValue, string errorMessage)
{
string expectedValue;
var element = new XElement("element");
if (hasAttr)
{
element.Add(new XAttribute("attr", actualValue));
expectedValue = actualValue;
}
else
{
// Don't add attr, but expect the call to use the default value.
expectedValue = defaultValue;
}
Assert.AreEqual(expectedValue, XmlUtils.GetOptionalAttributeValue(element, "attr", expectedValue), errorMessage);
}
[TestCase(false, "NotUsedValue" /* not used */, "No attr should return default of 'DefaultValue'")]
[TestCase(true, "RealValue", "Has attr should not return default of 'DefaultValue'")]
public void GetOptionalAttributeValue_Without_Using_Default(bool hasAttr, string actualValue, string errorMessage)
{
string expectedValue;
var element = new XElement("element");
if (hasAttr)
{
element.Add(new XAttribute("attr", actualValue));
expectedValue = actualValue;
}
else
{
// Don't add attr, but expect the call to use the default value.
expectedValue = null;
}
Assert.AreEqual(expectedValue, XmlUtils.GetOptionalAttributeValue(element, "attr"), errorMessage);
}
[TestCase("-1,1,2", "'-1,1,2' should return three integers in the array", "Expected order in array is: '-1,1,2'")]
[TestCase("1,2", "'1,2' should return two integers in the array", "Expected order in array is: '1,2'")]
[TestCase("2,1", "'2,1' should return two integers in the array", "Expected order in array is: '2,1'")]
public void GetMandatoryIntegerListAttributeValue_Has_Correct_List(string sourceAttrData, string errorMessageCount, string errorMessageOrder)
{
var element = new XElement("element", new XAttribute("intArray", sourceAttrData));
var resultArray = XmlUtils.GetMandatoryIntegerListAttributeValue(element, "intArray");
var sourceArray = sourceAttrData.Split(',');
Assert.AreEqual(sourceArray.Length, resultArray.Length, errorMessageCount);
for (var idx = 0; idx < sourceArray.Length; idx++)
{
Assert.AreEqual(int.Parse(sourceArray[idx], CultureInfo.InvariantCulture), resultArray[idx], errorMessageOrder);
}
}
[TestCase("1,2", "'1,2' should return two integers in the array", "Expected order in array is: '1,2'")]
[TestCase("2,1", "'2,1' should return two integers in the array", "Expected order in array is: '2,1'")]
public void GetMandatoryUIntegerListAttributeValue_Has_Correct_List(string sourceAttrData, string errorMessageCount, string errorMessageOrder)
{
var element = new XElement("element", new XAttribute("intArray", sourceAttrData));
var resultArray = XmlUtils.GetMandatoryUIntegerListAttributeValue(element, "intArray");
var sourceArray = sourceAttrData.Split(',');
Assert.AreEqual(sourceArray.Length, resultArray.Length, errorMessageCount);
for (var idx = 0; idx < sourceArray.Length; idx++)
{
Assert.AreEqual(uint.Parse(sourceArray[idx], CultureInfo.InvariantCulture), resultArray[idx], errorMessageOrder);
}
}
[Test]
public void MakeStringFromList_For_int()
{
Assert.AreEqual("1,2,3", XmlUtils.MakeStringFromList(new List<int>() { 1, 2, 3 }));
}
[Test]
public void MakeStringFromList_For_uint()
{
Assert.AreEqual("1,2,3", XmlUtils.MakeStringFromList(new List<uint>() { 1, 2, 3 }));
}
[Test]
public void DecodeXmlAttributeTest()
{
string sFixed = XmlUtils.DecodeXmlAttribute("abc&def<ghi>jkl"mno'pqr&stu");
Assert.AreEqual("abc&def<ghi>jkl\"mno'pqr&stu", sFixed, "First Test of DecodeXmlAttribute");
sFixed = XmlUtils.DecodeXmlAttribute("abc&def
ghijklŸmno");
Assert.AreEqual("abc&def\r\nghi\u001Fjkl\u007F\u009Fmno", sFixed, "Second Test of DecodeXmlAttribute");
}
[Test]
public void FindElement_For_XElements()
{
var grandfather = new XElement("grandfather");
var father = new XElement("father");
grandfather.Add(father);
var me = new XElement("me");
father.Add(me);
Assert.AreSame(grandfather, XmlUtils.FindElement(grandfather, "grandfather"));
Assert.AreSame(father, XmlUtils.FindElement(grandfather, "father"));
Assert.AreSame(me, XmlUtils.FindElement(grandfather, "me"));
}
[Test]
public void FindNode_For_XmlNodes()
{
var dom = new XmlDocument();
var root = dom.CreateElement("familyTree");
dom.AppendChild(root);
var grandfather = dom.CreateElement("grandfather");
root.AppendChild(grandfather);
var father = dom.CreateElement("father");
grandfather.AppendChild(father);
var me = dom.CreateElement("me");
father.AppendChild(me);
Assert.AreSame(grandfather, XmlUtils.FindNode(grandfather, "grandfather"));
Assert.AreSame(father, XmlUtils.FindNode(grandfather, "father"));
Assert.AreSame(me, XmlUtils.FindNode(grandfather, "me"));
}
[Test]
public void FindIndexOfMatchingNode()
{
var threeStooges = new List<XElement>
{
new XElement("Larry"),
new XElement("Moe"),
new XElement("Curly")
};
var target = new XElement("Moe");
// Moe is in the list.
Assert.AreEqual(1, XmlUtils.FindIndexOfMatchingNode(threeStooges, target));
// This one is not in the list.
Assert.AreEqual(-1, XmlUtils.FindIndexOfMatchingNode(threeStooges, new XElement("Flopsie")));
}
[Test]
public void SetAttribute_AddNewAttr()
{
var element = new XElement("element");
XmlUtils.SetAttribute(element, "newAttr", "newAttrValue");
Assert.IsNotNull(element.Attribute("newAttr"));
Assert.AreEqual("newAttrValue", element.Attribute("newAttr").Value);
}
[Test]
public void SetAttribute_ChangeAttrValue()
{
var element = new XElement("element", new XAttribute("oldAttr", "oldAttrValue"));
XmlUtils.SetAttribute(element, "oldAttr", "newAttrValue");
Assert.AreEqual("newAttrValue", element.Attribute("oldAttr").Value);
}
[Test]
public void SetAttribute_SameAttrValue()
{
var element = new XElement("element", new XAttribute("oldAttr", "oldAttrValue"));
XmlUtils.SetAttribute(element, "oldAttr", "oldAttrValue");
Assert.AreEqual("oldAttrValue", element.Attribute("oldAttr").Value);
}
}
}
| |
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Globalization;
namespace WebApplication2
{
/// <summary>
/// Summary description for frmResourcesInfo.
/// </summary>
public partial class frmOrgLocServices: System.Web.UI.Page
{
/*SqlConnection epsDbConn=new SqlConnection("Server=cp2693-a\\eps1;database=eps1;"+
"uid=tauheed;pwd=tauheed;");*/
private static string strURL =
System.Configuration.ConfigurationSettings.AppSettings["local_url"];
private static string strDB =
System.Configuration.ConfigurationSettings.AppSettings["local_db"];
public SqlConnection epsDbConn=new SqlConnection(strDB);
int LocFlag = 0;
protected void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
lblOrg.Text=Session["OrgName"].ToString();
if (Session["MgrOption"] == "Budget")
{
lblContents1.Text="Given below is a list of services delivered by the above organization"
+ " from the above location. You may provide a budget for the service as a whole "
+ " and/or for individual tasks undertaken as part of a given service.";
DataGrid1.Columns[4].Visible = false;
DataGrid2.Visible = false;
}
else if (Session["MgrOption"] == "Plan")
{
//DataGrid2.Columns[4].Visible=false;
DataGrid1.Visible = false;
}
if (!IsPostBack)
{
loadLocations();
setLoc();
/* LoadLocs *********************/
if (LocFlag == 1)
{
lblLoc.Visible = false;
btnLoc.Visible = false;
}
/* LoadLocs *********************/
if (Session["MgrOption"].ToString() == "Budget")
{
lblBd.Text = "Budget: " + Session["BudName"].ToString() + " - "
+ Session["CurrName"].ToString();
}
/*else
{
setBudget();
}*/
btnAdd.Text = "Show All Services";
loadData();
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.DataGrid1.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.DataGrid1_ItemCommand);
}
#endregion
/*private void loadBudgets()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = this.epsDbConn;
cmd.CommandText = "fms_RetrieveBudOrgs";
cmd.Parameters.Add("@OrgId", SqlDbType.Int);
cmd.Parameters["@OrgId"].Value = Session["OrgId"].ToString();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "Budgets");
lstBd.DataSource = ds;
lstBd.DataMember = "Budgets";
lstBd.DataTextField = "Name";
lstBd.DataValueField = "Id";
lstBd.DataBind();
//lstBudgets.SelectedIndex = GetIndexOfBudgets(ds.Tables["StaffAction"].Rows[0][13].ToString());
}
private int GetIndexOfBudgets(string s)
{
return (lstBd.Items.IndexOf(lstBd.Items.FindByValue(s)));
}*/
private void loadLocations()
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = this.epsDbConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "wms_RetrieveLocations";
cmd.Parameters.Add("@OrgId", SqlDbType.Int);
cmd.Parameters["@OrgId"].Value = Session["OrgId"].ToString();
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "Locations");
if (ds.Tables["Locations"].Rows.Count == 1)
{
LocFlag = 1;
}
lstLoc.DataSource = ds;
lstLoc.DataMember = "Locations";
lstLoc.DataTextField = "Name";
lstLoc.DataValueField = "Id";
lstLoc.DataBind();
}
private void loadData()
{
if (Session["MgrOption"] == "Plan")
{
loadDataP();
}
else if (Session["MgrOption"] == "Budget")
{
loadDataB();
}
}
private void loadDataP()
{
SqlCommand cmd=new SqlCommand();
cmd.CommandType=CommandType.StoredProcedure;
cmd.Connection=this.epsDbConn;
cmd.CommandText = "wms_RetrieveOrgServiceTypes";
cmd.Parameters.Add ("@EPSFlag",SqlDbType.Int);
cmd.Parameters["@EPSFlag"].Value=Int32.Parse(Session["EPS"].ToString());
cmd.Parameters.Add("@OrgId", SqlDbType.Int);
cmd.Parameters["@OrgId"].Value = Int32.Parse(Session["OrgId"].ToString());
DataSet ds=new DataSet();
SqlDataAdapter da=new SqlDataAdapter(cmd);
da.Fill(ds,"LocServices");
if (ds.Tables["LocServices"].Rows.Count == 0)
{
DataGrid2.Visible = false;
/* LoadLocs *********************/
btnLoc.Visible = false;
/* LoadLocs *********************/
lblContents1.Text = "Sorry. There are no existing services identified for this profile."
+ " Press 'Signoff' and contact your system administrator.";
}
else
{
lblContents1.Text = "Given below is a list of services delivered by your organization"
+ " from the above location. Click on 'Select' to enter planned inputs"
+ " and other details related to a given service. If possible at this stage, please"
+ " have identify the budget that will be charged for planned inputs"
+ " by clicking on the appropriate button above and selecting the"
+ " appropriate item from the list that will then appear. Do the same for location above.";
Session["ds"] = ds;
DataGrid2.DataSource = ds;
DataGrid2.DataBind();
refreshGridP();
/* LoadLocs *********************/
if (ds.Tables["LocServices"].Rows.Count == 1)
{
btnLoc.Visible = false;
}
/* LoadLocs *********************/
}
}
private void loadDataB()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = this.epsDbConn;
cmd.CommandText = "wms_RetrieveBudOLServiceTypes";
cmd.Parameters.Add("@EPSFlag", SqlDbType.Int);
cmd.Parameters["@EPSFlag"].Value = Int32.Parse(Session["EPS"].ToString());
cmd.Parameters.Add("@BudOrgsId", SqlDbType.Int);
cmd.Parameters["@BudOrgsId"].Value = Int32.Parse(Session["BDOId"].ToString());
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "LocServices");
if (ds.Tables["LocServices"].Rows.Count == 0)
{
DataGrid1.Visible = false;
btnLoc.Visible = false;
lblContents1.Text = "Sorry. There are no existing services identified for this profile."
+ " Press 'Signoff' and contact your system administrator.";
}
Session["ds"] = ds;
DataGrid1.DataSource = ds;
DataGrid1.DataBind();
refreshGridB();
}
/*private void loadBudget()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = this.epsDbConn;
cmd.CommandText = "wms_RetrieveOrgLocServiceTypes";
cmd.Parameters.Add("@OrgLocId", SqlDbType.Int);
cmd.Parameters["@OrgLocId"].Value = Session["OrgLocId"].ToString();
//cmd.Parameters.Add("@BudgetsId", SqlDbType.Int);
//cmd.Parameters["@BudgetsId"].Value = Session["BudgetsId"].ToString();
cmd.Parameters.Add("@EPSFlag", SqlDbType.Int);
cmd.Parameters["@EPSFlag"].Value = Int32.Parse(Session["EPS"].ToString());
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "LocServices");
if (ds.Tables["LocServices"].Rows.Count == 0)
{
DataGrid2.Visible = false;
lblContents1.Text = "Sorry. There are no existing services identified for this profile."
+ " Press 'Signoff' and contact your system administrator.";
}
Session["ds"] = ds;
DataGrid2.DataSource = ds;
DataGrid2.DataBind();
loadBudget();
refreshGrid();
}*/
private void refreshGridB()
{
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tb = (TextBox)(i.Cells[2].FindControl("txtBud"));
Button btp = (Button)(i.Cells[3].FindControl("btnProjects"));
Button btn = (Button)(i.Cells[3].FindControl("btnProcess"));
btp.Text = i.Cells[8].Text;
btn.Text = "Ongoing Tasks";
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = this.epsDbConn;
cmd.CommandText = "wms_RetrieveBudOLServices";
cmd.Parameters.Add("@LocationsId", SqlDbType.Int);
cmd.Parameters["@LocationsId"].Value = Int32.Parse(Session["LocationsId"].ToString());
cmd.Parameters.Add("@BudOrgsId", SqlDbType.Int);
cmd.Parameters["@BudOrgsId"].Value = Int32.Parse(Session["BDOId"].ToString());
cmd.Parameters.Add("@ServiceTypesId", SqlDbType.Int);
cmd.Parameters["@ServiceTypesId"].Value = Int32.Parse(i.Cells[0].Text);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds, "ServiceBudget");
if (ds.Tables["ServiceBudget"].Rows.Count > 0)
{
i.Cells[10].Text = ds.Tables["ServiceBudget"].Rows[0][1].ToString();
i.Cells[11].Text = ds.Tables["ServiceBudget"].Rows[0][0].ToString();
}
if (i.Cells[10].Text == " ")
{
tb.Text = null;
}
else
{
tb.Text = i.Cells[10].Text;
}
}
}
private void refreshGridP()
{
foreach (DataGridItem i in DataGrid2.Items)
{
Button btp = (Button)(i.Cells[2].FindControl("btnProjects"));
btp.Text = "Select";
//btp.Text = i.Cells[6].Text;
}
}
protected void btnExit_Click(object sender, System.EventArgs e)
{
updateBudAmt();
Response.Redirect (strURL + Session["COrgLocServices"].ToString() + ".aspx?");
}
private void updateBudAmt()
{
foreach (DataGridItem i in DataGrid1.Items)
{
TextBox tb = (TextBox)(i.Cells[2].FindControl("txtBud"));
{
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "fms_UpdateBudOLServiceAmt";
cmd.Connection = this.epsDbConn;
cmd.Parameters.Add("@BudAmt", SqlDbType.Decimal);
if (tb.Text != "")
{
cmd.Parameters["@BudAmt"].Value = decimal.Parse(tb.Text, NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands);
}
if (i.Cells[11].Text != " ")
{
cmd.Parameters.Add("@Id", SqlDbType.Int);
cmd.Parameters["@Id"].Value = Int32.Parse(i.Cells[11].Text);
}
else
{
cmd.Parameters.Add("@ServiceTypesId", SqlDbType.Int);
cmd.Parameters["@ServiceTypesId"].Value = Int32.Parse(i.Cells[0].Text);
cmd.Parameters.Add("@LocationsId", SqlDbType.Int);
cmd.Parameters["@LocationsId"].Value = Int32.Parse(Session["LocationsId"].ToString());
cmd.Parameters.Add("@BudOrgsId", SqlDbType.Int);
cmd.Parameters["@BudOrgsId"].Value = Int32.Parse(Session["BDOId"].ToString());
}
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
}
private void DataGrid1_ItemCommand(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e)
{
updateBudAmt();
Session["ProfileServicesId"]=e.Item.Cells[7].Text;
Session["ServiceName"]=e.Item.Cells[1].Text;
if (e.CommandName == "Procs")
{
Session["COrgLocSEProcs"]="frmOrgLocServices";
Session["PRS"]="0";
Response.Redirect (strURL + "frmOrgLocSEProcs.aspx?");
}
else if (e.CommandName == "Projects")
{
Session["PJName"]=e.Item.Cells[8].Text;
Session["PJNameS"]=e.Item.Cells[9].Text;
Session["BudOLServicesId"]=e.Item.Cells[11].Text;
Session["PRS"] = "1";
Session["CProjects"] = "frmOrgLocServices";
Response.Redirect(strURL + "frmProjects.aspx?");
}
else if (e.CommandName == "Remove")
{
/*SqlCommand cmd = new SqlCommand();
cmd.Connection = this.epsDbConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "wms_AddOrgLocServiceTypes";
//services are added since these services will be excluded from datagrid in method loadData.
cmd.Parameters.Add ("@OrgLocId",SqlDbType.Int);
cmd.Parameters["@OrgLocId"].Value=Session["OrgLocId"].ToString();
cmd.Parameters.Add ("@ServiceTypesId",SqlDbType.Int);
cmd.Parameters["@ServiceTypesId"].Value=e.Item.Cells[0].Text;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
//refreshGrid();*/
}
}
protected void btnAdd_Click(object sender, System.EventArgs e)
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = this.epsDbConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "wms_DeleteOrgLocServices";
cmd.Parameters.Add ("@OrgLocId",SqlDbType.Int);
cmd.Parameters["@OrgLocId"].Value=Session["OrgLocId"].ToString();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
protected void DataGrid2_ItemCommand(object source, DataGridCommandEventArgs e)
{
Session["ProfileServicesId"] = e.Item.Cells[5].Text;
Session["ServiceName"] = e.Item.Cells[1].Text;
if (e.CommandName == "Procs")
{
Session["COrgLocSEProcs"] = "frmOrgLocServices";
Session["PRS"] = "0";
Response.Redirect(strURL + "frmOrgLocSEProcs.aspx?");
}
else if (e.CommandName == "Projects")
{
Session["PJName"] = e.Item.Cells[6].Text;
Session["PJNameS"] = e.Item.Cells[7].Text;
Session["PRS"] = "1";
Session["CPSE"] = "frmOrgLocServices";
Response.Redirect(strURL + "frmPSEvents.aspx?");
}
else if (e.CommandName == "Remove")
{
SqlCommand cmd = new SqlCommand();
cmd.Connection = this.epsDbConn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "wms_AddOrgLocServiceTypes";
//services are added since these services will be excluded from datagrid in method loadData.
cmd.Parameters.Add("@OrgLocId", SqlDbType.Int);
cmd.Parameters["@OrgLocId"].Value = Session["OrgLocId"].ToString();
cmd.Parameters.Add("@ServiceTypesId", SqlDbType.Int);
cmd.Parameters["@ServiceTypesId"].Value = e.Item.Cells[0].Text;
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
loadData();
}
}
/* LoadLocs *********************/
protected void btnLoc_Click(object sender, EventArgs e)
{
lblLoc.Visible = false;
lblLocC.Visible = true;
btnLoc.Visible = false;
lstLoc.Visible = true;
}
protected void lstLoc_SelectedIndexChanged(object sender, EventArgs e)
{
if (Session["MgrOption"] == "Plan")
{
setLoc();
loadDataP();
}
else if (Session["MgrOption"] == "Budget")
{
updateBudAmt();
setLoc();
loadDataB();
}
lblLoc.Visible = true;
lblLocC.Visible = false;
btnLoc.Visible = true;
lstLoc.Visible = false;
}
private void setLoc()
{
Session["LocName"] = lstLoc.SelectedItem;
Session["LocationsId"] = lstLoc.SelectedValue;
lblLoc.Text = "Location: " + Session["LocName"].ToString();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
class Program
{
public const int Pass = 100;
public const int Fail = -1;
static int Main()
{
SimpleReadWriteThreadStaticTest.Run(42, "SimpleReadWriteThreadStatic");
// TODO: After issue https://github.com/dotnet/corert/issues/2695 is fixed, move FinalizeTest to run at the end
if (FinalizeTest.Run() != Pass)
return Fail;
ThreadStaticsTestWithTasks.Run();
if (ThreadTest.Run() != Pass)
return Fail;
return Pass;
}
}
class FinalizeTest
{
public static bool visited = false;
public class Dummy
{
~Dummy()
{
FinalizeTest.visited = true;
}
}
public static int Run()
{
int iterationCount = 0;
while (!visited && iterationCount++ < 10000)
{
GC.KeepAlive(new Dummy());
GC.Collect();
}
if (visited)
{
Console.WriteLine("FinalizeTest passed");
return Program.Pass;
}
else
{
Console.WriteLine("FinalizeTest failed");
return Program.Fail;
}
}
}
class SimpleReadWriteThreadStaticTest
{
public static void Run(int intValue, string stringValue)
{
NonGenericReadWriteThreadStaticsTest(intValue, "NonGeneric" + stringValue);
GenericReadWriteThreadStaticsTest(intValue + 1, "Generic" + stringValue);
}
class NonGenericType
{
[ThreadStatic]
public static int IntValue;
[ThreadStatic]
public static string StringValue;
}
class GenericType<T, V>
{
[ThreadStatic]
public static T ValueT;
[ThreadStatic]
public static V ValueV;
}
static void NonGenericReadWriteThreadStaticsTest(int intValue, string stringValue)
{
NonGenericType.IntValue = intValue;
NonGenericType.StringValue = stringValue;
if (NonGenericType.IntValue != intValue)
{
throw new Exception("SimpleReadWriteThreadStaticsTest: wrong integer value: " + NonGenericType.IntValue.ToString());
}
if (NonGenericType.StringValue != stringValue)
{
throw new Exception("SimpleReadWriteThreadStaticsTest: wrong string value: " + NonGenericType.StringValue);
}
}
static void GenericReadWriteThreadStaticsTest(int intValue, string stringValue)
{
GenericType<int, string>.ValueT = intValue;
GenericType<int, string>.ValueV = stringValue;
if (GenericType<int, string>.ValueT != intValue)
{
throw new Exception("GenericReadWriteThreadStaticsTest1a: wrong integer value: " + GenericType<int, string>.ValueT.ToString());
}
if (GenericType<int, string>.ValueV != stringValue)
{
throw new Exception("GenericReadWriteThreadStaticsTest1b: wrong string value: " + GenericType<int, string>.ValueV);
}
intValue++;
GenericType<int, int>.ValueT = intValue;
GenericType<int, int>.ValueV = intValue + 1;
if (GenericType<int, int>.ValueT != intValue)
{
throw new Exception("GenericReadWriteThreadStaticsTest2a: wrong integer value: " + GenericType<int, string>.ValueT.ToString());
}
if (GenericType<int, int>.ValueV != (intValue + 1))
{
throw new Exception("GenericReadWriteThreadStaticsTest2b: wrong integer value: " + GenericType<int, string>.ValueV.ToString());
}
GenericType<string, string>.ValueT = stringValue + "a";
GenericType<string, string>.ValueV = stringValue + "b";
if (GenericType<string, string>.ValueT != (stringValue + "a"))
{
throw new Exception("GenericReadWriteThreadStaticsTest3a: wrong string value: " + GenericType<string, string>.ValueT);
}
if (GenericType<string, string>.ValueV != (stringValue + "b"))
{
throw new Exception("GenericReadWriteThreadStaticsTest3b: wrong string value: " + GenericType<string, string>.ValueV);
}
}
}
class ThreadStaticsTestWithTasks
{
static object lockObject = new object();
const int TotalTaskCount = 32;
public static void Run()
{
Task[] tasks = new Task[TotalTaskCount];
for (int i = 0; i < tasks.Length; ++i)
{
tasks[i] = Task.Factory.StartNew((param) =>
{
int index = (int)param;
int intTestValue = index * 10;
string stringTestValue = "ThreadStaticsTestWithTasks" + index;
// Try to run the on every other task
if ((index % 2) == 0)
{
lock (lockObject)
{
SimpleReadWriteThreadStaticTest.Run(intTestValue, stringTestValue);
}
}
else
{
SimpleReadWriteThreadStaticTest.Run(intTestValue, stringTestValue);
}
}, i);
}
for (int i = 0; i < tasks.Length; ++i)
{
tasks[i].Wait();
}
}
}
class ThreadTest
{
private static readonly List<Thread> s_startedThreads = new List<Thread>();
private static int s_passed;
private static int s_failed;
private static void Expect(bool condition, string message)
{
if (condition)
{
Interlocked.Increment(ref s_passed);
}
else
{
Interlocked.Increment(ref s_failed);
Console.WriteLine("ERROR: " + message);
}
}
private static void ExpectException<T>(Action action, string message)
{
Exception ex = null;
try
{
action();
}
catch (Exception e)
{
ex = e;
}
if (!(ex is T))
{
message += string.Format(" (caught {0})", (ex == null) ? "no exception" : ex.GetType().Name);
}
Expect(ex is T, message);
}
private static void ExpectPassed(string testName, int expectedPassed)
{
// Wait for all started threads to finish execution
foreach (Thread t in s_startedThreads)
{
t.Join();
}
s_startedThreads.Clear();
Expect(s_passed == expectedPassed, string.Format("{0}: Expected s_passed == {1}, got {2}", testName, expectedPassed, s_passed));
s_passed = 0;
}
private static void TestStartMethod()
{
// Case 1: new Thread(ThreadStart).Start()
var t1 = new Thread(() => Expect(true, "Expected t1 to start"));
t1.Start();
s_startedThreads.Add(t1);
// Case 2: new Thread(ThreadStart).Start(parameter)
var t2 = new Thread(() => Expect(false, "This thread must not be started"));
// InvalidOperationException: The thread was created with a ThreadStart delegate that does not accept a parameter.
ExpectException<InvalidOperationException>(() => t2.Start(null), "Expected InvalidOperationException for t2.Start()");
// Case 3: new Thread(ParameterizedThreadStart).Start()
var t3 = new Thread(obj => Expect(obj == null, "Expected obj == null"));
t3.Start();
s_startedThreads.Add(t3);
// Case 4: new Thread(ParameterizedThreadStart).Start(parameter)
var t4 = new Thread(obj => Expect((int)obj == 42, "Expected (int)obj == 42"));
t4.Start(42);
s_startedThreads.Add(t4);
// Start an unstarted resurrected thread.
// CoreCLR: ThreadStateException, CoreRT: no exception.
Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected();
unstartedResurrected.Start();
s_startedThreads.Add(unstartedResurrected);
// Threads cannot started more than once
t1.Join();
ExpectException<ThreadStateException>(() => t1.Start(), "Expected ThreadStateException for t1.Start()");
ExpectException<ThreadStateException>(() => Thread.CurrentThread.Start(),
"Expected ThreadStateException for CurrentThread.Start()");
Thread stoppedResurrected = Resurrector.CreateStoppedResurrected();
ExpectException<ThreadStateException>(() => stoppedResurrected.Start(),
"Expected ThreadStateException for stoppedResurrected.Start()");
ExpectPassed(nameof(TestStartMethod), 7);
}
private static void TestJoinMethod()
{
var t = new Thread(() => { });
ExpectException<InvalidOperationException>(() => t.Start(null), "Expected InvalidOperationException for t.Start()");
ExpectException<ThreadStateException>(() => t.Join(), "Expected ThreadStateException for t.Join()");
Thread stoppedResurrected = Resurrector.CreateStoppedResurrected();
Expect(stoppedResurrected.Join(1), "Expected stoppedResurrected.Join(1) to return true");
Expect(!Thread.CurrentThread.Join(1), "Expected CurrentThread.Join(1) to return false");
ExpectPassed(nameof(TestJoinMethod), 4);
}
private static void TestCurrentThreadProperty()
{
Thread t = null;
t = new Thread(() => Expect(Thread.CurrentThread == t, "Expected CurrentThread == t on thread t"));
t.Start();
s_startedThreads.Add(t);
Expect(Thread.CurrentThread != t, "Expected CurrentThread != t on main thread");
ExpectPassed(nameof(TestCurrentThreadProperty), 2);
}
private static void TestNameProperty()
{
var t = new Thread(() => { });
t.Name = null;
// It is OK to set the null Name multiple times
t.Name = null;
Expect(t.Name == null, "Expected t.Name == null");
const string ThreadName = "My thread";
t.Name = ThreadName;
Expect(t.Name == ThreadName, string.Format("Expected t.Name == \"{0}\"", ThreadName));
ExpectException<InvalidOperationException>(() => { t.Name = null; },
"Expected InvalidOperationException setting Thread.Name back to null");
ExpectPassed(nameof(TestNameProperty), 3);
}
private static void TestIsBackgroundProperty()
{
// Thread created using Thread.Start
var t_event = new AutoResetEvent(false);
var t = new Thread(() => t_event.WaitOne());
t.Start();
s_startedThreads.Add(t);
Expect(!t.IsBackground, "Expected t.IsBackground == false");
t_event.Set();
t.Join();
ExpectException<ThreadStateException>(() => Console.WriteLine(t.IsBackground),
"Expected ThreadStateException for t.IsBackground");
// Thread pool thread
Task.Factory.StartNew(() => Expect(Thread.CurrentThread.IsBackground, "Expected IsBackground == true")).Wait();
// Resurrected threads
Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected();
Expect(unstartedResurrected.IsBackground == false, "Expected unstartedResurrected.IsBackground == false");
Thread stoppedResurrected = Resurrector.CreateStoppedResurrected();
ExpectException<ThreadStateException>(() => Console.WriteLine(stoppedResurrected.IsBackground),
"Expected ThreadStateException for stoppedResurrected.IsBackground");
// Main thread
Expect(!Thread.CurrentThread.IsBackground, "Expected CurrentThread.IsBackground == false");
ExpectPassed(nameof(TestIsBackgroundProperty), 6);
}
private static void TestIsThreadPoolThreadProperty()
{
#if false // The IsThreadPoolThread property is not in the contract version we compile against at present
var t = new Thread(() => { });
Expect(!t.IsThreadPoolThread, "Expected t.IsThreadPoolThread == false");
Task.Factory.StartNew(() => Expect(Thread.CurrentThread.IsThreadPoolThread, "Expected IsThreadPoolThread == true")).Wait();
Expect(!Thread.CurrentThread.IsThreadPoolThread, "Expected CurrentThread.IsThreadPoolThread == false");
ExpectPassed(nameof(TestIsThreadPoolThreadProperty), 3);
#endif
}
private static void TestManagedThreadIdProperty()
{
int t_id = 0;
var t = new Thread(() => {
Expect(Thread.CurrentThread.ManagedThreadId == t_id, "Expected CurrentTread.ManagedThreadId == t_id on thread t");
Expect(Environment.CurrentManagedThreadId == t_id, "Expected Environment.CurrentManagedThreadId == t_id on thread t");
});
t_id = t.ManagedThreadId;
Expect(t_id != 0, "Expected t_id != 0");
Expect(Thread.CurrentThread.ManagedThreadId != t_id, "Expected CurrentTread.ManagedThreadId != t_id on main thread");
Expect(Environment.CurrentManagedThreadId != t_id, "Expected Environment.CurrentManagedThreadId != t_id on main thread");
t.Start();
s_startedThreads.Add(t);
// Resurrected threads
Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected();
Expect(unstartedResurrected.ManagedThreadId != 0, "Expected unstartedResurrected.ManagedThreadId != 0");
Thread stoppedResurrected = Resurrector.CreateStoppedResurrected();
Expect(stoppedResurrected.ManagedThreadId != 0, "Expected stoppedResurrected.ManagedThreadId != 0");
ExpectPassed(nameof(TestManagedThreadIdProperty), 7);
}
private static void TestThreadStateProperty()
{
var t_event = new AutoResetEvent(false);
var t = new Thread(() => t_event.WaitOne());
Expect(t.ThreadState == ThreadState.Unstarted, "Expected t.ThreadState == ThreadState.Unstarted");
t.Start();
s_startedThreads.Add(t);
Expect(t.ThreadState == ThreadState.Running || t.ThreadState == ThreadState.WaitSleepJoin,
"Expected t.ThreadState is either ThreadState.Running or ThreadState.WaitSleepJoin");
t_event.Set();
t.Join();
Expect(t.ThreadState == ThreadState.Stopped, "Expected t.ThreadState == ThreadState.Stopped");
// Resurrected threads
Thread unstartedResurrected = Resurrector.CreateUnstartedResurrected();
Expect(unstartedResurrected.ThreadState == ThreadState.Unstarted,
"Expected unstartedResurrected.ThreadState == ThreadState.Unstarted");
Thread stoppedResurrected = Resurrector.CreateStoppedResurrected();
Expect(stoppedResurrected.ThreadState == ThreadState.Stopped,
"Expected stoppedResurrected.ThreadState == ThreadState.Stopped");
ExpectPassed(nameof(TestThreadStateProperty), 5);
}
private static unsafe void DoStackAlloc(int size)
{
byte* buffer = stackalloc byte[size];
Volatile.Write(ref buffer[0], 0);
}
private static void TestMaxStackSize()
{
#if false // The constructors with maxStackSize are not in the contract version we compile against at present
// Allocate a 3 MiB buffer on the 4 MiB stack
var t = new Thread(() => DoStackAlloc(3 << 20), 4 << 20);
t.Start();
s_startedThreads.Add(t);
#endif
ExpectPassed(nameof(TestMaxStackSize), 0);
}
static int s_startedThreadCount = 0;
private static void TestStartShutdown()
{
Thread[] threads = new Thread[2048];
// Creating a large number of threads
for (int i = 0; i < threads.Length; i++)
{
threads[i] = new Thread(() => { Interlocked.Increment(ref s_startedThreadCount); });
threads[i].Start();
}
// Wait for all threads to shutdown;
for (int i = 0; i < threads.Length; i++)
{
threads[i].Join();
}
Expect(s_startedThreadCount == threads.Length,
String.Format("Not all threads completed. Expected: {0}, Actual: {1}", threads.Length, s_startedThreadCount));
}
public static int Run()
{
TestStartMethod();
TestJoinMethod();
TestCurrentThreadProperty();
TestNameProperty();
TestIsBackgroundProperty();
TestIsThreadPoolThreadProperty();
TestManagedThreadIdProperty();
TestThreadStateProperty();
TestMaxStackSize();
TestStartShutdown();
return (s_failed == 0) ? Program.Pass : Program.Fail;
}
/// <summary>
/// Creates resurrected Thread objects.
/// </summary>
class Resurrector
{
static Thread s_unstartedResurrected;
static Thread s_stoppedResurrected;
bool _unstarted;
Thread _thread = new Thread(() => { });
Resurrector(bool unstarted)
{
_unstarted = unstarted;
if (!unstarted)
{
_thread.Start();
_thread.Join();
}
}
~Resurrector()
{
if (_unstarted && (s_unstartedResurrected == null))
{
s_unstartedResurrected = _thread;
}
else if(!_unstarted && (s_stoppedResurrected == null))
{
s_stoppedResurrected = _thread;
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
static void CreateInstance(bool unstarted)
{
GC.KeepAlive(new Resurrector(unstarted));
}
static Thread CreateResurrectedThread(ref Thread trap, bool unstarted)
{
trap = null;
while (trap == null)
{
// Call twice to override the address of the first allocation on the stack (for conservative GC)
CreateInstance(unstarted);
CreateInstance(unstarted);
GC.Collect();
GC.WaitForPendingFinalizers();
}
// We would like to get a Thread object with its internal SafeHandle member disposed.
// The current implementation of SafeHandle postpones disposing until the next garbage
// collection. For this reason we do a couple more collections.
for (int i = 0; i < 2; i++)
{
GC.Collect();
GC.WaitForPendingFinalizers();
}
return trap;
}
public static Thread CreateUnstartedResurrected()
{
return CreateResurrectedThread(ref s_unstartedResurrected, unstarted: true);
}
public static Thread CreateStoppedResurrected()
{
return CreateResurrectedThread(ref s_stoppedResurrected, unstarted: false);
}
}
}
| |
using System;
using System.IO;
using System.Collections;
using Helpers;
using System.Globalization;
using System.Xml.Linq;
using System.Linq;
namespace TestHarness
{
/// <summary>
/// Summary description for TestMain.
/// </summary>
class TestMain
{
public static bool fileoption = false;
public static bool zoption = false;
public static string strFilePath = "c:\\sundeep_personal\\in.csv";
public static bool capgains = false;
public static bool stocktaking = true;
public static bool debug = false;
public static bool unsold = false;
public static bool unsoldavg = false;
public static bool roi = false;
public static bool getquote = false;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Welcome to the Investment Manager application");
if (!ProcessArguments(args))
return;
try
{
Account myaccount;
ReadTransactionsIntoAccount(out myaccount);
if (getquote)
{
ArrayList stocklist = myaccount.GetStockList();
try
{
NSEQuoteRetriever nseQuote = new NSEQuoteRetriever();
nseQuote.ReadICICIDirectToNSEStockSymbolMapFile();
bool test = nseQuote.GetLiveQuote("TATASTEEL");
ArrayList nse;
Hashtable htResults;
if (nseQuote.GetNSESymbolFromICICIDirectCode(stocklist, out nse))
nseQuote.GetLiveQuote(nse, out htResults);
else
Console.WriteLine("Could not map symbols");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
//myaccount.StockTaking(DateTime.Now, zoption);
if (stocktaking)
{
Console.WriteLine("---------------------------------------------------------------------------------------------------------------------------------------------");
StockTakingListener mySTListener = new StockTakingListener(DateTime.Now);
mySTListener.ShowZeroBalances = zoption;
mySTListener.Debug = debug;
myaccount.MatchTransactions("", mySTListener);
}
if (unsold)
{
Console.WriteLine("---------------------------------------------------------------------------------------------------------------------------------------------");
UnsoldPositions myUnsoldListener = new UnsoldPositions(DateTime.Now);
myUnsoldListener.Debug = debug;
myaccount.MatchTransactions("", myUnsoldListener);
}
if (unsoldavg)
{
Console.WriteLine("---------------------------------------------------------------------------------------------------------------------------------------------");
UnsoldAverage myUnsoldListener = new UnsoldAverage(DateTime.Now);
myUnsoldListener.Debug = debug;
myaccount.MatchTransactions("", myUnsoldListener);
}
//myaccount.StockTaking2(DateTime.Now, zoption);
//myaccount.CapitalGains(new DateTime(2007, 4, 1), new DateTime(2008, 3, 31), 365);
if (capgains)
{
DateTime toDate = DateTime.Now;
DateTime fromDate = new DateTime((toDate.Month < 4 ? toDate.Year - 1 : toDate.Year), 4, 1);
Console.WriteLine("---------------------------------------------------------------------------------------------------------------------------------------------");
Console.WriteLine("----------------- CAPITAL GAINS from {0} to {1} -----------------------------------------------------------", fromDate, toDate);
Console.WriteLine("---------------------------------------------------------------------------------------------------------------------------------------------");
CapGainsListener myCGListener = new CapGainsListener(fromDate, toDate, 365);
myaccount.MatchTransactions("", myCGListener);
}
if (roi)
{
Console.WriteLine("-------------------------------------------------------------------------------------------------------------------------------------------------");
ReturnOnInvestmentListener myRoIistener = new ReturnOnInvestmentListener();
myaccount.MatchTransactions("", myRoIistener);
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("Caught an exception: {0}", e.Message);
}
return;
}// end Main
static bool ProcessArguments(string[] args)
{
foreach (string arg in args)
{
if (fileoption)
{
strFilePath = arg;
fileoption = false;
continue;
}
if (arg == "-f" || arg == "/f")
fileoption = true;
if (arg == "-z")
zoption = true;
if (arg == "-g")
capgains = true;
if (arg == "-t")
stocktaking = true;
if (arg == "-d")
debug = true;
if (arg == "-u")
unsold = true;
if (arg == "-a" || arg == "/a")
unsoldavg = true;
if (arg == "-r" || arg == "/r")
roi = true;
if (arg == "-q" || arg == "/q")
getquote = true;
if (arg == "-?" || arg == "/?")
{
Console.WriteLine("testharness [-t [-z]] [-g] [-u] -f [<filename>]");
Console.WriteLine("e.g. testharness -t -z -f mytrans.csv");
Console.WriteLine("-t\t\tStock balances as of today");
Console.WriteLine("-z\t\tInclude zero-balances in stock balance report. only used with -t");
Console.WriteLine("-g\t\tCapital gains for current financial year. As of today.");
Console.WriteLine("-u\t\tUnsold positions. As of today.");
Console.WriteLine("-a\t\tAverage price of unsold positions.");
Console.WriteLine("-r\t\tGain/Loss on each stock with Return on Investment percentage");
Console.WriteLine("-q\t\tGet current NSE Quotes for the stocks in the transactions file");
Console.WriteLine("-f\t\tIndicates param that follows is the input file of transactions.\nIf no file specified assumes e:\\in.csv");
return false;
}
} // foreach
return true;
} // ProcessArguments
static bool ReadTransactionsIntoAccount(out Account myaccount)
{
var lineCount = File.ReadAllLines(strFilePath).Length;
if (debug)
{
if (lineCount > 2000)
{
Console.WriteLine("The input file: {0} is larger than 2000 lines and may cause problems", strFilePath);
}
else
{
Console.WriteLine("The input file: {0} has {1} lines", strFilePath, lineCount);
}
}
myaccount = new Account(lineCount);
// Create an instance of StreamReader to read from a file.
StreamReader sr = new StreamReader(strFilePath);
String line;
int numLinesInFile = 0;
string delimStr = ",";
char[] delimiter = delimStr.ToCharArray();
string[] split = null;
bool firstline = true;
Hashtable columnmapper = new Hashtable();
int lotIdCounter = 0;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
numLinesInFile++;
split = line.Split(delimiter);
int nElmt = 0;
SingleTransaction.eTransactionType transtype = SingleTransaction.eTransactionType.None;
System.DateTime transdate = new DateTime();
String stock = null;
decimal price = 0.0M;
decimal charges = 0.0M;
int qty = 0;
string lotId = null;
try
{
foreach (string s in split)
{
if (!firstline)
{
if (nElmt == Convert.ToInt32(columnmapper["Action"]))
{
if (s == "Buy")
transtype = SingleTransaction.eTransactionType.Buy;
else if (s == "Sell")
transtype = SingleTransaction.eTransactionType.Sell;
else if (s == "Add")
transtype = SingleTransaction.eTransactionType.Add;
else if (s == "Remove")
transtype = SingleTransaction.eTransactionType.Remove;
else
transtype = SingleTransaction.eTransactionType.None;
}
else if (nElmt == Convert.ToInt32(columnmapper["Transaction Date"]))
{
String dtdelim = "-";
char[] dtdelimiter = dtdelim.ToCharArray();
String[] dtparts = s.Split(dtdelimiter);
lotId = string.Format("{0}_{1}", s, lotIdCounter++);
int day = Convert.ToInt32(dtparts[0]);
int mon = DateTime.ParseExact(dtparts[1], "MMM", CultureInfo.InvariantCulture).Month;
int year = Convert.ToInt32(dtparts[2]);
transdate = new DateTime(year, mon, day);
}
else if (nElmt == Convert.ToInt32(columnmapper["Stock Symbol"]))
{
stock = s;
}
else if (nElmt == Convert.ToInt32(columnmapper["Quantity"]))
{
qty = Convert.ToInt32(s);
}
else if (nElmt == Convert.ToInt32(columnmapper["Transaction Price"]))
{
price = Convert.ToDecimal(s);
}
else if (nElmt == Convert.ToInt32(columnmapper["Brokerage"]))
{
charges = Convert.ToDecimal(s);
}
else if (nElmt == Convert.ToInt32(columnmapper["Transaction Charges"]))
{
charges += Convert.ToDecimal(s);
}
else if (nElmt == Convert.ToInt32(columnmapper["Stamp Duty"]))
{
charges += Convert.ToDecimal(s);
}
else if (nElmt == Convert.ToInt32(columnmapper["Order Ref."]))
{
lotId = s;
}
else
{
//Console.WriteLine("-{0}-", s);
}
nElmt++;
}
else
columnmapper.Add(s, nElmt++);
}
if (firstline)
{
firstline = false;
continue;
}
if (stock != null)
myaccount.AddTransaction(transtype, transdate, stock, qty, price, charges, lotId);
else
Console.WriteLine("No stock code. Ignoring line: {0}", line);
}
catch (Exception e)
{
Console.WriteLine("Caught an exception: {0} processing {1}", e.Message, line);
}
}
Console.WriteLine("Read {0} lines from this file: {1}", numLinesInFile, strFilePath);
sr.Close();
return true;
} // ReadTransactionsIntoAccount
}
}
| |
// SPDX-License-Identifier: MIT
// Copyright wtfsckgh@gmail.com
// Copyright iced contributors
#if MASM
using System;
using Iced.Intel.FormatterInternal;
using Iced.Intel.Internal;
namespace Iced.Intel.MasmFormatterInternal {
static partial class InstrInfos {
public static readonly InstrInfo[] AllInfos = ReadInfos();
static string AddSuffix(string s, char[] ca) =>
string.Intern(s + new string(ca));
static string AddPrefix(string s, char[] ca) =>
string.Intern(new string(ca) + s);
static InstrInfo[] ReadInfos() {
var reader = new DataReader(GetSerializedInstrInfos());
var infos = new InstrInfo[IcedConstants.CodeEnumCount];
var strings = FormatterStringsTable.GetStringsTable();
var ca = new char[1];
string s, s2, s3, s4;
uint v, v2, v3;
int prevIndex = -1;
for (int i = 0; i < infos.Length; i++) {
byte f = reader.ReadByte();
var ctorKind = (CtorKind)(f & 0x7F);
int currentIndex;
if (ctorKind == CtorKind.Previous) {
currentIndex = reader.Index;
reader.Index = prevIndex;
ctorKind = (CtorKind)(reader.ReadByte() & 0x7F);
}
else {
currentIndex = -1;
prevIndex = reader.Index - 1;
}
s = strings[reader.ReadCompressedUInt32()];
if ((f & 0x80) != 0) {
ca[0] = 'v';
s = AddPrefix(s, ca);
}
InstrInfo instrInfo;
switch (ctorKind) {
case CtorKind.Normal_1:
instrInfo = new SimpleInstrInfo(s);
break;
case CtorKind.Normal_2:
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo(s, (InstrOpInfoFlags)v);
break;
case CtorKind.AamAad:
instrInfo = new SimpleInstrInfo_AamAad(s);
break;
case CtorKind.AX:
ca[0] = (char)reader.ReadByte();
s2 = AddSuffix(s, ca);
instrInfo = new SimpleInstrInfo_AX(s, s2);
break;
case CtorKind.AY:
ca[0] = (char)reader.ReadByte();
s2 = AddSuffix(s, ca);
instrInfo = new SimpleInstrInfo_AY(s, s2);
break;
case CtorKind.bnd:
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_bnd(s, (InstrOpInfoFlags)v);
break;
case CtorKind.DeclareData:
instrInfo = new SimpleInstrInfo_DeclareData((Code)i, s);
break;
case CtorKind.DX:
ca[0] = (char)reader.ReadByte();
s2 = AddSuffix(s, ca);
instrInfo = new SimpleInstrInfo_DX(s, s2);
break;
case CtorKind.fword:
ca[0] = (char)reader.ReadByte();
s2 = AddSuffix(s, ca);
v = reader.ReadByte();
v2 = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_fword((CodeSize)v, (InstrOpInfoFlags)v2, s, s2);
break;
case CtorKind.Int3:
instrInfo = new SimpleInstrInfo_Int3(s);
break;
case CtorKind.imul:
instrInfo = new SimpleInstrInfo_imul(s);
break;
case CtorKind.invlpga:
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_invlpga((int)v, s);
break;
case CtorKind.CCa_1:
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_cc((int)v, new[] { s });
break;
case CtorKind.CCa_2:
s2 = strings[reader.ReadCompressedUInt32()];
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_cc((int)v, new[] { s, s2 });
break;
case CtorKind.CCa_3:
s2 = strings[reader.ReadCompressedUInt32()];
s3 = strings[reader.ReadCompressedUInt32()];
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_cc((int)v, new[] { s, s2, s3 });
break;
case CtorKind.CCb_1:
v2 = reader.ReadCompressedUInt32();
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_cc((int)v2, new[] { s }, (InstrOpInfoFlags)v);
break;
case CtorKind.CCb_2:
s2 = strings[reader.ReadCompressedUInt32()];
v2 = reader.ReadCompressedUInt32();
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_cc((int)v2, new[] { s, s2 }, (InstrOpInfoFlags)v);
break;
case CtorKind.CCb_3:
s2 = strings[reader.ReadCompressedUInt32()];
s3 = strings[reader.ReadCompressedUInt32()];
v2 = reader.ReadCompressedUInt32();
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_cc((int)v2, new[] { s, s2, s3 }, (InstrOpInfoFlags)v);
break;
case CtorKind.jcc_1:
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_jcc((int)v, new[] { s });
break;
case CtorKind.jcc_2:
s2 = strings[reader.ReadCompressedUInt32()];
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_jcc((int)v, new[] { s, s2 });
break;
case CtorKind.jcc_3:
s2 = strings[reader.ReadCompressedUInt32()];
s3 = strings[reader.ReadCompressedUInt32()];
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_jcc((int)v, new[] { s, s2, s3 });
break;
case CtorKind.Loopcc1:
s2 = strings[reader.ReadCompressedUInt32()];
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_cc((int)v, new[] { s, s2 });
break;
case CtorKind.Loopcc2:
s2 = strings[reader.ReadCompressedUInt32()];
ca[0] = (char)reader.ReadByte();
v2 = reader.ReadCompressedUInt32();
s3 = AddSuffix(s, ca);
s4 = AddSuffix(s2, ca);
v = reader.ReadByte();
instrInfo = new SimpleInstrInfo_OpSize_cc((CodeSize)v, (int)v2, new[] { s, s2 }, new[] { s3, s4 });
break;
case CtorKind.maskmovq:
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_maskmovq(s, (InstrOpInfoFlags)v);
break;
case CtorKind.memsize:
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_memsize((int)v, s);
break;
case CtorKind.monitor:
v = reader.ReadByte();
v2 = reader.ReadByte();
v3 = reader.ReadByte();
instrInfo = new SimpleInstrInfo_monitor(s, (Register)v, (Register)v2, (Register)v3);
break;
case CtorKind.mwait:
instrInfo = new SimpleInstrInfo_mwait(s);
break;
case CtorKind.mwaitx:
instrInfo = new SimpleInstrInfo_mwaitx(s);
break;
case CtorKind.nop:
v = reader.ReadCompressedUInt32();
v2 = reader.ReadByte();
instrInfo = new SimpleInstrInfo_nop((int)v, s, (Register)v2);
break;
case CtorKind.OpSize_1:
v = reader.ReadByte();
ca[0] = 'w';
s2 = AddSuffix(s, ca);
ca[0] = 'd';
s3 = AddSuffix(s, ca);
ca[0] = 'q';
s4 = AddSuffix(s, ca);
instrInfo = new SimpleInstrInfo_OpSize((CodeSize)v, s, s2, s3, s4);
break;
case CtorKind.OpSize_2:
ca[0] = (char)reader.ReadByte();
s2 = AddSuffix(s, ca);
v = reader.ReadByte();
instrInfo = new SimpleInstrInfo_OpSize((CodeSize)v, s, s2, s2, s2);
break;
case CtorKind.OpSize2:
s2 = strings[reader.ReadCompressedUInt32()];
s3 = strings[reader.ReadCompressedUInt32()];
s4 = strings[reader.ReadCompressedUInt32()];
v = reader.ReadByte();
if (v > 1)
throw new InvalidOperationException();
instrInfo = new SimpleInstrInfo_OpSize2(s, s2, s3, s4, v != 0);
break;
case CtorKind.pblendvb:
instrInfo = new SimpleInstrInfo_pblendvb(s);
break;
case CtorKind.pclmulqdq:
v = reader.ReadByte();
instrInfo = new SimpleInstrInfo_pclmulqdq(s, FormatterConstants.GetPseudoOps((PseudoOpsKind)v));
break;
case CtorKind.pops_2:
v = reader.ReadByte();
instrInfo = new SimpleInstrInfo_pops(s, FormatterConstants.GetPseudoOps((PseudoOpsKind)v));
break;
case CtorKind.pops_3:
v = reader.ReadByte();
v2 = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_pops(s, FormatterConstants.GetPseudoOps((PseudoOpsKind)v), (InstrOpInfoFlags)v2);
break;
case CtorKind.reg:
v = reader.ReadByte();
instrInfo = new SimpleInstrInfo_reg(s, (Register)v);
break;
case CtorKind.Reg16:
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_Reg16(s, (InstrOpInfoFlags)v);
break;
case CtorKind.Reg32:
v = reader.ReadCompressedUInt32();
instrInfo = new SimpleInstrInfo_Reg32(s, (InstrOpInfoFlags)v);
break;
case CtorKind.reverse:
instrInfo = new SimpleInstrInfo_reverse(s);
break;
case CtorKind.ST_STi:
instrInfo = new SimpleInstrInfo_ST_STi(s);
break;
case CtorKind.STi_ST:
v = reader.ReadByte();
if (v > 1)
throw new InvalidOperationException();
instrInfo = new SimpleInstrInfo_STi_ST(s, v != 0);
break;
case CtorKind.STIG1:
v = reader.ReadByte();
if (v > 1)
throw new InvalidOperationException();
instrInfo = new SimpleInstrInfo_STIG1(s, v != 0);
break;
case CtorKind.XLAT:
ca[0] = 'b';
s2 = AddSuffix(s, ca);
instrInfo = new SimpleInstrInfo_XLAT(s, s2);
break;
case CtorKind.XY:
ca[0] = (char)reader.ReadByte();
s2 = AddSuffix(s, ca);
instrInfo = new SimpleInstrInfo_XY(s, s2);
break;
case CtorKind.YA:
ca[0] = (char)reader.ReadByte();
s2 = AddSuffix(s, ca);
instrInfo = new SimpleInstrInfo_YA(s, s2);
break;
case CtorKind.YD:
ca[0] = (char)reader.ReadByte();
s2 = AddSuffix(s, ca);
instrInfo = new SimpleInstrInfo_YD(s, s2);
break;
case CtorKind.YX:
ca[0] = (char)reader.ReadByte();
s2 = AddSuffix(s, ca);
instrInfo = new SimpleInstrInfo_YX(s, s2);
break;
default:
throw new InvalidOperationException();
}
infos[i] = instrInfo;
if (currentIndex >= 0)
reader.Index = currentIndex;
}
if (reader.CanRead)
throw new InvalidOperationException();
return infos;
}
}
}
#endif
| |
// 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.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using Xunit;
namespace System.Data.SqlClient.ManualTesting.Tests
{
public class MultipleResultsTest
{
private StringBuilder _globalBuilder = new StringBuilder();
private StringBuilder _outputBuilder;
private string[] _outputFilter;
[Fact]
public void TestMain()
{
Assert.True(RunTestCoreAndCompareWithBaseline());
}
private void RunTest()
{
MultipleErrorHandling(new SqlConnection((new SqlConnectionStringBuilder(DataTestUtility.TcpConnStr) { MultipleActiveResultSets = true }).ConnectionString));
}
private void MultipleErrorHandling(DbConnection connection)
{
try
{
Console.WriteLine("MultipleErrorHandling {0}", connection.GetType().Name);
Type expectedException = null;
if (connection is SqlConnection)
{
((SqlConnection)connection).InfoMessage += delegate (object sender, SqlInfoMessageEventArgs args)
{
Console.WriteLine("*** SQL CONNECTION INFO MESSAGE : {0} ****", args.Message);
};
expectedException = typeof(SqlException);
}
connection.Open();
using (DbCommand command = connection.CreateCommand())
{
command.CommandText =
"PRINT N'0';\n" +
"SELECT num = 1, str = 'ABC';\n" +
"PRINT N'1';\n" +
"RAISERROR('Error 1', 15, 1);\n" +
"PRINT N'3';\n" +
"SELECT num = 2, str = 'ABC';\n" +
"PRINT N'4';\n" +
"RAISERROR('Error 2', 15, 1);\n" +
"PRINT N'5';\n" +
"SELECT num = 3, str = 'ABC';\n" +
"PRINT N'6';\n" +
"RAISERROR('Error 3', 15, 1);\n" +
"PRINT N'7';\n" +
"SELECT num = 4, str = 'ABC';\n" +
"PRINT N'8';\n" +
"RAISERROR('Error 4', 15, 1);\n" +
"PRINT N'9';\n" +
"SELECT num = 5, str = 'ABC';\n" +
"PRINT N'10';\n" +
"RAISERROR('Error 5', 15, 1);\n" +
"PRINT N'11';\n";
try
{
Console.WriteLine("**** ExecuteNonQuery *****");
command.ExecuteNonQuery();
}
catch (Exception e)
{
PrintException(expectedException, e);
}
try
{
Console.WriteLine("**** ExecuteScalar ****");
command.ExecuteScalar();
}
catch (Exception e)
{
PrintException(expectedException, e);
}
try
{
Console.WriteLine("**** ExecuteReader ****");
using (DbDataReader reader = command.ExecuteReader())
{
bool moreResults = true;
do
{
try
{
Console.WriteLine("NextResult");
moreResults = reader.NextResult();
}
catch (Exception e)
{
PrintException(expectedException, e);
}
} while (moreResults);
}
}
catch (Exception e)
{
PrintException(null, e);
}
}
}
catch (Exception e)
{
PrintException(null, e);
}
try
{
connection.Dispose();
}
catch (Exception e)
{
PrintException(null, e);
}
}
private bool RunTestCoreAndCompareWithBaseline()
{
string outputPath = "MultipleResultsTest.out";
string baselinePath = "MultipleResultsTest.bsl";
var fstream = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Read);
var swriter = new StreamWriter(fstream, Encoding.UTF8);
// Convert all string writes of '\n' to '\r\n' so output files can be 'text' not 'binary'
var twriter = new CarriageReturnLineFeedReplacer(swriter);
Console.SetOut(twriter); // "redirect" Console.Out
// Run Test
RunTest();
Console.Out.Flush();
Console.Out.Dispose();
// Recover the standard output stream
StreamWriter standardOutput = new StreamWriter(Console.OpenStandardOutput());
standardOutput.AutoFlush = true;
Console.SetOut(standardOutput);
// Compare output file
var comparisonResult = FindDiffFromBaseline(baselinePath, outputPath);
if (string.IsNullOrEmpty(comparisonResult))
{
return true;
}
Console.WriteLine("Test Failed!");
Console.WriteLine("Please compare baseline : {0} with output :{1}", Path.GetFullPath(baselinePath), Path.GetFullPath(outputPath));
Console.WriteLine("Comparison Results : ");
Console.WriteLine(comparisonResult);
return false;
}
private void PrintException(Type expected, Exception e, params string[] values)
{
try
{
Debug.Assert(null != e, "PrintException: null exception");
_globalBuilder.Length = 0;
_globalBuilder.Append(e.GetType().Name).Append(": ");
if (e is COMException)
{
_globalBuilder.Append("0x").Append((((COMException)e).HResult).ToString("X8"));
if (expected != e.GetType())
{
_globalBuilder.Append(": ").Append(e.ToString());
}
}
else
{
_globalBuilder.Append(e.Message);
}
AssemblyFilter(_globalBuilder);
Console.WriteLine(_globalBuilder.ToString());
if (expected != e.GetType())
{
Console.WriteLine(e.StackTrace);
}
if (null != values)
{
foreach (string value in values)
{
Console.WriteLine(value);
}
}
if (null != e.InnerException)
{
PrintException(e.InnerException.GetType(), e.InnerException);
}
Console.Out.Flush();
}
catch (Exception f)
{
Console.WriteLine(f);
}
}
private string FindDiffFromBaseline(string baselinePath, string outputPath)
{
var expectedLines = File.ReadAllLines(baselinePath);
var outputLines = File.ReadAllLines(outputPath);
var comparisonSb = new StringBuilder();
// Start compare results
var expectedLength = expectedLines.Length;
var outputLength = outputLines.Length;
var findDiffLength = Math.Min(expectedLength, outputLength);
// Find diff for each lines
for (var lineNo = 0; lineNo < findDiffLength; lineNo++)
{
if (!expectedLines[lineNo].Equals(outputLines[lineNo]))
{
comparisonSb.AppendFormat("** DIFF at line {0} \n", lineNo);
comparisonSb.AppendFormat("A : {0} \n", outputLines[lineNo]);
comparisonSb.AppendFormat("E : {0} \n", expectedLines[lineNo]);
}
}
var startIndex = findDiffLength - 1;
if (startIndex < 0) startIndex = 0;
if (findDiffLength < expectedLength)
{
comparisonSb.AppendFormat("** MISSING \n");
for (var lineNo = startIndex; lineNo < expectedLength; lineNo++)
{
comparisonSb.AppendFormat("{0} : {1}", lineNo, expectedLines[lineNo]);
}
}
if (findDiffLength < outputLength)
{
comparisonSb.AppendFormat("** EXTRA \n");
for (var lineNo = startIndex; lineNo < outputLength; lineNo++)
{
comparisonSb.AppendFormat("{0} : {1}", lineNo, outputLines[lineNo]);
}
}
return comparisonSb.ToString();
}
private string AssemblyFilter(StreamWriter writer)
{
if (null == _outputBuilder)
{
_outputBuilder = new StringBuilder();
}
_outputBuilder.Length = 0;
byte[] utf8 = ((MemoryStream)writer.BaseStream).ToArray();
string value = System.Text.Encoding.UTF8.GetString(utf8, 3, utf8.Length - 3); // skip 0xEF, 0xBB, 0xBF
_outputBuilder.Append(value);
AssemblyFilter(_outputBuilder);
return _outputBuilder.ToString();
}
private void AssemblyFilter(StringBuilder builder)
{
string[] filter = _outputFilter;
if (null == filter)
{
filter = new string[5];
string tmp = typeof(System.Guid).AssemblyQualifiedName;
filter[0] = tmp.Substring(tmp.IndexOf(','));
filter[1] = filter[0].Replace("mscorlib", "System");
filter[2] = filter[0].Replace("mscorlib", "System.Data");
filter[3] = filter[0].Replace("mscorlib", "System.Data.OracleClient");
filter[4] = filter[0].Replace("mscorlib", "System.Xml");
_outputFilter = filter;
}
for (int i = 0; i < filter.Length; ++i)
{
builder.Replace(filter[i], "");
}
}
/// <summary>
/// special wrapper for the text writer to replace single "\n" with "\n"
/// </summary>
private sealed class CarriageReturnLineFeedReplacer : TextWriter
{
private TextWriter _output;
private int _lineFeedCount;
private bool _hasCarriageReturn;
internal CarriageReturnLineFeedReplacer(TextWriter output)
{
if (output == null)
throw new ArgumentNullException("output");
_output = output;
}
public int LineFeedCount
{
get { return _lineFeedCount; }
}
public override Encoding Encoding
{
get { return _output.Encoding; }
}
public override IFormatProvider FormatProvider
{
get { return _output.FormatProvider; }
}
public override string NewLine
{
get { return _output.NewLine; }
set { _output.NewLine = value; }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
((IDisposable)_output).Dispose();
}
_output = null;
}
public override void Flush()
{
_output.Flush();
}
public override void Write(char value)
{
if ('\n' == value)
{
_lineFeedCount++;
if (!_hasCarriageReturn)
{ // X'\n'Y -> X'\r\n'Y
_output.Write('\r');
}
}
_hasCarriageReturn = '\r' == value;
_output.Write(value);
}
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="httpapplicationstate.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* Application State Dictionary class
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web {
using System.Threading;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using System.Collections;
using System.Collections.Specialized;
using System.Web;
using System.Web.Util;
//
// Application state collection
//
/// <devdoc>
/// <para>
/// The HttpApplicationState class enables developers to
/// share global information across multiple requests, sessions, and pipelines
/// within an ASP.NET application. (An ASP.NET application is the sum of all files, pages,
/// handlers, modules, and code
/// within the scope of a virtual directory and its
/// subdirectories on a single web server).
/// </para>
/// </devdoc>
public sealed class HttpApplicationState : NameObjectCollectionBase {
// app lock with auto-unlock feature
private HttpApplicationStateLock _lock = new HttpApplicationStateLock();
// static object collections
private HttpStaticObjectsCollection _applicationStaticObjects;
private HttpStaticObjectsCollection _sessionStaticObjects;
internal HttpApplicationState() : this(null, null) {
}
internal HttpApplicationState(HttpStaticObjectsCollection applicationStaticObjects,
HttpStaticObjectsCollection sessionStaticObjects)
: base(Misc.CaseInsensitiveInvariantKeyComparer) {
_applicationStaticObjects = applicationStaticObjects;
if (_applicationStaticObjects == null)
_applicationStaticObjects = new HttpStaticObjectsCollection();
_sessionStaticObjects = sessionStaticObjects;
if (_sessionStaticObjects == null)
_sessionStaticObjects = new HttpStaticObjectsCollection();
}
//
// Internal accessor to session static objects collection
//
internal HttpStaticObjectsCollection SessionStaticObjects {
get { return _sessionStaticObjects;}
}
//
// Implementation of standard collection stuff
//
/// <devdoc>
/// <para>Gets
/// the number of item objects in the application state collection.</para>
/// </devdoc>
public override int Count {
get {
int c = 0;
_lock.AcquireRead();
try {
c = base.Count;
}
finally {
_lock.ReleaseRead();
}
return c;
}
}
// modifying methods
/// <devdoc>
/// <para>
/// Adds
/// a new state object to the application state collection.
/// </para>
/// </devdoc>
public void Add(String name, Object value) {
_lock.AcquireWrite();
try {
BaseAdd(name, value);
}
finally {
_lock.ReleaseWrite();
}
}
/// <devdoc>
/// <para>Updates an HttpApplicationState value within the collection.</para>
/// </devdoc>
public void Set(String name, Object value) {
_lock.AcquireWrite();
try {
BaseSet(name, value);
}
finally {
_lock.ReleaseWrite();
}
}
/// <devdoc>
/// <para>Removes
/// an
/// object from the application state collection by name.</para>
/// </devdoc>
public void Remove(String name) {
_lock.AcquireWrite();
try {
BaseRemove(name);
}
finally {
_lock.ReleaseWrite();
}
}
/// <devdoc>
/// <para>Removes
/// an
/// object from the application state collection by name.</para>
/// </devdoc>
public void RemoveAt(int index) {
_lock.AcquireWrite();
try {
BaseRemoveAt(index);
}
finally {
_lock.ReleaseWrite();
}
}
/// <devdoc>
/// <para>
/// Removes
/// all objects from the application state collection.
/// </para>
/// </devdoc>
public void Clear() {
_lock.AcquireWrite();
try {
BaseClear();
}
finally {
_lock.ReleaseWrite();
}
}
/// <devdoc>
/// <para>
/// Removes
/// all objects from the application state collection.
/// </para>
/// </devdoc>
public void RemoveAll() {
Clear();
}
// access by key
/// <devdoc>
/// <para>
/// Enables user to retrieve application state object by name.
/// </para>
/// </devdoc>
public Object Get(String name) {
Object obj = null;
_lock.AcquireRead();
try {
obj = BaseGet(name);
}
finally {
_lock.ReleaseRead();
}
return obj;
}
/// <devdoc>
/// <para>Enables
/// a user to add/remove/update a single application state object.</para>
/// </devdoc>
public Object this[String name]
{
get { return Get(name);}
set { Set(name, value);}
}
// access by index
/// <devdoc>
/// <para>
/// Enables user
/// to retrieve a single application state object by index.
/// </para>
/// </devdoc>
public Object Get(int index) {
Object obj = null;
_lock.AcquireRead();
try {
obj = BaseGet(index);
}
finally {
_lock.ReleaseRead();
}
return obj;
}
/// <devdoc>
/// <para>
/// Enables user to retrieve an application state object name by index.
/// </para>
/// </devdoc>
public String GetKey(int index) {
String s = null;
_lock.AcquireRead();
try {
s = BaseGetKey(index);
}
finally {
_lock.ReleaseRead();
}
return s;
}
/// <devdoc>
/// <para>
/// Enables
/// user to retrieve an application state object by index.
/// </para>
/// </devdoc>
public Object this[int index]
{
get { return Get(index);}
}
// access to keys and values as arrays
/// <devdoc>
/// <para>
/// Enables user
/// to retrieve all application state object names in collection.
/// </para>
/// </devdoc>
public String[] AllKeys {
get {
String [] allKeys = null;
_lock.AcquireRead();
try {
allKeys = BaseGetAllKeys();
}
finally {
_lock.ReleaseRead();
}
return allKeys;
}
}
//
// Public properties
//
/// <devdoc>
/// <para>
/// Returns "this". Provided for legacy ASP compatibility.
/// </para>
/// </devdoc>
public HttpApplicationState Contents {
get { return this;}
}
/// <devdoc>
/// <para>
/// Exposes all objects declared via an <object
/// runat=server></object> tag within the ASP.NET application file.
/// </para>
/// </devdoc>
public HttpStaticObjectsCollection StaticObjects {
get { return _applicationStaticObjects;}
}
//
// Locking support
//
/// <devdoc>
/// <para>
/// Locks
/// access to all application state variables. Facilitates access
/// synchronization.
/// </para>
/// </devdoc>
public void Lock() {
_lock.AcquireWrite();
}
/// <devdoc>
/// <para>
/// Unocks access to all application state variables. Facilitates access
/// synchronization.
/// </para>
/// </devdoc>
public void UnLock() {
_lock.ReleaseWrite();
}
internal void EnsureUnLock() {
_lock.EnsureReleaseWrite();
}
}
//
// Recursive read-write lock that allows removing of all
// outstanding write locks from the current thread at once
//
internal class HttpApplicationStateLock : ReadWriteObjectLock {
private int _recursionCount;
private int _threadId;
internal HttpApplicationStateLock() {
}
internal override void AcquireRead() {
int currentThreadId = SafeNativeMethods.GetCurrentThreadId();
if (_threadId != currentThreadId)
base.AcquireRead(); // only if no write lock
}
internal override void ReleaseRead() {
int currentThreadId = SafeNativeMethods.GetCurrentThreadId();
if (_threadId != currentThreadId)
base.ReleaseRead(); // only if no write lock
}
internal override void AcquireWrite() {
int currentThreadId = SafeNativeMethods.GetCurrentThreadId();
if (_threadId == currentThreadId) {
_recursionCount++;
}
else {
base.AcquireWrite();
_threadId = currentThreadId;
_recursionCount = 1;
}
}
internal override void ReleaseWrite() {
int currentThreadId = SafeNativeMethods.GetCurrentThreadId();
if (_threadId == currentThreadId) {
if (--_recursionCount == 0) {
_threadId = 0;
base.ReleaseWrite();
}
}
}
//
// release all write locks held by the current thread
//
internal void EnsureReleaseWrite() {
int currentThreadId = SafeNativeMethods.GetCurrentThreadId();
if (_threadId == currentThreadId) {
_threadId = 0;
_recursionCount = 0;
base.ReleaseWrite();
}
}
}
}
| |
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 Articles.WebAPI.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Globalization;
using System.Linq;
using System.Runtime.Versioning;
using NuGet.Resources;
namespace NuGet
{
public class PackageManager : IPackageManager
{
private ILogger _logger;
public event EventHandler<PackageOperationEventArgs> PackageInstalling;
public event EventHandler<PackageOperationEventArgs> PackageInstalled;
public event EventHandler<PackageOperationEventArgs> PackageUninstalling;
public event EventHandler<PackageOperationEventArgs> PackageUninstalled;
public PackageManager(IPackageRepository sourceRepository, string path)
: this(sourceRepository, new DefaultPackagePathResolver(path), new PhysicalFileSystem(path))
{
}
public PackageManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IFileSystem fileSystem) :
this(sourceRepository, pathResolver, fileSystem, new LocalPackageRepository(pathResolver, fileSystem))
{
}
public PackageManager(IPackageRepository sourceRepository, IPackagePathResolver pathResolver, IFileSystem fileSystem, IPackageRepository localRepository)
{
if (sourceRepository == null)
{
throw new ArgumentNullException("sourceRepository");
}
if (pathResolver == null)
{
throw new ArgumentNullException("pathResolver");
}
if (fileSystem == null)
{
throw new ArgumentNullException("fileSystem");
}
if (localRepository == null)
{
throw new ArgumentNullException("localRepository");
}
SourceRepository = sourceRepository;
PathResolver = pathResolver;
FileSystem = fileSystem;
LocalRepository = localRepository;
DependencyVersion = DependencyVersion.Lowest;
CheckDowngrade = true;
}
public IFileSystem FileSystem
{
get;
set;
}
public IPackageRepository SourceRepository
{
get;
private set;
}
public IPackageRepository LocalRepository
{
get;
private set;
}
public IPackagePathResolver PathResolver
{
get;
private set;
}
public ILogger Logger
{
get
{
return _logger ?? NullLogger.Instance;
}
set
{
_logger = value;
}
}
public DependencyVersion DependencyVersion
{
get;
set;
}
public bool WhatIf
{
get;
set;
}
public void InstallPackage(string packageId)
{
InstallPackage(packageId, version: null, ignoreDependencies: false, allowPrereleaseVersions: false);
}
public void InstallPackage(string packageId, SemanticVersion version)
{
InstallPackage(packageId: packageId, version: version, ignoreDependencies: false, allowPrereleaseVersions: false);
}
public virtual void InstallPackage(string packageId, SemanticVersion version, bool ignoreDependencies, bool allowPrereleaseVersions)
{
IPackage package = PackageRepositoryHelper.ResolvePackage(SourceRepository, LocalRepository, packageId, version, allowPrereleaseVersions);
InstallPackage(package, ignoreDependencies, allowPrereleaseVersions);
}
public virtual void InstallPackage(IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions)
{
InstallPackage(package, targetFramework: null, ignoreDependencies: ignoreDependencies, allowPrereleaseVersions: allowPrereleaseVersions);
}
public void InstallPackage(IPackage package, bool ignoreDependencies, bool allowPrereleaseVersions, bool ignoreWalkInfo)
{
InstallPackage(package, targetFramework: null, ignoreDependencies: ignoreDependencies, allowPrereleaseVersions: allowPrereleaseVersions, ignoreWalkInfo: ignoreWalkInfo);
}
protected void InstallPackage(
IPackage package,
FrameworkName targetFramework,
bool ignoreDependencies,
bool allowPrereleaseVersions,
bool ignoreWalkInfo = false)
{
if (WhatIf)
{
// This prevents InstallWalker from downloading the packages
ignoreWalkInfo = true;
}
var installerWalker = new InstallWalker(
LocalRepository, SourceRepository,
targetFramework, Logger,
ignoreDependencies, allowPrereleaseVersions,
DependencyVersion)
{
DisableWalkInfo = ignoreWalkInfo,
CheckDowngrade = CheckDowngrade
};
Execute(package, installerWalker);
}
private void Execute(IPackage package, IPackageOperationResolver resolver)
{
var operations = resolver.ResolveOperations(package);
if (operations.Any())
{
foreach (PackageOperation operation in operations)
{
Execute(operation);
}
}
else if (LocalRepository.Exists(package))
{
// If the package wasn't installed by our set of operations, notify the user.
Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageAlreadyInstalled, package.GetFullName());
}
}
protected void Execute(PackageOperation operation)
{
bool packageExists = LocalRepository.Exists(operation.Package);
if (operation.Action == PackageAction.Install)
{
// If the package is already installed, then skip it
if (packageExists)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageAlreadyInstalled, operation.Package.GetFullName());
}
else
{
if (WhatIf)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_InstallPackage, operation.Package);
}
else
{
ExecuteInstall(operation.Package);
}
}
}
else
{
if (packageExists)
{
if (WhatIf)
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_UninstallPackage, operation.Package);
}
else
{
ExecuteUninstall(operation.Package);
}
}
}
}
protected void ExecuteInstall(IPackage package)
{
string packageFullName = package.GetFullName();
Logger.Log(MessageLevel.Info, NuGetResources.Log_BeginInstallPackage, packageFullName);
PackageOperationEventArgs args = CreateOperation(package);
OnInstalling(args);
if (args.Cancel)
{
return;
}
OnExpandFiles(args);
LocalRepository.AddPackage(package);
Logger.Log(MessageLevel.Info, NuGetResources.Log_PackageInstalledSuccessfully, packageFullName);
OnInstalled(args);
}
private void ExpandFiles(IPackage package)
{
var batchProcessor = FileSystem as IBatchProcessor<string>;
try
{
var files = package.GetFiles().ToList();
if (batchProcessor != null)
{
// Notify the batch processor that the files are being added. This is to allow source controlled file systems
// to manage previously uninstalled files.
batchProcessor.BeginProcessing(files.Select(p => p.Path), PackageAction.Install);
}
string packageDirectory = PathResolver.GetPackageDirectory(package);
// Add files
FileSystem.AddFiles(files, packageDirectory);
// If this is a Satellite Package, then copy the satellite files into the related runtime package folder too
IPackage runtimePackage;
if (PackageHelper.IsSatellitePackage(package, LocalRepository, targetFramework: null, runtimePackage: out runtimePackage))
{
var satelliteFiles = package.GetSatelliteFiles();
var runtimePath = PathResolver.GetPackageDirectory(runtimePackage);
FileSystem.AddFiles(satelliteFiles, runtimePath);
}
}
finally
{
if (batchProcessor != null)
{
batchProcessor.EndProcessing();
}
}
}
public void UninstallPackage(string packageId)
{
UninstallPackage(packageId, version: null, forceRemove: false, removeDependencies: false);
}
public void UninstallPackage(string packageId, SemanticVersion version)
{
UninstallPackage(packageId, version: version, forceRemove: false, removeDependencies: false);
}
public void UninstallPackage(string packageId, SemanticVersion version, bool forceRemove)
{
UninstallPackage(packageId, version: version, forceRemove: forceRemove, removeDependencies: false);
}
public virtual void UninstallPackage(string packageId, SemanticVersion version, bool forceRemove, bool removeDependencies)
{
if (String.IsNullOrEmpty(packageId))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId");
}
IPackage package = LocalRepository.FindPackage(packageId, version: version);
if (package == null)
{
throw new InvalidOperationException(String.Format(
CultureInfo.CurrentCulture,
NuGetResources.UnknownPackage, packageId));
}
UninstallPackage(package, forceRemove, removeDependencies);
}
public void UninstallPackage(IPackage package)
{
UninstallPackage(package, forceRemove: false, removeDependencies: false);
}
public void UninstallPackage(IPackage package, bool forceRemove)
{
UninstallPackage(package, forceRemove: forceRemove, removeDependencies: false);
}
public virtual void UninstallPackage(IPackage package, bool forceRemove, bool removeDependencies)
{
Execute(package, new UninstallWalker(LocalRepository,
new DependentsWalker(LocalRepository, targetFramework: null),
targetFramework: null,
logger: Logger,
removeDependencies: removeDependencies,
forceRemove: forceRemove)
{
DisableWalkInfo = WhatIf
});
}
protected virtual void ExecuteUninstall(IPackage package)
{
string packageFullName = package.GetFullName();
Logger.Log(MessageLevel.Info, NuGetResources.Log_BeginUninstallPackage, packageFullName);
PackageOperationEventArgs args = CreateOperation(package);
OnUninstalling(args);
if (args.Cancel)
{
return;
}
OnRemoveFiles(args);
LocalRepository.RemovePackage(package);
Logger.Log(MessageLevel.Info, NuGetResources.Log_SuccessfullyUninstalledPackage, packageFullName);
OnUninstalled(args);
}
private void RemoveFiles(IPackage package)
{
string packageDirectory = PathResolver.GetPackageDirectory(package);
// If this is a Satellite Package, then remove the files from the related runtime package folder too
IPackage runtimePackage;
if (PackageHelper.IsSatellitePackage(package, LocalRepository, targetFramework: null, runtimePackage: out runtimePackage))
{
var satelliteFiles = package.GetSatelliteFiles();
var runtimePath = PathResolver.GetPackageDirectory(runtimePackage);
FileSystem.DeleteFiles(satelliteFiles, runtimePath);
}
// Remove package files
// IMPORTANT: This has to be done AFTER removing satellite files from runtime package,
// because starting from 2.1, we read satellite files directly from package files, instead of .nupkg
FileSystem.DeleteFiles(package.GetFiles(), packageDirectory);
}
protected virtual void OnInstalling(PackageOperationEventArgs e)
{
if (PackageInstalling != null)
{
PackageInstalling(this, e);
}
}
protected virtual void OnExpandFiles(PackageOperationEventArgs e)
{
ExpandFiles(e.Package);
}
protected virtual void OnInstalled(PackageOperationEventArgs e)
{
if (PackageInstalled != null)
{
PackageInstalled(this, e);
}
}
protected virtual void OnUninstalling(PackageOperationEventArgs e)
{
if (PackageUninstalling != null)
{
PackageUninstalling(this, e);
}
}
protected virtual void OnRemoveFiles(PackageOperationEventArgs e)
{
RemoveFiles(e.Package);
}
protected virtual void OnUninstalled(PackageOperationEventArgs e)
{
if (PackageUninstalled != null)
{
PackageUninstalled(this, e);
}
}
private PackageOperationEventArgs CreateOperation(IPackage package)
{
return new PackageOperationEventArgs(package, FileSystem, PathResolver.GetInstallPath(package));
}
public void UpdatePackage(string packageId, bool updateDependencies, bool allowPrereleaseVersions)
{
UpdatePackage(packageId, version: null, updateDependencies: updateDependencies, allowPrereleaseVersions: allowPrereleaseVersions);
}
public void UpdatePackage(string packageId, IVersionSpec versionSpec, bool updateDependencies, bool allowPrereleaseVersions)
{
UpdatePackage(packageId, () => SourceRepository.FindPackage(packageId, versionSpec, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies, allowPrereleaseVersions);
}
public void UpdatePackage(string packageId, SemanticVersion version, bool updateDependencies, bool allowPrereleaseVersions)
{
UpdatePackage(packageId, () => SourceRepository.FindPackage(packageId, version, allowPrereleaseVersions, allowUnlisted: false),
updateDependencies, allowPrereleaseVersions);
}
internal void UpdatePackage(string packageId, Func<IPackage> resolvePackage, bool updateDependencies, bool allowPrereleaseVersions)
{
if (String.IsNullOrEmpty(packageId))
{
throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, "packageId");
}
IPackage oldPackage = LocalRepository.FindPackage(packageId);
// Check to see if this package is installed
if (oldPackage == null)
{
throw new InvalidOperationException(
String.Format(CultureInfo.CurrentCulture,
NuGetResources.UnknownPackage, packageId));
}
Logger.Log(MessageLevel.Debug, NuGetResources.Debug_LookingForUpdates, packageId);
IPackage newPackage = resolvePackage();
if (newPackage != null && oldPackage.Version != newPackage.Version)
{
UpdatePackage(newPackage, updateDependencies, allowPrereleaseVersions);
}
else
{
Logger.Log(MessageLevel.Info, NuGetResources.Log_NoUpdatesAvailable, packageId);
}
}
public void UpdatePackage(IPackage newPackage, bool updateDependencies, bool allowPrereleaseVersions)
{
Execute(newPackage, new UpdateWalker(LocalRepository,
SourceRepository,
new DependentsWalker(LocalRepository, targetFramework: null),
NullConstraintProvider.Instance,
targetFramework: null,
logger: Logger,
updateDependencies: updateDependencies,
allowPrereleaseVersions: allowPrereleaseVersions));
}
public bool CheckDowngrade { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using WebApiApplication.Areas.HelpPage.ModelDescriptions;
using WebApiApplication.Areas.HelpPage.Models;
namespace WebApiApplication.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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.Buffers;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;
namespace System.Text.Encodings.Web.Tests
{
public class TextEncoderTests
{
[Fact]
public void EncodeIntoBuffer_SurrogatePairs()
{
// Arange
ScalarTestEncoder encoder = new ScalarTestEncoder();
const string X = "\U00000058"; // LATIN CAPITAL LETTER X (ascii)
const string Pair = "\U0001033A"; // GOTHIC LETTER KUSMA (surrogate pair)
const string eX = "00000058";
const string ePair = "0001033A";
// Act & assert
Assert.Equal("", encoder.Encode(""));
Assert.Equal(eX, encoder.Encode(X)); // no iteration, block
Assert.Equal(eX + eX, encoder.Encode(X + X)); // two iterations, no block
Assert.Equal(eX + eX + eX, encoder.Encode(X + X + X)); // two iterations, block
Assert.Equal(ePair, encoder.Encode(Pair)); // one iteration, no block
Assert.Equal(ePair + ePair, encoder.Encode(Pair + Pair)); // two iterations, no block
Assert.Equal(eX + ePair, encoder.Encode(X + Pair)); // two iterations, no block
Assert.Equal(ePair + eX, encoder.Encode(Pair + X)); // one iteration, block
Assert.Equal(eX + ePair + eX, encoder.Encode(X + Pair + X)); // two iterations, block, even length
Assert.Equal(ePair + eX + ePair, encoder.Encode(Pair + X + Pair)); // three iterations, no block, odd length
}
[Theory]
[InlineData(0, 0)]
[InlineData(1, 0)]
[InlineData(2, 2)]
[InlineData(3, 3)]
[InlineData(4, 3)]
[InlineData(5, 3)]
[InlineData(6, 6)]
[InlineData(7, 6)]
[InlineData(8, 6)]
[InlineData(9, 6)]
[InlineData(10, 10)]
[InlineData(11, 11)]
[InlineData(12, 11)]
public void EncodeUtf8_WellFormedInput_DoesNotRequireEncoding_CopiedToDestinationCorrectly(int destinationSize, int expectedBytesCopied)
{
// This test considers input which is well-formed and doesn't need to be encoded.
// If the destination buffer is large enough, the data should be copied in its entirety.
// If the destination buffer is too small, only complete UTF-8 subsequences should be copied.
// We should never copy a partial subsequence, as it would cause a future call to EncodeUtf8
// to misinterpret the data as ill-formed.
// Arrange
byte[] fullUtf8Input = new byte[] {
0xC2, 0x82,
0x40,
0xE2, 0x90, 0x91,
0xF3, 0xA0, 0xA1, 0xA2,
0x50 }; // UTF-8 subsequences of varying length
var encoder = new ConfigurableScalarTextEncoder(_ => true /* allow everything */);
// Act & assert
OperationStatus expectedOpStatus = (expectedBytesCopied == fullUtf8Input.Length) ? OperationStatus.Done : OperationStatus.DestinationTooSmall;
byte[] destination = new byte[destinationSize];
Assert.Equal(expectedOpStatus, encoder.EncodeUtf8(fullUtf8Input, destination, out int bytesConsumed, out int bytesWritten, isFinalBlock: true));
Assert.Equal(expectedBytesCopied, bytesConsumed);
Assert.Equal(expectedBytesCopied, bytesWritten); // bytes written should match bytes consumed if no encoding needs to take place
Assert.Equal(fullUtf8Input.AsSpan(0, bytesConsumed).ToArray(), destination.AsSpan(0, bytesWritten).ToArray()); // ensure byte-for-byte copy
Assert.True(destination.AsSpan(bytesWritten).ToArray().All(el => el == 0)); // all remaining bytes should be unchanged
destination = new byte[destinationSize];
Assert.Equal(expectedOpStatus, encoder.EncodeUtf8(fullUtf8Input, destination, out bytesConsumed, out bytesWritten, isFinalBlock: false));
Assert.Equal(expectedBytesCopied, bytesConsumed);
Assert.Equal(expectedBytesCopied, bytesWritten); // bytes written should match bytes consumed if no encoding needs to take place
Assert.Equal(fullUtf8Input.AsSpan(0, bytesConsumed).ToArray(), destination.AsSpan(0, bytesWritten).ToArray()); // ensure byte-for-byte copy
Assert.True(destination.AsSpan(bytesWritten).ToArray().All(el => el == 0)); // all remaining bytes should be unchanged
}
[Fact]
public void EncodeUtf8_MixedInputWhichRequiresEncodingOrReplacement()
{
// Arrange
var fullInput = new[]
{
new { utf8Bytes = new byte[] { 0x40 }, output = "@" },
new { utf8Bytes = new byte[] { 0xC3, 0x85 }, output = "[00C5]" }, // U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE (encoded since odd scalar value)
new { utf8Bytes = new byte[] { 0xC3, 0x86 }, output = "\u00C6" }, // U+00C6 LATIN CAPITAL LETTER AE (on allow list)
new { utf8Bytes = new byte[] { 0xFF }, output = "[FFFD]" }, // (invalid UTF-8, replaced with encoded form of U+FFFD)
new { utf8Bytes = new byte[] { 0xEF, 0xBF, 0xBD }, output = "[FFFD]" }, // U+FFFD REPLACEMENT CHARACTER (encoded since not on allow list)
new { utf8Bytes = new byte[] { 0xF0, 0x90, 0x82, 0x82 }, output = "\U00010082" }, // U+10082 LINEAR B IDEOGRAM B104 DEER (not encoded since on allow list)
new { utf8Bytes = new byte[] { 0xF0, 0x90, 0x82, 0x83 }, output = "[10083]" }, // U+10083 LINEAR B IDEOGRAM B105 EQUID (encoded since not on allow list)
};
var encoder = new ConfigurableScalarTextEncoder(scalarValue => (scalarValue % 2) == 0 /* allow only even-valued scalars to be represented unescaped */);
// Act & assert
List<byte> aggregateInputBytesSoFar = new List<byte>();
List<byte> expectedOutputBytesSoFar = new List<byte>();
foreach (var entry in fullInput)
{
int aggregateInputByteCountAtStartOfLoop = aggregateInputBytesSoFar.Count;
byte[] destination;
int bytesConsumed, bytesWritten;
for (int i = 0; i < entry.utf8Bytes.Length - 1; i++)
{
aggregateInputBytesSoFar.Add(entry.utf8Bytes[i]);
// If not final block, partial encoding should say "needs more data".
// We'll try with various destination lengths just to make sure it doesn't affect result.
foreach (int destinationLength in new[] { expectedOutputBytesSoFar.Count, expectedOutputBytesSoFar.Count + 1024 })
{
destination = new byte[destinationLength];
Assert.Equal(OperationStatus.NeedMoreData, encoder.EncodeUtf8(aggregateInputBytesSoFar.ToArray(), destination, out bytesConsumed, out bytesWritten, isFinalBlock: false));
Assert.Equal(aggregateInputByteCountAtStartOfLoop, bytesConsumed);
Assert.Equal(expectedOutputBytesSoFar.Count, bytesWritten);
Assert.Equal(expectedOutputBytesSoFar.ToArray(), new Span<byte>(destination, 0, expectedOutputBytesSoFar.Count).ToArray());
}
// Now try it with "isFinalBlock = true" to force the U+FFFD conversion
destination = new byte[expectedOutputBytesSoFar.Count]; // first with not enough output space to write "[FFFD]"
Assert.Equal(OperationStatus.DestinationTooSmall, encoder.EncodeUtf8(aggregateInputBytesSoFar.ToArray(), destination, out bytesConsumed, out bytesWritten, isFinalBlock: true));
Assert.Equal(aggregateInputByteCountAtStartOfLoop, bytesConsumed);
Assert.Equal(expectedOutputBytesSoFar.Count, bytesWritten);
Assert.Equal(expectedOutputBytesSoFar.ToArray(), new Span<byte>(destination, 0, expectedOutputBytesSoFar.Count).ToArray());
destination = new byte[expectedOutputBytesSoFar.Count + 1024]; // then with enough output space to write "[FFFD]"
Assert.Equal(OperationStatus.Done, encoder.EncodeUtf8(aggregateInputBytesSoFar.ToArray(), destination, out bytesConsumed, out bytesWritten, isFinalBlock: true));
Assert.Equal(aggregateInputBytesSoFar.Count, bytesConsumed);
Assert.Equal(expectedOutputBytesSoFar.Count + "[FFFD]".Length, bytesWritten);
Assert.Equal(expectedOutputBytesSoFar.Concat(Encoding.UTF8.GetBytes("[FFFD]")).ToArray(), new Span<byte>(destination, 0, expectedOutputBytesSoFar.Count + "[FFFD]".Length).ToArray());
}
// Consume the remainder of this entry and make sure it escaped properly (if needed).
aggregateInputBytesSoFar.Add(entry.utf8Bytes.Last());
// First with not enough space in the destination buffer.
destination = new byte[expectedOutputBytesSoFar.Count + Encoding.UTF8.GetByteCount(entry.output) - 1];
Assert.Equal(OperationStatus.DestinationTooSmall, encoder.EncodeUtf8(aggregateInputBytesSoFar.ToArray(), destination, out bytesConsumed, out bytesWritten, isFinalBlock: true));
Assert.Equal(aggregateInputByteCountAtStartOfLoop, bytesConsumed);
Assert.Equal(expectedOutputBytesSoFar.Count, bytesWritten);
Assert.Equal(expectedOutputBytesSoFar.ToArray(), new Span<byte>(destination, 0, expectedOutputBytesSoFar.Count).ToArray());
// Then with exactly enough space in the destination buffer,
// and again with more than enough space in the destination buffer.
expectedOutputBytesSoFar.AddRange(Encoding.UTF8.GetBytes(entry.output));
foreach (int destinationLength in new[] { expectedOutputBytesSoFar.Count, expectedOutputBytesSoFar.Count + 1024 })
{
destination = new byte[destinationLength];
Assert.Equal(OperationStatus.Done, encoder.EncodeUtf8(aggregateInputBytesSoFar.ToArray(), destination, out bytesConsumed, out bytesWritten, isFinalBlock: false));
Assert.Equal(aggregateInputBytesSoFar.Count, bytesConsumed);
Assert.Equal(expectedOutputBytesSoFar.Count, bytesWritten);
Assert.Equal(expectedOutputBytesSoFar.ToArray(), new Span<byte>(destination, 0, expectedOutputBytesSoFar.Count).ToArray());
}
}
}
[Fact]
public void EncodeUtf8_EmptyInput_AlwaysSucceeds()
{
// Arrange
var encoder = new ConfigurableScalarTextEncoder(_ => false /* disallow everything */);
// Act & assert
Assert.Equal(OperationStatus.Done, encoder.EncodeUtf8(ReadOnlySpan<byte>.Empty, Span<byte>.Empty, out int bytesConsumed, out int bytesWritten, isFinalBlock: true));
Assert.Equal(0, bytesConsumed);
Assert.Equal(0, bytesWritten);
Assert.Equal(OperationStatus.Done, encoder.EncodeUtf8(ReadOnlySpan<byte>.Empty, Span<byte>.Empty, out bytesConsumed, out bytesWritten, isFinalBlock: false));
Assert.Equal(0, bytesConsumed);
Assert.Equal(0, bytesWritten);
}
[Fact]
public void FindFirstCharToEncodeUtf8_EmptyInput_ReturnsNegOne()
{
// Arrange
var encoder = new ConfigurableScalarTextEncoder(_ => false /* disallow everything */);
// Act
int idxOfFirstByteToEncode = encoder.FindFirstCharacterToEncodeUtf8(ReadOnlySpan<byte>.Empty);
// Assert
Assert.Equal(-1, idxOfFirstByteToEncode);
}
[Fact]
public void FindFirstCharToEncodeUtf8_WellFormedData_AllCharsAllowed()
{
// Arrange
byte[] inputBytes = Encoding.UTF8.GetBytes("\U00000040\U00000400\U00004000\U00040000"); // code units of different lengths
var encoder = new ConfigurableScalarTextEncoder(_ => true /* allow everything */);
// Act
int idxOfFirstByteToEncode = encoder.FindFirstCharacterToEncodeUtf8(inputBytes);
// Assert
Assert.Equal(-1, idxOfFirstByteToEncode);
}
[Fact]
public void FindFirstCharToEncodeUtf8_WellFormedData_SomeCharsDisallowed()
{
// Arrange
byte[] inputBytes = Encoding.UTF8.GetBytes("\U00000040\U00000400\U00004000\U00040000"); // code units of different lengths
var encoder = new ConfigurableScalarTextEncoder(codePoint => codePoint != 0x4000 /* disallow U+4000, allow all else */);
// Act
int idxOfFirstByteToEncode = encoder.FindFirstCharacterToEncodeUtf8(inputBytes);
// Assert
Assert.Equal(3, idxOfFirstByteToEncode);
}
[Theory]
[InlineData(new byte[] { 0x00, 0xC0, 0x80, 0x80 }, 1)]
[InlineData(new byte[] { 0x00, 0xC2, 0x80, 0x80 }, 3)]
[InlineData(new byte[] { 0xF1, 0x80, 0x80 }, 0)]
[InlineData(new byte[] { 0xF1, 0x80, 0x80, 0x80, 0xFF }, 4)]
[InlineData(new byte[] { 0xFF, 0x80, 0x80, 0x80, 0xFF }, 0)]
public void FindFirstCharToEncodeUtf8_IllFormedData_ReturnsIndexOfIllFormedSubsequence(byte[] utf8Data, int expectedIndex)
{
// Arrange
var encoder = new ConfigurableScalarTextEncoder(_ => true /* allow everything */);
// Act
int actualIndex = encoder.FindFirstCharacterToEncodeUtf8(utf8Data);
// Assert
Assert.Equal(expectedIndex, actualIndex);
}
}
}
| |
using UnityEngine;
using System;
using System.Collections.Generic;
using UnityEngine.Events;
namespace UMA
{
/// <summary>
/// UMA data holds the recipe for creating a character and skeleton and Unity references for a built character.
/// </summary>
public class UMAData : MonoBehaviour
{
[Obsolete("UMA 2.5 myRenderer is now obsolete, an uma can have multiple renderers. Use int rendererCount { get; } and GetRenderer(int) instead.", false)]
public SkinnedMeshRenderer myRenderer;
private SkinnedMeshRenderer[] renderers;
public int rendererCount { get { return renderers == null ? 0 : renderers.Length; } }
public SkinnedMeshRenderer GetRenderer(int idx)
{
return renderers[idx];
}
public SkinnedMeshRenderer[] GetRenderers()
{
return renderers;
}
public void SetRenderers(SkinnedMeshRenderer[] renderers)
{
#pragma warning disable 618
myRenderer = (renderers != null && renderers.Length > 0) ? renderers[0] : null;
#pragma warning restore 618
this.renderers = renderers;
}
[NonSerialized]
public bool firstBake;
public UMAGeneratorBase umaGenerator;
[NonSerialized]
public GeneratedMaterials generatedMaterials = new GeneratedMaterials();
private LinkedListNode<UMAData> listNode;
public void MoveToList(LinkedList<UMAData> list)
{
if (listNode.List != null)
{
listNode.List.Remove(listNode);
}
list.AddLast(listNode);
}
public float atlasResolutionScale = 1f;
/// <summary>
/// Has the character mesh changed?
/// </summary>
public bool isMeshDirty;
/// <summary>
/// Has the character skeleton changed?
/// </summary>
public bool isShapeDirty;
/// <summary>
/// Have the overlay textures changed?
/// </summary>
public bool isTextureDirty;
/// <summary>
/// Have the texture atlases changed?
/// </summary>
public bool isAtlasDirty;
public BlendShapeSettings blendShapeSettings = new BlendShapeSettings();
public RuntimeAnimatorController animationController;
private Dictionary<int, int> animatedBonesTable;
public void ResetAnimatedBones()
{
if (animatedBonesTable == null)
{
animatedBonesTable = new Dictionary<int, int>();
}
else
{
animatedBonesTable.Clear();
}
}
public void RegisterAnimatedBone(int hash)
{
if (!animatedBonesTable.ContainsKey(hash))
{
animatedBonesTable.Add(hash, animatedBonesTable.Count);
}
}
public Transform GetGlobalTransform()
{
return (renderers != null && renderers.Length > 0) ? renderers[0].rootBone : umaRoot.transform.Find("Global");
}
public void RegisterAnimatedBoneHierarchy(int hash)
{
if (!animatedBonesTable.ContainsKey(hash))
{
animatedBonesTable.Add(hash, animatedBonesTable.Count);
}
}
public bool cancelled { get; private set; }
[NonSerialized]
public bool dirty = false;
private bool isOfficiallyCreated = false;
/// <summary>
/// Callback event when character has been updated.
/// </summary>
public event Action<UMAData> OnCharacterUpdated { add { if (CharacterUpdated == null) CharacterUpdated = new UMADataEvent(); CharacterUpdated.AddListener(new UnityAction<UMAData>(value)); } remove { CharacterUpdated.RemoveListener(new UnityAction<UMAData>(value)); } }
/// <summary>
/// Callback event when character has been completely created.
/// </summary>
public event Action<UMAData> OnCharacterCreated { add { if (CharacterCreated == null) CharacterCreated = new UMADataEvent(); CharacterCreated.AddListener(new UnityAction<UMAData>(value)); } remove { CharacterCreated.RemoveListener(new UnityAction<UMAData>(value)); } }
/// <summary>
/// Callback event when character has been destroyed.
/// </summary>
public event Action<UMAData> OnCharacterDestroyed { add { if (CharacterDestroyed == null) CharacterDestroyed = new UMADataEvent(); CharacterDestroyed.AddListener(new UnityAction<UMAData>(value)); } remove { CharacterDestroyed.RemoveListener(new UnityAction<UMAData>(value)); } }
/// <summary>
/// Callback event when character DNA has been updated.
/// </summary>
public event Action<UMAData> OnCharacterDnaUpdated { add { if (CharacterDnaUpdated == null) CharacterDnaUpdated = new UMADataEvent(); CharacterDnaUpdated.AddListener(new UnityAction<UMAData>(value)); } remove { CharacterDnaUpdated.RemoveListener(new UnityAction<UMAData>(value)); } }
public UMADataEvent CharacterCreated;
public UMADataEvent CharacterDestroyed;
public UMADataEvent CharacterUpdated;
public UMADataEvent CharacterDnaUpdated;
public UMADataEvent CharacterBegun;
public GameObject umaRoot;
public UMARecipe umaRecipe;
public Animator animator;
public UMASkeleton skeleton;
/// <summary>
/// The approximate height of the character. Calculated by DNA converters.
/// </summary>
public float characterHeight = 2f;
/// <summary>
/// The approximate radius of the character. Calculated by DNA converters.
/// </summary>
public float characterRadius = 0.25f;
/// <summary>
/// The approximate mass of the character. Calculated by DNA converters.
/// </summary>
public float characterMass = 50f;
public UMAData()
{
listNode = new LinkedListNode<UMAData>(this);
}
void Awake()
{
firstBake = true;
if (!umaGenerator)
{
var generatorGO = GameObject.Find("UMAGenerator");
if (generatorGO == null) return;
umaGenerator = generatorGO.GetComponent<UMAGeneratorBase>();
}
if (umaRecipe == null)
{
umaRecipe = new UMARecipe();
}
else
{
SetupOnAwake();
}
}
public void SetupOnAwake()
{
//umaRoot = gameObject;
//animator = umaRoot.GetComponent<Animator>();
animator = gameObject.GetComponent<Animator>();
}
#pragma warning disable 618
/// <summary>
/// Shallow copy from another UMAData.
/// </summary>
/// <param name="other">Source UMAData.</param>
public void Assign(UMAData other)
{
animator = other.animator;
//myRenderer = other.myRenderer;
renderers = other.renderers;
umaRoot = other.umaRoot;
if (animationController == null)
{
animationController = other.animationController;
}
}
#pragma warning restore 618
public bool Validate()
{
bool valid = true;
if (umaGenerator == null)
{
Debug.LogError("UMA data missing required generator!");
valid = false;
}
if (umaRecipe == null)
{
Debug.LogError("UMA data missing required recipe!");
valid = false;
}
else
{
valid = valid && umaRecipe.Validate();
}
if (animationController == null)
{
if (Application.isPlaying)
Debug.LogWarning("No animation controller supplied.");
}
#if UNITY_EDITOR
if (!valid && UnityEditor.EditorApplication.isPlaying)
{
Debug.LogError("UMAData: Recipe or Generator is not valid!");
UnityEditor.EditorApplication.isPaused = true;
}
#endif
return valid;
}
[System.Serializable]
public class GeneratedMaterials
{
public List<GeneratedMaterial> materials = new List<GeneratedMaterial>();
public int rendererCount;
}
[System.Serializable]
public class GeneratedMaterial
{
public UMAMaterial umaMaterial;
public Material material;
public List<MaterialFragment> materialFragments = new List<MaterialFragment>();
public Texture[] resultingAtlasList;
public Vector2 cropResolution;
public float resolutionScale;
public string[] textureNameList;
public int renderer;
}
[System.Serializable]
public class MaterialFragment
{
public int size;
public Color baseColor;
public UMAMaterial umaMaterial;
public Rect[] rects;
public textureData[] overlays;
public Color32[] overlayColors;
public Color[][] channelMask;
public Color[][] channelAdditiveMask;
public SlotData slotData;
public OverlayData[] overlayData;
public Rect atlasRegion;
public bool isRectShared;
public List<OverlayData> overlayList;
public MaterialFragment rectFragment;
public textureData baseOverlay;
public Color GetMultiplier(int overlay, int textureType)
{
if (channelMask[overlay] != null && channelMask[overlay].Length > 0)
{
return channelMask[overlay][textureType];
}
else
{
if (textureType > 0) return Color.white;
if (overlay == 0) return baseColor;
return overlayColors[overlay - 1];
}
}
public Color32 GetAdditive(int overlay, int textureType)
{
if (channelAdditiveMask[overlay] != null && channelAdditiveMask[overlay].Length > 0)
{
return channelAdditiveMask[overlay][textureType];
}
else
{
return new Color32(0, 0, 0, 0);
}
}
}
public void Show()
{
for (int i = 0; i < rendererCount; i++)
GetRenderer(i).enabled = true;
}
public void Hide()
{
for (int i = 0; i < rendererCount; i++)
GetRenderer(i).enabled = false;
}
[System.Serializable]
public class textureData
{
public Texture[] textureList;
public Texture alphaTexture;
public OverlayDataAsset.OverlayType overlayType;
}
[System.Serializable]
public class resultAtlasTexture
{
public Texture[] textureList;
}
/// <summary>
/// The UMARecipe class contains the race, DNA, and color data required to build a UMA character.
/// </summary>
[System.Serializable]
public class UMARecipe
{
public RaceData raceData;
Dictionary<int, UMADnaBase> _umaDna;
protected Dictionary<int, UMADnaBase> umaDna
{
get
{
if (_umaDna == null)
{
_umaDna = new Dictionary<int, UMADnaBase>();
for (int i = 0; i < dnaValues.Count; i++)
_umaDna.Add(dnaValues[i].DNATypeHash, dnaValues[i]);
}
return _umaDna;
}
set
{
_umaDna = value;
}
}
protected Dictionary<int, DnaConverterBehaviour.DNAConvertDelegate> umaDnaConverter = new Dictionary<int, DnaConverterBehaviour.DNAConvertDelegate>();
protected Dictionary<string, int> mergedSharedColors = new Dictionary<string, int>();
public List<UMADnaBase> dnaValues = new List<UMADnaBase>();
public SlotData[] slotDataList;
public OverlayColorData[] sharedColors;
public bool Validate()
{
bool valid = true;
if (raceData == null)
{
Debug.LogError("UMA recipe missing required race!");
valid = false;
}
else
{
valid = valid && raceData.Validate();
}
if (slotDataList == null || slotDataList.Length == 0)
{
Debug.LogError("UMA recipe slot list is empty!");
valid = false;
}
int slotDataCount = 0;
for (int i = 0; i < slotDataList.Length; i++)
{
var slotData = slotDataList[i];
if (slotData != null)
{
slotDataCount++;
valid = valid && slotData.Validate();
}
}
if (slotDataCount < 1)
{
Debug.LogError("UMA recipe slot list contains only null objects!");
valid = false;
}
return valid;
}
/// <summary>
/// Checks to see if the sharedColors array contains the passed color
/// </summary>
/// <param name="col"></param>
/// <returns></returns>
public bool HasSharedColor(OverlayColorData col)
{
foreach(OverlayColorData ocd in sharedColors)
{
if (ocd.Equals(col))
{
return true;
}
}
return false;
}
#pragma warning disable 618
/// <summary>
/// Gets the DNA array.
/// </summary>
/// <returns>The DNA array.</returns>
public UMADnaBase[] GetAllDna()
{
if ((raceData == null) || (slotDataList == null))
{
return new UMADnaBase[0];
}
return dnaValues.ToArray();
}
/// <summary>
/// Adds the DNA specified.
/// </summary>
/// <param name="dna">DNA.</param>
public void AddDna(UMADnaBase dna)
{
umaDna.Add(dna.DNATypeHash, dna);
dnaValues.Add(dna);
}
/// <summary>
/// Get DNA of specified type.
/// </summary>
/// <returns>The DNA (or null if not found).</returns>
/// <typeparam name="T">Type.</typeparam>
public T GetDna<T>()
where T : UMADnaBase
{
UMADnaBase dna;
if (umaDna.TryGetValue(UMAUtils.StringToHash(typeof(T).Name), out dna))
{
return dna as T;
}
return null;
}
/// <summary>
/// Removes all DNA.
/// </summary>
public void ClearDna()
{
umaDna.Clear();
dnaValues.Clear();
}
/// <summary>
/// DynamicUMADna:: a version of RemoveDna that uses the dnaTypeNameHash
/// </summary>
/// <param name="dnaTypeNameHash"></param>
public void RemoveDna(int dnaTypeNameHash)
{
dnaValues.Remove(umaDna[dnaTypeNameHash]);
umaDna.Remove(dnaTypeNameHash);
}
/// <summary>
/// Removes the specified DNA.
/// </summary>
/// <param name="type">Type.</param>
public void RemoveDna(Type type)
{
int dnaTypeNameHash = UMAUtils.StringToHash(type.Name);
dnaValues.Remove(umaDna[dnaTypeNameHash]);
umaDna.Remove(dnaTypeNameHash);
}
/// <summary>
/// Get DNA of specified type.
/// </summary>
/// <returns>The DNA (or null if not found).</returns>
/// <param name="type">Type.</param>
public UMADnaBase GetDna(Type type)
{
UMADnaBase dna;
if (umaDna.TryGetValue(UMAUtils.StringToHash(type.Name), out dna))
{
return dna;
}
return null;
}
/// <summary>
/// Get DNA of specified type.
/// </summary>
/// <returns>The DNA (or null if not found).</returns>
/// <param name="dnaTypeNameHash">Type.</param>
public UMADnaBase GetDna(int dnaTypeNameHash)
{
UMADnaBase dna;
if (umaDna.TryGetValue(dnaTypeNameHash, out dna))
{
return dna;
}
return null;
}
/// <summary>
/// Get DNA of specified type, adding if not found.
/// </summary>
/// <returns>The DNA.</returns>
/// <typeparam name="T">Type.</typeparam>
public T GetOrCreateDna<T>()
where T : UMADnaBase
{
T res = GetDna<T>();
if (res == null)
{
res = typeof(T).GetConstructor(System.Type.EmptyTypes).Invoke(null) as T;
umaDna.Add(res.DNATypeHash, res);
dnaValues.Add(res);
}
return res;
}
/// <summary>
/// Get DNA of specified type, adding if not found.
/// </summary>
/// <returns>The DNA.</returns>
/// <param name="type">Type.</param>
public UMADnaBase GetOrCreateDna(Type type)
{
UMADnaBase dna;
var typeNameHash = UMAUtils.StringToHash(type.Name);
if (umaDna.TryGetValue(typeNameHash, out dna))
{
return dna;
}
dna = type.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
umaDna.Add(typeNameHash, dna);
dnaValues.Add(dna);
return dna;
}
/// <summary>
/// Get DNA of specified type, adding if not found.
/// </summary>
/// <returns>The DNA.</returns>
/// <param name="type">Type.</param>
/// <param name="dnaTypeHash">The DNAType's hash."</param>
public UMADnaBase GetOrCreateDna(Type type, int dnaTypeHash)
{
UMADnaBase dna;
if (umaDna.TryGetValue(dnaTypeHash, out dna))
{
return dna;
}
dna = type.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
dna.DNATypeHash = dnaTypeHash;
umaDna.Add(dnaTypeHash, dna);
dnaValues.Add(dna);
return dna;
}
#pragma warning restore 618
/// <summary>
/// Sets the race.
/// </summary>
/// <param name="raceData">Race.</param>
public void SetRace(RaceData raceData)
{
this.raceData = raceData;
ClearDNAConverters();
}
/// <summary>
/// Gets the race.
/// </summary>
/// <returns>The race.</returns>
public RaceData GetRace()
{
return this.raceData;
}
/// <summary>
/// Sets the slot at a given index.
/// </summary>
/// <param name="index">Index.</param>
/// <param name="slot">Slot.</param>
public void SetSlot(int index, SlotData slot)
{
if (slotDataList == null)
{
slotDataList = new SlotData[1];
}
if (index >= slotDataList.Length)
{
System.Array.Resize<SlotData>(ref slotDataList, index + 1);
}
slotDataList[index] = slot;
}
/// <summary>
/// Sets the entire slot array.
/// </summary>
/// <param name="slots">Slots.</param>
public void SetSlots(SlotData[] slots)
{
slotDataList = slots;
}
/// <summary>
/// Combine additional slot with current data.
/// </summary>
/// <param name="slot">Slot.</param>
/// <param name="dontSerialize">If set to <c>true</c> slot will not be serialized.</param>
public SlotData MergeSlot(SlotData slot, bool dontSerialize)
{
if ((slot == null) || (slot.asset == null))
return null;
int overlayCount = 0;
for (int i = 0; i < slotDataList.Length; i++)
{
if (slotDataList[i] == null)
continue;
if (slot.asset == slotDataList[i].asset)
{
SlotData originalSlot = slotDataList[i];
overlayCount = slot.OverlayCount;
for (int j = 0; j < overlayCount; j++)
{
OverlayData overlay = slot.GetOverlay(j);
//DynamicCharacterSystem:: Needs to use alternative methods that find equivalent overlays since they may not be Equal if they were in an assetBundle
OverlayData originalOverlay = originalSlot.GetEquivalentUsedOverlay(overlay);
if (originalOverlay != null)
{
originalOverlay.CopyColors(overlay);//also copies textures
if (overlay.colorData.HasName())
{
int sharedIndex;
if (mergedSharedColors.TryGetValue(overlay.colorData.name, out sharedIndex))
{
originalOverlay.colorData = sharedColors[sharedIndex];
}
}
}
else
{
OverlayData overlayCopy = overlay.Duplicate();
if (overlayCopy.colorData.HasName())
{
int sharedIndex;
if (mergedSharedColors.TryGetValue(overlayCopy.colorData.name, out sharedIndex))
{
overlayCopy.colorData = sharedColors[sharedIndex];
}
}
originalSlot.AddOverlay(overlayCopy);
}
}
originalSlot.dontSerialize = dontSerialize;
return originalSlot;
}
}
int insertIndex = slotDataList.Length;
System.Array.Resize<SlotData>(ref slotDataList, slotDataList.Length + 1);
SlotData slotCopy = slot.Copy();
slotCopy.dontSerialize = dontSerialize;
overlayCount = slotCopy.OverlayCount;
for (int j = 0; j < overlayCount; j++)
{
OverlayData overlay = slotCopy.GetOverlay(j);
if (overlay.colorData.HasName())
{
int sharedIndex;
if (mergedSharedColors.TryGetValue(overlay.colorData.name, out sharedIndex))
{
overlay.colorData = sharedColors[sharedIndex];
}
}
}
slotDataList[insertIndex] = slotCopy;
MergeMatchingOverlays();
return slotCopy;
}
/// <summary>
/// Gets a slot by index.
/// </summary>
/// <returns>The slot.</returns>
/// <param name="index">Index.</param>
public SlotData GetSlot(int index)
{
if (index < slotDataList.Length)
return slotDataList[index];
return null;
}
/// <summary>
/// Gets the complete array of slots.
/// </summary>
/// <returns>The slot array.</returns>
public SlotData[] GetAllSlots()
{
return slotDataList;
}
/// <summary>
/// Gets the number of slots.
/// </summary>
/// <returns>The slot array size.</returns>
public int GetSlotArraySize()
{
return slotDataList.Length;
}
/// <summary>
/// Are two overlay lists the same?
/// </summary>
/// <returns><c>true</c>, if lists match, <c>false</c> otherwise.</returns>
/// <param name="list1">List1.</param>
/// <param name="list2">List2.</param>
public static bool OverlayListsMatch(List<OverlayData> list1, List<OverlayData> list2)
{
if ((list1 == null) || (list2 == null))
return false;
if ((list1.Count == 0) || (list1.Count != list2.Count))
return false;
for (int i = 0; i < list1.Count; i++)
{
OverlayData overlay1 = list1[i];
if (!(overlay1))
continue;
bool found = false;
for (int j = 0; j < list2.Count; j++)
{
OverlayData overlay2 = list2[i];
if (!(overlay2))
continue;
if (OverlayData.Equivalent(overlay1, overlay2))
{
found = true;
break;
}
}
if (!found)
return false;
}
return true;
}
/// <summary>
/// Ensures slots with matching overlays will share the same references.
/// </summary>
public void MergeMatchingOverlays()
{
for (int i = 0; i < slotDataList.Length; i++)
{
if (slotDataList[i] == null)
continue;
List<OverlayData> slotOverlays = slotDataList[i].GetOverlayList();
for (int j = i + 1; j < slotDataList.Length; j++)
{
if (slotDataList[j] == null)
continue;
List<OverlayData> slot2Overlays = slotDataList[j].GetOverlayList();
if (OverlayListsMatch(slotOverlays, slot2Overlays))
{
slotDataList[j].SetOverlayList(slotOverlays);
}
}
}
}
#pragma warning disable 618
/// <summary>
/// Applies each DNA converter to the UMA data and skeleton.
/// </summary>
/// <param name="umaData">UMA data.</param>
/// <param name="fixUpUMADnaToDynamicUMADna"></param>
public void ApplyDNA(UMAData umaData, bool fixUpUMADnaToDynamicUMADna = false)
{
EnsureAllDNAPresent();
//DynamicUMADna:: when loading an older recipe that has UMADnaHumanoid/Tutorial into a race that now uses DynamicUmaDna the following wont work
//so check that and fix it if it happens
if (fixUpUMADnaToDynamicUMADna)
DynamicDNAConverterBehaviourBase.FixUpUMADnaToDynamicUMADna(this);
foreach (var dnaEntry in umaDna)
{
DnaConverterBehaviour.DNAConvertDelegate dnaConverter;
if (umaDnaConverter.TryGetValue(dnaEntry.Key, out dnaConverter))
{
dnaConverter(umaData, umaData.GetSkeleton());
}
else
{
//DynamicUMADna:: try again this time calling FixUpUMADnaToDynamicUMADna first
if (fixUpUMADnaToDynamicUMADna == false)
{
ApplyDNA(umaData, true);
break;
}
else
{
Debug.LogWarning("Cannot apply dna: " + dnaEntry.Value.GetType().Name + " using key " + dnaEntry.Key);
}
}
}
}
/// <summary>
/// Ensures all DNA convertes from slot and race data are defined.
/// </summary>
public void EnsureAllDNAPresent()
{
List<int> requiredDnas = new List<int>();
if (raceData != null)
{
foreach (var converter in raceData.dnaConverterList)
{
var dnaTypeHash = converter.DNATypeHash;
//'old' dna converters return a typehash based on the type name.
//Dynamic DNA Converters return the typehash of their dna asset or 0 if none is assigned- we dont want to include those
if (dnaTypeHash == 0)
continue;
requiredDnas.Add(dnaTypeHash);
if (!umaDna.ContainsKey(dnaTypeHash))
{
var dna = converter.DNAType.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
dna.DNATypeHash = dnaTypeHash;
//DynamicUMADna:: needs the DNAasset from the converter - moved because this might change
if (converter is DynamicDNAConverterBehaviourBase)
{
((DynamicUMADnaBase)dna).dnaAsset = ((DynamicDNAConverterBehaviourBase)converter).dnaAsset;
}
umaDna.Add(dnaTypeHash, dna);
dnaValues.Add(dna);
}
else if (converter is DynamicDNAConverterBehaviourBase)
{
var dna = umaDna[dnaTypeHash];
((DynamicUMADnaBase)dna).dnaAsset = ((DynamicDNAConverterBehaviourBase)converter).dnaAsset;
}
}
}
foreach (var slotData in slotDataList)
{
if (slotData != null && slotData.asset.slotDNA != null)
{
var dnaTypeHash = slotData.asset.slotDNA.DNATypeHash;
//'old' dna converters return a typehash based on the type name.
//Dynamic DNA Converters return the typehash of their dna asset or 0 if none is assigned- we dont want to include those
if (dnaTypeHash == 0)
continue;
requiredDnas.Add(dnaTypeHash);
if (!umaDna.ContainsKey(dnaTypeHash))
{
var dna = slotData.asset.slotDNA.DNAType.GetConstructor(System.Type.EmptyTypes).Invoke(null) as UMADnaBase;
dna.DNATypeHash = dnaTypeHash;
//DynamicUMADna:: needs the DNAasset from the converter TODO are there other places where I heed to sort out this slotDNA?
if (slotData.asset.slotDNA is DynamicDNAConverterBehaviourBase)
{
((DynamicUMADnaBase)dna).dnaAsset = ((DynamicDNAConverterBehaviourBase)slotData.asset.slotDNA).dnaAsset;
}
umaDna.Add(dnaTypeHash, dna);
dnaValues.Add(dna);
}
else if (slotData.asset.slotDNA is DynamicDNAConverterBehaviourBase)
{
var dna = umaDna[dnaTypeHash];
((DynamicUMADnaBase)dna).dnaAsset = ((DynamicDNAConverterBehaviourBase)slotData.asset.slotDNA).dnaAsset;
}
}
}
foreach (int addedDNAHash in umaDnaConverter.Keys)
{
requiredDnas.Add(addedDNAHash);
}
//now remove any we no longer need
var keysToRemove = new List<int>();
foreach(var kvp in umaDna)
{
if (!requiredDnas.Contains(kvp.Key))
keysToRemove.Add(kvp.Key);
}
for(int i = 0; i < keysToRemove.Count; i++)
{
RemoveDna(keysToRemove[i]);
}
}
#pragma warning restore 618
/// <summary>
/// Resets the DNA converters to those defined in the race.
/// </summary>
public void ClearDNAConverters()
{
umaDnaConverter.Clear();
if (raceData != null)
{
foreach (var converter in raceData.dnaConverterList)
{
if(converter == null)
{
Debug.LogWarning("RaceData " + raceData.raceName + " has a missing DNAConverter");
continue;
}
//'old' dna converters return a typehash based on the type name.
//Dynamic DNA Converters return the typehash of their dna asset or 0 if none is assigned- we dont want to include those
if (converter.DNATypeHash == 0)
continue;
if (!umaDnaConverter.ContainsKey(converter.DNATypeHash))
{
umaDnaConverter.Add(converter.DNATypeHash, converter.ApplyDnaAction);
}
else
{
//We MUST NOT give DynamicDNA the same hash a UMADnaHumanoid or else we loose the values
Debug.Log(raceData.raceName + " has multiple dna converters that are trying to use the same dna (" + converter.DNATypeHash + "). This is not allowed.");
}
}
}
}
/// <summary>
/// Adds a DNA converter.
/// </summary>
/// <param name="dnaConverter">DNA converter.</param>
public void AddDNAUpdater(DnaConverterBehaviour dnaConverter)
{
if (dnaConverter == null) return;
//DynamicDNAConverter:: We need to SET these values using the TypeHash since
//just getting the hash of the DNAType will set the same value for all instance of a DynamicDNAConverter
if (!umaDnaConverter.ContainsKey(dnaConverter.DNATypeHash))
{
umaDnaConverter.Add(dnaConverter.DNATypeHash, dnaConverter.ApplyDnaAction);
}
else
{
Debug.Log(raceData.raceName + " has multiple dna converters that are trying to use the same dna ("+ dnaConverter.DNATypeHash+"). This is not allowed.");
}
}
/// <summary>
/// Shallow copy of UMARecipe.
/// </summary>
public UMARecipe Mirror()
{
var newRecipe = new UMARecipe();
newRecipe.raceData = raceData;
newRecipe.umaDna = umaDna;
newRecipe.dnaValues = dnaValues;
newRecipe.slotDataList = slotDataList;
return newRecipe;
}
/// <summary>
/// Combine additional recipe with current data.
/// </summary>
/// <param name="recipe">Recipe.</param>
/// <param name="dontSerialize">If set to <c>true</c> recipe will not be serialized.</param>
public void Merge(UMARecipe recipe, bool dontSerialize)
{
if (recipe == null)
return;
if ((recipe.raceData != null) && (recipe.raceData != raceData))
{
Debug.LogWarning("Merging recipe with conflicting race data: " + recipe.raceData.name);
}
foreach (var dnaEntry in recipe.umaDna)
{
var destDNA = GetOrCreateDna(dnaEntry.Value.GetType(), dnaEntry.Key);
destDNA.Values = dnaEntry.Value.Values;
}
mergedSharedColors.Clear();
if (sharedColors == null)
sharedColors = new OverlayColorData[0];
if (recipe.sharedColors != null)
{
for (int i = 0; i < sharedColors.Length; i++)
{
if (sharedColors[i] != null && sharedColors[i].HasName())
{
while (mergedSharedColors.ContainsKey(sharedColors[i].name))
{
sharedColors[i].name = sharedColors[i].name + ".";
}
mergedSharedColors.Add(sharedColors[i].name, i);
}
}
for (int i = 0; i < recipe.sharedColors.Length; i++)
{
OverlayColorData sharedColor = recipe.sharedColors[i];
if (sharedColor != null && sharedColor.HasName())
{
int sharedIndex;
if (!mergedSharedColors.TryGetValue(sharedColor.name, out sharedIndex))
{
int index = sharedColors.Length;
mergedSharedColors.Add(sharedColor.name, index);
Array.Resize<OverlayColorData>(ref sharedColors, index + 1);
sharedColors[index] = sharedColor.Duplicate();
}
}
}
}
if (slotDataList == null)
slotDataList = new SlotData[0];
if (recipe.slotDataList != null)
{
for (int i = 0; i < recipe.slotDataList.Length; i++)
{
MergeSlot(recipe.slotDataList[i], dontSerialize);
}
}
}
}
[System.Serializable]
public class BoneData
{
public Transform boneTransform;
public Vector3 originalBoneScale;
public Vector3 originalBonePosition;
public Quaternion originalBoneRotation;
}
/// <summary>
/// Calls character updated and/or created events.
/// </summary>
public void FireUpdatedEvent(bool cancelled)
{
this.cancelled = cancelled;
if (!this.cancelled && !isOfficiallyCreated)
{
isOfficiallyCreated = true;
if (CharacterCreated != null)
{
CharacterCreated.Invoke(this);
}
}
if (CharacterUpdated != null)
{
CharacterUpdated.Invoke(this);
}
dirty = false;
}
public void ApplyDNA()
{
umaRecipe.ApplyDNA(this);
}
public virtual void Dirty()
{
if (dirty) return;
dirty = true;
if (!umaGenerator)
{
umaGenerator = FindObjectOfType<UMAGeneratorBase>();
}
if (umaGenerator)
{
umaGenerator.addDirtyUMA(this);
}
}
void OnDestroy()
{
if (isOfficiallyCreated)
{
if (CharacterDestroyed != null)
{
CharacterDestroyed.Invoke(this);
}
isOfficiallyCreated = false;
}
if (umaRoot != null)
{
CleanTextures();
CleanMesh(true);
CleanAvatar();
UMAUtils.DestroySceneObject(umaRoot);
}
}
/// <summary>
/// Destory Mecanim avatar and animator.
/// </summary>
public void CleanAvatar()
{
animationController = null;
if (animator != null)
{
if (animator.avatar) UMAUtils.DestroySceneObject(animator.avatar);
if (animator) UMAUtils.DestroySceneObject(animator);
}
}
/// <summary>
/// Destroy textures used to render mesh.
/// </summary>
public void CleanTextures()
{
for (int atlasIndex = 0; atlasIndex < generatedMaterials.materials.Count; atlasIndex++)
{
if (generatedMaterials.materials[atlasIndex] != null && generatedMaterials.materials[atlasIndex].resultingAtlasList != null)
{
for (int textureIndex = 0; textureIndex < generatedMaterials.materials[atlasIndex].resultingAtlasList.Length; textureIndex++)
{
if (generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex] != null)
{
Texture tempTexture = generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex];
if (tempTexture is RenderTexture)
{
RenderTexture tempRenderTexture = tempTexture as RenderTexture;
tempRenderTexture.Release();
UMAUtils.DestroySceneObject(tempRenderTexture);
}
else
{
UMAUtils.DestroySceneObject(tempTexture);
}
generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex] = null;
}
}
}
}
}
/// <summary>
/// Destroy materials used to render mesh.
/// </summary>
/// <param name="destroyRenderer">If set to <c>true</c> destroy mesh renderer.</param>
public void CleanMesh(bool destroyRenderer)
{
for(int j = 0; j < rendererCount; j++)
{
var renderer = GetRenderer(j);
var mats = renderer.sharedMaterials;
for (int i = 0; i < mats.Length; i++)
{
if (mats[i])
{
UMAUtils.DestroySceneObject(mats[i]);
}
}
if (destroyRenderer)
{
UMAUtils.DestroySceneObject(renderer.sharedMesh);
UMAUtils.DestroySceneObject(renderer);
}
}
}
public Texture[] backUpTextures()
{
List<Texture> textureList = new List<Texture>();
for (int atlasIndex = 0; atlasIndex < generatedMaterials.materials.Count; atlasIndex++)
{
if (generatedMaterials.materials[atlasIndex] != null && generatedMaterials.materials[atlasIndex].resultingAtlasList != null)
{
for (int textureIndex = 0; textureIndex < generatedMaterials.materials[atlasIndex].resultingAtlasList.Length; textureIndex++)
{
if (generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex] != null)
{
Texture tempTexture = generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex];
textureList.Add(tempTexture);
generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex] = null;
}
}
}
}
return textureList.ToArray();
}
public RenderTexture GetFirstRenderTexture()
{
for (int atlasIndex = 0; atlasIndex < generatedMaterials.materials.Count; atlasIndex++)
{
if (generatedMaterials.materials[atlasIndex] != null && generatedMaterials.materials[atlasIndex].resultingAtlasList != null)
{
for (int textureIndex = 0; textureIndex < generatedMaterials.materials[atlasIndex].resultingAtlasList.Length; textureIndex++)
{
if (generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex] != null)
{
RenderTexture tempTexture = generatedMaterials.materials[atlasIndex].resultingAtlasList[textureIndex] as RenderTexture;
if (tempTexture != null)
{
return tempTexture;
}
}
}
}
}
return null;
}
/// <summary>
/// Gets the game object for a bone by name.
/// </summary>
/// <returns>The game object (or null if hash not in skeleton).</returns>
/// <param name="boneName">Bone name.</param>
public GameObject GetBoneGameObject(string boneName)
{
return GetBoneGameObject(UMAUtils.StringToHash(boneName));
}
/// <summary>
/// Gets the game object for a bone by name hash.
/// </summary>
/// <returns>The game object (or null if hash not in skeleton).</returns>
/// <param name="boneHash">Bone name hash.</param>
public GameObject GetBoneGameObject(int boneHash)
{
return skeleton.GetBoneGameObject(boneHash);
}
/// <summary>
/// Gets the complete DNA array.
/// </summary>
/// <returns>The DNA array.</returns>
public UMADnaBase[] GetAllDna()
{
return umaRecipe.GetAllDna();
}
/// <summary>
/// DynamicUMADna:: Retrieve DNA by dnaTypeNameHash.
/// </summary>
/// <returns>The DNA (or null if not found).</returns>
/// <param name="dnaTypeNameHash">dnaTypeNameHash.</param>
public UMADnaBase GetDna(int dnaTypeNameHash)
{
return umaRecipe.GetDna(dnaTypeNameHash);
}
/// <summary>
/// Retrieve DNA by type.
/// </summary>
/// <returns>The DNA (or null if not found).</returns>
/// <param name="type">Type.</param>
public UMADnaBase GetDna(Type type)
{
return umaRecipe.GetDna(type);
}
/// <summary>
/// Retrieve DNA by type.
/// </summary>
/// <returns>The DNA (or null if not found).</returns>
/// <typeparam name="T">The type od DNA requested.</typeparam>
public T GetDna<T>()
where T : UMADnaBase
{
return umaRecipe.GetDna<T>();
}
/// <summary>
/// Marks portions of the UMAData as modified.
/// </summary>
/// <param name="dnaDirty">If set to <c>true</c> DNA has changed.</param>
/// <param name="textureDirty">If set to <c>true</c> texture has changed.</param>
/// <param name="meshDirty">If set to <c>true</c> mesh has changed.</param>
public void Dirty(bool dnaDirty, bool textureDirty, bool meshDirty)
{
isShapeDirty |= dnaDirty;
isTextureDirty |= textureDirty;
isMeshDirty |= meshDirty;
Dirty();
}
/// <summary>
/// Sets the slot at a given index.
/// </summary>
/// <param name="index">Index.</param>
/// <param name="slot">Slot.</param>
public void SetSlot(int index, SlotData slot)
{
umaRecipe.SetSlot(index, slot);
}
/// <summary>
/// Sets the entire slot array.
/// </summary>
/// <param name="slots">Slots.</param>
public void SetSlots(SlotData[] slots)
{
umaRecipe.SetSlots(slots);
}
/// <summary>
/// Gets a slot by index.
/// </summary>
/// <returns>The slot.</returns>
/// <param name="index">Index.</param>
public SlotData GetSlot(int index)
{
return umaRecipe.GetSlot(index);
}
/// <summary>
/// Gets the number of slots.
/// </summary>
/// <returns>The slot array size.</returns>
public int GetSlotArraySize()
{
return umaRecipe.GetSlotArraySize();
}
/// <summary>
/// Gets the skeleton.
/// </summary>
/// <returns>The skeleton.</returns>
public UMASkeleton GetSkeleton()
{
return skeleton;
}
/// <summary>
/// Align skeleton to the TPose.
/// </summary>
public void GotoTPose()
{
if ((umaRecipe.raceData != null) && (umaRecipe.raceData.TPose != null))
{
var tpose = umaRecipe.raceData.TPose;
tpose.DeSerialize();
for (int i = 0; i < tpose.boneInfo.Length; i++)
{
var bone = tpose.boneInfo[i];
var hash = UMAUtils.StringToHash(bone.name);
if (!skeleton.HasBone(hash)) continue;
skeleton.Set(hash, bone.position, bone.scale, bone.rotation);
}
}
}
public int[] GetAnimatedBones()
{
var res = new int[animatedBonesTable.Count];
foreach (var entry in animatedBonesTable)
{
res[entry.Value] = entry.Key;
}
return res;
}
/// <summary>
/// Calls character begun events on slots.
/// </summary>
public void FireCharacterBegunEvents()
{
if (CharacterBegun != null)
CharacterBegun.Invoke(this);
foreach (var slotData in umaRecipe.slotDataList)
{
if (slotData != null && slotData.asset.CharacterBegun != null)
{
slotData.asset.CharacterBegun.Invoke(this);
}
}
}
/// <summary>
/// Calls DNA applied events on slots.
/// </summary>
public void FireDNAAppliedEvents()
{
if (CharacterDnaUpdated != null)
{
CharacterDnaUpdated.Invoke(this);
}
foreach (var slotData in umaRecipe.slotDataList)
{
if (slotData != null && slotData.asset.DNAApplied != null)
{
slotData.asset.DNAApplied.Invoke(this);
}
}
}
/// <summary>
/// Calls character completed events on slots.
/// </summary>
public void FireCharacterCompletedEvents()
{
foreach (var slotData in umaRecipe.slotDataList)
{
if (slotData != null && slotData.asset.CharacterCompleted != null)
{
slotData.asset.CharacterCompleted.Invoke(this);
}
}
}
/// <summary>
/// Adds additional, non serialized, recipes.
/// </summary>
/// <param name="umaAdditionalRecipes">Additional recipes.</param>
/// <param name="context">Context.</param>
public void AddAdditionalRecipes(UMARecipeBase[] umaAdditionalRecipes, UMAContext context)
{
if (umaAdditionalRecipes != null)
{
foreach (var umaAdditionalRecipe in umaAdditionalRecipes)
{
UMARecipe cachedRecipe = umaAdditionalRecipe.GetCachedRecipe(context);
umaRecipe.Merge(cachedRecipe, true);
}
}
}
#region BlendShape Support
public class BlendShapeSettings
{
public bool ignoreBlendShapes; //default false
public Dictionary<string,float> bakeBlendShapes;
public BlendShapeSettings()
{
ignoreBlendShapes = false;
bakeBlendShapes = new Dictionary<string, float>();
}
}
/// <summary>
/// Sets the blendshape by index and renderer.
/// </summary>
/// <param name="shapeIndex">Name of the blendshape.</param>
/// <param name="weight">Weight(float) to set this blendshape to.</param>
/// <param name="rIndex">index (default first) of the renderer this blendshape is on.</param>
public void SetBlendShape(int shapeIndex, float weight, int rIndex = 0)
{
if (rIndex >= rendererCount) //for multi-renderer support
{
Debug.LogError ("SetBlendShape: This renderer doesn't exist!");
return;
}
if (shapeIndex < 0)
{
Debug.LogError ("SetBlendShape: Index is less than zero!");
return;
}
if (shapeIndex >= renderers [rIndex].sharedMesh.blendShapeCount) //for multi-renderer support
{
Debug.LogError ("SetBlendShape: Index is greater than blendShapeCount!");
return;
}
if (weight < 0.0f || weight > 1.0f)
Debug.LogWarning ("SetBlendShape: Weight is out of range, clamping...");
weight = Mathf.Clamp01 (weight);
weight *= 100.0f; //Scale up to 1-100 for SetBlendShapeWeight.
renderers [rIndex].SetBlendShapeWeight (shapeIndex, weight);//for multi-renderer support
}
/// <summary>
/// Set the blendshape by it's name.
/// </summary>
/// <param name="name">Name of the blendshape.</param>
/// <param name="weight">Weight(float) to set this blendshape to.</param>
public void SetBlendShape(string name, float weight)
{
if (weight < 0.0f || weight > 1.0f)
Debug.LogWarning ("SetBlendShape: Weight is out of range, clamping...");
weight = Mathf.Clamp01 (weight);
weight *= 100.0f; //Scale up to 1-100 for SetBlendShapeWeight.
foreach (SkinnedMeshRenderer renderer in renderers)
{
int index = renderer.sharedMesh.GetBlendShapeIndex(name);
if (index >= 0)
renderer.SetBlendShapeWeight(index, weight);
}
}
/// <summary>
/// Gets the name of the blendshape by index and renderer
/// </summary>
/// <param name="shapeIndex">Index of the blendshape.</param>
/// <param name="rendererIndex">Index of the renderer (default = 0).</param>
public string GetBlendShapeName(int shapeIndex, int rendererIndex = 0)
{
if (shapeIndex < 0)
{
Debug.LogError ("GetBlendShapeName: Index is less than zero!");
return "";
}
if (rendererIndex >= rendererCount) //for multi-renderer support
{
Debug.LogError ("GetBlendShapeName: This renderer doesn't exist!");
return "";
}
//for multi-renderer support
if( shapeIndex < renderers [rendererIndex].sharedMesh.blendShapeCount )
return renderers [rendererIndex].sharedMesh.GetBlendShapeName (shapeIndex);
Debug.LogError ("GetBlendShapeName: no blendshape at index " + shapeIndex + "!");
return "";
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Nop.Core;
using Nop.Core.Domain.Customers;
using Nop.Core.Domain.Orders;
using Nop.Core.Domain.Payments;
using Nop.Core.Plugins;
using Nop.Services.Catalog;
using Nop.Services.Configuration;
namespace Nop.Services.Payments
{
/// <summary>
/// Payment service
/// </summary>
public partial class PaymentService : IPaymentService
{
#region Fields
private readonly PaymentSettings _paymentSettings;
private readonly IPluginFinder _pluginFinder;
private readonly ISettingService _settingService;
private readonly ShoppingCartSettings _shoppingCartSettings;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="paymentSettings">Payment settings</param>
/// <param name="pluginFinder">Plugin finder</param>
/// <param name="settingService">Setting service</param>
/// <param name="shoppingCartSettings">Shopping cart settings</param>
public PaymentService(PaymentSettings paymentSettings,
IPluginFinder pluginFinder,
ISettingService settingService,
ShoppingCartSettings shoppingCartSettings)
{
this._paymentSettings = paymentSettings;
this._pluginFinder = pluginFinder;
this._settingService = settingService;
this._shoppingCartSettings = shoppingCartSettings;
}
#endregion
#region Methods
#region Payment methods
/// <summary>
/// Load active payment methods
/// </summary>
/// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param>
/// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
/// <param name="filterByCountryId">Load records allowed only in a specified country; pass 0 to load all records</param>
/// <returns>Payment methods</returns>
public virtual IList<IPaymentMethod> LoadActivePaymentMethods(Customer customer = null, int storeId = 0, int filterByCountryId = 0)
{
return LoadAllPaymentMethods(customer, storeId, filterByCountryId)
.Where(provider => _paymentSettings.ActivePaymentMethodSystemNames
.Contains(provider.PluginDescriptor.SystemName, StringComparer.InvariantCultureIgnoreCase)).ToList();
}
/// <summary>
/// Load payment provider by system name
/// </summary>
/// <param name="systemName">System name</param>
/// <returns>Found payment provider</returns>
public virtual IPaymentMethod LoadPaymentMethodBySystemName(string systemName)
{
var descriptor = _pluginFinder.GetPluginDescriptorBySystemName<IPaymentMethod>(systemName);
if (descriptor != null)
return descriptor.Instance<IPaymentMethod>();
return null;
}
/// <summary>
/// Load all payment providers
/// </summary>
/// <param name="customer">Load records allowed only to a specified customer; pass null to ignore ACL permissions</param>
/// <param name="storeId">Load records allowed only in a specified store; pass 0 to load all records</param>
/// <param name="filterByCountryId">Load records allowed only in a specified country; pass 0 to load all records</param>
/// <returns>Payment providers</returns>
public virtual IList<IPaymentMethod> LoadAllPaymentMethods(Customer customer = null, int storeId = 0, int filterByCountryId = 0)
{
var paymentMethods = _pluginFinder.GetPlugins<IPaymentMethod>(customer: customer, storeId: storeId).ToList();
if (filterByCountryId == 0)
return paymentMethods;
//filter by country
var paymentMetodsByCountry = new List<IPaymentMethod>();
foreach (var pm in paymentMethods)
{
var restictedCountryIds = GetRestictedCountryIds(pm);
if (!restictedCountryIds.Contains(filterByCountryId))
{
paymentMetodsByCountry.Add(pm);
}
}
return paymentMetodsByCountry;
}
#endregion
#region Restrictions
/// <summary>
/// Gets a list of coutnry identifiers in which a certain payment method is now allowed
/// </summary>
/// <param name="paymentMethod">Payment method</param>
/// <returns>A list of country identifiers</returns>
public virtual IList<int> GetRestictedCountryIds(IPaymentMethod paymentMethod)
{
if (paymentMethod == null)
throw new ArgumentNullException("paymentMethod");
var settingKey = string.Format("PaymentMethodRestictions.{0}", paymentMethod.PluginDescriptor.SystemName);
var restictedCountryIds = _settingService.GetSettingByKey<List<int>>(settingKey);
if (restictedCountryIds == null)
restictedCountryIds = new List<int>();
return restictedCountryIds;
}
/// <summary>
/// Saves a list of coutnry identifiers in which a certain payment method is now allowed
/// </summary>
/// <param name="paymentMethod">Payment method</param>
/// <param name="countryIds">A list of country identifiers</param>
public virtual void SaveRestictedCountryIds(IPaymentMethod paymentMethod, List<int> countryIds)
{
if (paymentMethod == null)
throw new ArgumentNullException("paymentMethod");
//we should be sure that countryIds is of type List<int> (not IList<int>)
var settingKey = string.Format("PaymentMethodRestictions.{0}", paymentMethod.PluginDescriptor.SystemName);
_settingService.SetSetting(settingKey, countryIds);
}
#endregion
#region Processing
/// <summary>
/// Process a payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public virtual ProcessPaymentResult ProcessPayment(ProcessPaymentRequest processPaymentRequest)
{
if (processPaymentRequest.OrderTotal == decimal.Zero)
{
var result = new ProcessPaymentResult
{
NewPaymentStatus = PaymentStatus.Paid
};
return result;
}
//We should strip out any white space or dash in the CC number entered.
if (!String.IsNullOrWhiteSpace(processPaymentRequest.CreditCardNumber))
{
processPaymentRequest.CreditCardNumber = processPaymentRequest.CreditCardNumber.Replace(" ", "");
processPaymentRequest.CreditCardNumber = processPaymentRequest.CreditCardNumber.Replace("-", "");
}
var paymentMethod = LoadPaymentMethodBySystemName(processPaymentRequest.PaymentMethodSystemName);
if (paymentMethod == null)
throw new NopException("Payment method couldn't be loaded");
return paymentMethod.ProcessPayment(processPaymentRequest);
}
/// <summary>
/// Post process payment (used by payment gateways that require redirecting to a third-party URL)
/// </summary>
/// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
public virtual void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
{
//already paid or order.OrderTotal == decimal.Zero
if (postProcessPaymentRequest.Order.PaymentStatus == PaymentStatus.Paid)
return;
var paymentMethod = LoadPaymentMethodBySystemName(postProcessPaymentRequest.Order.PaymentMethodSystemName);
if (paymentMethod == null)
throw new NopException("Payment method couldn't be loaded");
paymentMethod.PostProcessPayment(postProcessPaymentRequest);
}
/// <summary>
/// Gets a value indicating whether customers can complete a payment after order is placed but not completed (for redirection payment methods)
/// </summary>
/// <param name="order">Order</param>
/// <returns>Result</returns>
public virtual bool CanRePostProcessPayment(Order order)
{
if (order == null)
throw new ArgumentNullException("order");
if (!_paymentSettings.AllowRePostingPayments)
return false;
var paymentMethod = LoadPaymentMethodBySystemName(order.PaymentMethodSystemName);
if (paymentMethod == null)
return false; //Payment method couldn't be loaded (for example, was uninstalled)
if (paymentMethod.PaymentMethodType != PaymentMethodType.Redirection)
return false; //this option is available only for redirection payment methods
if (order.Deleted)
return false; //do not allow for deleted orders
if (order.OrderStatus == OrderStatus.Cancelled)
return false; //do not allow for cancelled orders
if (order.PaymentStatus != PaymentStatus.Pending)
return false; //payment status should be Pending
return paymentMethod.CanRePostProcessPayment(order);
}
/// <summary>
/// Gets an additional handling fee of a payment method
/// </summary>
/// <param name="cart">Shoping cart</param>
/// <param name="paymentMethodSystemName">Payment method system name</param>
/// <returns>Additional handling fee</returns>
public virtual decimal GetAdditionalHandlingFee(IList<ShoppingCartItem> cart, string paymentMethodSystemName)
{
if (String.IsNullOrEmpty(paymentMethodSystemName))
return decimal.Zero;
var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);
if (paymentMethod == null)
return decimal.Zero;
decimal result = paymentMethod.GetAdditionalHandlingFee(cart);
if (result < decimal.Zero)
result = decimal.Zero;
if (_shoppingCartSettings.RoundPricesDuringCalculation)
{
result = RoundingHelper.RoundPrice(result);
}
return result;
}
/// <summary>
/// Gets a value indicating whether capture is supported by payment method
/// </summary>
/// <param name="paymentMethodSystemName">Payment method system name</param>
/// <returns>A value indicating whether capture is supported</returns>
public virtual bool SupportCapture(string paymentMethodSystemName)
{
var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);
if (paymentMethod == null)
return false;
return paymentMethod.SupportCapture;
}
/// <summary>
/// Captures payment
/// </summary>
/// <param name="capturePaymentRequest">Capture payment request</param>
/// <returns>Capture payment result</returns>
public virtual CapturePaymentResult Capture(CapturePaymentRequest capturePaymentRequest)
{
var paymentMethod = LoadPaymentMethodBySystemName(capturePaymentRequest.Order.PaymentMethodSystemName);
if (paymentMethod == null)
throw new NopException("Payment method couldn't be loaded");
return paymentMethod.Capture(capturePaymentRequest);
}
/// <summary>
/// Gets a value indicating whether partial refund is supported by payment method
/// </summary>
/// <param name="paymentMethodSystemName">Payment method system name</param>
/// <returns>A value indicating whether partial refund is supported</returns>
public virtual bool SupportPartiallyRefund(string paymentMethodSystemName)
{
var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);
if (paymentMethod == null)
return false;
return paymentMethod.SupportPartiallyRefund;
}
/// <summary>
/// Gets a value indicating whether refund is supported by payment method
/// </summary>
/// <param name="paymentMethodSystemName">Payment method system name</param>
/// <returns>A value indicating whether refund is supported</returns>
public virtual bool SupportRefund(string paymentMethodSystemName)
{
var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);
if (paymentMethod == null)
return false;
return paymentMethod.SupportRefund;
}
/// <summary>
/// Refunds a payment
/// </summary>
/// <param name="refundPaymentRequest">Request</param>
/// <returns>Result</returns>
public virtual RefundPaymentResult Refund(RefundPaymentRequest refundPaymentRequest)
{
var paymentMethod = LoadPaymentMethodBySystemName(refundPaymentRequest.Order.PaymentMethodSystemName);
if (paymentMethod == null)
throw new NopException("Payment method couldn't be loaded");
return paymentMethod.Refund(refundPaymentRequest);
}
/// <summary>
/// Gets a value indicating whether void is supported by payment method
/// </summary>
/// <param name="paymentMethodSystemName">Payment method system name</param>
/// <returns>A value indicating whether void is supported</returns>
public virtual bool SupportVoid(string paymentMethodSystemName)
{
var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);
if (paymentMethod == null)
return false;
return paymentMethod.SupportVoid;
}
/// <summary>
/// Voids a payment
/// </summary>
/// <param name="voidPaymentRequest">Request</param>
/// <returns>Result</returns>
public virtual VoidPaymentResult Void(VoidPaymentRequest voidPaymentRequest)
{
var paymentMethod = LoadPaymentMethodBySystemName(voidPaymentRequest.Order.PaymentMethodSystemName);
if (paymentMethod == null)
throw new NopException("Payment method couldn't be loaded");
return paymentMethod.Void(voidPaymentRequest);
}
/// <summary>
/// Gets a recurring payment type of payment method
/// </summary>
/// <param name="paymentMethodSystemName">Payment method system name</param>
/// <returns>A recurring payment type of payment method</returns>
public virtual RecurringPaymentType GetRecurringPaymentType(string paymentMethodSystemName)
{
var paymentMethod = LoadPaymentMethodBySystemName(paymentMethodSystemName);
if (paymentMethod == null)
return RecurringPaymentType.NotSupported;
return paymentMethod.RecurringPaymentType;
}
/// <summary>
/// Process recurring payment
/// </summary>
/// <param name="processPaymentRequest">Payment info required for an order processing</param>
/// <returns>Process payment result</returns>
public virtual ProcessPaymentResult ProcessRecurringPayment(ProcessPaymentRequest processPaymentRequest)
{
if (processPaymentRequest.OrderTotal == decimal.Zero)
{
var result = new ProcessPaymentResult
{
NewPaymentStatus = PaymentStatus.Paid
};
return result;
}
var paymentMethod = LoadPaymentMethodBySystemName(processPaymentRequest.PaymentMethodSystemName);
if (paymentMethod == null)
throw new NopException("Payment method couldn't be loaded");
return paymentMethod.ProcessRecurringPayment(processPaymentRequest);
}
/// <summary>
/// Cancels a recurring payment
/// </summary>
/// <param name="cancelPaymentRequest">Request</param>
/// <returns>Result</returns>
public virtual CancelRecurringPaymentResult CancelRecurringPayment(CancelRecurringPaymentRequest cancelPaymentRequest)
{
if (cancelPaymentRequest.Order.OrderTotal == decimal.Zero)
return new CancelRecurringPaymentResult();
var paymentMethod = LoadPaymentMethodBySystemName(cancelPaymentRequest.Order.PaymentMethodSystemName);
if (paymentMethod == null)
throw new NopException("Payment method couldn't be loaded");
return paymentMethod.CancelRecurringPayment(cancelPaymentRequest);
}
/// <summary>
/// Gets masked credit card number
/// </summary>
/// <param name="creditCardNumber">Credit card number</param>
/// <returns>Masked credit card number</returns>
public virtual string GetMaskedCreditCardNumber(string creditCardNumber)
{
if (String.IsNullOrEmpty(creditCardNumber))
return string.Empty;
if (creditCardNumber.Length <= 4)
return creditCardNumber;
string last4 = creditCardNumber.Substring(creditCardNumber.Length - 4, 4);
string maskedChars = string.Empty;
for (int i = 0; i < creditCardNumber.Length - 4; i++)
{
maskedChars += "*";
}
return maskedChars + last4;
}
#endregion
#endregion
}
}
| |
//
// Copyright (C) Microsoft. All rights reserved.
//
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using Microsoft.Win32;
using System;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Collections.Generic;
using Dbg = System.Management.Automation.Diagnostics;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Represent a control panel item
/// </summary>
public sealed class ControlPanelItem
{
/// <summary>
/// Control panel applet name
/// </summary>
public string Name { get; }
/// <summary>
/// Control panel applet canonical name
/// </summary>
public string CanonicalName { get; }
/// <summary>
/// Control panel applet category
/// </summary>
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Category { get; }
/// <summary>
/// Control panel applet description
/// </summary>
public string Description { get; }
/// <summary>
/// Control panel applet path
/// </summary>
internal string Path { get; }
/// <summary>
/// Internal constructor for ControlPanelItem
/// </summary>
/// <param name="name"></param>
/// <param name="canonicalName"></param>
/// <param name="category"></param>
/// <param name="description"></param>
/// <param name="path"></param>
internal ControlPanelItem(string name, string canonicalName, string[] category, string description, string path)
{
Name = name;
Path = path;
CanonicalName = canonicalName;
Category = category;
Description = description;
}
/// <summary>
/// ToString method
/// </summary>
/// <returns></returns>
public override string ToString()
{
return this.Name;
}
}
/// <summary>
/// This class implements the base for ControlPanelItem commands
/// </summary>
public abstract class ControlPanelItemBaseCommand : PSCmdlet
{
/// <summary>
/// Locale specific verb action Open string exposed by the control panel item.
/// </summary>
private static string s_verbActionOpenName = null;
/// <summary>
/// Canonical name of the control panel item used as a reference to fetch the verb
/// action Open string. This control panel item exists on all SKU's.
/// </summary>
private const string RegionCanonicalName = "Microsoft.RegionAndLanguage";
private const string ControlPanelShellFolder = "shell:::{26EE0668-A00A-44D7-9371-BEB064C98683}";
private static readonly string[] s_controlPanelItemFilterList = new string[] { "Folder Options", "Taskbar and Start Menu" };
private const string TestHeadlessServerScript = @"
$result = $false
$serverManagerModule = Get-Module -ListAvailable | ? {$_.Name -eq 'ServerManager'}
if ($serverManagerModule -ne $null)
{
Import-Module ServerManager
$Gui = (Get-WindowsFeature Server-Gui-Shell).Installed
if ($Gui -eq $false)
{
$result = $true
}
}
$result
";
internal readonly Dictionary<string, string> CategoryMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
internal string[] CategoryNames = { "*" };
internal string[] RegularNames = { "*" };
internal string[] CanonicalNames = { "*" };
internal ControlPanelItem[] ControlPanelItems = new ControlPanelItem[0];
/// <summary>
/// Get all executable control panel items
/// </summary>
internal List<ShellFolderItem> AllControlPanelItems
{
get
{
if (_allControlPanelItems == null)
{
_allControlPanelItems = new List<ShellFolderItem>();
string allItemFolderPath = ControlPanelShellFolder + "\\0";
IShellDispatch4 shell2 = (IShellDispatch4)new Shell();
Folder2 allItemFolder = (Folder2)shell2.NameSpace(allItemFolderPath);
FolderItems3 allItems = (FolderItems3)allItemFolder.Items();
bool applyControlPanelItemFilterList = IsServerCoreOrHeadLessServer();
foreach (ShellFolderItem item in allItems)
{
if (applyControlPanelItemFilterList)
{
bool match = false;
foreach (string name in s_controlPanelItemFilterList)
{
if (name.Equals(item.Name, StringComparison.OrdinalIgnoreCase))
{
match = true;
break;
}
}
if (match)
continue;
}
if (ContainVerbOpen(item))
_allControlPanelItems.Add(item);
}
}
return _allControlPanelItems;
}
}
private List<ShellFolderItem> _allControlPanelItems;
#region Cmdlet Overrides
/// <summary>
/// Does the preprocessing for ControlPanelItem cmdlets
/// </summary>
protected override void BeginProcessing()
{
System.OperatingSystem osInfo = System.Environment.OSVersion;
PlatformID platform = osInfo.Platform;
Version version = osInfo.Version;
if (platform.Equals(PlatformID.Win32NT) &&
((version.Major < 6) ||
((version.Major == 6) && (version.Minor < 2))
))
{
// Below Win8, this cmdlet is not supported because of Win8:794135
// throw terminating
string message = string.Format(CultureInfo.InvariantCulture,
ControlPanelResources.ControlPanelItemCmdletNotSupported,
this.CommandInfo.Name);
throw new PSNotSupportedException(message);
}
}
#endregion
/// <summary>
/// Test if an item can be invoked
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
private bool ContainVerbOpen(ShellFolderItem item)
{
bool result = false;
FolderItemVerbs verbs = item.Verbs();
foreach (FolderItemVerb verb in verbs)
{
if (!String.IsNullOrEmpty(verb.Name) &&
(verb.Name.Equals(ControlPanelResources.VerbActionOpen, StringComparison.OrdinalIgnoreCase) ||
CompareVerbActionOpen(verb.Name)))
{
result = true;
break;
}
}
return result;
}
/// <summary>
/// CompareVerbActionOpen is a helper function used to perform locale specific
/// comparison of the verb action Open exposed by various control panel items.
/// </summary>
/// <param name="verbActionName">Locale specific verb action exposed by the control panel item.</param>
/// <returns>True if the control panel item supports verb action open or else returns false.</returns>
private static bool CompareVerbActionOpen(string verbActionName)
{
if (s_verbActionOpenName == null)
{
const string allItemFolderPath = ControlPanelShellFolder + "\\0";
IShellDispatch4 shell2 = (IShellDispatch4)new Shell();
Folder2 allItemFolder = (Folder2)shell2.NameSpace(allItemFolderPath);
FolderItems3 allItems = (FolderItems3)allItemFolder.Items();
foreach (ShellFolderItem item in allItems)
{
string canonicalName = (string)item.ExtendedProperty("System.ApplicationName");
canonicalName = !String.IsNullOrEmpty(canonicalName)
? canonicalName.Substring(0, canonicalName.IndexOf("\0", StringComparison.OrdinalIgnoreCase))
: null;
if (canonicalName != null && canonicalName.Equals(RegionCanonicalName, StringComparison.OrdinalIgnoreCase))
{
// The 'Region' control panel item always has '&Open' (english or other locale) as the first verb name
s_verbActionOpenName = item.Verbs().Item(0).Name;
break;
}
}
Dbg.Assert(s_verbActionOpenName != null, "The 'Region' control panel item is available on all SKUs and it always "
+ "has '&Open' as the first verb item, so VerbActionOpenName should never be null at this point");
}
return s_verbActionOpenName.Equals(verbActionName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// IsServerCoreORHeadLessServer is a helper function that checks if the current SKU is a
/// Server Core machine or if the Server-GUI-Shell feature is removed on the machine.
/// </summary>
/// <returns>True if the current SKU is a Server Core machine or if the Server-GUI-Shell
/// feature is removed on the machine or else returns false.</returns>
private bool IsServerCoreOrHeadLessServer()
{
bool result = false;
using (RegistryKey installation = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"))
{
Dbg.Assert(installation != null, "the CurrentVersion subkey should exist");
string installationType = (string)installation.GetValue("InstallationType", "");
if (installationType.Equals("Server Core"))
{
result = true;
}
else if (installationType.Equals("Server"))
{
using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create())
{
ps.AddScript(TestHeadlessServerScript);
Collection<PSObject> psObjectCollection = ps.Invoke(new object[0]);
Dbg.Assert(psObjectCollection != null && psObjectCollection.Count == 1, "invoke should never return null, there should be only one return item");
if (LanguagePrimitives.IsTrue(PSObject.Base(psObjectCollection[0])))
{
result = true;
}
}
}
}
return result;
}
/// <summary>
/// Get the category number and name map
/// </summary>
internal void GetCategoryMap()
{
if (CategoryMap.Count != 0)
{
return;
}
IShellDispatch4 shell2 = (IShellDispatch4)new Shell();
Folder2 categoryFolder = (Folder2)shell2.NameSpace(ControlPanelShellFolder);
FolderItems3 catItems = (FolderItems3)categoryFolder.Items();
foreach (ShellFolderItem category in catItems)
{
string path = category.Path;
string catNum = path.Substring(path.LastIndexOf("\\", StringComparison.OrdinalIgnoreCase) + 1);
CategoryMap.Add(catNum, category.Name);
}
}
/// <summary>
/// Get control panel item by the category
/// </summary>
/// <param name="controlPanelItems"></param>
/// <returns></returns>
internal List<ShellFolderItem> GetControlPanelItemByCategory(List<ShellFolderItem> controlPanelItems)
{
List<ShellFolderItem> list = new List<ShellFolderItem>();
HashSet<string> itemSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string pattern in CategoryNames)
{
bool found = false;
WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
foreach (ShellFolderItem item in controlPanelItems)
{
string path = item.Path;
int[] categories = (int[])item.ExtendedProperty("System.ControlPanel.Category");
foreach (int cat in categories)
{
string catStr = (string)LanguagePrimitives.ConvertTo(cat, typeof(string), CultureInfo.InvariantCulture);
Dbg.Assert(CategoryMap.ContainsKey(catStr), "the category should be contained in _categoryMap");
string catName = CategoryMap[catStr];
if (!wildcard.IsMatch(catName))
continue;
if (itemSet.Contains(path))
{
found = true;
break;
}
found = true;
itemSet.Add(path);
list.Add(item);
break;
}
}
if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern))
{
string errMsg = StringUtil.Format(ControlPanelResources.NoControlPanelItemFoundForGivenCategory, pattern);
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg),
"NoControlPanelItemFoundForGivenCategory",
ErrorCategory.InvalidArgument, pattern);
WriteError(error);
}
}
return list;
}
/// <summary>
/// Get control panel item by the regular name
/// </summary>
/// <param name="controlPanelItems"></param>
/// <param name="withCategoryFilter"></param>
/// <returns></returns>
internal List<ShellFolderItem> GetControlPanelItemByName(List<ShellFolderItem> controlPanelItems, bool withCategoryFilter)
{
List<ShellFolderItem> list = new List<ShellFolderItem>();
HashSet<string> itemSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (string pattern in RegularNames)
{
bool found = false;
WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
foreach (ShellFolderItem item in controlPanelItems)
{
string name = item.Name;
string path = item.Path;
if (!wildcard.IsMatch(name))
continue;
if (itemSet.Contains(path))
{
found = true;
continue;
}
found = true;
itemSet.Add(path);
list.Add(item);
}
if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern))
{
string formatString = withCategoryFilter
? ControlPanelResources.NoControlPanelItemFoundForGivenNameWithCategory
: ControlPanelResources.NoControlPanelItemFoundForGivenName;
string errMsg = StringUtil.Format(formatString, pattern);
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg),
"NoControlPanelItemFoundForGivenName",
ErrorCategory.InvalidArgument, pattern);
WriteError(error);
}
}
return list;
}
/// <summary>
/// Get control panel item by the canonical name
/// </summary>
/// <param name="controlPanelItems"></param>
/// <param name="withCategoryFilter"></param>
/// <returns></returns>
internal List<ShellFolderItem> GetControlPanelItemByCanonicalName(List<ShellFolderItem> controlPanelItems, bool withCategoryFilter)
{
List<ShellFolderItem> list = new List<ShellFolderItem>();
HashSet<string> itemSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (CanonicalNames == null)
{
bool found = false;
foreach (ShellFolderItem item in controlPanelItems)
{
string canonicalName = (string)item.ExtendedProperty("System.ApplicationName");
if (canonicalName == null)
{
found = true;
list.Add(item);
}
}
if (!found)
{
string errMsg = withCategoryFilter
? ControlPanelResources.NoControlPanelItemFoundWithNullCanonicalNameWithCategory
: ControlPanelResources.NoControlPanelItemFoundWithNullCanonicalName;
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "",
ErrorCategory.InvalidArgument, CanonicalNames);
WriteError(error);
}
return list;
}
foreach (string pattern in CanonicalNames)
{
bool found = false;
WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
foreach (ShellFolderItem item in controlPanelItems)
{
string path = item.Path;
string canonicalName = (string)item.ExtendedProperty("System.ApplicationName");
canonicalName = canonicalName != null
? canonicalName.Substring(0, canonicalName.IndexOf("\0", StringComparison.OrdinalIgnoreCase))
: null;
if (canonicalName == null)
{
if (pattern.Equals("*", StringComparison.OrdinalIgnoreCase))
{
found = true;
if (!itemSet.Contains(path))
{
itemSet.Add(path);
list.Add(item);
}
}
}
else
{
if (!wildcard.IsMatch(canonicalName))
continue;
if (itemSet.Contains(path))
{
found = true;
continue;
}
found = true;
itemSet.Add(path);
list.Add(item);
}
}
if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern))
{
string formatString = withCategoryFilter
? ControlPanelResources.NoControlPanelItemFoundForGivenCanonicalNameWithCategory
: ControlPanelResources.NoControlPanelItemFoundForGivenCanonicalName;
string errMsg = StringUtil.Format(formatString, pattern);
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg),
"NoControlPanelItemFoundForGivenCanonicalName",
ErrorCategory.InvalidArgument, pattern);
WriteError(error);
}
}
return list;
}
/// <summary>
/// Get control panel item by the ControlPanelItem instances
/// </summary>
/// <param name="controlPanelItems"></param>
/// <returns></returns>
internal List<ShellFolderItem> GetControlPanelItemsByInstance(List<ShellFolderItem> controlPanelItems)
{
List<ShellFolderItem> list = new List<ShellFolderItem>();
HashSet<string> itemSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (ControlPanelItem controlPanelItem in ControlPanelItems)
{
bool found = false;
foreach (ShellFolderItem item in controlPanelItems)
{
string path = item.Path;
if (!controlPanelItem.Path.Equals(path, StringComparison.OrdinalIgnoreCase))
continue;
if (itemSet.Contains(path))
{
found = true;
break;
}
found = true;
itemSet.Add(path);
list.Add(item);
break;
}
if (!found)
{
string errMsg = StringUtil.Format(ControlPanelResources.NoControlPanelItemFoundForGivenInstance,
controlPanelItem.GetType().Name);
ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg),
"NoControlPanelItemFoundForGivenInstance",
ErrorCategory.InvalidArgument, controlPanelItem);
WriteError(error);
}
}
return list;
}
}
/// <summary>
/// Get all control panel items that is available in the "All Control Panel Items" category
/// </summary>
[Cmdlet(VerbsCommon.Get, "ControlPanelItem", DefaultParameterSetName = RegularNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=219982")]
[OutputType(typeof(ControlPanelItem))]
public sealed class GetControlPanelItemCommand : ControlPanelItemBaseCommand
{
private const string RegularNameParameterSet = "RegularName";
private const string CanonicalNameParameterSet = "CanonicalName";
#region "Parameters"
/// <summary>
/// Control panel item names
/// </summary>
[Parameter(Position = 0, ParameterSetName = RegularNameParameterSet, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Name
{
get { return RegularNames; }
set
{
RegularNames = value;
_nameSpecified = true;
}
}
private bool _nameSpecified = false;
/// <summary>
/// Canonical names of control panel items
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = CanonicalNameParameterSet)]
[AllowNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] CanonicalName
{
get { return CanonicalNames; }
set
{
CanonicalNames = value;
_canonicalNameSpecified = true;
}
}
private bool _canonicalNameSpecified = false;
/// <summary>
/// Category of control panel items
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Category
{
get { return CategoryNames; }
set
{
CategoryNames = value;
_categorySpecified = true;
}
}
private bool _categorySpecified = false;
#endregion "Parameters"
/// <summary>
///
/// </summary>
protected override void ProcessRecord()
{
GetCategoryMap();
List<ShellFolderItem> items = GetControlPanelItemByCategory(AllControlPanelItems);
if (_nameSpecified)
{
items = GetControlPanelItemByName(items, _categorySpecified);
}
else if (_canonicalNameSpecified)
{
items = GetControlPanelItemByCanonicalName(items, _categorySpecified);
}
List<ControlPanelItem> results = new List<ControlPanelItem>();
foreach (ShellFolderItem item in items)
{
string name = item.Name;
string path = item.Path;
string description = (string)item.ExtendedProperty("InfoTip");
string canonicalName = (string)item.ExtendedProperty("System.ApplicationName");
canonicalName = canonicalName != null
? canonicalName.Substring(0, canonicalName.IndexOf("\0", StringComparison.OrdinalIgnoreCase))
: null;
int[] categories = (int[])item.ExtendedProperty("System.ControlPanel.Category");
string[] cateStrings = new string[categories.Length];
for (int i = 0; i < categories.Length; i++)
{
string catStr = (string)LanguagePrimitives.ConvertTo(categories[i], typeof(string), CultureInfo.InvariantCulture);
Dbg.Assert(CategoryMap.ContainsKey(catStr), "the category should be contained in CategoryMap");
cateStrings[i] = CategoryMap[catStr];
}
ControlPanelItem controlPanelItem = new ControlPanelItem(name, canonicalName, cateStrings, description, path);
results.Add(controlPanelItem);
}
// Sort the results by Canonical Name
results.Sort(CompareControlPanelItems);
foreach (ControlPanelItem controlPanelItem in results)
{
WriteObject(controlPanelItem);
}
}
#region "Private Methods"
private static int CompareControlPanelItems(ControlPanelItem x, ControlPanelItem y)
{
// In the case that at least one of them is null
if (x.CanonicalName == null && y.CanonicalName == null)
return 0;
if (x.CanonicalName == null)
return 1;
if (y.CanonicalName == null)
return -1;
// In the case that both are not null
return string.Compare(x.CanonicalName, y.CanonicalName, StringComparison.OrdinalIgnoreCase);
}
#endregion "Private Methods"
}
/// <summary>
/// Show the specified control panel applet
/// </summary>
[Cmdlet(VerbsCommon.Show, "ControlPanelItem", DefaultParameterSetName = RegularNameParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=219983")]
public sealed class ShowControlPanelItemCommand : ControlPanelItemBaseCommand
{
private const string RegularNameParameterSet = "RegularName";
private const string CanonicalNameParameterSet = "CanonicalName";
private const string ControlPanelItemParameterSet = "ControlPanelItem";
#region "Parameters"
/// <summary>
/// Control panel item names
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = RegularNameParameterSet, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] Name
{
get { return RegularNames; }
set { RegularNames = value; }
}
/// <summary>
/// Canonical names of control panel items
/// </summary>
[Parameter(Mandatory = true, ParameterSetName = CanonicalNameParameterSet)]
[AllowNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public string[] CanonicalName
{
get { return CanonicalNames; }
set { CanonicalNames = value; }
}
/// <summary>
/// Control panel items returned by Get-ControlPanelItem
/// </summary>
[Parameter(Position = 0, ParameterSetName = ControlPanelItemParameterSet, ValueFromPipeline = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public ControlPanelItem[] InputObject
{
get { return ControlPanelItems; }
set { ControlPanelItems = value; }
}
#endregion "Parameters"
/// <summary>
///
/// </summary>
protected override void ProcessRecord()
{
List<ShellFolderItem> items;
if (ParameterSetName == RegularNameParameterSet)
{
items = GetControlPanelItemByName(AllControlPanelItems, false);
}
else if (ParameterSetName == CanonicalNameParameterSet)
{
items = GetControlPanelItemByCanonicalName(AllControlPanelItems, false);
}
else
{
items = GetControlPanelItemsByInstance(AllControlPanelItems);
}
foreach (ShellFolderItem item in items)
{
item.InvokeVerb();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using UnityEngine;
using InControl;
using UnityEditor.SceneManagement;
//#if UNITY_EDITOR
//using UnityEditor;
//#endif
/**
* WARNING: This is NOT an example of how to use InControl.
* It is intended for testing and troubleshooting the library.
* It can also be used for create new device profiles as it will
* show the default Unity mappings for unknown devices.
**/
namespace InControl
{
public class TestInputManager : MonoBehaviour
{
public Font font;
GUIStyle style = new GUIStyle();
List<LogMessage> logMessages = new List<LogMessage>();
bool isPaused;
void OnEnable()
{
isPaused = false;
Time.timeScale = 1.0f;
Logger.OnLogMessage += logMessage => logMessages.Add( logMessage );
// InputManager.HideDevicesWithProfile( typeof( Xbox360MacProfile ) );
InputManager.OnDeviceAttached += inputDevice => Debug.Log( "Attached: " + inputDevice.Name );
InputManager.OnDeviceDetached += inputDevice => Debug.Log( "Detached: " + inputDevice.Name );
InputManager.OnActiveDeviceChanged += inputDevice => Debug.Log( "Active device changed to: " + inputDevice.Name );
InputManager.OnUpdate += HandleInputUpdate;
// UnityInputDeviceManager.DumpSystemDeviceProfiles();
}
void HandleInputUpdate( ulong updateTick, float deltaTime )
{
CheckForPauseButton();
// var inputDevice = InputManager.ActiveDevice;
// if (inputDevice.Direction.Left.WasPressed)
// {
// Debug.Log( "Left.WasPressed" );
// }
// if (inputDevice.Direction.Left.WasReleased)
// {
// Debug.Log( "Left.WasReleased" );
// }
// if (inputDevice.Action1.WasPressed)
// {
// Debug.Log( "Action1.WasPressed" );
// }
// var inputDevice = InputManager.ActiveDevice;
// var control = inputDevice.Action1;
// if (control.WasReleased)
// {
// InputManager.ClearInputState();
// Debug.Log( "WasPressed = " + control.WasPressed );
// Debug.Log( "WasReleased = " + control.WasReleased );
// }
}
void Start()
{
// var unityDeviceManager = InputManager.GetDeviceManager<UnityInputDeviceManager>();
// unityDeviceManager.ReloadDevices();
// Debug.Log( "IntPtr.Size = " + IntPtr.Size );
#if UNITY_IOS
ICadeDeviceManager.Active = true;
#endif
}
void Update()
{
// Thread.Sleep( 250 );
if (Input.GetKeyDown( KeyCode.R ))
{
//Application.LoadLevel( "TestInputManager" );
}
}
void CheckForPauseButton()
{
if (Input.GetKeyDown( KeyCode.P ) || InputManager.MenuWasPressed)
{
Time.timeScale = isPaused ? 1.0f : 0.0f;
isPaused = !isPaused;
}
}
void SetColor( Color color )
{
style.normal.textColor = color;
}
void OnGUI()
{
var w = 300;
var x = 10;
var y = 10;
var lineHeight = 15;
GUI.skin.font = font;
SetColor( Color.white );
string info = "Devices:";
info += " (Platform: " + InputManager.Platform + ")";
// info += " (Joysticks " + InputManager.JoystickHash + ")";
info += " " + InputManager.ActiveDevice.Direction.Vector;
// #if UNITY_EDITOR
// if (EditorWindow.focusedWindow != null)
// {
// info += " " + EditorWindow.focusedWindow.ToString();
// }
// #endif
if (isPaused)
{
SetColor( Color.red );
info = "+++ PAUSED +++";
}
GUI.Label( new Rect( x, y, x + w, y + 10 ), info, style );
SetColor( Color.white );
foreach (var inputDevice in InputManager.Devices)
{
bool active = InputManager.ActiveDevice == inputDevice;
Color color = active ? Color.yellow : Color.white;
y = 35;
SetColor( color );
GUI.Label( new Rect( x, y, x + w, y + 10 ), inputDevice.Name, style );
y += lineHeight;
if (inputDevice.IsUnknown)
{
GUI.Label( new Rect( x, y, x + w, y + 10 ), inputDevice.Meta, style );
y += lineHeight;
}
GUI.Label( new Rect( x, y, x + w, y + 10 ), "SortOrder: " + inputDevice.SortOrder, style );
y += lineHeight;
GUI.Label( new Rect( x, y, x + w, y + 10 ), "LastChangeTick: " + inputDevice.LastChangeTick, style );
y += lineHeight;
foreach (var control in inputDevice.Controls)
{
if (control != null)
{
string controlName;
if (inputDevice.IsKnown)
{
controlName = string.Format( "{0} ({1})", control.Target, control.Handle );
}
else
{
controlName = control.Handle;
}
SetColor( control.State ? Color.green : color );
var label = string.Format( "{0} {1}", controlName, control.State ? "= " + control.Value : "" );
GUI.Label( new Rect( x, y, x + w, y + 10 ), label, style );
y += lineHeight;
}
}
y += lineHeight;
color = active ? new Color( 1.0f, 0.7f, 0.2f ) : Color.white;
if (inputDevice.IsKnown)
{
var control = inputDevice.LeftStickX;
SetColor( control.State ? Color.green : color );
var label = string.Format( "{0} {1}", "Left Stick X", control.State ? "= " + control.Value : "" );
GUI.Label( new Rect( x, y, x + w, y + 10 ), label, style );
y += lineHeight;
control = inputDevice.LeftStickY;
SetColor( control.State ? Color.green : color );
label = string.Format( "{0} {1}", "Left Stick Y", control.State ? "= " + control.Value : "" );
GUI.Label( new Rect( x, y, x + w, y + 10 ), label, style );
y += lineHeight;
SetColor( inputDevice.LeftStick.State ? Color.green : color );
label = string.Format( "{0} {1}", "Left Stick A", inputDevice.LeftStick.State ? "= " + inputDevice.LeftStick.Angle : "" );
GUI.Label( new Rect( x, y, x + w, y + 10 ), label, style );
y += lineHeight;
control = inputDevice.RightStickX;
SetColor( control.State ? Color.green : color );
label = string.Format( "{0} {1}", "Right Stick X", control.State ? "= " + control.Value : "" );
GUI.Label( new Rect( x, y, x + w, y + 10 ), label, style );
y += lineHeight;
control = inputDevice.RightStickY;
SetColor( control.State ? Color.green : color );
label = string.Format( "{0} {1}", "Right Stick Y", control.State ? "= " + control.Value : "" );
GUI.Label( new Rect( x, y, x + w, y + 10 ), label, style );
y += lineHeight;
SetColor( inputDevice.RightStick.State ? Color.green : color );
label = string.Format( "{0} {1}", "Right Stick A", inputDevice.RightStick.State ? "= " + inputDevice.RightStick.Angle : "" );
GUI.Label( new Rect( x, y, x + w, y + 10 ), label, style );
y += lineHeight;
control = inputDevice.DPadX;
SetColor( control.State ? Color.green : color );
label = string.Format( "{0} {1}", "DPad X", control.State ? "= " + control.Value : "" );
GUI.Label( new Rect( x, y, x + w, y + 10 ), label, style );
y += lineHeight;
control = inputDevice.DPadY;
SetColor( control.State ? Color.green : color );
label = string.Format( "{0} {1}", "DPad Y", control.State ? "= " + control.Value : "" );
GUI.Label( new Rect( x, y, x + w, y + 10 ), label, style );
y += lineHeight;
}
SetColor( Color.cyan );
var anyButton = inputDevice.AnyButton;
if (anyButton)
{
GUI.Label( new Rect( x, y, x + w, y + 10 ), "AnyButton = " + anyButton.Handle, style );
}
x += 200;
}
Color[] logColors = { Color.gray, Color.yellow, Color.white };
SetColor( Color.white );
x = 10;
y = Screen.height - (10 + lineHeight);
for (int i = logMessages.Count - 1; i >= 0; i--)
{
var logMessage = logMessages[i];
SetColor( logColors[(int) logMessage.type] );
foreach (var line in logMessage.text.Split('\n'))
{
GUI.Label( new Rect( x, y, Screen.width, y + 10 ), line, style );
y -= lineHeight;
}
}
// DrawUnityInputDebugger();
}
void DrawUnityInputDebugger()
{
var w = 300;
var x = Screen.width / 2;
var y = 10;
var lineHeight = 20;
SetColor( Color.white );
var joystickNames = Input.GetJoystickNames();
var numJoysticks = joystickNames.Length;
for (var i = 0; i < numJoysticks; i++)
{
var joystickName = joystickNames[i];
var joystickId = i + 1;
GUI.Label( new Rect( x, y, x + w, y + 10 ), "Joystick " + joystickId + ": \"" + joystickName + "\"", style );
y += lineHeight;
var buttonInfo = "Buttons: ";
for (int button = 0; button < 20; button++)
{
var buttonQuery = "joystick " + joystickId + " button " + button;
var buttonState = Input.GetKey( buttonQuery );
if (buttonState)
{
buttonInfo += "B" + button + " ";
}
}
GUI.Label( new Rect( x, y, x + w, y + 10 ), buttonInfo, style );
y += lineHeight;
var analogInfo = "Analogs: ";
for (int analog = 0; analog < 20; analog++)
{
var analogQuery = "joystick " + joystickId + " analog " + analog;
var analogValue = Input.GetAxisRaw( analogQuery );
if (Utility.AbsoluteIsOverThreshold( analogValue, 0.2f ))
{
analogInfo += "A" + analog + ": " + analogValue.ToString( "0.00" ) + " ";
}
}
GUI.Label( new Rect( x, y, x + w, y + 10 ), analogInfo, style );
y += lineHeight;
y += 25;
}
}
void OnDrawGizmos()
{
var inputDevice = InputManager.ActiveDevice;
var vector = new Vector2( inputDevice.LeftStickX, inputDevice.LeftStickY );
// var vector = inputDevice.LeftStick.Vector;
Gizmos.color = Color.blue;
var lz = new Vector2( -3.0f, -1.0f );
var lp = lz + (vector * 2.0f);
Gizmos.DrawSphere( lz, 0.1f );
Gizmos.DrawLine( lz, lp );
Gizmos.DrawSphere( lp, 1.0f );
Gizmos.color = Color.red;
var rz = new Vector2( +3.0f, -1.0f );
var rp = rz + (inputDevice.RightStick.Vector * 2.0f);
Gizmos.DrawSphere( rz, 0.1f );
Gizmos.DrawLine( rz, rp );
Gizmos.DrawSphere( rp, 1.0f );
}
}
}
| |
// 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.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using Internal.Cryptography.Pal.Native;
namespace Internal.Cryptography.Pal
{
internal sealed partial class StorePal : IDisposable, IStorePal, IExportPal, ILoaderPal
{
public static ILoaderPal FromBlob(byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
{
return FromBlobOrFile(rawData, null, password, keyStorageFlags);
}
public static ILoaderPal FromFile(string fileName, string password, X509KeyStorageFlags keyStorageFlags)
{
return FromBlobOrFile(null, fileName, password, keyStorageFlags);
}
private static StorePal FromBlobOrFile(byte[] rawData, string fileName, string password, X509KeyStorageFlags keyStorageFlags)
{
bool fromFile = fileName != null;
unsafe
{
fixed (byte* pRawData = rawData)
{
fixed (char* pFileName = fileName)
{
CRYPTOAPI_BLOB blob = new CRYPTOAPI_BLOB(fromFile ? 0 : rawData.Length, pRawData);
bool persistKeySet = (0 != (keyStorageFlags & X509KeyStorageFlags.PersistKeySet));
PfxCertStoreFlags certStoreFlags = MapKeyStorageFlags(keyStorageFlags);
void* pvObject = fromFile ? (void*)pFileName : (void*)&blob;
ContentType contentType;
SafeCertStoreHandle certStore;
if (!Interop.crypt32.CryptQueryObject(
fromFile ? CertQueryObjectType.CERT_QUERY_OBJECT_FILE : CertQueryObjectType.CERT_QUERY_OBJECT_BLOB,
pvObject,
StoreExpectedContentFlags,
ExpectedFormatTypeFlags.CERT_QUERY_FORMAT_FLAG_ALL,
0,
IntPtr.Zero,
out contentType,
IntPtr.Zero,
out certStore,
IntPtr.Zero,
IntPtr.Zero
))
{
throw Marshal.GetLastWin32Error().ToCryptographicException();
}
if (contentType == ContentType.CERT_QUERY_CONTENT_PFX)
{
certStore.Dispose();
if (fromFile)
{
rawData = File.ReadAllBytes(fileName);
}
fixed (byte* pRawData2 = rawData)
{
CRYPTOAPI_BLOB blob2 = new CRYPTOAPI_BLOB(rawData.Length, pRawData2);
certStore = Interop.crypt32.PFXImportCertStore(ref blob2, password, certStoreFlags);
if (certStore == null || certStore.IsInvalid)
throw Marshal.GetLastWin32Error().ToCryptographicException();
}
if (!persistKeySet)
{
//
// If the user did not want us to persist private keys, then we should loop through all
// the certificates in the collection and set our custom CERT_DELETE_KEYSET_PROP_ID property
// so the key container will be deleted when the cert contexts will go away.
//
SafeCertContextHandle pCertContext = null;
while (Interop.crypt32.CertEnumCertificatesInStore(certStore, ref pCertContext))
{
CRYPTOAPI_BLOB nullBlob = new CRYPTOAPI_BLOB(0, null);
if (!Interop.crypt32.CertSetCertificateContextProperty(pCertContext, CertContextPropId.CERT_DELETE_KEYSET_PROP_ID, CertSetPropertyFlags.CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG, &nullBlob))
throw Marshal.GetLastWin32Error().ToCryptographicException();
}
}
}
return new StorePal(certStore);
}
}
}
}
public static IExportPal FromCertificate(ICertificatePal cert)
{
CertificatePal certificatePal = (CertificatePal)cert;
SafeCertStoreHandle certStore = Interop.crypt32.CertOpenStore(
CertStoreProvider.CERT_STORE_PROV_MEMORY,
CertEncodingType.All,
IntPtr.Zero,
CertStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG | CertStoreFlags.CERT_STORE_CREATE_NEW_FLAG | CertStoreFlags.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG,
null);
if (certStore.IsInvalid)
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
if (!Interop.crypt32.CertAddCertificateContextToStore(certStore, certificatePal.CertContext, CertStoreAddDisposition.CERT_STORE_ADD_ALWAYS, IntPtr.Zero))
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
return new StorePal(certStore);
}
/// <summary>
/// Note: this factory method creates the store using links to the original certificates rather than copies. This means that any changes to certificate properties
/// in the store changes the original.
/// </summary>
public static IExportPal LinkFromCertificateCollection(X509Certificate2Collection certificates)
{
// we always want to use CERT_STORE_ENUM_ARCHIVED_FLAG since we want to preserve the collection in this operation.
// By default, Archived certificates will not be included.
SafeCertStoreHandle certStore = Interop.crypt32.CertOpenStore(
CertStoreProvider.CERT_STORE_PROV_MEMORY,
CertEncodingType.All,
IntPtr.Zero,
CertStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG | CertStoreFlags.CERT_STORE_CREATE_NEW_FLAG,
null);
if (certStore.IsInvalid)
throw Marshal.GetHRForLastWin32Error().ToCryptographicException();;
//
// We use CertAddCertificateLinkToStore to keep a link to the original store, so any property changes get
// applied to the original store. This has a limit of 99 links per cert context however.
//
foreach (X509Certificate2 certificate in certificates)
{
SafeCertContextHandle certContext = Interop.crypt32.CertDuplicateCertificateContext(certificate.Handle);
if (!Interop.crypt32.CertAddCertificateLinkToStore(certStore, certContext, CertStoreAddDisposition.CERT_STORE_ADD_ALWAYS, IntPtr.Zero))
throw Marshal.GetLastWin32Error().ToCryptographicException();
}
return new StorePal(certStore);
}
public static IStorePal FromSystemStore(string storeName, StoreLocation storeLocation, OpenFlags openFlags)
{
CertStoreFlags certStoreFlags = MapX509StoreFlags(storeLocation, openFlags);
SafeCertStoreHandle certStore = Interop.crypt32.CertOpenStore(CertStoreProvider.CERT_STORE_PROV_SYSTEM_W, CertEncodingType.All, IntPtr.Zero, certStoreFlags, storeName);
if (certStore.IsInvalid)
throw Marshal.GetLastWin32Error().ToCryptographicException();
//
// We want the store to auto-resync when requesting a snapshot so that
// updates to the store will be taken into account.
//
// For compat with desktop, ignoring any failures from this call. (It is pretty unlikely to fail, in any case.)
//
bool ignore = Interop.crypt32.CertControlStore(certStore, CertControlStoreFlags.None, CertControlStoreType.CERT_STORE_CTRL_AUTO_RESYNC, IntPtr.Zero);
return new StorePal(certStore);
}
// this method maps a X509KeyStorageFlags enum to a combination of crypto API flags
private static PfxCertStoreFlags MapKeyStorageFlags(X509KeyStorageFlags keyStorageFlags)
{
PfxCertStoreFlags dwFlags = 0;
if ((keyStorageFlags & X509KeyStorageFlags.UserKeySet) == X509KeyStorageFlags.UserKeySet)
dwFlags |= PfxCertStoreFlags.CRYPT_USER_KEYSET;
else if ((keyStorageFlags & X509KeyStorageFlags.MachineKeySet) == X509KeyStorageFlags.MachineKeySet)
dwFlags |= PfxCertStoreFlags.CRYPT_MACHINE_KEYSET;
if ((keyStorageFlags & X509KeyStorageFlags.Exportable) == X509KeyStorageFlags.Exportable)
dwFlags |= PfxCertStoreFlags.CRYPT_EXPORTABLE;
if ((keyStorageFlags & X509KeyStorageFlags.UserProtected) == X509KeyStorageFlags.UserProtected)
dwFlags |= PfxCertStoreFlags.CRYPT_USER_PROTECTED;
return dwFlags;
}
// this method maps X509Store OpenFlags to a combination of crypto API flags
private static CertStoreFlags MapX509StoreFlags(StoreLocation storeLocation, OpenFlags flags)
{
CertStoreFlags dwFlags = 0;
uint openMode = ((uint)flags) & 0x3;
switch (openMode)
{
case (uint)OpenFlags.ReadOnly:
dwFlags |= CertStoreFlags.CERT_STORE_READONLY_FLAG;
break;
case (uint)OpenFlags.MaxAllowed:
dwFlags |= CertStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG;
break;
}
if ((flags & OpenFlags.OpenExistingOnly) == OpenFlags.OpenExistingOnly)
dwFlags |= CertStoreFlags.CERT_STORE_OPEN_EXISTING_FLAG;
if ((flags & OpenFlags.IncludeArchived) == OpenFlags.IncludeArchived)
dwFlags |= CertStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG;
if (storeLocation == StoreLocation.LocalMachine)
dwFlags |= CertStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE;
else if (storeLocation == StoreLocation.CurrentUser)
dwFlags |= CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER;
return dwFlags;
}
private const ExpectedContentTypeFlags StoreExpectedContentFlags =
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_CERT |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_PFX |
ExpectedContentTypeFlags.CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE;
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Diagnostics;
using RegularExpressions = System.Text.RegularExpressions;
namespace Microsoft.Web.XmlTransform
{
internal static class CommonErrors
{
internal static void ExpectNoArguments(XmlTransformationLogger log, string transformName, string argumentString) {
if (!String.IsNullOrEmpty(argumentString)) {
log.LogWarning(SR.XMLTRANSFORMATION_TransformDoesNotExpectArguments, transformName);
}
}
internal static void WarnIfMultipleTargets(XmlTransformationLogger log, string transformName, XmlNodeList targetNodes, bool applyTransformToAllTargets) {
Debug.Assert(applyTransformToAllTargets == false);
if (targetNodes.Count > 1) {
log.LogWarning(SR.XMLTRANSFORMATION_TransformOnlyAppliesOnce, transformName);
}
}
}
internal class Replace : Transform
{
protected override void Apply() {
CommonErrors.ExpectNoArguments(Log, TransformNameShort, ArgumentString);
CommonErrors.WarnIfMultipleTargets(Log, TransformNameShort, TargetNodes, ApplyTransformToAllTargetNodes);
XmlNode parentNode = TargetNode.ParentNode;
parentNode.ReplaceChild(
TransformNode,
TargetNode);
Log.LogMessage(MessageType.Verbose, SR.XMLTRANSFORMATION_TransformMessageReplace, TargetNode.Name);
}
}
internal class Remove : Transform
{
protected override void Apply() {
CommonErrors.WarnIfMultipleTargets(Log, TransformNameShort, TargetNodes, ApplyTransformToAllTargetNodes);
RemoveNode();
}
protected void RemoveNode() {
CommonErrors.ExpectNoArguments(Log, TransformNameShort, ArgumentString);
string targetNodeName = TargetNode.Name;
XmlNode parentNode = TargetNode.ParentNode;
parentNode.RemoveChild(TargetNode);
Log.LogMessage(MessageType.Verbose, SR.XMLTRANSFORMATION_TransformMessageRemove, targetNodeName);
}
}
internal class RemoveAll : Remove
{
public RemoveAll() {
ApplyTransformToAllTargetNodes = true;
}
protected override void Apply() {
RemoveNode();
}
}
internal class Insert : Transform
{
public Insert()
: base(TransformFlags.UseParentAsTargetNode, MissingTargetMessage.Error) {
}
protected override void Apply() {
CommonErrors.ExpectNoArguments(Log, TransformNameShort, ArgumentString);
TargetNode.AppendChild(TransformNode);
Log.LogMessage(MessageType.Verbose, SR.XMLTRANSFORMATION_TransformMessageInsert, TransformNode.Name);
}
}
internal class InsertIfMissing : Insert
{
protected override void Apply()
{
CommonErrors.ExpectNoArguments(Log, TransformNameShort, ArgumentString);
if (this.TargetChildNodes == null || this.TargetChildNodes.Count == 0)
{
TargetNode.AppendChild(TransformNode);
Log.LogMessage(MessageType.Verbose, SR.XMLTRANSFORMATION_TransformMessageInsert, TransformNode.Name);
}
}
}
internal abstract class InsertBase : Transform
{
internal InsertBase()
: base(TransformFlags.UseParentAsTargetNode, MissingTargetMessage.Error) {
}
private XmlElement siblingElement = null;
protected XmlElement SiblingElement {
get {
if (siblingElement == null) {
if (Arguments == null || Arguments.Count == 0) {
throw new XmlTransformationException(string.Format(System.Globalization.CultureInfo.CurrentCulture,SR.XMLTRANSFORMATION_InsertMissingArgument, GetType().Name));
}
else if (Arguments.Count > 1) {
throw new XmlTransformationException(string.Format(System.Globalization.CultureInfo.CurrentCulture,SR.XMLTRANSFORMATION_InsertTooManyArguments, GetType().Name));
}
else {
string xpath = Arguments[0];
XmlNodeList siblings = TargetNode.SelectNodes(xpath);
if (siblings.Count == 0) {
throw new XmlTransformationException(string.Format(System.Globalization.CultureInfo.CurrentCulture,SR.XMLTRANSFORMATION_InsertBadXPath, xpath));
}
else {
siblingElement = siblings[0] as XmlElement;
if (siblingElement == null) {
throw new XmlTransformationException(string.Format(System.Globalization.CultureInfo.CurrentCulture,SR.XMLTRANSFORMATION_InsertBadXPathResult, xpath));
}
}
}
}
return siblingElement;
}
}
}
internal class InsertAfter : InsertBase
{
protected override void Apply() {
SiblingElement.ParentNode.InsertAfter(TransformNode, SiblingElement);
Log.LogMessage(MessageType.Verbose, string.Format(System.Globalization.CultureInfo.CurrentCulture,SR.XMLTRANSFORMATION_TransformMessageInsert, TransformNode.Name));
}
}
internal class InsertBefore : InsertBase
{
protected override void Apply() {
SiblingElement.ParentNode.InsertBefore(TransformNode, SiblingElement);
Log.LogMessage(MessageType.Verbose, string.Format(System.Globalization.CultureInfo.CurrentCulture,SR.XMLTRANSFORMATION_TransformMessageInsert, TransformNode.Name));
}
}
public class SetAttributes : AttributeTransform
{
protected override void Apply() {
foreach (XmlAttribute transformAttribute in TransformAttributes) {
XmlAttribute targetAttribute = TargetNode.Attributes.GetNamedItem(transformAttribute.Name) as XmlAttribute;
if (targetAttribute != null) {
targetAttribute.Value = transformAttribute.Value;
}
else {
TargetNode.Attributes.Append((XmlAttribute)transformAttribute.Clone());
}
Log.LogMessage(MessageType.Verbose, SR.XMLTRANSFORMATION_TransformMessageSetAttribute, transformAttribute.Name);
}
if (TransformAttributes.Count > 0) {
Log.LogMessage(MessageType.Verbose, SR.XMLTRANSFORMATION_TransformMessageSetAttributes, TransformAttributes.Count);
}
else {
Log.LogWarning(SR.XMLTRANSFORMATION_TransformMessageNoSetAttributes);
}
}
}
public class SetTokenizedAttributeStorage
{
public List<Dictionary<string, string>> DictionaryList { get; set; }
public string TokenFormat { get; set; }
public bool EnableTokenizeParameters { get; set; }
public bool UseXpathToFormParameter { get; set; }
public SetTokenizedAttributeStorage() : this(4) { }
public SetTokenizedAttributeStorage(int capacity)
{
DictionaryList = new List<Dictionary<string, string>>(capacity);
TokenFormat = string.Concat("$(ReplacableToken_#(", SetTokenizedAttributes.ParameterAttribute, ")_#(", SetTokenizedAttributes.TokenNumber, "))");
EnableTokenizeParameters = false;
UseXpathToFormParameter = true;
}
}
/// <summary>
/// Utility class to Transform the SetAttribute to replace token
/// 1. if it trigger by the regular TransformXml task, it only replace the $(name) from the parent node
/// 2. If it trigger by the TokenizedTransformXml task, it replace $(name) then parse the declareation of the parameter
/// </summary>
public class SetTokenizedAttributes : AttributeTransform
{
private SetTokenizedAttributeStorage storageDictionary = null;
private bool fInitStorageDictionary = false;
public static readonly string Token = "Token";
public static readonly string TokenNumber = "TokenNumber";
public static readonly string XPathWithIndex = "XPathWithIndex";
public static readonly string ParameterAttribute = "Parameter";
public static readonly string XpathLocator = "XpathLocator";
public static readonly string XPathWithLocator = "XPathWithLocator";
private XmlAttribute tokenizeValueCurrentXmlAttribute = null;
protected SetTokenizedAttributeStorage TransformStorage
{
get
{
if (storageDictionary == null && !fInitStorageDictionary)
{
storageDictionary = GetService<SetTokenizedAttributeStorage>();
fInitStorageDictionary = true;
}
return storageDictionary;
}
}
protected override void Apply()
{
bool fTokenizeParameter = false;
SetTokenizedAttributeStorage storage = TransformStorage;
List<Dictionary<string, string> > parameters = null;
if (storage != null)
{
fTokenizeParameter = storage.EnableTokenizeParameters;
if (fTokenizeParameter)
{
parameters = storage.DictionaryList;
}
}
foreach (XmlAttribute transformAttribute in TransformAttributes)
{
XmlAttribute targetAttribute = TargetNode.Attributes.GetNamedItem(transformAttribute.Name) as XmlAttribute;
string newValue = TokenizeValue(targetAttribute, transformAttribute, fTokenizeParameter, parameters);
if (targetAttribute != null)
{
targetAttribute.Value = newValue;
}
else
{
XmlAttribute newAttribute = (XmlAttribute)transformAttribute.Clone();
newAttribute.Value = newValue;
TargetNode.Attributes.Append(newAttribute);
}
Log.LogMessage(MessageType.Verbose, SR.XMLTRANSFORMATION_TransformMessageSetAttribute, transformAttribute.Name);
}
if (TransformAttributes.Count > 0)
{
Log.LogMessage(MessageType.Verbose, SR.XMLTRANSFORMATION_TransformMessageSetAttributes, TransformAttributes.Count);
}
else
{
Log.LogWarning(SR.XMLTRANSFORMATION_TransformMessageNoSetAttributes);
}
}
static private RegularExpressions.Regex s_dirRegex = null;
static private RegularExpressions.Regex s_parentAttribRegex = null;
static private RegularExpressions.Regex s_tokenFormatRegex = null;
// Directory registrory
static internal RegularExpressions.Regex DirRegex
{
get
{
if (s_dirRegex == null)
{
s_dirRegex = new RegularExpressions.Regex(@"\G\{%(\s*(?<attrname>\w+(?=\W))(\s*(?<equal>=)\s*'(?<attrval>[^']*)'|\s*(?<equal>=)\s*(?<attrval>[^\s%>]*)|(?<equal>)(?<attrval>\s*?)))*\s*?%\}");
}
return s_dirRegex;
}
}
static internal RegularExpressions.Regex ParentAttributeRegex
{
get
{
if (s_parentAttribRegex == null)
{
s_parentAttribRegex = new RegularExpressions.Regex(@"\G\$\((?<tagname>[\w:\.]+)\)");
}
return s_parentAttribRegex;
}
}
static internal RegularExpressions.Regex TokenFormatRegex
{
get
{
if (s_tokenFormatRegex == null)
{
s_tokenFormatRegex = new RegularExpressions.Regex(@"\G\#\((?<tagname>[\w:\.]+)\)");
}
return s_tokenFormatRegex;
}
}
protected delegate string GetValueCallback(string key);
protected string GetAttributeValue(string attributeName)
{
string dataValue = null;
XmlAttribute sourceAttribute = TargetNode.Attributes.GetNamedItem(attributeName) as XmlAttribute;
if (sourceAttribute == null)
{
if (string.Compare(attributeName, tokenizeValueCurrentXmlAttribute.Name, StringComparison.OrdinalIgnoreCase) != 0)
{ // if it is other attributename, we fall back to the current now
sourceAttribute = TransformNode.Attributes.GetNamedItem(attributeName) as XmlAttribute;
}
}
if (sourceAttribute != null)
{
dataValue = sourceAttribute.Value;
}
return dataValue;
}
//DirRegex treat single quote differently
protected string EscapeDirRegexSpecialCharacter(string value, bool escape)
{
if (escape)
{
return value.Replace("'", "'");
}
else
{
return value.Replace("'", "'");
}
}
protected static string SubstituteKownValue(string transformValue, RegularExpressions.Regex patternRegex, string patternPrefix, GetValueCallback getValueDelegate )
{
int position = 0;
List<RegularExpressions.Match> matchsExpr = new List<RegularExpressions.Match>();
do
{
position = transformValue.IndexOf(patternPrefix, position, StringComparison.OrdinalIgnoreCase);
if (position > -1)
{
RegularExpressions.Match match = patternRegex.Match(transformValue, position);
// Add the successful match to collection
if (match.Success)
{
matchsExpr.Add(match);
position = match.Index + match.Length;
}
else
{
position++;
}
}
} while (position > -1);
System.Text.StringBuilder strbuilder = new StringBuilder(transformValue.Length);
if (matchsExpr.Count > 0)
{
strbuilder.Remove(0, strbuilder.Length);
position = 0;
int index = 0;
foreach (RegularExpressions.Match match in matchsExpr)
{
strbuilder.Append(transformValue.Substring(position, match.Index - position));
RegularExpressions.Capture captureTagName = match.Groups["tagname"];
string attributeName = captureTagName.Value;
string newValue = getValueDelegate(attributeName);
if (newValue != null) // null indicate that the attribute is not exist
{
strbuilder.Append(newValue);
}
else
{
// keep original value
strbuilder.Append(match.Value);
}
position = match.Index + match.Length;
index++;
}
strbuilder.Append(transformValue.Substring(position));
transformValue = strbuilder.ToString();
}
return transformValue;
}
private string GetXPathToAttribute(XmlAttribute xmlAttribute)
{
return GetXPathToAttribute(xmlAttribute, null);
}
private string GetXPathToAttribute(XmlAttribute xmlAttribute, IList<string> locators)
{
string path = string.Empty;
if (xmlAttribute != null)
{
string pathToNode = GetXPathToNode(xmlAttribute.OwnerElement);
if (!string.IsNullOrEmpty(pathToNode))
{
System.Text.StringBuilder identifier = new StringBuilder(256);
if (!(locators == null || locators.Count == 0))
{
foreach (string match in locators)
{
string val = this.GetAttributeValue(match);
if (!string.IsNullOrEmpty(val))
{
if (identifier.Length != 0)
{
identifier.Append(" and ");
}
identifier.Append(String.Format(System.Globalization.CultureInfo.InvariantCulture, "@{0}='{1}'", match, val));
}
else
{
throw new XmlTransformationException(string.Format(System.Globalization.CultureInfo.CurrentCulture,SR.XMLTRANSFORMATION_MatchAttributeDoesNotExist, match));
}
}
}
if (identifier.Length == 0)
{
for (int i = 0; i < TargetNodes.Count; i++)
{
if (TargetNodes[i] == xmlAttribute.OwnerElement)
{
// Xpath is 1 based
identifier.Append((i + 1).ToString(System.Globalization.CultureInfo.InvariantCulture));
break;
}
}
}
pathToNode = string.Concat(pathToNode, "[", identifier.ToString(), "]");
}
path = string.Concat(pathToNode, "/@", xmlAttribute.Name);
}
return path;
}
private string GetXPathToNode(XmlNode xmlNode)
{
if (xmlNode == null || xmlNode.NodeType == XmlNodeType.Document)
{
return null;
}
string parentPath = GetXPathToNode(xmlNode.ParentNode);
return string.Concat(parentPath, "/", xmlNode.Name);
}
private string TokenizeValue(XmlAttribute targetAttribute,
XmlAttribute transformAttribute,
bool fTokenizeParameter,
List<Dictionary<string, string>> parameters)
{
Debug.Assert(!fTokenizeParameter || parameters != null);
tokenizeValueCurrentXmlAttribute = transformAttribute;
string transformValue = transformAttribute.Value;
string xpath = GetXPathToAttribute(targetAttribute);
//subsitute the know value first in the transformAttribute
transformValue = SubstituteKownValue(transformValue, ParentAttributeRegex, "$(", delegate(string key) { return EscapeDirRegexSpecialCharacter(GetAttributeValue(key), true); });
// then use the directive to parse the value. --- if TokenizeParameterize is enable
if (fTokenizeParameter && parameters != null)
{
int position = 0;
System.Text.StringBuilder strbuilder = new StringBuilder(transformValue.Length);
position = 0;
List<RegularExpressions.Match> matchs = new List<RegularExpressions.Match>();
do
{
position = transformValue.IndexOf("{%", position, StringComparison.OrdinalIgnoreCase);
if (position > -1)
{
RegularExpressions.Match match = DirRegex.Match(transformValue, position);
// Add the successful match to collection
if (match.Success)
{
matchs.Add(match);
position = match.Index + match.Length;
}
else
{
position++;
}
}
} while (position > -1);
if (matchs.Count > 0)
{
strbuilder.Remove(0, strbuilder.Length);
position = 0;
int index = 0;
foreach (RegularExpressions.Match match in matchs)
{
strbuilder.Append(transformValue.Substring(position, match.Index - position));
RegularExpressions.CaptureCollection attrnames = match.Groups["attrname"].Captures;
if (attrnames != null && attrnames.Count > 0)
{
RegularExpressions.CaptureCollection attrvalues = match.Groups["attrval"].Captures;
Dictionary<string, string> paramDictionary = new Dictionary<string, string>(4, StringComparer.OrdinalIgnoreCase);
paramDictionary[XPathWithIndex] = xpath;
paramDictionary[TokenNumber] = index.ToString(System.Globalization.CultureInfo.InvariantCulture);
// Get the key-value pare of the in the tranform form
for (int i = 0; i < attrnames.Count; i++)
{
string name = attrnames[i].Value;
string val = null;
if (attrvalues != null && i < attrvalues.Count)
{
val = EscapeDirRegexSpecialCharacter(attrvalues[i].Value, false);
}
paramDictionary[name] = val;
}
//Identify the Token format
string strTokenFormat = null;
if (!paramDictionary.TryGetValue(Token, out strTokenFormat))
{
strTokenFormat = storageDictionary.TokenFormat;
}
if (!string.IsNullOrEmpty(strTokenFormat))
{
paramDictionary[Token] = strTokenFormat;
}
// Second translation of #() -- replace with the existing Parameters
int count = paramDictionary.Count;
string[] keys = new string[count];
paramDictionary.Keys.CopyTo(keys, 0);
for (int i = 0; i < count; i++)
{
// if token format contain the #(),we replace with the known value such that it is unique identify
// for example, intokenizeTransformXml.cs, default token format is
// string.Concat("$(ReplacableToken_#(", SetTokenizedAttributes.ParameterAttribute, ")_#(", SetTokenizedAttributes.TokenNumber, "))");
// which ParameterAttribute will be translate to parameterDictionary["parameter"} and TokenNumber will be translate to parameter
// parameterDictionary["TokenNumber"]
string keyindex = keys[i];
string val = paramDictionary[keyindex];
string newVal = SubstituteKownValue(val, TokenFormatRegex, "#(",
delegate(string key) { return paramDictionary.ContainsKey(key) ? paramDictionary[key] : null; });
paramDictionary[keyindex] = newVal;
}
if (paramDictionary.TryGetValue(Token, out strTokenFormat))
{
// Replace with token
strbuilder.Append(strTokenFormat);
}
string attributeLocator;
if (paramDictionary.TryGetValue(XpathLocator, out attributeLocator) && !string.IsNullOrEmpty(attributeLocator))
{
IList<string> locators = XmlArgumentUtility.SplitArguments(attributeLocator);
string xpathwithlocator = GetXPathToAttribute(targetAttribute,locators);
if (!string.IsNullOrEmpty(xpathwithlocator))
{
paramDictionary[XPathWithLocator] = xpathwithlocator;
}
}
parameters.Add(paramDictionary);
}
position = match.Index + match.Length;
index++;
}
strbuilder.Append(transformValue.Substring(position));
transformValue = strbuilder.ToString();
}
}
return transformValue;
}
}
public class RemoveAttributes : AttributeTransform
{
protected override void Apply() {
foreach (XmlAttribute attribute in TargetAttributes) {
TargetNode.Attributes.Remove(attribute);
Log.LogMessage(MessageType.Verbose, SR.XMLTRANSFORMATION_TransformMessageRemoveAttribute, attribute.Name);
}
if (TargetAttributes.Count > 0) {
Log.LogMessage(MessageType.Verbose, SR.XMLTRANSFORMATION_TransformMessageRemoveAttributes, TargetAttributes.Count);
}
else {
Log.LogWarning(TargetNode, SR.XMLTRANSFORMATION_TransformMessageNoRemoveAttributes);
}
}
}
}
| |
// 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.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Navigation;
using Microsoft.CodeAnalysis.Diagnostics.Log;
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
using Microsoft.VisualStudio.Text.Differencing;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.PreviewPane
{
internal partial class PreviewPane : UserControl, IDisposable
{
private static readonly string s_dummyThreeLineTitle = "A" + Environment.NewLine + "A" + Environment.NewLine + "A";
private static readonly Size s_infiniteSize = new Size(double.PositiveInfinity, double.PositiveInfinity);
private readonly string _id;
private readonly bool _logIdVerbatimInTelemetry;
private bool _isExpanded;
private double _heightForThreeLineTitle;
private IWpfDifferenceViewer _previewDiffViewer;
public PreviewPane(Image severityIcon, string id, string title, string description, Uri helpLink, string helpLinkToolTipText,
object previewContent, bool logIdVerbatimInTelemetry)
{
InitializeComponent();
_id = id;
_logIdVerbatimInTelemetry = logIdVerbatimInTelemetry;
// Initialize header portion.
if ((severityIcon != null) && !string.IsNullOrWhiteSpace(id) && !string.IsNullOrWhiteSpace(title))
{
HeaderStackPanel.Visibility = Visibility.Visible;
SeverityIconBorder.Child = severityIcon;
// Set the initial title text to three lines worth so that we can measure the pixel height
// that WPF requires to render three lines of text under the current font and DPI settings.
TitleRun.Text = s_dummyThreeLineTitle;
TitleTextBlock.Measure(availableSize: s_infiniteSize);
_heightForThreeLineTitle = TitleTextBlock.DesiredSize.Height;
// Now set the actual title text.
TitleRun.Text = title;
InitializeHyperlinks(helpLink, helpLinkToolTipText);
if (!string.IsNullOrWhiteSpace(description))
{
DescriptionParagraph.Inlines.Add(description);
}
}
// Initialize preview (i.e. diff view) portion.
InitializePreviewElement(previewContent);
}
private void InitializePreviewElement(object previewContent)
{
FrameworkElement previewElement = null;
if (previewContent is IWpfDifferenceViewer)
{
_previewDiffViewer = previewContent as IWpfDifferenceViewer;
previewElement = _previewDiffViewer.VisualElement;
PreviewDockPanel.Background = _previewDiffViewer.InlineView.Background;
}
else if (previewContent is string)
{
previewElement = GetPreviewForString(previewContent as string);
}
else if (previewContent is FrameworkElement)
{
previewElement = previewContent as FrameworkElement;
}
if (previewElement != null)
{
HeaderSeparator.Visibility = Visibility.Visible;
PreviewDockPanel.Visibility = Visibility.Visible;
PreviewScrollViewer.Content = previewElement;
previewElement.VerticalAlignment = VerticalAlignment.Top;
previewElement.HorizontalAlignment = HorizontalAlignment.Left;
}
// 1. Width of the header section should not exceed the width of the preview content.
// In other words, the text we put in the header at the top of the preview pane
// should not cause the preview pane itself to grow wider than the width required to
// display the preview content at the bottom of the pane.
// 2. Adjust the height of the header section so that it displays only three lines worth
// by default.
AdjustWidthAndHeight(previewElement);
}
private void InitializeHyperlinks(Uri helpLink, string helpLinkToolTipText)
{
IdHyperlink.SetVSHyperLinkStyle();
LearnMoreHyperlink.SetVSHyperLinkStyle();
IdHyperlink.Inlines.Add(_id);
IdHyperlink.NavigateUri = helpLink;
IdHyperlink.IsEnabled = true;
IdHyperlink.ToolTip = helpLinkToolTipText;
LearnMoreHyperlink.Inlines.Add(string.Format(ServicesVSResources.LearnMoreLinkText, _id));
LearnMoreHyperlink.NavigateUri = helpLink;
LearnMoreHyperlink.ToolTip = helpLinkToolTipText;
}
public static Border GetPreviewForString(string previewContent, bool useItalicFontStyle = false, bool centerAlignTextHorizontally = false)
{
var textBlock = new TextBlock()
{
Margin = new Thickness(5),
VerticalAlignment = VerticalAlignment.Center,
Text = previewContent,
TextWrapping = TextWrapping.Wrap,
};
if (useItalicFontStyle)
{
textBlock.FontStyle = FontStyles.Italic;
}
if (centerAlignTextHorizontally)
{
textBlock.TextAlignment = TextAlignment.Center;
}
var preview = new Border()
{
Width = 400,
MinHeight = 75,
Child = textBlock
};
return preview;
}
// This method adjusts the width of the header section to match that of the preview content
// thereby ensuring that the preview pane itself is never wider than the preview content.
// This method also adjusts the height of the header section so that it displays only three lines
// worth by default.
private void AdjustWidthAndHeight(FrameworkElement previewElement)
{
var headerStackPanelWidth = double.PositiveInfinity;
var titleTextBlockHeight = double.PositiveInfinity;
if (previewElement == null)
{
HeaderStackPanel.Measure(availableSize: s_infiniteSize);
headerStackPanelWidth = HeaderStackPanel.DesiredSize.Width;
TitleTextBlock.Measure(availableSize: s_infiniteSize);
titleTextBlockHeight = TitleTextBlock.DesiredSize.Height;
}
else
{
PreviewDockPanel.Measure(availableSize: new Size(previewElement.Width, double.PositiveInfinity));
headerStackPanelWidth = PreviewDockPanel.DesiredSize.Width;
if (IsNormal(headerStackPanelWidth))
{
TitleTextBlock.Measure(availableSize: new Size(headerStackPanelWidth, double.PositiveInfinity));
titleTextBlockHeight = TitleTextBlock.DesiredSize.Height;
}
}
if (IsNormal(headerStackPanelWidth))
{
HeaderStackPanel.Width = headerStackPanelWidth;
}
// If the pixel height required to render the complete title in the
// TextBlock is larger than that required to render three lines worth,
// then trim the contents of the TextBlock with an ellipsis at the end and
// display the expander button that will allow users to view the full text.
if (HasDescription || (IsNormal(titleTextBlockHeight) && (titleTextBlockHeight > _heightForThreeLineTitle)))
{
TitleTextBlock.MaxHeight = _heightForThreeLineTitle;
TitleTextBlock.TextTrimming = TextTrimming.CharacterEllipsis;
ExpanderToggleButton.Visibility = Visibility.Visible;
if (_isExpanded)
{
ExpanderToggleButton.IsChecked = true;
}
}
}
private static bool IsNormal(double size)
{
return size > 0 && !double.IsNaN(size) && !double.IsInfinity(size);
}
private bool HasDescription
{
get
{
return DescriptionParagraph.Inlines.Count > 0;
}
}
#region IDisposable Implementation
private bool _disposedValue = false;
// VS editor will call Dispose at which point we should Close() the embedded IWpfDifferenceViewer.
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing && (_previewDiffViewer != null) && !_previewDiffViewer.IsClosed)
{
_previewDiffViewer.Close();
}
}
_disposedValue = true;
}
void IDisposable.Dispose()
{
Dispose(true);
}
#endregion
private void LearnMoreHyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
if (e.Uri == null)
{
return;
}
BrowserHelper.StartBrowser(e.Uri);
e.Handled = true;
var hyperlink = sender as Hyperlink;
if (hyperlink == null)
{
return;
}
DiagnosticLogger.LogHyperlink(hyperlink.Name ?? "Preview", _id, HasDescription, _logIdVerbatimInTelemetry, e.Uri.AbsoluteUri);
}
private void ExpanderToggleButton_CheckedChanged(object sender, RoutedEventArgs e)
{
if (ExpanderToggleButton.IsChecked ?? false)
{
TitleTextBlock.MaxHeight = double.PositiveInfinity;
TitleTextBlock.TextTrimming = TextTrimming.None;
if (HasDescription)
{
DescriptionDockPanel.Visibility = Visibility.Visible;
if (LearnMoreHyperlink.NavigateUri != null)
{
LearnMoreTextBlock.Visibility = Visibility.Visible;
LearnMoreHyperlink.IsEnabled = true;
}
}
_isExpanded = true;
}
else
{
TitleTextBlock.MaxHeight = _heightForThreeLineTitle;
TitleTextBlock.TextTrimming = TextTrimming.CharacterEllipsis;
DescriptionDockPanel.Visibility = Visibility.Collapsed;
_isExpanded = false;
}
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.14.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.WebSites
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// RecommendationsOperations operations.
/// </summary>
internal partial class RecommendationsOperations : IServiceOperations<WebSiteManagementClient>, IRecommendationsOperations
{
/// <summary>
/// Initializes a new instance of the RecommendationsOperations class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal RecommendationsOperations(WebSiteManagementClient client)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
this.Client = client;
}
/// <summary>
/// Gets a reference to the WebSiteManagementClient
/// </summary>
public WebSiteManagementClient Client { get; private set; }
/// <summary>
/// Gets a list of recommendations associated with the specified subscription.
/// </summary>
/// <param name='featured'>
/// If set, this API returns only the most critical recommendation among the
/// others. Otherwise this API returns all recommendations available
/// </param>
/// <param name='filter'>
/// Return only channels specified in the filter. Filter is specified by using
/// OData syntax. Example: $filter=channels eq 'Api' or channel eq
/// 'Notification'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<IList<Recommendation>>> GetRecommendationBySubscriptionWithHttpMessagesAsync(bool? featured = default(bool?), string filter = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("featured", featured);
tracingParameters.Add("filter", filter);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetRecommendationBySubscription", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Web/recommendations").ToString();
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (featured != null)
{
_queryParameters.Add(string.Format("featured={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(featured, this.Client.SerializationSettings).Trim('"'))));
}
if (filter != null)
{
_queryParameters.Add(string.Format("$filter={0}", Uri.EscapeDataString(filter)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<Recommendation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<Recommendation>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the detailed properties of the recommendation object for the
/// specified web site.
/// </summary>
/// <param name='resourceGroupName'>
/// Resource group name
/// </param>
/// <param name='siteName'>
/// Site name
/// </param>
/// <param name='name'>
/// Recommendation rule name
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<RecommendationRule>> GetRuleDetailsBySiteNameWithHttpMessagesAsync(string resourceGroupName, string siteName, string name, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (siteName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "siteName");
}
if (name == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "name");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("siteName", siteName);
tracingParameters.Add("name", name);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetRuleDetailsBySiteName", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/recommendations/{name}").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{siteName}", Uri.EscapeDataString(siteName));
_url = _url.Replace("{name}", Uri.EscapeDataString(name));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<RecommendationRule>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<RecommendationRule>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets a list of recommendations associated with the specified web site.
/// </summary>
/// <param name='resourceGroupName'>
/// Resource group name
/// </param>
/// <param name='siteName'>
/// Site name
/// </param>
/// <param name='featured'>
/// If set, this API returns only the most critical recommendation among the
/// others. Otherwise this API returns all recommendations available
/// </param>
/// <param name='siteSku'>
/// The name of site SKU.
/// </param>
/// <param name='numSlots'>
/// The number of site slots associated to the site
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<IList<Recommendation>>> GetRecommendedRulesForSiteWithHttpMessagesAsync(string resourceGroupName, string siteName, bool? featured = default(bool?), string siteSku = default(string), int? numSlots = default(int?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (siteName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "siteName");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("siteName", siteName);
tracingParameters.Add("featured", featured);
tracingParameters.Add("siteSku", siteSku);
tracingParameters.Add("numSlots", numSlots);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetRecommendedRulesForSite", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/recommendations").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{siteName}", Uri.EscapeDataString(siteName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (featured != null)
{
_queryParameters.Add(string.Format("featured={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(featured, this.Client.SerializationSettings).Trim('"'))));
}
if (siteSku != null)
{
_queryParameters.Add(string.Format("siteSku={0}", Uri.EscapeDataString(siteSku)));
}
if (numSlots != null)
{
_queryParameters.Add(string.Format("numSlots={0}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(numSlots, this.Client.SerializationSettings).Trim('"'))));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<Recommendation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<Recommendation>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Gets the list of past recommendations optionally specified by the time
/// range.
/// </summary>
/// <param name='resourceGroupName'>
/// Resource group name
/// </param>
/// <param name='siteName'>
/// Site name
/// </param>
/// <param name='startTime'>
/// The start time of a time range to query, e.g. $filter=startTime eq
/// '2015-01-01T00:00:00Z' and endTime eq '2015-01-02T00:00:00Z'
/// </param>
/// <param name='endTime'>
/// The end time of a time range to query, e.g. $filter=startTime eq
/// '2015-01-01T00:00:00Z' and endTime eq '2015-01-02T00:00:00Z'
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
public async Task<AzureOperationResponse<IList<Recommendation>>> GetRecommendationHistoryForSiteWithHttpMessagesAsync(string resourceGroupName, string siteName, string startTime = default(string), string endTime = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
if (resourceGroupName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName");
}
if (siteName == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "siteName");
}
if (this.Client.SubscriptionId == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId");
}
if (this.Client.ApiVersion == null)
{
throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion");
}
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceGroupName", resourceGroupName);
tracingParameters.Add("siteName", siteName);
tracingParameters.Add("startTime", startTime);
tracingParameters.Add("endTime", endTime);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetRecommendationHistoryForSite", tracingParameters);
}
// Construct URL
var _baseUrl = this.Client.BaseUri.AbsoluteUri;
var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{siteName}/recommendationHistory").ToString();
_url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName));
_url = _url.Replace("{siteName}", Uri.EscapeDataString(siteName));
_url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId));
List<string> _queryParameters = new List<string>();
if (startTime != null)
{
_queryParameters.Add(string.Format("startTime={0}", Uri.EscapeDataString(startTime)));
}
if (endTime != null)
{
_queryParameters.Add(string.Format("endTime={0}", Uri.EscapeDataString(endTime)));
}
if (this.Client.ApiVersion != null)
{
_queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion)));
}
if (_queryParameters.Count > 0)
{
_url += "?" + string.Join("&", _queryParameters);
}
// Create HTTP transport objects
HttpRequestMessage _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new Uri(_url);
// Set Headers
if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value)
{
_httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString());
}
if (this.Client.AcceptLanguage != null)
{
if (_httpRequest.Headers.Contains("accept-language"))
{
_httpRequest.Headers.Remove("accept-language");
}
_httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
// Set Credentials
if (this.Client.Credentials != null)
{
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings);
if (_errorBody != null)
{
ex = new CloudException(_errorBody.Message);
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new AzureOperationResponse<IList<Recommendation>>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
if (_httpResponse.Headers.Contains("x-ms-request-id"))
{
_result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<IList<Recommendation>>(_responseContent, this.Client.DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.ApplicationModel.Resources;
using Windows.Security.ExchangeActiveSyncProvisioning;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Lumia.Sense;
using StepsTracker.Models;
using StepsTracker.StepsEngine;
namespace StepsTracker.SensorCore
{
/// <summary>
/// Steps engine that wraps the Lumia SensorCore StepCounter APIs
/// </summary>
public class LumiaStepsEngine : IStepsEngine
{
#region Private members
/// <summary>
/// Step counter instance
/// </summary>
private IStepCounter _stepCounter;
/// <summary>
/// Is step counter currently active?
/// </summary>
private bool _sensorActive = false;
/// <summary>
/// Constructs a new ResourceLoader object.
/// </summary>
protected static readonly ResourceLoader _resourceLoader = ResourceLoader.GetForCurrentView("Resources");
#endregion
/// <summary>
/// Constructor
/// </summary>
public LumiaStepsEngine()
{
}
/// <summary>
/// Makes sure necessary settings are enabled in order to use SensorCore
/// </summary>
/// <returns>Asynchronous task</returns>
public static async Task ValidateSettingsAsync()
{
if (await StepCounter.IsSupportedAsync())
{
// Starting from version 2 of Motion data settings Step counter and Acitivity monitor are always available. In earlier versions system
// location setting and Motion data had to be enabled.
MotionDataSettings settings = await SenseHelper.GetSettingsAsync();
if (settings.Version < 2)
{
if (!settings.LocationEnabled)
{
MessageDialog dlg = new MessageDialog("In order to count steps you need to enable location in system settings. Do you want to open settings now? If not, application will exit.", "Information");
dlg.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(async (cmd) => await SenseHelper.LaunchLocationSettingsAsync())));
dlg.Commands.Add(new UICommand("No", new UICommandInvokedHandler((cmd) => { Application.Current.Exit(); })));
await dlg.ShowAsync();
}
if (!settings.PlacesVisited)
{
MessageDialog dlg = new MessageDialog("In order to count steps you need to enable Motion data in Motion data settings. Do you want to open settings now? If not, application will exit.", "Information");
dlg.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(async (cmd) => await SenseHelper.LaunchSenseSettingsAsync())));
dlg.Commands.Add(new UICommand("No", new UICommandInvokedHandler((cmd) => { Application.Current.Exit(); })));
await dlg.ShowAsync();
}
}
}
}
/// <summary>
/// SensorCore needs to be deactivated when app goes to background
/// </summary>
/// <returns>Asynchronous task</returns>
public async Task DeactivateAsync()
{
_sensorActive = false;
if (_stepCounter != null) await _stepCounter.DeactivateAsync();
}
/// <summary>
/// SensorCore needs to be activated when app comes back to foreground
/// </summary>
public async Task ActivateAsync()
{
if (_sensorActive) return;
if (_stepCounter != null)
{
await _stepCounter.ActivateAsync();
}
else
{
await InitializeAsync();
}
_sensorActive = true;
}
/// <summary>
/// Returns steps for given day at given resolution
/// </summary>
/// <param name="day">Day to fetch data for</param>
/// <param name="resolution">Resolution in minutes. Minimum resolution is five minutes.</param>
/// <returns>List of steps counts for the given day at given resolution.</returns>
public async Task<List<KeyValuePair<TimeSpan, uint>>> GetStepsCountsForDay(DateTime day, uint resolution)
{
List<KeyValuePair<TimeSpan, uint>> steps = new List<KeyValuePair<TimeSpan, uint>>();
uint totalSteps = 0;
uint numIntervals = (((24 * 60) / resolution) + 1);
if (day.Date.Equals(DateTime.Today))
{
numIntervals = (uint)((DateTime.Now - DateTime.Today).TotalMinutes / resolution) + 1;
}
for (int i = 0; i < numIntervals; i++)
{
TimeSpan ts = TimeSpan.FromMinutes(i * resolution);
DateTime startTime = day.Date + ts;
if (startTime < DateTime.Now)
{
try
{
var stepCount = await _stepCounter.GetStepCountForRangeAsync(startTime, TimeSpan.FromMinutes(resolution));
if (stepCount != null)
{
totalSteps += (stepCount.WalkingStepCount + stepCount.RunningStepCount);
steps.Add(new KeyValuePair<TimeSpan, uint>(ts, totalSteps));
}
}
catch (Exception)
{
}
}
else
{
break;
}
}
return steps;
}
/// <summary>
/// Returns step count for given day
/// </summary>
/// <returns>Step count for given day</returns>
public async Task<StepCountData> GetTotalStepCountAsync(DateTime day)
{
if (_stepCounter != null && _sensorActive)
{
StepCount steps = await _stepCounter.GetStepCountForRangeAsync(day.Date, TimeSpan.FromDays(1));
return StepCountData.FromLumiaStepCount(steps);
}
return null;
}
public async Task<List<ReadingByDate>> GetStepsForHour(int hour, int days)
{
List<ReadingByDate> stepsByDay = new List<ReadingByDate>();
for (int i = 0; i < days; i++)
{
try
{
var dateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0).Subtract(TimeSpan.FromDays(i));
Debug.WriteLine("hour: " + i);
Debug.WriteLine("date: " + dateTime);
if (hour == 0) hour = 1;
var stepsForDay = await _stepCounter.GetStepCountForRangeAsync(dateTime, TimeSpan.FromHours(hour));
var data = StepCountData.FromLumiaStepCount(stepsForDay);
stepsByDay.Add(new ReadingByDate
{
DateTime = dateTime.AddHours(hour),
RunningStepsCount = data.RunningCount,
WalkingStepsCount = data.WalkingCount,
TotalStepsCount = data.TotalCount
});
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
}
}
return stepsByDay;
}
/// <summary>
/// Initializes simulator if example runs on emulator otherwise initializes StepCounter
/// </summary>
private async Task InitializeAsync()
{
// Using this method to detect if the application runs in the emulator or on a real device. Later the *Simulator API is used to read fake sense data on emulator.
// In production code you do not need this and in fact you should ensure that you do not include the Lumia.Sense.Testing reference in your project.
EasClientDeviceInformation x = new EasClientDeviceInformation();
if (x.SystemProductName.StartsWith("Virtual"))
{
//await InitializeSimulatorAsync();
}
else
{
await InitializeSensorAsync();
}
}
/// <summary>
/// Initializes the step counter
/// </summary>
private async Task InitializeSensorAsync()
{
if (_stepCounter == null)
{
await CallSensorCoreApiAsync(async () => { _stepCounter = await StepCounter.GetDefaultAsync(); });
}
else
{
await _stepCounter.ActivateAsync();
}
_sensorActive = true;
}
/// <summary>
/// Initializes StepCounterSimulator (requires Lumia.Sense.Testing)
/// </summary>
//public async Task InitializeSimulatorAsync()
//{
// var obj = await SenseRecording.LoadFromFileAsync("Simulations\\short recording.txt");
// if (!await CallSensorCoreApiAsync(async () => { _stepCounter = await StepCounterSimulator.GetDefaultAsync(obj, DateTime.Now - TimeSpan.FromHours(12)); }))
// {
// Application.Current.Exit();
// }
// _sensorActive = true;
//}
/// <summary>
/// Performs asynchronous Sensorcore SDK operation and handles any exceptions
/// </summary>
/// <param name="action">Action for which the SensorCore will be activated.</param>
/// <returns><c>true</c> if call was successful, <c>false</c> otherwise</returns>
private async Task<bool> CallSensorCoreApiAsync(Func<Task> action)
{
Exception failure = null;
try
{
await action();
}
catch (Exception e)
{
failure = e;
}
if (failure != null)
{
MessageDialog dlg = null;
switch (SenseHelper.GetSenseError(failure.HResult))
{
case SenseError.LocationDisabled:
{
dlg = new MessageDialog(_resourceLoader.GetString("FeatureDisabled/Location"), _resourceLoader.GetString("FeatureDisabled/Title"));
dlg.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(async (cmd) => await SenseHelper.LaunchLocationSettingsAsync())));
dlg.Commands.Add(new UICommand("No", new UICommandInvokedHandler((cmd) => { /* do nothing */ })));
await dlg.ShowAsync();
new System.Threading.ManualResetEvent(false).WaitOne(500);
return false;
}
case SenseError.SenseDisabled:
{
dlg = new MessageDialog(_resourceLoader.GetString("FeatureDisabled/MotionData"), _resourceLoader.GetString("FeatureDisabled/Title"));
dlg.Commands.Add(new UICommand("Yes", new UICommandInvokedHandler(async (cmd) => await SenseHelper.LaunchSenseSettingsAsync())));
dlg.Commands.Add(new UICommand("No", new UICommandInvokedHandler((cmd) => { /* do nothing */ })));
await dlg.ShowAsync();
return false;
}
case SenseError.SenseNotAvailable:
{
dlg = new MessageDialog(_resourceLoader.GetString("FeatureNotSupported/Message"), _resourceLoader.GetString("FeatureNotSupported/Title"));
await dlg.ShowAsync();
return false;
}
default:
{
dlg = new MessageDialog("Failure: " + SenseHelper.GetSenseError(failure.HResult), "");
await dlg.ShowAsync();
return false;
}
}
}
else
{
return true;
}
}
}
}
| |
// 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.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.PythonTools.Analysis.Analyzer;
using Microsoft.PythonTools.Analysis.Values;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Parsing.Ast;
namespace Microsoft.PythonTools.Analysis {
/// <summary>
/// Provides interactions to analysis a single file in a project and get the results back.
///
/// To analyze a file the tree should be updated with a call to UpdateTree and then PreParse
/// should be called on all files. Finally Parse should then be called on all files.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "Unclear ownership makes it unlikely this object will be disposed correctly")]
internal sealed class ProjectEntry : IPythonProjectEntry, IAggregateableProjectEntry {
private readonly PythonAnalyzer _projectState;
private readonly string _moduleName;
private readonly string _filePath;
private readonly ModuleInfo _myScope;
private IAnalysisCookie _cookie;
private PythonAst _tree;
private ModuleAnalysis _currentAnalysis;
private AnalysisUnit _unit;
private int _analysisVersion;
private Dictionary<object, object> _properties = new Dictionary<object, object>();
private ManualResetEventSlim _curWaiter;
private int _updatesPending, _waiters;
internal readonly HashSet<AggregateProjectEntry> _aggregates = new HashSet<AggregateProjectEntry>();
// we expect to have at most 1 waiter on updated project entries, so we attempt to share the event.
private static ManualResetEventSlim _sharedWaitEvent = new ManualResetEventSlim(false);
internal ProjectEntry(PythonAnalyzer state, string moduleName, string filePath, IAnalysisCookie cookie) {
_projectState = state;
_moduleName = moduleName ?? "";
_filePath = filePath;
_cookie = cookie;
_myScope = new ModuleInfo(_moduleName, this, state.Interpreter.CreateModuleContext());
_unit = new AnalysisUnit(_tree, _myScope.Scope);
AnalysisLog.NewUnit(_unit);
}
public event EventHandler<EventArgs> OnNewParseTree;
public event EventHandler<EventArgs> OnNewAnalysis;
public void UpdateTree(PythonAst newAst, IAnalysisCookie newCookie) {
lock (this) {
if (_updatesPending > 0) {
_updatesPending--;
}
if (newAst == null) {
// there was an error in parsing, just let the waiter go...
if (_curWaiter != null) {
_curWaiter.Set();
}
_tree = null;
return;
}
_tree = newAst;
_cookie = newCookie;
if (_curWaiter != null) {
_curWaiter.Set();
}
}
var newParse = OnNewParseTree;
if (newParse != null) {
newParse(this, EventArgs.Empty);
}
}
internal bool IsVisible(ProjectEntry assigningScope) {
return true;
}
public void GetTreeAndCookie(out PythonAst tree, out IAnalysisCookie cookie) {
lock (this) {
tree = _tree;
cookie = _cookie;
}
}
public void BeginParsingTree() {
lock (this) {
_updatesPending++;
}
}
public PythonAst WaitForCurrentTree(int timeout = -1) {
lock (this) {
if (_updatesPending == 0) {
return Tree;
}
_waiters++;
if (_curWaiter == null) {
_curWaiter = Interlocked.Exchange(ref _sharedWaitEvent, null);
if (_curWaiter == null) {
_curWaiter = new ManualResetEventSlim(false);
} else {
_curWaiter.Reset();
}
}
}
bool gotNewTree = _curWaiter.Wait(timeout);
lock (this) {
_waiters--;
if (_waiters == 0 &&
Interlocked.CompareExchange(ref _sharedWaitEvent, _curWaiter, null) != null) {
_curWaiter.Dispose();
}
_curWaiter = null;
}
return gotNewTree ? _tree : null;
}
public void Analyze(CancellationToken cancel) {
Analyze(cancel, false);
}
public void Analyze(CancellationToken cancel, bool enqueueOnly) {
if (cancel.IsCancellationRequested) {
return;
}
lock (this) {
_analysisVersion++;
foreach (var aggregate in _aggregates) {
aggregate.BumpVersion();
}
Parse(enqueueOnly, cancel);
}
if (!enqueueOnly) {
RaiseOnNewAnalysis();
}
}
internal void RaiseOnNewAnalysis() {
var evt = OnNewAnalysis;
if (evt != null) {
evt(this, EventArgs.Empty);
}
}
public int AnalysisVersion {
get {
return _analysisVersion;
}
}
public bool IsAnalyzed {
get {
return Analysis != null;
}
}
private void Parse(bool enqueueOnly, CancellationToken cancel) {
PythonAst tree;
IAnalysisCookie cookie;
GetTreeAndCookie(out tree, out cookie);
if (tree == null) {
return;
}
var oldParent = _myScope.ParentPackage;
if (_filePath != null) {
ProjectState.ModulesByFilename[_filePath] = _myScope;
}
if (oldParent != null) {
// update us in our parent package
oldParent.AddChildPackage(_myScope, _unit);
} else if (_filePath != null) {
// we need to check and see if our parent is a package for the case where we're adding a new
// file but not re-analyzing our parent package.
string parentFilename;
if (ModulePath.IsInitPyFile(_filePath)) {
// subpackage
parentFilename = Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(_filePath)), "__init__.py");
} else {
// just a module
parentFilename = Path.Combine(Path.GetDirectoryName(_filePath), "__init__.py");
}
ModuleInfo parentPackage;
if (ProjectState.ModulesByFilename.TryGetValue(parentFilename, out parentPackage)) {
parentPackage.AddChildPackage(_myScope, _unit);
}
}
_unit = new AnalysisUnit(tree, _myScope.Scope);
AnalysisLog.NewUnit(_unit);
foreach (var value in MyScope.Scope.AllVariables) {
value.Value.EnqueueDependents();
}
MyScope.Scope.Children.Clear();
MyScope.Scope.ClearNodeScopes();
MyScope.Scope.ClearNodeValues();
MyScope.ClearUnresolvedModules();
// collect top-level definitions first
var walker = new OverviewWalker(this, _unit, tree);
tree.Walk(walker);
_myScope.Specialize();
// It may be that we have analyzed some child packages of this package already, but because it wasn't analyzed,
// the children were not registered. To handle this possibility, scan analyzed packages for children of this
// package (checked by module name first, then sanity-checked by path), and register any that match.
if (ModulePath.IsInitPyFile(_filePath)) {
string pathPrefix = Path.GetDirectoryName(_filePath) + "\\";
var children =
from pair in _projectState.ModulesByFilename
// Is the candidate child package in a subdirectory of our package?
let fileName = pair.Key
where fileName.StartsWith(pathPrefix)
let moduleName = pair.Value.Name
// Is the full name of the candidate child package qualified with the name of our package?
let lastDot = moduleName.LastIndexOf('.')
where lastDot > 0
let parentModuleName = moduleName.Substring(0, lastDot)
where parentModuleName == _myScope.Name
select pair.Value;
foreach (var child in children) {
_myScope.AddChildPackage(child, _unit);
}
}
_unit.Enqueue();
if (!enqueueOnly) {
_projectState.AnalyzeQueuedEntries(cancel);
}
// publish the analysis now that it's complete/running
_currentAnalysis = new ModuleAnalysis(
_unit,
((ModuleScope)_unit.Scope).CloneForPublish()
);
}
private void ClearScope() {
MyScope.Scope.Children.Clear();
MyScope.Scope.ClearNodeScopes();
MyScope.Scope.ClearNodeValues();
MyScope.ClearUnresolvedModules();
}
public IGroupableAnalysisProject AnalysisGroup {
get {
return _projectState;
}
}
public ModuleAnalysis Analysis {
get { return _currentAnalysis; }
}
public string FilePath {
get { return _filePath; }
}
public IAnalysisCookie Cookie {
get { return _cookie; }
}
internal PythonAnalyzer ProjectState {
get { return _projectState; }
}
public PythonAst Tree {
get { return _tree; }
}
internal ModuleInfo MyScope {
get { return _myScope; }
}
public IModuleContext AnalysisContext {
get { return _myScope.InterpreterContext; }
}
public string ModuleName {
get {
return _moduleName;
}
}
public Dictionary<object, object> Properties {
get {
if (_properties == null) {
_properties = new Dictionary<object, object>();
}
return _properties;
}
}
#region IProjectEntry2 Members
public void RemovedFromProject() {
_analysisVersion = -1;
foreach (var aggregatedInto in _aggregates) {
if (aggregatedInto.AnalysisVersion != -1) {
ProjectState.ClearAggregate(aggregatedInto);
aggregatedInto.RemovedFromProject();
}
}
}
#endregion
internal void Enqueue() {
_unit.Enqueue();
}
public void AggregatedInto(AggregateProjectEntry into) {
_aggregates.Add(into);
}
}
/// <summary>
/// Represents a unit of work which can be analyzed.
/// </summary>
public interface IAnalyzable {
void Analyze(CancellationToken cancel);
}
public interface IVersioned {
/// <summary>
/// Returns the current analysis version of the project entry.
/// </summary>
int AnalysisVersion {
get;
}
}
/// <summary>
/// Represents a file which is capable of being analyzed. Can be cast to other project entry types
/// for more functionality. See also IPythonProjectEntry and IXamlProjectEntry.
/// </summary>
public interface IProjectEntry : IAnalyzable, IVersioned {
/// <summary>
/// Returns true if the project entry has been parsed and analyzed.
/// </summary>
bool IsAnalyzed { get; }
/// <summary>
/// Returns the project entries file path.
/// </summary>
string FilePath { get; }
/// <summary>
/// Provides storage of arbitrary properties associated with the project entry.
/// </summary>
Dictionary<object, object> Properties {
get;
}
/// <summary>
/// Called when the project entry is removed from the project.
///
/// Implementors of this method must ensure this method is thread safe.
/// </summary>
void RemovedFromProject();
IModuleContext AnalysisContext {
get;
}
}
/// <summary>
/// Represents a project entry which is created by an interpreter for additional
/// files which it supports analyzing. Provides the ParseContent method which
/// is called when the parse queue is ready to update the file contents.
/// </summary>
public interface IExternalProjectEntry : IProjectEntry {
void ParseContent(TextReader content, IAnalysisCookie fileCookie);
}
/// <summary>
/// Represents a project entry which can be analyzed together with other project entries for
/// more efficient analysis.
///
/// To analyze the full group you call Analyze(true) on all the items in the same group (determined
/// by looking at the identity of the AnalysGroup object). Then you call AnalyzeQueuedEntries on the
/// group.
/// </summary>
public interface IGroupableAnalysisProjectEntry {
/// <summary>
/// Analyzes this project entry optionally just adding it to the queue shared by the project.
/// </summary>
void Analyze(CancellationToken cancel, bool enqueueOnly);
IGroupableAnalysisProject AnalysisGroup { get; }
}
/// <summary>
/// Represents a project which can support more efficent analysis of individual items via
/// analyzing them together.
/// </summary>
public interface IGroupableAnalysisProject {
void AnalyzeQueuedEntries(CancellationToken cancel);
}
public interface IPythonProjectEntry : IGroupableAnalysisProjectEntry, IProjectEntry {
/// <summary>
/// Returns the last parsed AST.
/// </summary>
PythonAst Tree {
get;
}
string ModuleName { get; }
ModuleAnalysis Analysis {
get;
}
event EventHandler<EventArgs> OnNewParseTree;
event EventHandler<EventArgs> OnNewAnalysis;
/// <summary>
/// Informs the project entry that a new tree will soon be available and will be provided by
/// a call to UpdateTree. Calling this method will cause WaitForCurrentTree to block until
/// UpdateTree has been called.
///
/// Calls to BeginParsingTree should be balanced with calls to UpdateTree.
///
/// This method is thread safe.
/// </summary>
void BeginParsingTree();
void UpdateTree(PythonAst ast, IAnalysisCookie fileCookie);
void GetTreeAndCookie(out PythonAst ast, out IAnalysisCookie cookie);
/// <summary>
/// Returns the current tree if no parsing is currently pending, otherwise waits for the
/// current parse to finish and returns the up-to-date tree.
/// </summary>
PythonAst WaitForCurrentTree(int timeout = -1);
}
}
| |
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 DevOpsDashboard.Web.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 .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.IO;
using System.Collections.Generic;
using System.Text;
using Internal.IL.Stubs;
using Internal.TypeSystem;
using Internal.Metadata.NativeFormat.Writer;
using ILCompiler.Metadata;
using ILCompiler.DependencyAnalysis;
using Debug = System.Diagnostics.Debug;
using DependencyList = ILCompiler.DependencyAnalysisFramework.DependencyNodeCore<ILCompiler.DependencyAnalysis.NodeFactory>.DependencyList;
namespace ILCompiler
{
/// <summary>
/// This class is responsible for managing native metadata to be emitted into the compiled
/// module. It applies a policy that every type/method emitted shall be reflectable.
/// </summary>
public sealed class CompilerGeneratedMetadataManager : MetadataManager
{
private readonly string _metadataLogFile;
private Dictionary<DynamicInvokeMethodSignature, MethodDesc> _dynamicInvokeThunks;
public CompilerGeneratedMetadataManager(CompilationModuleGroup group, CompilerTypeSystemContext typeSystemContext, string logFile)
: base(group, typeSystemContext, new BlockedInternalsBlockingPolicy())
{
_metadataLogFile = logFile;
if (DynamicInvokeMethodThunk.SupportsThunks(typeSystemContext))
{
_dynamicInvokeThunks = new Dictionary<DynamicInvokeMethodSignature, MethodDesc>();
}
}
public override bool WillUseMetadataTokenToReferenceMethod(MethodDesc method)
{
return (GetMetadataCategory(method) & MetadataCategory.Description) != 0;
}
public override bool WillUseMetadataTokenToReferenceField(FieldDesc field)
{
return (GetMetadataCategory(field) & MetadataCategory.Description) != 0;
}
protected override MetadataCategory GetMetadataCategory(FieldDesc field)
{
MetadataCategory category = 0;
if (!IsReflectionBlocked(field))
{
category = MetadataCategory.RuntimeMapping;
if (_compilationModuleGroup.ContainsType(field.GetTypicalFieldDefinition().OwningType))
category |= MetadataCategory.Description;
}
return category;
}
protected override MetadataCategory GetMetadataCategory(MethodDesc method)
{
MetadataCategory category = 0;
if (!IsReflectionBlocked(method))
{
category = MetadataCategory.RuntimeMapping;
if (_compilationModuleGroup.ContainsType(method.GetTypicalMethodDefinition().OwningType))
category |= MetadataCategory.Description;
}
return category;
}
protected override MetadataCategory GetMetadataCategory(TypeDesc type)
{
MetadataCategory category = 0;
if (!IsReflectionBlocked(type))
{
category = MetadataCategory.RuntimeMapping;
if (_compilationModuleGroup.ContainsType(type.GetTypeDefinition()))
category |= MetadataCategory.Description;
}
return category;
}
protected override void ComputeMetadata(NodeFactory factory,
out byte[] metadataBlob,
out List<MetadataMapping<MetadataType>> typeMappings,
out List<MetadataMapping<MethodDesc>> methodMappings,
out List<MetadataMapping<FieldDesc>> fieldMappings)
{
var transformed = MetadataTransform.Run(new GeneratedTypesAndCodeMetadataPolicy(_blockingPolicy, factory), GetCompilationModulesWithMetadata());
// TODO: DeveloperExperienceMode: Use transformed.Transform.HandleType() to generate
// TypeReference records for _typeDefinitionsGenerated that don't have metadata.
// (To be used in MissingMetadataException messages)
// Generate metadata blob
var writer = new MetadataWriter();
writer.ScopeDefinitions.AddRange(transformed.Scopes);
var ms = new MemoryStream();
// .NET metadata is UTF-16 and UTF-16 contains code points that don't translate to UTF-8.
var noThrowUtf8Encoding = new UTF8Encoding(false, false);
using (var logWriter = _metadataLogFile != null ? new StreamWriter(File.Open(_metadataLogFile, FileMode.Create, FileAccess.Write, FileShare.Read), noThrowUtf8Encoding) : null)
{
writer.LogWriter = logWriter;
writer.Write(ms);
}
metadataBlob = ms.ToArray();
typeMappings = new List<MetadataMapping<MetadataType>>();
methodMappings = new List<MetadataMapping<MethodDesc>>();
fieldMappings = new List<MetadataMapping<FieldDesc>>();
// Generate type definition mappings
foreach (var type in factory.MetadataManager.GetTypesWithEETypes())
{
MetadataType definition = type.IsTypeDefinition ? type as MetadataType : null;
if (definition == null)
continue;
MetadataRecord record = transformed.GetTransformedTypeDefinition(definition);
// Reflection requires that we maintain type identity. Even if we only generated a TypeReference record,
// if there is an EEType for it, we also need a mapping table entry for it.
if (record == null)
record = transformed.GetTransformedTypeReference(definition);
if (record != null)
typeMappings.Add(new MetadataMapping<MetadataType>(definition, writer.GetRecordHandle(record)));
}
foreach (var method in GetCompiledMethods())
{
if (method.IsCanonicalMethod(CanonicalFormKind.Specific))
{
// Canonical methods are not interesting.
continue;
}
if (IsReflectionBlocked(method.Instantiation) || IsReflectionBlocked(method.OwningType.Instantiation))
continue;
MetadataRecord record = transformed.GetTransformedMethodDefinition(method.GetTypicalMethodDefinition());
if (record != null)
methodMappings.Add(new MetadataMapping<MethodDesc>(method, writer.GetRecordHandle(record)));
}
foreach (var eetypeGenerated in GetTypesWithEETypes())
{
if (eetypeGenerated.IsGenericDefinition)
continue;
if (eetypeGenerated.HasInstantiation)
{
// Collapsing of field map entries based on canonicalization, to avoid redundant equivalent entries
TypeDesc canonicalType = eetypeGenerated.ConvertToCanonForm(CanonicalFormKind.Specific);
if (canonicalType != eetypeGenerated && TypeGeneratesEEType(canonicalType))
continue;
}
foreach (FieldDesc field in eetypeGenerated.GetFields())
{
if (IsReflectionBlocked(field.OwningType.Instantiation))
continue;
Field record = transformed.GetTransformedFieldDefinition(field.GetTypicalFieldDefinition());
if (record != null)
fieldMappings.Add(new MetadataMapping<FieldDesc>(field, writer.GetRecordHandle(record)));
}
}
}
/// <summary>
/// Is there a reflection invoke stub for a method that is invokable?
/// </summary>
public override bool HasReflectionInvokeStubForInvokableMethod(MethodDesc method)
{
Debug.Assert(IsReflectionInvokable(method));
if (_dynamicInvokeThunks == null)
return false;
// Place an upper limit on how many parameters a method can have to still get a static stub.
// From the past experience, methods taking 8000+ parameters get a stub that can hit various limitations
// in the codegen. On Project N, we were limited to 256 parameters because of MDIL limitations.
// We don't have such limitations here, but it's a nice round number.
// Reflection invoke will still work, but will go through the calling convention converter.
return method.Signature.Length <= 256;
}
/// <summary>
/// Gets a stub that can be used to reflection-invoke a method with a given signature.
/// </summary>
public override MethodDesc GetCanonicalReflectionInvokeStub(MethodDesc method)
{
TypeSystemContext context = method.Context;
var sig = method.Signature;
// Get a generic method that can be used to invoke method with this shape.
MethodDesc thunk;
var lookupSig = new DynamicInvokeMethodSignature(sig);
if (!_dynamicInvokeThunks.TryGetValue(lookupSig, out thunk))
{
thunk = new DynamicInvokeMethodThunk(_compilationModuleGroup.GeneratedAssembly.GetGlobalModuleType(), lookupSig);
_dynamicInvokeThunks.Add(lookupSig, thunk);
}
return InstantiateCanonicalDynamicInvokeMethodForMethod(thunk, method);
}
protected override void GetMetadataDependenciesDueToReflectability(ref DependencyList dependencies, NodeFactory factory, MethodDesc method)
{
dependencies = dependencies ?? new DependencyList();
dependencies.Add(factory.MethodMetadata(method.GetTypicalMethodDefinition()), "Reflectable method");
}
protected override void GetMetadataDependenciesDueToReflectability(ref DependencyList dependencies, NodeFactory factory, TypeDesc type)
{
TypeMetadataNode.GetMetadataDependencies(ref dependencies, factory, type, "Reflectable type");
}
private struct GeneratedTypesAndCodeMetadataPolicy : IMetadataPolicy
{
private readonly MetadataBlockingPolicy _blockingPolicy;
private readonly NodeFactory _factory;
private readonly ExplicitScopeAssemblyPolicyMixin _explicitScopeMixin;
public GeneratedTypesAndCodeMetadataPolicy(MetadataBlockingPolicy blockingPolicy, NodeFactory factory)
{
_blockingPolicy = blockingPolicy;
_factory = factory;
_explicitScopeMixin = new ExplicitScopeAssemblyPolicyMixin();
}
public bool GeneratesMetadata(FieldDesc fieldDef)
{
return _factory.FieldMetadata(fieldDef).Marked;
}
public bool GeneratesMetadata(MethodDesc methodDef)
{
return _factory.MethodMetadata(methodDef).Marked;
}
public bool GeneratesMetadata(MetadataType typeDef)
{
return _factory.TypeMetadata(typeDef).Marked;
}
public bool IsBlocked(MetadataType typeDef)
{
return _blockingPolicy.IsBlocked(typeDef);
}
public bool IsBlocked(MethodDesc methodDef)
{
return _blockingPolicy.IsBlocked(methodDef);
}
public ModuleDesc GetModuleOfType(MetadataType typeDef)
{
return _explicitScopeMixin.GetModuleOfType(typeDef);
}
}
}
}
| |
using System;
using Buildron.Domain.Builds;
using Skahal;
using Skahal.Camera;
using Skahal.Logging;
using UnityEngine;
using UnityEngine.UI;
using Zenject;
using System.Linq;
using Buildron.Domain.Mods;
namespace Buildron.ClassicMods.BuildMod.Controllers
{
/// <summary>
/// Build controller.
/// </summary>
public class BuildController : MonoBehaviour, ISHController<IBuild>, IBuildController
{
#region Fields
private static UnityEngine.Object s_buildFailedExplosionPrefab;
private static UnityEngine.Object s_buildSuccessFireworksPrefab;
private static UnityEngine.Object s_buildHidingEffectPrefab;
private BuildProgressBarController m_progressBar;
private bool m_groundReachdAlreadRaised;
private Text m_projectLabel;
private Text m_configurationLabel;
private Image m_runningStatusIcon;
private Image m_userAvatarIcon;
private Collider m_bodyCollider;
private Renderer m_bodyRenderer;
private Renderer m_focusedPanelRenderer;
private bool m_isFirstCheckState = true;
private BuildStatus m_lastCheckStateStatus;
private GameObject m_focusedPanel;
#endregion
#region Properties
public bool IsHistoryBuild { get; set; }
public bool IsVisible { get; private set; }
public bool HasReachGround { get; private set; }
public GameObject Body { get; private set; }
public Rigidbody Rigidbody { get; private set; }
public Collider CenterCollider { get; private set; }
public Collider TopCollider { get; private set; }
public Collider BottomCollider { get; private set; }
public Collider LeftCollider { get; private set; }
public Collider RightCollider { get; private set; }
public string ProjectText {
get {
return m_projectLabel.text;
}
set {
if (m_projectLabel == null) {
m_projectLabel = transform.FindChild ("Canvas/ProjectLabel").GetComponent<Text> ();
}
m_projectLabel.text = value;
}
}
public IBuild Model { get; set; }
public bool Cloneable { get; set; }
#endregion
#region Editor properties
public Material BuildHidingMaterial;
public Color SuccessColor = new Color (1, 0, 0.95f, 1);
public Color FailedColor = new Color (1, 0, 0, 1);
public Color RunningColor = new Color (1, 0.98f, 0, 1);
public Color QueuedColor = new Color (0.36f, 0.45f, 0.55f, 1);
public Material UserAvatarIconMaterial;
public Vector3 StatusChangedForce = new Vector3 (0, 10, 0);
public float BuildHighlightZChange = -2;
public float VisibleMaxYVelocity = 0.1f;
public Sprite[] BuildRunningIcons;
public Sprite BuildRunningFallbackIcon;
#endregion
#region Life cycle
private void Start ()
{
IsVisible = true;
if (m_projectLabel == null) {
ProjectText = Model.Configuration.Project.Name;
}
m_configurationLabel = transform.FindChild ("Canvas/ConfigurationLabel").GetComponent<Text> ();
m_configurationLabel.text = Model.Configuration.Name;
m_runningStatusIcon = transform.FindChild ("Canvas/RunningStatusIcon").GetComponent<Image> ();
m_runningStatusIcon.enabled = false;
m_userAvatarIcon = transform.FindChild ("Canvas/UserAvatarIcon").GetComponent<Image> ();
m_userAvatarIcon.enabled = false;
Body = transform.FindChild ("Buildron-Totem").gameObject;
m_focusedPanel = transform.FindChild ("FocusedPanel").gameObject;
CenterCollider = transform.FindChild ("Edges/CenterCollider").GetComponent<Collider> ();
TopCollider = transform.FindChild ("Edges/TopCollider").GetComponent<Collider> ();
BottomCollider = transform.FindChild ("Edges/BottomCollider").GetComponent<Collider> ();
LeftCollider = transform.FindChild ("Edges/LeftCollider").GetComponent<Collider> ();
RightCollider = transform.FindChild ("Edges/RightCollider").GetComponent<Collider> ();
Rigidbody = GetComponent<Rigidbody> ();
m_bodyCollider = GetComponent<Collider> ();
m_bodyRenderer = Body.GetComponent<Renderer> ();
m_focusedPanelRenderer = m_focusedPanel.GetComponent<Renderer> ();
m_progressBar = GetComponentInChildren<BuildProgressBarController> ();
CheckState ();
MonitorTriggeredByPhotoUpdated ();
if (!IsHistoryBuild) {
Model.StatusChanged += delegate {
if (Model.Status <= BuildStatus.Running && Model.Status != BuildStatus.Queued) {
Rigidbody.AddForce (StatusChangedForce);
}
CheckState ();
};
Model.TriggeredByChanged += (sender, e) => {
MonitorTriggeredByPhotoUpdated ();
UpdateUserAvatar ();
};
}
Mod.Context.RemoteControlChanged += (sender, e) => {
var rc = e.RemoteControl;
if (rc.Connected) {
var rcUserName = rc == null ? null : rc.UserName.ToLowerInvariant ();
var userName = Model.TriggeredBy == null ? null : Model.TriggeredBy.UserName.ToLowerInvariant ();
if (!String.IsNullOrEmpty (rcUserName)
&& !String.IsNullOrEmpty (userName)
&& rcUserName.Equals (userName)) {
m_userAvatarIcon.enabled = true;
}
} else {
m_userAvatarIcon.enabled = true;
UpdateUserAvatar ();
}
};
Messenger.Send ("OnBuildStarted", Model);
}
private void MonitorTriggeredByPhotoUpdated ()
{
if (Model.TriggeredBy != null) {
Model.TriggeredBy.PhotoUpdated += delegate {
UpdateUserAvatar ();
};
}
}
private void CheckState ()
{
SHLog.Debug ("{0} | {1} | {2}", m_isFirstCheckState, m_lastCheckStateStatus, Model.Status);
var statusChanged = m_isFirstCheckState || m_lastCheckStateStatus != Model.Status;
if (Model.IsRunning()) {
m_progressBar.Show ();
} else {
m_progressBar.Hide ();
}
Color color;
switch (Model.Status) {
case BuildStatus.Failed:
case BuildStatus.Error:
case BuildStatus.Canceled:
color = FailedColor;
UpdateRunningStatusIcon (true);
if (statusChanged) {
CreateFailedEffects ();
}
break;
case BuildStatus.Success:
color = SuccessColor;
UpdateRunningStatusIcon (true);
if (statusChanged) {
CreateSuccessEffects ();
}
break;
case BuildStatus.Queued:
color = QueuedColor;
UpdateRunningStatusIcon (true);
break;
default:
color = RunningColor;
UpdateRunningStatusIcon (false);
m_progressBar.UpdateValue (Model.PercentageComplete);
break;
}
UpdateUserAvatar ();
m_bodyRenderer.materials [1].SetColor ("_Color", color);
m_focusedPanelRenderer.materials [1].SetColor ("_Color", color);
m_isFirstCheckState = false;
m_lastCheckStateStatus = Model.Status;
}
private void UpdateRunningStatusIcon (bool hide)
{
var stepType = Model.LastRanStep == null ? BuildStepType.None : Model.LastRanStep.StepType;
var spriteName = stepType.ToString ();
var sprite = BuildRunningIcons.FirstOrDefault(s => s.name.Equals(spriteName, StringComparison.OrdinalIgnoreCase));
if (sprite == null)
{
sprite = BuildRunningFallbackIcon;
}
m_runningStatusIcon.sprite = sprite;
m_runningStatusIcon.enabled = IsVisible && !hide;
}
private void UpdateUserAvatar ()
{
m_userAvatarIcon.enabled = !(!IsVisible || Model.IsRunning());
if (Model.TriggeredBy != null) {
var photo = Model.TriggeredBy.Photo;
if (photo != null) {
m_userAvatarIcon.sprite = photo.ToSprite ();
}
}
}
private void OnCollisionEnter ()
{
if (!m_groundReachdAlreadRaised && !IsHistoryBuild) {
m_groundReachdAlreadRaised = true;
HasReachGround = true;
}
}
private void Hide ()
{
if (IsVisible) {
CheckState ();
CreateHiddingEffect ();
Rigidbody.isKinematic = true;
m_bodyCollider.enabled = false;
CenterCollider.enabled = false;
TopCollider.enabled = false;
RightCollider.enabled = false;
BottomCollider.enabled = false;
LeftCollider.enabled = false;
Body.SetActive (false);
IsVisible = false;
m_runningStatusIcon.enabled = false;
m_userAvatarIcon.enabled = false;
m_projectLabel.enabled = false;
m_configurationLabel.enabled = false;
m_progressBar.Hide ();
HasReachGround = false;
m_groundReachdAlreadRaised = false;
m_focusedPanel.SetActive (false);
}
}
private void Show ()
{
if (!IsVisible) {
CheckState ();
transform.position += Vector3.up * 20;
Rigidbody.isKinematic = false;
m_bodyCollider.enabled = true;
CenterCollider.enabled = true;
TopCollider.enabled = true;
RightCollider.enabled = true;
BottomCollider.enabled = true;
LeftCollider.enabled = true;
Body.SetActive (true);
IsVisible = true;
UpdateUserAvatar ();
m_projectLabel.enabled = true;
m_configurationLabel.enabled = true;
m_focusedPanel.SetActive (true);
if (Model.IsRunning()) {
m_runningStatusIcon.enabled = true;
m_progressBar.Show ();
}
}
}
private void CreateFailedEffects ()
{
if (!IsHistoryBuild) {
if (s_buildFailedExplosionPrefab == null) {
s_buildFailedExplosionPrefab = Mod.Context.Assets.Load("BuildFailedExplosionPrefab");
}
var explosion = Mod.Context.GameObjects.Create (s_buildFailedExplosionPrefab);
explosion.transform.parent = transform;
explosion.transform.position = transform.position;
SHCameraHelper.Shake ();
}
}
private void CreateSuccessEffects ()
{
if (!m_isFirstCheckState && !IsHistoryBuild) {
if (s_buildSuccessFireworksPrefab == null) {
s_buildSuccessFireworksPrefab = Mod.Context.Assets.Load ("BuildSuccessFireworksPrefab");
}
var fireworks = Mod.Context.GameObjects.Create (s_buildSuccessFireworksPrefab);
fireworks.transform.parent = transform;
fireworks.transform.position = transform.position;
}
}
private void CreateHiddingEffect ()
{
if (s_buildHidingEffectPrefab == null) {
s_buildHidingEffectPrefab = Mod.Context.Assets.Load ("BuildHidingEffectPrefab");
}
var effect = Mod.Context.GameObjects.Create (s_buildHidingEffectPrefab);
effect.transform.parent = transform;
effect.transform.position = transform.position;
effect.GetComponent<ParticleSystem> ().Play ();
}
#endregion
}
}
| |
namespace SandcastleBuilder.Gui.ContentEditors
{
partial class SiteMapEditorWindow
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if(disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SiteMapEditorWindow));
this.tvContent = new System.Windows.Forms.TreeView();
this.ilImages = new System.Windows.Forms.ImageList(this.components);
this.miPasteAsChild = new System.Windows.Forms.ToolStripMenuItem();
this.cmsTopics = new System.Windows.Forms.ContextMenuStrip(this.components);
this.miDefaultTopic = new System.Windows.Forms.ToolStripMenuItem();
this.miSplitToc = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
this.miMoveUp = new System.Windows.Forms.ToolStripMenuItem();
this.miMoveDown = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripSeparator();
this.miAddSibling = new System.Windows.Forms.ToolStripMenuItem();
this.cmsNewSiblingTopic = new System.Windows.Forms.ContextMenuStrip(this.components);
this.miCustomSibling = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripSeparator();
this.addExistingTopicFileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.addAllTopicsInFolderToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
this.miAddEmptySibling = new System.Windows.Forms.ToolStripMenuItem();
this.miAddChild = new System.Windows.Forms.ToolStripMenuItem();
this.cmsNewChildTopic = new System.Windows.Forms.ContextMenuStrip(this.components);
this.miCustomChild = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator();
this.miAddEmptyChild = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripSeparator();
this.miDelete = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripSeparator();
this.miCut = new System.Windows.Forms.ToolStripMenuItem();
this.miPaste = new System.Windows.Forms.ToolStripMenuItem();
this.miCopyAsLink = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator();
this.miEditTopic = new System.Windows.Forms.ToolStripMenuItem();
this.miSortTopics = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator();
this.miHelp = new System.Windows.Forms.ToolStripMenuItem();
this.tsbAddSiblingTopic = new System.Windows.Forms.ToolStripSplitButton();
this.tsbAddChildTopic = new System.Windows.Forms.ToolStripSplitButton();
this.pgProps = new SandcastleBuilder.Utils.Controls.CustomPropertyGrid();
this.tsTopics = new System.Windows.Forms.ToolStrip();
this.tsbDefaultTopic = new System.Windows.Forms.ToolStripButton();
this.tsbSplitTOC = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.tsbMoveUp = new System.Windows.Forms.ToolStripButton();
this.tsbMoveDown = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
this.tsbDeleteTopic = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.tsbCut = new System.Windows.Forms.ToolStripButton();
this.tsbPaste = new System.Windows.Forms.ToolStripSplitButton();
this.tsmiPasteAsSibling = new System.Windows.Forms.ToolStripMenuItem();
this.tsmiPasteAsChild = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator();
this.tsbEditTopic = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
this.tsbHelp = new System.Windows.Forms.ToolStripButton();
this.sbStatusBarText = new SandcastleBuilder.Utils.Controls.StatusBarTextProvider(this.components);
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.cmsTopics.SuspendLayout();
this.cmsNewSiblingTopic.SuspendLayout();
this.cmsNewChildTopic.SuspendLayout();
this.tsTopics.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.SuspendLayout();
//
// tvContent
//
this.tvContent.AllowDrop = true;
this.tvContent.Dock = System.Windows.Forms.DockStyle.Fill;
this.tvContent.HideSelection = false;
this.tvContent.ImageIndex = 0;
this.tvContent.ImageList = this.ilImages;
this.tvContent.Location = new System.Drawing.Point(0, 0);
this.tvContent.Name = "tvContent";
this.tvContent.SelectedImageIndex = 0;
this.tvContent.ShowNodeToolTips = true;
this.tvContent.Size = new System.Drawing.Size(383, 313);
this.sbStatusBarText.SetStatusBarText(this.tvContent, "Content: Drag an item and drop it in the topic");
this.tvContent.TabIndex = 0;
this.tvContent.NodeMouseDoubleClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(this.tvContent_NodeMouseDoubleClick);
this.tvContent.DragDrop += new System.Windows.Forms.DragEventHandler(this.tvContent_DragDrop);
this.tvContent.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvContent_AfterSelect);
this.tvContent.MouseDown += new System.Windows.Forms.MouseEventHandler(this.tvContent_MouseDown);
this.tvContent.DragEnter += new System.Windows.Forms.DragEventHandler(this.tvContent_DragOver);
this.tvContent.KeyDown += new System.Windows.Forms.KeyEventHandler(this.tvContent_KeyDown);
this.tvContent.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.tvContent_ItemDrag);
this.tvContent.DragOver += new System.Windows.Forms.DragEventHandler(this.tvContent_DragOver);
//
// ilImages
//
this.ilImages.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("ilImages.ImageStream")));
this.ilImages.TransparentColor = System.Drawing.Color.Magenta;
this.ilImages.Images.SetKeyName(0, "NormalTopic.bmp");
this.ilImages.Images.SetKeyName(1, "DefaultTopic.bmp");
this.ilImages.Images.SetKeyName(2, "MoveUp.bmp");
this.ilImages.Images.SetKeyName(3, "MoveDown.bmp");
this.ilImages.Images.SetKeyName(4, "AddRootItem.bmp");
this.ilImages.Images.SetKeyName(5, "AddChildItem.bmp");
this.ilImages.Images.SetKeyName(6, "Cut.bmp");
this.ilImages.Images.SetKeyName(7, "Copy.bmp");
this.ilImages.Images.SetKeyName(8, "Paste.bmp");
this.ilImages.Images.SetKeyName(9, "Delete.bmp");
this.ilImages.Images.SetKeyName(10, "SplitTOC.bmp");
this.ilImages.Images.SetKeyName(11, "DefaultAndSplit.bmp");
//
// miPasteAsChild
//
this.miPasteAsChild.Name = "miPasteAsChild";
this.miPasteAsChild.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miPasteAsChild, "Paste the topic in the clipboard as a sibling of the selected item");
this.miPasteAsChild.Text = "&Paste as Child";
this.miPasteAsChild.Click += new System.EventHandler(this.tsbPaste_ButtonClick);
//
// cmsTopics
//
this.cmsTopics.Font = new System.Drawing.Font("Microsoft Sans Serif", 7.8F);
this.cmsTopics.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miDefaultTopic,
this.miSplitToc,
this.toolStripMenuItem1,
this.miMoveUp,
this.miMoveDown,
this.toolStripMenuItem9,
this.miAddSibling,
this.miAddChild,
this.toolStripMenuItem4,
this.miDelete,
this.toolStripMenuItem7,
this.miCut,
this.miPaste,
this.miPasteAsChild,
this.miCopyAsLink,
this.toolStripSeparator10,
this.miEditTopic,
this.miSortTopics,
this.toolStripSeparator11,
this.miHelp});
this.cmsTopics.Name = "ctxTasks";
this.cmsTopics.Size = new System.Drawing.Size(219, 404);
//
// miDefaultTopic
//
this.miDefaultTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.DefaultTopic;
this.miDefaultTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miDefaultTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miDefaultTopic.Name = "miDefaultTopic";
this.miDefaultTopic.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miDefaultTopic, "Mark the selected topic as the default topic");
this.miDefaultTopic.Text = "Mark as De&fault Topic";
this.miDefaultTopic.Click += new System.EventHandler(this.tsbDefaultTopic_Click);
//
// miSplitToc
//
this.miSplitToc.Image = global::SandcastleBuilder.Gui.Properties.Resources.InsertApiAfter;
this.miSplitToc.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miSplitToc.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miSplitToc.Name = "miSplitToc";
this.miSplitToc.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miSplitToc, "Split the table of contents so that API content appears immediately before the sel" +
"ected topic");
this.miSplitToc.Text = "Split Ta&ble of Content";
this.miSplitToc.Click += new System.EventHandler(this.tsbSplitTOC_Click);
//
// toolStripMenuItem1
//
this.toolStripMenuItem1.Name = "toolStripMenuItem1";
this.toolStripMenuItem1.Size = new System.Drawing.Size(215, 6);
//
// miMoveUp
//
this.miMoveUp.Image = global::SandcastleBuilder.Gui.Properties.Resources.MoveUp;
this.miMoveUp.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miMoveUp.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miMoveUp.Name = "miMoveUp";
this.miMoveUp.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miMoveUp, "Move the selected topic up within its group");
this.miMoveUp.Text = "Move &Up";
this.miMoveUp.Click += new System.EventHandler(this.tsbMoveItem_Click);
//
// miMoveDown
//
this.miMoveDown.Image = global::SandcastleBuilder.Gui.Properties.Resources.MoveDown;
this.miMoveDown.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miMoveDown.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miMoveDown.Name = "miMoveDown";
this.miMoveDown.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miMoveDown, "Move the selected topic down within its group");
this.miMoveDown.Text = "Move Do&wn";
this.miMoveDown.Click += new System.EventHandler(this.tsbMoveItem_Click);
//
// toolStripMenuItem9
//
this.toolStripMenuItem9.Name = "toolStripMenuItem9";
this.toolStripMenuItem9.Size = new System.Drawing.Size(215, 6);
//
// miAddSibling
//
this.miAddSibling.DropDown = this.cmsNewSiblingTopic;
this.miAddSibling.Image = global::SandcastleBuilder.Gui.Properties.Resources.AddRootItem;
this.miAddSibling.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miAddSibling.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miAddSibling.Name = "miAddSibling";
this.miAddSibling.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miAddSibling, "Add a new topic as a sibling of the selected item");
this.miAddSibling.Text = "&Add Sibling Topic";
//
// cmsNewSiblingTopic
//
this.cmsNewSiblingTopic.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miCustomSibling,
this.toolStripMenuItem2,
this.addExistingTopicFileToolStripMenuItem,
this.addAllTopicsInFolderToolStripMenuItem,
this.toolStripSeparator6,
this.miAddEmptySibling});
this.cmsNewSiblingTopic.Name = "cmsNewTopic";
this.cmsNewSiblingTopic.OwnerItem = this.tsbAddSiblingTopic;
this.cmsNewSiblingTopic.Size = new System.Drawing.Size(262, 112);
//
// miCustomSibling
//
this.miCustomSibling.Name = "miCustomSibling";
this.miCustomSibling.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.miCustomSibling, "Select a custom template");
this.miCustomSibling.Text = "Custom Templates";
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(258, 6);
//
// addExistingTopicFileToolStripMenuItem
//
this.addExistingTopicFileToolStripMenuItem.Name = "addExistingTopicFileToolStripMenuItem";
this.addExistingTopicFileToolStripMenuItem.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.addExistingTopicFileToolStripMenuItem, "Add an existing topic file");
this.addExistingTopicFileToolStripMenuItem.Text = "&Add Existing Topic File...";
this.addExistingTopicFileToolStripMenuItem.Click += new System.EventHandler(this.AddExistingTopicFile_Click);
//
// addAllTopicsInFolderToolStripMenuItem
//
this.addAllTopicsInFolderToolStripMenuItem.Name = "addAllTopicsInFolderToolStripMenuItem";
this.addAllTopicsInFolderToolStripMenuItem.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.addAllTopicsInFolderToolStripMenuItem, "Add all topics found in a folder and its subfolders");
this.addAllTopicsInFolderToolStripMenuItem.Text = "Add All Topics in &Folder...";
this.addAllTopicsInFolderToolStripMenuItem.Click += new System.EventHandler(this.AddAllTopicsInFolder_Click);
//
// toolStripSeparator6
//
this.toolStripSeparator6.Name = "toolStripSeparator6";
this.toolStripSeparator6.Size = new System.Drawing.Size(258, 6);
//
// miAddEmptySibling
//
this.miAddEmptySibling.Image = global::SandcastleBuilder.Gui.Properties.Resources.AddRootItem;
this.miAddEmptySibling.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miAddEmptySibling.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miAddEmptySibling.Name = "miAddEmptySibling";
this.miAddEmptySibling.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.miAddEmptySibling, "Add a container not associated with a topic file");
this.miAddEmptySibling.Text = "Add &Empty Container Node";
this.miAddEmptySibling.Click += new System.EventHandler(this.tsbAddTopic_ButtonClick);
//
// miAddChild
//
this.miAddChild.DropDown = this.cmsNewChildTopic;
this.miAddChild.Image = global::SandcastleBuilder.Gui.Properties.Resources.AddChildItem;
this.miAddChild.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miAddChild.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miAddChild.Name = "miAddChild";
this.miAddChild.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miAddChild, "Add a topic as a child of the selected topic");
this.miAddChild.Text = "Add C&hild Topic";
//
// cmsNewChildTopic
//
this.cmsNewChildTopic.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miCustomChild,
this.toolStripSeparator7,
this.toolStripMenuItem5,
this.toolStripMenuItem6,
this.toolStripSeparator8,
this.miAddEmptyChild});
this.cmsNewChildTopic.Name = "cmsNewTopic";
this.cmsNewChildTopic.OwnerItem = this.tsbAddChildTopic;
this.cmsNewChildTopic.Size = new System.Drawing.Size(262, 112);
//
// miCustomChild
//
this.miCustomChild.Name = "miCustomChild";
this.miCustomChild.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.miCustomChild, "Select a custom template");
this.miCustomChild.Text = "Custom Templates";
//
// toolStripSeparator7
//
this.toolStripSeparator7.Name = "toolStripSeparator7";
this.toolStripSeparator7.Size = new System.Drawing.Size(258, 6);
//
// toolStripMenuItem5
//
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.toolStripMenuItem5, "Add an existing topic file");
this.toolStripMenuItem5.Text = "&Add Existing Topic File...";
this.toolStripMenuItem5.Click += new System.EventHandler(this.AddExistingTopicFile_Click);
//
// toolStripMenuItem6
//
this.toolStripMenuItem6.Name = "toolStripMenuItem6";
this.toolStripMenuItem6.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.toolStripMenuItem6, "Add all topics found in a folder and its subfolders");
this.toolStripMenuItem6.Text = "Add All Topics in &Folder...";
this.toolStripMenuItem6.Click += new System.EventHandler(this.AddAllTopicsInFolder_Click);
//
// toolStripSeparator8
//
this.toolStripSeparator8.Name = "toolStripSeparator8";
this.toolStripSeparator8.Size = new System.Drawing.Size(258, 6);
//
// miAddEmptyChild
//
this.miAddEmptyChild.Image = global::SandcastleBuilder.Gui.Properties.Resources.AddChildItem;
this.miAddEmptyChild.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miAddEmptyChild.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miAddEmptyChild.Name = "miAddEmptyChild";
this.miAddEmptyChild.Size = new System.Drawing.Size(261, 24);
this.sbStatusBarText.SetStatusBarText(this.miAddEmptyChild, "Add a container not associated with a topic file");
this.miAddEmptyChild.Text = "Add &Empty Container Node";
this.miAddEmptyChild.Click += new System.EventHandler(this.tsbAddTopic_ButtonClick);
//
// toolStripMenuItem4
//
this.toolStripMenuItem4.Name = "toolStripMenuItem4";
this.toolStripMenuItem4.Size = new System.Drawing.Size(215, 6);
//
// miDelete
//
this.miDelete.Image = global::SandcastleBuilder.Gui.Properties.Resources.Delete;
this.miDelete.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miDelete.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miDelete.Name = "miDelete";
this.miDelete.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miDelete, "Delete the selected topic");
this.miDelete.Text = "&Delete";
this.miDelete.Click += new System.EventHandler(this.tsbDeleteTopic_Click);
//
// toolStripMenuItem7
//
this.toolStripMenuItem7.Name = "toolStripMenuItem7";
this.toolStripMenuItem7.Size = new System.Drawing.Size(215, 6);
//
// miCut
//
this.miCut.Image = global::SandcastleBuilder.Gui.Properties.Resources.Cut;
this.miCut.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miCut.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miCut.Name = "miCut";
this.miCut.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miCut, "Cut the selected topic to the clipboard");
this.miCut.Text = "&Cut";
this.miCut.Click += new System.EventHandler(this.tsbCutCopy_Click);
//
// miPaste
//
this.miPaste.Image = global::SandcastleBuilder.Gui.Properties.Resources.Paste;
this.miPaste.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miPaste.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miPaste.Name = "miPaste";
this.miPaste.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miPaste, "Paste the topic on the clipboard as a sibling of the selected topic");
this.miPaste.Text = "Pa&ste as Sibling";
this.miPaste.Click += new System.EventHandler(this.tsbPaste_ButtonClick);
//
// miCopyAsLink
//
this.miCopyAsLink.Name = "miCopyAsLink";
this.miCopyAsLink.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miCopyAsLink, "Copy as a topic link");
this.miCopyAsLink.Text = "Cop&y as Topic Link";
this.miCopyAsLink.Click += new System.EventHandler(this.miCopyAsLink_Click);
//
// toolStripSeparator10
//
this.toolStripSeparator10.Name = "toolStripSeparator10";
this.toolStripSeparator10.Size = new System.Drawing.Size(215, 6);
//
// miEditTopic
//
this.miEditTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.PageEdit;
this.miEditTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miEditTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miEditTopic.Name = "miEditTopic";
this.miEditTopic.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miEditTopic, "Edit the selected topic");
this.miEditTopic.Text = "&Edit Topic";
this.miEditTopic.Click += new System.EventHandler(this.tsbEditTopic_Click);
//
// miSortTopics
//
this.miSortTopics.Name = "miSortTopics";
this.miSortTopics.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miSortTopics, "Sort this topics and its siblings by their display title");
this.miSortTopics.Text = "Sor&t Topics";
this.miSortTopics.Click += new System.EventHandler(this.miSortTopics_Click);
//
// toolStripSeparator11
//
this.toolStripSeparator11.Name = "toolStripSeparator11";
this.toolStripSeparator11.Size = new System.Drawing.Size(215, 6);
//
// miHelp
//
this.miHelp.Image = global::SandcastleBuilder.Gui.Properties.Resources.About;
this.miHelp.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.miHelp.ImageTransparentColor = System.Drawing.Color.Magenta;
this.miHelp.Name = "miHelp";
this.miHelp.Size = new System.Drawing.Size(218, 26);
this.sbStatusBarText.SetStatusBarText(this.miHelp, "View help for this form");
this.miHelp.Text = "Help";
this.miHelp.Click += new System.EventHandler(this.tsbHelp_Click);
//
// tsbAddSiblingTopic
//
this.tsbAddSiblingTopic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbAddSiblingTopic.DropDown = this.cmsNewSiblingTopic;
this.tsbAddSiblingTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.AddRootItem;
this.tsbAddSiblingTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbAddSiblingTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbAddSiblingTopic.Name = "tsbAddSiblingTopic";
this.tsbAddSiblingTopic.Size = new System.Drawing.Size(32, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbAddSiblingTopic, "Add a topic as a sibling of the selected item");
this.tsbAddSiblingTopic.ToolTipText = "Add topic as sibling of selected item";
this.tsbAddSiblingTopic.ButtonClick += new System.EventHandler(this.tsbAddTopic_ButtonClick);
//
// tsbAddChildTopic
//
this.tsbAddChildTopic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbAddChildTopic.DropDown = this.cmsNewChildTopic;
this.tsbAddChildTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.AddChildItem;
this.tsbAddChildTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbAddChildTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbAddChildTopic.Name = "tsbAddChildTopic";
this.tsbAddChildTopic.Size = new System.Drawing.Size(32, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbAddChildTopic, "Add a topic as a child of the selected item");
this.tsbAddChildTopic.ToolTipText = "Add topic as child of selected item";
this.tsbAddChildTopic.ButtonClick += new System.EventHandler(this.tsbAddTopic_ButtonClick);
//
// pgProps
//
this.pgProps.Dock = System.Windows.Forms.DockStyle.Fill;
this.pgProps.Location = new System.Drawing.Point(0, 0);
this.pgProps.Name = "pgProps";
this.pgProps.PropertyNamePaneWidth = 150;
this.pgProps.Size = new System.Drawing.Size(383, 310);
this.sbStatusBarText.SetStatusBarText(this.pgProps, "Properties for the selected content item");
this.pgProps.TabIndex = 0;
this.pgProps.PropertyValueChanged += new System.Windows.Forms.PropertyValueChangedEventHandler(this.pgProps_PropertyValueChanged);
//
// tsTopics
//
this.tsTopics.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
this.tsTopics.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsbDefaultTopic,
this.tsbSplitTOC,
this.toolStripSeparator1,
this.tsbMoveUp,
this.tsbMoveDown,
this.toolStripSeparator2,
this.tsbAddSiblingTopic,
this.tsbAddChildTopic,
this.toolStripSeparator4,
this.tsbDeleteTopic,
this.toolStripSeparator3,
this.tsbCut,
this.tsbPaste,
this.toolStripSeparator9,
this.tsbEditTopic,
this.toolStripSeparator5,
this.tsbHelp});
this.tsTopics.Location = new System.Drawing.Point(0, 0);
this.tsTopics.Name = "tsTopics";
this.tsTopics.Size = new System.Drawing.Size(385, 27);
this.tsTopics.TabIndex = 3;
//
// tsbDefaultTopic
//
this.tsbDefaultTopic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbDefaultTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.DefaultTopic;
this.tsbDefaultTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbDefaultTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbDefaultTopic.Name = "tsbDefaultTopic";
this.tsbDefaultTopic.Size = new System.Drawing.Size(23, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbDefaultTopic, "Toggle the default topic");
this.tsbDefaultTopic.ToolTipText = "Toggle the default topic";
this.tsbDefaultTopic.Click += new System.EventHandler(this.tsbDefaultTopic_Click);
//
// tsbSplitTOC
//
this.tsbSplitTOC.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbSplitTOC.Image = global::SandcastleBuilder.Gui.Properties.Resources.InsertApiAfter;
this.tsbSplitTOC.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbSplitTOC.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbSplitTOC.Name = "tsbSplitTOC";
this.tsbSplitTOC.Size = new System.Drawing.Size(23, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbSplitTOC, "Split the table of contents so that API entries appear immediately before the sele" +
"cted entry");
this.tsbSplitTOC.ToolTipText = "Split the TOC at selected entry";
this.tsbSplitTOC.Click += new System.EventHandler(this.tsbSplitTOC_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 27);
//
// tsbMoveUp
//
this.tsbMoveUp.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbMoveUp.Image = global::SandcastleBuilder.Gui.Properties.Resources.MoveUp;
this.tsbMoveUp.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbMoveUp.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbMoveUp.Name = "tsbMoveUp";
this.tsbMoveUp.Size = new System.Drawing.Size(23, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbMoveUp, "Move the selected topic up within its group");
this.tsbMoveUp.ToolTipText = "Move the selected topic up within its group";
this.tsbMoveUp.Click += new System.EventHandler(this.tsbMoveItem_Click);
//
// tsbMoveDown
//
this.tsbMoveDown.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbMoveDown.Image = global::SandcastleBuilder.Gui.Properties.Resources.MoveDown;
this.tsbMoveDown.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbMoveDown.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbMoveDown.Name = "tsbMoveDown";
this.tsbMoveDown.Size = new System.Drawing.Size(23, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbMoveDown, "Move the selected topic down within its group");
this.tsbMoveDown.ToolTipText = "Move the selected topic down within its group";
this.tsbMoveDown.Click += new System.EventHandler(this.tsbMoveItem_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 27);
//
// toolStripSeparator4
//
this.toolStripSeparator4.Name = "toolStripSeparator4";
this.toolStripSeparator4.Size = new System.Drawing.Size(6, 27);
//
// tsbDeleteTopic
//
this.tsbDeleteTopic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbDeleteTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.Delete;
this.tsbDeleteTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbDeleteTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbDeleteTopic.Name = "tsbDeleteTopic";
this.tsbDeleteTopic.Size = new System.Drawing.Size(23, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbDeleteTopic, "Delete the selected topic and all of its children");
this.tsbDeleteTopic.ToolTipText = "Delete topic and all children";
this.tsbDeleteTopic.Click += new System.EventHandler(this.tsbDeleteTopic_Click);
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(6, 27);
//
// tsbCut
//
this.tsbCut.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbCut.Image = global::SandcastleBuilder.Gui.Properties.Resources.Cut;
this.tsbCut.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbCut.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbCut.Name = "tsbCut";
this.tsbCut.Size = new System.Drawing.Size(23, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbCut, "Cut the selected topic and its children to the clipboard");
this.tsbCut.ToolTipText = "Cut topic and children to clipboard";
this.tsbCut.Click += new System.EventHandler(this.tsbCutCopy_Click);
//
// tsbPaste
//
this.tsbPaste.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbPaste.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.tsmiPasteAsSibling,
this.tsmiPasteAsChild});
this.tsbPaste.Image = global::SandcastleBuilder.Gui.Properties.Resources.Paste;
this.tsbPaste.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbPaste.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbPaste.Name = "tsbPaste";
this.tsbPaste.Size = new System.Drawing.Size(32, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbPaste, "Paste the clipboard item as a sibling of the selected item");
this.tsbPaste.ToolTipText = "Paste clipboard item as sibling of selected item";
this.tsbPaste.ButtonClick += new System.EventHandler(this.tsbPaste_ButtonClick);
//
// tsmiPasteAsSibling
//
this.tsmiPasteAsSibling.Image = global::SandcastleBuilder.Gui.Properties.Resources.Paste;
this.tsmiPasteAsSibling.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsmiPasteAsSibling.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsmiPasteAsSibling.Name = "tsmiPasteAsSibling";
this.tsmiPasteAsSibling.Size = new System.Drawing.Size(179, 24);
this.sbStatusBarText.SetStatusBarText(this.tsmiPasteAsSibling, "Paste the clipboard item as a sibiling of the selected item");
this.tsmiPasteAsSibling.Text = "Paste as sibling";
this.tsmiPasteAsSibling.Click += new System.EventHandler(this.tsbPaste_ButtonClick);
//
// tsmiPasteAsChild
//
this.tsmiPasteAsChild.Name = "tsmiPasteAsChild";
this.tsmiPasteAsChild.Size = new System.Drawing.Size(179, 24);
this.sbStatusBarText.SetStatusBarText(this.tsmiPasteAsChild, "Paste the clipboard item as a child of the selected item");
this.tsmiPasteAsChild.Text = "Paste as child";
this.tsmiPasteAsChild.Click += new System.EventHandler(this.tsbPaste_ButtonClick);
//
// toolStripSeparator9
//
this.toolStripSeparator9.Name = "toolStripSeparator9";
this.toolStripSeparator9.Size = new System.Drawing.Size(6, 27);
//
// tsbEditTopic
//
this.tsbEditTopic.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbEditTopic.Image = global::SandcastleBuilder.Gui.Properties.Resources.PageEdit;
this.tsbEditTopic.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbEditTopic.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbEditTopic.Name = "tsbEditTopic";
this.tsbEditTopic.Size = new System.Drawing.Size(23, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbEditTopic, "Edit the selected topic");
this.tsbEditTopic.ToolTipText = "Edit the selected topic";
this.tsbEditTopic.Click += new System.EventHandler(this.tsbEditTopic_Click);
//
// toolStripSeparator5
//
this.toolStripSeparator5.Name = "toolStripSeparator5";
this.toolStripSeparator5.Size = new System.Drawing.Size(6, 27);
//
// tsbHelp
//
this.tsbHelp.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.tsbHelp.Image = global::SandcastleBuilder.Gui.Properties.Resources.About;
this.tsbHelp.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.tsbHelp.ImageTransparentColor = System.Drawing.Color.Magenta;
this.tsbHelp.Name = "tsbHelp";
this.tsbHelp.Size = new System.Drawing.Size(24, 24);
this.sbStatusBarText.SetStatusBarText(this.tsbHelp, "View help for this editor");
this.tsbHelp.ToolTipText = "View help for this editor";
this.tsbHelp.Click += new System.EventHandler(this.tsbHelp_Click);
//
// splitContainer1
//
this.splitContainer1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.splitContainer1.Location = new System.Drawing.Point(1, 28);
this.splitContainer1.Name = "splitContainer1";
this.splitContainer1.Orientation = System.Windows.Forms.Orientation.Horizontal;
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.tvContent);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.Controls.Add(this.pgProps);
this.splitContainer1.Size = new System.Drawing.Size(383, 631);
this.splitContainer1.SplitterDistance = 313;
this.splitContainer1.SplitterWidth = 8;
this.splitContainer1.TabIndex = 2;
//
// SiteMapEditorWindow
//
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
this.ClientSize = new System.Drawing.Size(385, 660);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.tsTopics);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimizeBox = false;
this.Name = "SiteMapEditorWindow";
this.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.DockLeft;
this.ShowInTaskbar = false;
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.SiteMapEditorWindow_FormClosing);
this.cmsTopics.ResumeLayout(false);
this.cmsNewSiblingTopic.ResumeLayout(false);
this.cmsNewChildTopic.ResumeLayout(false);
this.tsTopics.ResumeLayout(false);
this.tsTopics.PerformLayout();
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TreeView tvContent;
private SandcastleBuilder.Utils.Controls.StatusBarTextProvider sbStatusBarText;
private System.Windows.Forms.ImageList ilImages;
private System.Windows.Forms.ContextMenuStrip cmsTopics;
private System.Windows.Forms.ToolStripMenuItem miCut;
private System.Windows.Forms.ToolStripMenuItem miPasteAsChild;
private System.Windows.Forms.ToolStripMenuItem miPaste;
private System.Windows.Forms.ToolStripMenuItem miAddSibling;
private System.Windows.Forms.ToolStripMenuItem miAddChild;
private System.Windows.Forms.ToolStripMenuItem miDelete;
private System.Windows.Forms.ToolStripMenuItem miMoveUp;
private System.Windows.Forms.ToolStripMenuItem miMoveDown;
private System.Windows.Forms.ToolStripMenuItem miDefaultTopic;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem4;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem7;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem9;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem1;
private SandcastleBuilder.Utils.Controls.CustomPropertyGrid pgProps;
private System.Windows.Forms.ToolStripMenuItem miSplitToc;
private System.Windows.Forms.ToolStrip tsTopics;
private System.Windows.Forms.ToolStripButton tsbDefaultTopic;
private System.Windows.Forms.ToolStripButton tsbSplitTOC;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton tsbMoveUp;
private System.Windows.Forms.ToolStripButton tsbMoveDown;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripSplitButton tsbAddSiblingTopic;
private System.Windows.Forms.ToolStripSplitButton tsbAddChildTopic;
private System.Windows.Forms.ToolStripButton tsbDeleteTopic;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
private System.Windows.Forms.ToolStripButton tsbCut;
private System.Windows.Forms.ToolStripSplitButton tsbPaste;
private System.Windows.Forms.ToolStripMenuItem tsmiPasteAsChild;
private System.Windows.Forms.ToolStripMenuItem tsmiPasteAsSibling;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator4;
private System.Windows.Forms.ContextMenuStrip cmsNewSiblingTopic;
private System.Windows.Forms.ToolStripSeparator toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem addExistingTopicFileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem addAllTopicsInFolderToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator6;
private System.Windows.Forms.ToolStripMenuItem miAddEmptySibling;
private System.Windows.Forms.ContextMenuStrip cmsNewChildTopic;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator7;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem5;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem6;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator8;
private System.Windows.Forms.ToolStripMenuItem miAddEmptyChild;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator9;
private System.Windows.Forms.ToolStripButton tsbEditTopic;
private System.Windows.Forms.ToolStripMenuItem miCustomSibling;
private System.Windows.Forms.ToolStripMenuItem miCustomChild;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator10;
private System.Windows.Forms.ToolStripMenuItem miEditTopic;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.ToolStripMenuItem miSortTopics;
private System.Windows.Forms.ToolStripMenuItem miCopyAsLink;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator11;
private System.Windows.Forms.ToolStripMenuItem miHelp;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator5;
private System.Windows.Forms.ToolStripButton tsbHelp;
}
}
| |
// 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 SafeWinHttpHandle = Interop.WinHttp.SafeWinHttpHandle;
namespace System.Net.Http
{
internal class WinHttpAuthHelper
{
// TODO: Issue #2165. This looks messy but it is fast. Research a cleaner way
// to do this which keeps high performance lookup.
//
// Fast lookup table to convert WINHTTP_AUTH constants to strings.
// WINHTTP_AUTH_SCHEME_BASIC = 0x00000001;
// WINHTTP_AUTH_SCHEME_NTLM = 0x00000002;
// WINHTTP_AUTH_SCHEME_DIGEST = 0x00000008;
// WINHTTP_AUTH_SCHEME_NEGOTIATE = 0x00000010;
private static readonly string[] s_authSchemeStringMapping =
{
null,
"Basic",
"NTLM",
null,
null,
null,
null,
null,
"Digest",
null,
null,
null,
null,
null,
null,
null,
"Negotiate"
};
private static readonly uint[] s_authSchemePriorityOrder =
{
Interop.WinHttp.WINHTTP_AUTH_SCHEME_NEGOTIATE,
Interop.WinHttp.WINHTTP_AUTH_SCHEME_NTLM,
Interop.WinHttp.WINHTTP_AUTH_SCHEME_DIGEST,
Interop.WinHttp.WINHTTP_AUTH_SCHEME_BASIC
};
// TODO: Issue #2165. This current design uses a handler-wide lock to Add/Retrieve
// from the cache. Need to improve this for next iteration in order
// to boost performance and scalability.
private readonly CredentialCache _credentialCache = new CredentialCache();
private readonly object _credentialCacheLock = new object();
public void CheckResponseForAuthentication(
WinHttpRequestState state,
ref uint proxyAuthScheme,
ref uint serverAuthScheme)
{
uint supportedSchemes = 0;
uint firstSchemeIgnored = 0;
uint authTarget = 0;
Uri uri = state.RequestMessage.RequestUri;
state.RetryRequest = false;
// Check the status code and retry the request applying credentials if needed.
var statusCode = (HttpStatusCode)WinHttpResponseParser.GetResponseHeaderNumberInfo(
state.RequestHandle,
Interop.WinHttp.WINHTTP_QUERY_STATUS_CODE);
switch (statusCode)
{
case HttpStatusCode.Unauthorized:
if (state.ServerCredentials == null || state.LastStatusCode == HttpStatusCode.Unauthorized)
{
// Either we don't have server credentials or we already tried
// to set the credentials and it failed before.
// So we will let the 401 be the final status code returned.
break;
}
state.LastStatusCode = statusCode;
// Determine authorization scheme to use. We ignore the firstScheme
// parameter which is included in the supportedSchemes flags already.
// We pass the schemes to ChooseAuthScheme which will pick the scheme
// based on most secure scheme to least secure scheme ordering.
if (!Interop.WinHttp.WinHttpQueryAuthSchemes(
state.RequestHandle,
out supportedSchemes,
out firstSchemeIgnored,
out authTarget))
{
// WinHTTP returns an error for schemes it doesn't handle.
// So, we need to ignore the error and just let it stay at 401.
break;
}
// WinHTTP returns the proper authTarget based on the status code (401, 407).
// But we can validate with assert.
Debug.Assert(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER);
serverAuthScheme = ChooseAuthScheme(supportedSchemes);
if (serverAuthScheme != 0)
{
if (SetWinHttpCredential(
state.RequestHandle,
state.ServerCredentials,
uri,
serverAuthScheme,
authTarget))
{
state.RetryRequest = true;
}
}
break;
case HttpStatusCode.ProxyAuthenticationRequired:
if (state.LastStatusCode == HttpStatusCode.ProxyAuthenticationRequired)
{
// We tried already to set the credentials.
break;
}
state.LastStatusCode = statusCode;
// If we don't have any proxy credentials to try, then we end up with 407.
ICredentials proxyCreds = state.Proxy == null ?
state.DefaultProxyCredentials :
state.Proxy.Credentials;
if (proxyCreds == null)
{
break;
}
// Determine authorization scheme to use. We ignore the firstScheme
// parameter which is included in the supportedSchemes flags already.
// We pass the schemes to ChooseAuthScheme which will pick the scheme
// based on most secure scheme to least secure scheme ordering.
if (!Interop.WinHttp.WinHttpQueryAuthSchemes(
state.RequestHandle,
out supportedSchemes,
out firstSchemeIgnored,
out authTarget))
{
// WinHTTP returns an error for schemes it doesn't handle.
// So, we need to ignore the error and just let it stay at 401.
break;
}
// WinHTTP returns the proper authTarget based on the status code (401, 407).
// But we can validate with assert.
Debug.Assert(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_PROXY);
proxyAuthScheme = ChooseAuthScheme(supportedSchemes);
state.RetryRequest = true;
break;
default:
if (state.PreAuthenticate && serverAuthScheme != 0)
{
SaveServerCredentialsToCache(uri, serverAuthScheme, state.ServerCredentials);
}
break;
}
}
public void PreAuthenticateRequest(WinHttpRequestState state, uint proxyAuthScheme)
{
// Set proxy credentials if we have them.
// If a proxy authentication challenge was responded to, reset
// those credentials before each SendRequest, because the proxy
// may require re-authentication after responding to a 401 or
// to a redirect. If you don't, you can get into a
// 407-401-407-401- loop.
if (proxyAuthScheme != 0)
{
ICredentials proxyCredentials;
Uri proxyUri;
if (state.Proxy != null)
{
proxyCredentials = state.Proxy.Credentials;
proxyUri = state.Proxy.GetProxy(state.RequestMessage.RequestUri);
}
else
{
proxyCredentials = state.DefaultProxyCredentials;
proxyUri = state.RequestMessage.RequestUri;
}
SetWinHttpCredential(
state.RequestHandle,
proxyCredentials,
proxyUri,
proxyAuthScheme,
Interop.WinHttp.WINHTTP_AUTH_TARGET_PROXY);
}
// Apply pre-authentication headers for server authentication?
if (state.PreAuthenticate)
{
uint authScheme;
NetworkCredential serverCredentials;
if (GetServerCredentialsFromCache(
state.RequestMessage.RequestUri,
out authScheme,
out serverCredentials))
{
SetWinHttpCredential(
state.RequestHandle,
serverCredentials,
state.RequestMessage.RequestUri,
authScheme,
Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER);
state.LastStatusCode = HttpStatusCode.Unauthorized; // Remember we already set the creds.
}
// No cached credential to use at this time. The request will first go out with no
// 'Authorization' header. Later, if a 401 occurs, we will be able to cache the credential
// since we will then know the proper auth scheme to use.
//
// TODO: Issue #2165. Adding logging to highlight the 'cache miss'.
}
}
// TODO: Issue #2165. Consider refactoring cache logic in separate class and avoid out parameters.
public bool GetServerCredentialsFromCache(
Uri uri,
out uint serverAuthScheme,
out NetworkCredential serverCredentials)
{
serverAuthScheme = 0;
serverCredentials = null;
NetworkCredential cred = null;
lock (_credentialCacheLock)
{
foreach (uint authScheme in s_authSchemePriorityOrder)
{
cred = _credentialCache.GetCredential(uri, s_authSchemeStringMapping[authScheme]);
if (cred != null)
{
serverAuthScheme = authScheme;
serverCredentials = cred;
return true;
}
}
}
return false;
}
public void SaveServerCredentialsToCache(Uri uri, uint authScheme, ICredentials serverCredentials)
{
string authType = s_authSchemeStringMapping[authScheme];
Debug.Assert(!string.IsNullOrEmpty(authType));
NetworkCredential cred = serverCredentials.GetCredential(uri, authType);
if (cred != null)
{
lock (_credentialCacheLock)
{
try
{
_credentialCache.Add(uri, authType, cred);
}
catch (ArgumentException)
{
// The credential was already added.
}
}
}
}
public void ChangeDefaultCredentialsPolicy(
SafeWinHttpHandle requestHandle,
uint authTarget,
bool allowDefaultCredentials)
{
Debug.Assert(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_PROXY ||
authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER);
uint optionData = allowDefaultCredentials ?
(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_PROXY ?
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_MEDIUM :
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_LOW) :
Interop.WinHttp.WINHTTP_AUTOLOGON_SECURITY_LEVEL_HIGH;
if (!Interop.WinHttp.WinHttpSetOption(
requestHandle,
Interop.WinHttp.WINHTTP_OPTION_AUTOLOGON_POLICY,
ref optionData))
{
WinHttpException.ThrowExceptionUsingLastError();
}
}
private bool SetWinHttpCredential(
SafeWinHttpHandle requestHandle,
ICredentials credentials,
Uri uri,
uint authScheme,
uint authTarget)
{
string userName;
string password;
Debug.Assert(credentials != null);
Debug.Assert(authScheme != 0);
Debug.Assert(authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_PROXY ||
authTarget == Interop.WinHttp.WINHTTP_AUTH_TARGET_SERVER);
NetworkCredential networkCredential = credentials.GetCredential(uri, s_authSchemeStringMapping[authScheme]);
if (networkCredential == null)
{
return false;
}
if (networkCredential == CredentialCache.DefaultNetworkCredentials)
{
// Only Negotiate and NTLM can use default credentials. Otherwise,
// behave as-if there were no credentials.
if (authScheme == Interop.WinHttp.WINHTTP_AUTH_SCHEME_NEGOTIATE ||
authScheme == Interop.WinHttp.WINHTTP_AUTH_SCHEME_NTLM)
{
// Allow WinHTTP to transmit the default credentials.
ChangeDefaultCredentialsPolicy(requestHandle, authTarget, allowDefaultCredentials:true);
userName = null;
password = null;
}
else
{
return false;
}
}
else
{
userName = networkCredential.UserName;
password = networkCredential.Password;
string domain = networkCredential.Domain;
// WinHTTP does not support a blank username. So, we will throw an exception.
if (string.IsNullOrEmpty(userName))
{
throw new InvalidOperationException(SR.net_http_username_empty_string);
}
if (!string.IsNullOrEmpty(domain))
{
userName = domain + "\\" + userName;
}
}
if (!Interop.WinHttp.WinHttpSetCredentials(
requestHandle,
authTarget,
authScheme,
userName,
password,
IntPtr.Zero))
{
WinHttpException.ThrowExceptionUsingLastError();
}
return true;
}
private static uint ChooseAuthScheme(uint supportedSchemes)
{
foreach (uint authScheme in s_authSchemePriorityOrder)
{
if ((supportedSchemes & authScheme) != 0)
{
return authScheme;
}
}
return 0;
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Editor;
using Microsoft.CodeAnalysis.Editor.Implementation.Structure;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.GeneratedCodeRecognition;
using Microsoft.CodeAnalysis.Navigation;
using Microsoft.CodeAnalysis.Options;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.ComponentModelHost;
using Microsoft.VisualStudio.Editor;
using Microsoft.VisualStudio.LanguageServices.Implementation.Extensions;
using Microsoft.VisualStudio.LanguageServices.Implementation.Library;
using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.TextManager.Interop;
using Roslyn.Utilities;
using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
namespace Microsoft.VisualStudio.LanguageServices.Implementation
{
internal partial class VisualStudioSymbolNavigationService : ForegroundThreadAffinitizedObject, ISymbolNavigationService
{
private readonly IServiceProvider _serviceProvider;
private readonly IVsEditorAdaptersFactoryService _editorAdaptersFactory;
private readonly ITextEditorFactoryService _textEditorFactoryService;
private readonly ITextDocumentFactoryService _textDocumentFactoryService;
private readonly IMetadataAsSourceFileService _metadataAsSourceFileService;
private readonly VisualStudio14StructureTaggerProvider _outliningTaggerProvider;
public VisualStudioSymbolNavigationService(
SVsServiceProvider serviceProvider,
VisualStudio14StructureTaggerProvider outliningTaggerProvider)
{
_serviceProvider = serviceProvider;
_outliningTaggerProvider = outliningTaggerProvider;
var componentModel = _serviceProvider.GetService<SComponentModel, IComponentModel>();
_editorAdaptersFactory = componentModel.GetService<IVsEditorAdaptersFactoryService>();
_textEditorFactoryService = componentModel.GetService<ITextEditorFactoryService>();
_textDocumentFactoryService = componentModel.GetService<ITextDocumentFactoryService>();
_metadataAsSourceFileService = componentModel.GetService<IMetadataAsSourceFileService>();
}
public bool TryNavigateToSymbol(ISymbol symbol, Project project, OptionSet options, CancellationToken cancellationToken)
{
if (project == null || symbol == null)
{
return false;
}
options = options ?? project.Solution.Workspace.Options;
symbol = symbol.OriginalDefinition;
// Prefer visible source locations if possible.
var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource);
var visibleSourceLocations = sourceLocations.Where(loc => loc.IsVisibleSourceLocation());
var sourceLocation = visibleSourceLocations.FirstOrDefault() ?? sourceLocations.FirstOrDefault();
if (sourceLocation != null)
{
var targetDocument = project.Solution.GetDocument(sourceLocation.SourceTree);
if (targetDocument != null)
{
var editorWorkspace = targetDocument.Project.Solution.Workspace;
var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
return navigationService.TryNavigateToSpan(editorWorkspace, targetDocument.Id, sourceLocation.SourceSpan, options);
}
}
// We don't have a source document, so show the Metadata as Source view in a preview tab.
var metadataLocation = symbol.Locations.Where(loc => loc.IsInMetadata).FirstOrDefault();
if (metadataLocation == null || !_metadataAsSourceFileService.IsNavigableMetadataSymbol(symbol))
{
return false;
}
// Should we prefer navigating to the Object Browser over metadata-as-source?
if (options.GetOption(VisualStudioNavigationOptions.NavigateToObjectBrowser, project.Language))
{
var libraryService = project.LanguageServices.GetService<ILibraryService>();
if (libraryService == null)
{
return false;
}
var compilation = project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
var navInfo = libraryService.NavInfoFactory.CreateForSymbol(symbol, project, compilation);
if (navInfo == null)
{
navInfo = libraryService.NavInfoFactory.CreateForProject(project);
}
if (navInfo != null)
{
var navigationTool = _serviceProvider.GetService<SVsObjBrowser, IVsNavigationTool>();
return navigationTool.NavigateToNavInfo(navInfo) == VSConstants.S_OK;
}
// Note: we'll fallback to Metadata-As-Source if we fail to get IVsNavInfo, but that should never happen.
}
// Generate new source or retrieve existing source for the symbol in question
var result = _metadataAsSourceFileService.GetGeneratedFileAsync(project, symbol, cancellationToken).WaitAndGetResult(cancellationToken);
var vsRunningDocumentTable4 = _serviceProvider.GetService<SVsRunningDocumentTable, IVsRunningDocumentTable4>();
var fileAlreadyOpen = vsRunningDocumentTable4.IsMonikerValid(result.FilePath);
var openDocumentService = _serviceProvider.GetService<SVsUIShellOpenDocument, IVsUIShellOpenDocument>();
openDocumentService.OpenDocumentViaProject(result.FilePath, VSConstants.LOGVIEWID.TextView_guid, out var localServiceProvider, out var hierarchy, out var itemId, out var windowFrame);
var documentCookie = vsRunningDocumentTable4.GetDocumentCookie(result.FilePath);
var vsTextBuffer = (IVsTextBuffer)vsRunningDocumentTable4.GetDocumentData(documentCookie);
var textBuffer = _editorAdaptersFactory.GetDataBuffer(vsTextBuffer);
if (!fileAlreadyOpen)
{
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_IsProvisional, true));
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideCaption, result.DocumentTitle));
ErrorHandler.ThrowOnFailure(windowFrame.SetProperty((int)__VSFPROPID5.VSFPROPID_OverrideToolTip, result.DocumentTooltip));
}
windowFrame.Show();
var openedDocument = textBuffer.AsTextContainer().GetRelatedDocuments().FirstOrDefault();
if (openedDocument != null)
{
var editorWorkspace = openedDocument.Project.Solution.Workspace;
var navigationService = editorWorkspace.Services.GetService<IDocumentNavigationService>();
return navigationService.TryNavigateToSpan(
workspace: editorWorkspace,
documentId: openedDocument.Id,
textSpan: result.IdentifierLocation.SourceSpan,
options: options.WithChangedOption(NavigationOptions.PreferProvisionalTab, true));
}
return true;
}
public bool TrySymbolNavigationNotify(ISymbol symbol, Solution solution)
{
return TryNotifyForSpecificSymbol(symbol, solution);
}
private bool TryNotifyForSpecificSymbol(ISymbol symbol, Solution solution)
{
AssertIsForeground();
if (!TryGetNavigationAPIRequiredArguments(symbol, solution, out var hierarchy, out var itemID, out var navigationNotify, out var rqname))
{
return false;
}
int returnCode = navigationNotify.OnBeforeNavigateToSymbol(
hierarchy,
itemID,
rqname,
out var navigationHandled);
if (returnCode == VSConstants.S_OK && navigationHandled == 1)
{
return true;
}
return false;
}
public bool WouldNavigateToSymbol(ISymbol symbol, Solution solution, out string filePath, out int lineNumber, out int charOffset)
{
if (WouldNotifyToSpecificSymbol(symbol, solution, out filePath, out lineNumber, out charOffset))
{
return true;
}
// If the symbol being considered is a constructor and no third parties choose to
// navigate to the constructor, then try the constructor's containing type.
if (symbol.IsConstructor() && WouldNotifyToSpecificSymbol(symbol.ContainingType, solution, out filePath, out lineNumber, out charOffset))
{
return true;
}
filePath = null;
lineNumber = 0;
charOffset = 0;
return false;
}
public bool WouldNotifyToSpecificSymbol(ISymbol symbol, Solution solution, out string filePath, out int lineNumber, out int charOffset)
{
AssertIsForeground();
filePath = null;
lineNumber = 0;
charOffset = 0;
if (!TryGetNavigationAPIRequiredArguments(symbol, solution, out var hierarchy, out var itemID, out var navigationNotify, out var rqname))
{
return false;
}
var navigateToTextSpan = new Microsoft.VisualStudio.TextManager.Interop.TextSpan[1];
int queryNavigateStatusCode = navigationNotify.QueryNavigateToSymbol(
hierarchy,
itemID,
rqname,
out var navigateToHierarchy,
out var navigateToItem,
navigateToTextSpan,
out var wouldNavigate);
if (queryNavigateStatusCode == VSConstants.S_OK && wouldNavigate == 1)
{
navigateToHierarchy.GetCanonicalName(navigateToItem, out filePath);
lineNumber = navigateToTextSpan[0].iStartLine;
charOffset = navigateToTextSpan[0].iStartIndex;
return true;
}
return false;
}
private bool TryGetNavigationAPIRequiredArguments(
ISymbol symbol,
Solution solution,
out IVsHierarchy hierarchy,
out uint itemID,
out IVsSymbolicNavigationNotify navigationNotify,
out string rqname)
{
AssertIsForeground();
hierarchy = null;
navigationNotify = null;
rqname = null;
itemID = (uint)VSConstants.VSITEMID.Nil;
if (!symbol.Locations.Any())
{
return false;
}
var sourceLocations = symbol.Locations.Where(loc => loc.IsInSource);
if (!sourceLocations.Any())
{
return false;
}
var documents = sourceLocations.Select(loc => solution.GetDocument(loc.SourceTree)).WhereNotNull();
if (!documents.Any())
{
return false;
}
// We can only pass one itemid to IVsSymbolicNavigationNotify, so prefer itemids from
// documents we consider to be "generated" to give external language services the best
// chance of participating.
var generatedDocuments = documents.Where(d => d.IsGeneratedCode());
var documentToUse = generatedDocuments.FirstOrDefault() ?? documents.First();
if (!TryGetVsHierarchyAndItemId(documentToUse, out hierarchy, out itemID))
{
return false;
}
navigationNotify = hierarchy as IVsSymbolicNavigationNotify;
if (navigationNotify == null)
{
return false;
}
rqname = LanguageServices.RQName.From(symbol);
return rqname != null;
}
private bool TryGetVsHierarchyAndItemId(Document document, out IVsHierarchy hierarchy, out uint itemID)
{
AssertIsForeground();
var visualStudioWorkspace = document.Project.Solution.Workspace as VisualStudioWorkspaceImpl;
if (visualStudioWorkspace != null)
{
var hostProject = visualStudioWorkspace.GetHostProject(document.Project.Id);
hierarchy = hostProject.Hierarchy;
itemID = hostProject.GetDocumentOrAdditionalDocument(document.Id).GetItemId();
return true;
}
hierarchy = null;
itemID = (uint)VSConstants.VSITEMID.Nil;
return false;
}
private IVsRunningDocumentTable GetRunningDocumentTable()
{
var runningDocumentTable = _serviceProvider.GetService<SVsRunningDocumentTable, IVsRunningDocumentTable>();
Debug.Assert(runningDocumentTable != null);
return runningDocumentTable;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.Build.Engine
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Microsoft.DocAsCode.Common;
using Microsoft.DocAsCode.Plugins;
public class TemplateProcessor : IDisposable
{
private readonly ResourceCollection _resourceProvider;
private readonly TemplateCollection _templateCollection;
public static readonly TemplateProcessor DefaultProcessor = new TemplateProcessor(new EmptyResourceCollection(), null, 1);
public IDictionary<string, string> Tokens { get; }
/// <summary>
/// TemplateName can be either file or folder
/// 1. If TemplateName is file, it is considered as the default template
/// 2. If TemplateName is a folder, files inside the folder is considered as the template, each file is named after {DocumentType}.{extension}
/// </summary>
/// <param name="templateName"></param>
/// <param name="resourceProvider"></param>
public TemplateProcessor(ResourceCollection resourceProvider, DocumentBuildContext context, int maxParallelism = 0)
{
if (maxParallelism <= 0)
{
maxParallelism = Environment.ProcessorCount;
}
_resourceProvider = resourceProvider;
_templateCollection = new TemplateCollection(resourceProvider, context, maxParallelism);
Tokens = LoadTokenJson(resourceProvider) ?? new Dictionary<string, string>();
}
public TemplateBundle GetTemplateBundle(string documentType)
{
if (string.IsNullOrEmpty(documentType)) throw new ArgumentNullException(nameof(documentType));
return _templateCollection[documentType];
}
public bool TryGetFileExtension(string documentType, out string fileExtension)
{
if (string.IsNullOrEmpty(documentType)) throw new ArgumentNullException(nameof(documentType));
fileExtension = string.Empty;
if (_templateCollection.Count == 0) return false;
var templateBundle = _templateCollection[documentType];
// Get default template extension
if (templateBundle == null) return false;
fileExtension = templateBundle.Extension;
return true;
}
internal List<ManifestItem> Process(List<InternalManifestItem> manifest, DocumentBuildContext context, ApplyTemplateSettings settings, IDictionary<string, object> globals = null)
{
using (new LoggerPhaseScope("Apply Templates", LogLevel.Verbose))
{
if (globals == null)
{
globals = Tokens.ToDictionary(pair => pair.Key, pair => (object)pair.Value);
}
if (settings == null)
{
settings = context.ApplyTemplateSettings;
}
Logger.LogInfo($"Applying templates to {manifest.Count} model(s)...");
var documentTypes = new HashSet<string>(manifest.Select(s => s.DocumentType));
ProcessDependencies(documentTypes, settings);
var templateManifest = ProcessCore(manifest, context, settings, globals);
return templateManifest;
}
}
internal void ProcessDependencies(HashSet<string> documentTypes, ApplyTemplateSettings settings)
{
if (settings.Options.HasFlag(ApplyTemplateOptions.TransformDocument))
{
var notSupportedDocumentTypes = documentTypes.Where(s => s != "Resource" && _templateCollection[s] == null);
if (notSupportedDocumentTypes.Any())
{
Logger.LogWarning($"There is no template processing document type(s): {StringExtension.ToDelimitedString(notSupportedDocumentTypes)}");
}
var templatesInUse = documentTypes.Select(s => _templateCollection[s]).Where(s => s != null).ToList();
ProcessDependenciesCore(settings.OutputFolder, templatesInUse);
}
else
{
Logger.LogInfo("Dryrun, no template will be applied to the documents.");
}
}
private void ProcessDependenciesCore(string outputDirectory, IEnumerable<TemplateBundle> templateBundles)
{
foreach (var resourceInfo in templateBundles.SelectMany(s => s.Resources).Distinct())
{
try
{
// TODO: support glob pattern
if (resourceInfo.IsRegexPattern)
{
var regex = new Regex(resourceInfo.ResourceKey, RegexOptions.IgnoreCase);
foreach (var name in _resourceProvider.Names)
{
if (regex.IsMatch(name))
{
using (var stream = _resourceProvider.GetResourceStream(name))
{
ProcessSingleDependency(stream, outputDirectory, name);
}
}
}
}
else
{
using (var stream = _resourceProvider.GetResourceStream(resourceInfo.ResourceKey))
{
ProcessSingleDependency(stream, outputDirectory, resourceInfo.FilePath);
}
}
}
catch (Exception e)
{
Logger.Log(LogLevel.Info, $"Unable to get relative resource for {resourceInfo.FilePath}: {e.Message}");
}
}
}
private void ProcessSingleDependency(Stream stream, string outputDirectory, string filePath)
{
if (stream != null)
{
var path = Path.Combine(outputDirectory, filePath);
var dir = Path.GetDirectoryName(path);
if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir);
using (var writer = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
{
stream.CopyTo(writer);
}
Logger.Log(LogLevel.Verbose, $"Saved resource {filePath} that template dependants on to {path}");
}
else
{
Logger.Log(LogLevel.Info, $"Unable to get relative resource for {filePath}");
}
}
private List<ManifestItem> ProcessCore(List<InternalManifestItem> items, DocumentBuildContext context, ApplyTemplateSettings settings, IDictionary<string, object> globals)
{
var manifest = new ConcurrentBag<ManifestItem>();
var systemAttributeGenerator = new SystemMetadataGenerator(context);
var transformer = new TemplateModelTransformer(context, _templateCollection, settings, globals);
items.RunAll(
item =>
{
using (new LoggerFileScope(item.LocalPathFromRoot))
{
var manifestItem = transformer.Transform(item);
if (manifestItem.OutputFiles?.Count > 0)
{
manifest.Add(manifestItem);
}
}
},
context.MaxParallelism);
return manifest.ToList();
}
private static IDictionary<string, string> LoadTokenJson(ResourceCollection resource)
{
var tokenJson = resource.GetResource("token.json");
if (string.IsNullOrEmpty(tokenJson))
{
// also load `global.json` for backward compatibility
// TODO: remove this
tokenJson = resource.GetResource("global.json");
if (string.IsNullOrEmpty(tokenJson))
{
return null;
}
}
return JsonUtility.FromJsonString<Dictionary<string, string>>(tokenJson);
}
public void Dispose()
{
_resourceProvider?.Dispose();
}
}
}
| |
// Generated from https://github.com/nuke-build/nuke/blob/master/source/Nuke.Common/Tools/MinVer/MinVer.json
using JetBrains.Annotations;
using Newtonsoft.Json;
using Nuke.Common;
using Nuke.Common.Execution;
using Nuke.Common.Tooling;
using Nuke.Common.Tools;
using Nuke.Common.Utilities.Collections;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Text;
namespace Nuke.Common.Tools.MinVer
{
/// <summary>
/// <p>Minimalistic versioning using Git tags.</p>
/// <p>For more details, visit the <a href="https://github.com/adamralph/minver">official website</a>.</p>
/// </summary>
[PublicAPI]
[ExcludeFromCodeCoverage]
public static partial class MinVerTasks
{
/// <summary>
/// Path to the MinVer executable.
/// </summary>
public static string MinVerPath =>
ToolPathResolver.TryGetEnvironmentExecutable("MINVER_EXE") ??
ToolPathResolver.GetPackageExecutable("minver-cli", "minver-cli.dll");
public static Action<OutputType, string> MinVerLogger { get; set; } = ProcessTasks.DefaultLogger;
/// <summary>
/// <p>Minimalistic versioning using Git tags.</p>
/// <p>For more details, visit the <a href="https://github.com/adamralph/minver">official website</a>.</p>
/// </summary>
public static IReadOnlyCollection<Output> MinVer(string arguments, string workingDirectory = null, IReadOnlyDictionary<string, string> environmentVariables = null, int? timeout = null, bool? logOutput = null, bool? logInvocation = null, Func<string, string> outputFilter = null)
{
using var process = ProcessTasks.StartProcess(MinVerPath, arguments, workingDirectory, environmentVariables, timeout, logOutput, logInvocation, MinVerLogger, outputFilter);
process.AssertZeroExitCode();
return process.Output;
}
/// <summary>
/// <p>Minimalistic versioning using Git tags.</p>
/// <p>For more details, visit the <a href="https://github.com/adamralph/minver">official website</a>.</p>
/// </summary>
/// <remarks>
/// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p>
/// <ul>
/// <li><c>--auto-increment</c> via <see cref="MinVerSettings.AutoIncrement"/></li>
/// <li><c>--build-metadata</c> via <see cref="MinVerSettings.BuildMetadata"/></li>
/// <li><c>--default-pre-release-phase</c> via <see cref="MinVerSettings.DefaultPreReleasePhase"/></li>
/// <li><c>--minimum-major-minor</c> via <see cref="MinVerSettings.MinimumMajorMinor"/></li>
/// <li><c>--tag-prefix</c> via <see cref="MinVerSettings.TagPrefix"/></li>
/// <li><c>--verbosity</c> via <see cref="MinVerSettings.Verbosity"/></li>
/// </ul>
/// </remarks>
public static (MinVer Result, IReadOnlyCollection<Output> Output) MinVer(MinVerSettings toolSettings = null)
{
toolSettings = toolSettings ?? new MinVerSettings();
using var process = ProcessTasks.StartProcess(toolSettings);
process.AssertZeroExitCode();
return (GetResult(process, toolSettings), process.Output);
}
/// <summary>
/// <p>Minimalistic versioning using Git tags.</p>
/// <p>For more details, visit the <a href="https://github.com/adamralph/minver">official website</a>.</p>
/// </summary>
/// <remarks>
/// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p>
/// <ul>
/// <li><c>--auto-increment</c> via <see cref="MinVerSettings.AutoIncrement"/></li>
/// <li><c>--build-metadata</c> via <see cref="MinVerSettings.BuildMetadata"/></li>
/// <li><c>--default-pre-release-phase</c> via <see cref="MinVerSettings.DefaultPreReleasePhase"/></li>
/// <li><c>--minimum-major-minor</c> via <see cref="MinVerSettings.MinimumMajorMinor"/></li>
/// <li><c>--tag-prefix</c> via <see cref="MinVerSettings.TagPrefix"/></li>
/// <li><c>--verbosity</c> via <see cref="MinVerSettings.Verbosity"/></li>
/// </ul>
/// </remarks>
public static (MinVer Result, IReadOnlyCollection<Output> Output) MinVer(Configure<MinVerSettings> configurator)
{
return MinVer(configurator(new MinVerSettings()));
}
/// <summary>
/// <p>Minimalistic versioning using Git tags.</p>
/// <p>For more details, visit the <a href="https://github.com/adamralph/minver">official website</a>.</p>
/// </summary>
/// <remarks>
/// <p>This is a <a href="http://www.nuke.build/docs/authoring-builds/cli-tools.html#fluent-apis">CLI wrapper with fluent API</a> that allows to modify the following arguments:</p>
/// <ul>
/// <li><c>--auto-increment</c> via <see cref="MinVerSettings.AutoIncrement"/></li>
/// <li><c>--build-metadata</c> via <see cref="MinVerSettings.BuildMetadata"/></li>
/// <li><c>--default-pre-release-phase</c> via <see cref="MinVerSettings.DefaultPreReleasePhase"/></li>
/// <li><c>--minimum-major-minor</c> via <see cref="MinVerSettings.MinimumMajorMinor"/></li>
/// <li><c>--tag-prefix</c> via <see cref="MinVerSettings.TagPrefix"/></li>
/// <li><c>--verbosity</c> via <see cref="MinVerSettings.Verbosity"/></li>
/// </ul>
/// </remarks>
public static IEnumerable<(MinVerSettings Settings, MinVer Result, IReadOnlyCollection<Output> Output)> MinVer(CombinatorialConfigure<MinVerSettings> configurator, int degreeOfParallelism = 1, bool completeOnFailure = false)
{
return configurator.Invoke(MinVer, MinVerLogger, degreeOfParallelism, completeOnFailure);
}
}
#region MinVerSettings
/// <summary>
/// Used within <see cref="MinVerTasks"/>.
/// </summary>
[PublicAPI]
[ExcludeFromCodeCoverage]
[Serializable]
public partial class MinVerSettings : ToolSettings
{
/// <summary>
/// Path to the MinVer executable.
/// </summary>
public override string ProcessToolPath => base.ProcessToolPath ?? MinVerTasks.MinVerPath;
public override Action<OutputType, string> ProcessCustomLogger => MinVerTasks.MinVerLogger;
public virtual MinVerVersionPart AutoIncrement { get; internal set; }
public virtual string BuildMetadata { get; internal set; }
public virtual string DefaultPreReleasePhase { get; internal set; }
public virtual string MinimumMajorMinor { get; internal set; }
public virtual string TagPrefix { get; internal set; }
public virtual MinVerVerbosity Verbosity { get; internal set; }
protected override Arguments ConfigureProcessArguments(Arguments arguments)
{
arguments
.Add("--auto-increment {value}", AutoIncrement)
.Add("--build-metadata {value}", BuildMetadata)
.Add("--default-pre-release-phase {value}", DefaultPreReleasePhase)
.Add("--minimum-major-minor {value}", MinimumMajorMinor)
.Add("--tag-prefix {value}", TagPrefix)
.Add("--verbosity {value}", Verbosity);
return base.ConfigureProcessArguments(arguments);
}
}
#endregion
#region MinVer
/// <summary>
/// Used within <see cref="MinVerTasks"/>.
/// </summary>
[PublicAPI]
[ExcludeFromCodeCoverage]
[Serializable]
public partial class MinVer : ISettingsEntity
{
public virtual string MinVerVersion { get; internal set; }
public virtual string MinVerMajor { get; internal set; }
public virtual string MinVerMinor { get; internal set; }
public virtual string MinVerPatch { get; internal set; }
public virtual string MinVerPreRelease { get; internal set; }
public virtual string MinVerBuildMetadata { get; internal set; }
public virtual string AssemblyVersion { get; internal set; }
public virtual string FileVersion { get; internal set; }
public virtual string PackageVersion { get; internal set; }
public virtual string Version { get; internal set; }
}
#endregion
#region MinVerSettingsExtensions
/// <summary>
/// Used within <see cref="MinVerTasks"/>.
/// </summary>
[PublicAPI]
[ExcludeFromCodeCoverage]
public static partial class MinVerSettingsExtensions
{
#region AutoIncrement
/// <summary>
/// <p><em>Sets <see cref="MinVerSettings.AutoIncrement"/></em></p>
/// </summary>
[Pure]
public static T SetAutoIncrement<T>(this T toolSettings, MinVerVersionPart autoIncrement) where T : MinVerSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.AutoIncrement = autoIncrement;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MinVerSettings.AutoIncrement"/></em></p>
/// </summary>
[Pure]
public static T ResetAutoIncrement<T>(this T toolSettings) where T : MinVerSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.AutoIncrement = null;
return toolSettings;
}
#endregion
#region BuildMetadata
/// <summary>
/// <p><em>Sets <see cref="MinVerSettings.BuildMetadata"/></em></p>
/// </summary>
[Pure]
public static T SetBuildMetadata<T>(this T toolSettings, string buildMetadata) where T : MinVerSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.BuildMetadata = buildMetadata;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MinVerSettings.BuildMetadata"/></em></p>
/// </summary>
[Pure]
public static T ResetBuildMetadata<T>(this T toolSettings) where T : MinVerSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.BuildMetadata = null;
return toolSettings;
}
#endregion
#region DefaultPreReleasePhase
/// <summary>
/// <p><em>Sets <see cref="MinVerSettings.DefaultPreReleasePhase"/></em></p>
/// </summary>
[Pure]
public static T SetDefaultPreReleasePhase<T>(this T toolSettings, string defaultPreReleasePhase) where T : MinVerSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DefaultPreReleasePhase = defaultPreReleasePhase;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MinVerSettings.DefaultPreReleasePhase"/></em></p>
/// </summary>
[Pure]
public static T ResetDefaultPreReleasePhase<T>(this T toolSettings) where T : MinVerSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.DefaultPreReleasePhase = null;
return toolSettings;
}
#endregion
#region MinimumMajorMinor
/// <summary>
/// <p><em>Sets <see cref="MinVerSettings.MinimumMajorMinor"/></em></p>
/// </summary>
[Pure]
public static T SetMinimumMajorMinor<T>(this T toolSettings, string minimumMajorMinor) where T : MinVerSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.MinimumMajorMinor = minimumMajorMinor;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MinVerSettings.MinimumMajorMinor"/></em></p>
/// </summary>
[Pure]
public static T ResetMinimumMajorMinor<T>(this T toolSettings) where T : MinVerSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.MinimumMajorMinor = null;
return toolSettings;
}
#endregion
#region TagPrefix
/// <summary>
/// <p><em>Sets <see cref="MinVerSettings.TagPrefix"/></em></p>
/// </summary>
[Pure]
public static T SetTagPrefix<T>(this T toolSettings, string tagPrefix) where T : MinVerSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.TagPrefix = tagPrefix;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MinVerSettings.TagPrefix"/></em></p>
/// </summary>
[Pure]
public static T ResetTagPrefix<T>(this T toolSettings) where T : MinVerSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.TagPrefix = null;
return toolSettings;
}
#endregion
#region Verbosity
/// <summary>
/// <p><em>Sets <see cref="MinVerSettings.Verbosity"/></em></p>
/// </summary>
[Pure]
public static T SetVerbosity<T>(this T toolSettings, MinVerVerbosity verbosity) where T : MinVerSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Verbosity = verbosity;
return toolSettings;
}
/// <summary>
/// <p><em>Resets <see cref="MinVerSettings.Verbosity"/></em></p>
/// </summary>
[Pure]
public static T ResetVerbosity<T>(this T toolSettings) where T : MinVerSettings
{
toolSettings = toolSettings.NewInstance();
toolSettings.Verbosity = null;
return toolSettings;
}
#endregion
}
#endregion
#region MinVerVerbosity
/// <summary>
/// Used within <see cref="MinVerTasks"/>.
/// </summary>
[PublicAPI]
[Serializable]
[ExcludeFromCodeCoverage]
[TypeConverter(typeof(TypeConverter<MinVerVerbosity>))]
public partial class MinVerVerbosity : Enumeration
{
public static MinVerVerbosity Error = (MinVerVerbosity) "Error";
public static MinVerVerbosity Warn = (MinVerVerbosity) "Warn";
public static MinVerVerbosity Info = (MinVerVerbosity) "Info";
public static MinVerVerbosity Debug = (MinVerVerbosity) "Debug";
public static MinVerVerbosity Trace = (MinVerVerbosity) "Trace";
public static implicit operator MinVerVerbosity(string value)
{
return new MinVerVerbosity { Value = value };
}
}
#endregion
#region MinVerVersionPart
/// <summary>
/// Used within <see cref="MinVerTasks"/>.
/// </summary>
[PublicAPI]
[Serializable]
[ExcludeFromCodeCoverage]
[TypeConverter(typeof(TypeConverter<MinVerVersionPart>))]
public partial class MinVerVersionPart : Enumeration
{
public static MinVerVersionPart Major = (MinVerVersionPart) "Major";
public static MinVerVersionPart Minor = (MinVerVersionPart) "Minor";
public static MinVerVersionPart Patch = (MinVerVersionPart) "Patch";
public static implicit operator MinVerVersionPart(string value)
{
return new MinVerVersionPart { Value = value };
}
}
#endregion
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.CloudRuntimeConfig.v1
{
/// <summary>The CloudRuntimeConfig Service.</summary>
public class CloudRuntimeConfigService : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v1";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public CloudRuntimeConfigService() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public CloudRuntimeConfigService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Operations = new OperationsResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "runtimeconfig";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://runtimeconfig.googleapis.com/";
#else
"https://runtimeconfig.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://runtimeconfig.googleapis.com/batch";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Cloud Runtime Configuration API.</summary>
public class Scope
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>Manage your Google Cloud Platform services' runtime configuration</summary>
public static string Cloudruntimeconfig = "https://www.googleapis.com/auth/cloudruntimeconfig";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Cloud Runtime Configuration API.</summary>
public static class ScopeConstants
{
/// <summary>
/// See, edit, configure, and delete your Google Cloud data and see the email address for your Google
/// Account.
/// </summary>
public const string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform";
/// <summary>Manage your Google Cloud Platform services' runtime configuration</summary>
public const string Cloudruntimeconfig = "https://www.googleapis.com/auth/cloudruntimeconfig";
}
/// <summary>Gets the Operations resource.</summary>
public virtual OperationsResource Operations { get; }
}
/// <summary>A base abstract class for CloudRuntimeConfig requests.</summary>
public abstract class CloudRuntimeConfigBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new CloudRuntimeConfigBaseServiceRequest instance.</summary>
protected CloudRuntimeConfigBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>V1 error format.</summary>
[Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<XgafvEnum> Xgafv { get; set; }
/// <summary>V1 error format.</summary>
public enum XgafvEnum
{
/// <summary>v1 error format</summary>
[Google.Apis.Util.StringValueAttribute("1")]
Value1 = 0,
/// <summary>v2 error format</summary>
[Google.Apis.Util.StringValueAttribute("2")]
Value2 = 1,
}
/// <summary>OAuth access token.</summary>
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
/// <summary>Data format for response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
/// <summary>Media download with context-dependent Content-Type</summary>
[Google.Apis.Util.StringValueAttribute("media")]
Media = 1,
/// <summary>Responses with Content-Type of application/x-protobuf</summary>
[Google.Apis.Util.StringValueAttribute("proto")]
Proto = 2,
}
/// <summary>JSONP</summary>
[Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Callback { get; set; }
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a
/// user, but should not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadType { get; set; }
/// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary>
[Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UploadProtocol { get; set; }
/// <summary>Initializes CloudRuntimeConfig parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter
{
Name = "$.xgafv",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter
{
Name = "callback",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter
{
Name = "uploadType",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter
{
Name = "upload_protocol",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "operations" collection of methods.</summary>
public class OperationsResource
{
private const string Resource = "operations";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public OperationsResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
/// <summary>
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the
/// operation, but success is not guaranteed. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether
/// the cancellation succeeded or whether the operation completed despite cancellation. On successful
/// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value
/// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
/// </summary>
/// <param name="body">The body of the request.</param>
/// <param name="name">The name of the operation resource to be cancelled.</param>
public virtual CancelRequest Cancel(Google.Apis.CloudRuntimeConfig.v1.Data.CancelOperationRequest body, string name)
{
return new CancelRequest(service, body, name);
}
/// <summary>
/// Starts asynchronous cancellation on a long-running operation. The server makes a best effort to cancel the
/// operation, but success is not guaranteed. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether
/// the cancellation succeeded or whether the operation completed despite cancellation. On successful
/// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value
/// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.
/// </summary>
public class CancelRequest : CloudRuntimeConfigBaseServiceRequest<Google.Apis.CloudRuntimeConfig.v1.Data.Empty>
{
/// <summary>Constructs a new Cancel request.</summary>
public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudRuntimeConfig.v1.Data.CancelOperationRequest body, string name) : base(service)
{
Name = name;
Body = body;
InitParameters();
}
/// <summary>The name of the operation resource to be cancelled.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets or sets the body of this request.</summary>
Google.Apis.CloudRuntimeConfig.v1.Data.CancelOperationRequest Body { get; set; }
/// <summary>Returns the body of the request.</summary>
protected override object GetBody() => Body;
/// <summary>Gets the method name.</summary>
public override string MethodName => "cancel";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}:cancel";
/// <summary>Initializes Cancel parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^operations/.*$",
});
}
}
/// <summary>
/// Deletes a long-running operation. This method indicates that the client is no longer interested in the
/// operation result. It does not cancel the operation. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`.
/// </summary>
/// <param name="name">The name of the operation resource to be deleted.</param>
public virtual DeleteRequest Delete(string name)
{
return new DeleteRequest(service, name);
}
/// <summary>
/// Deletes a long-running operation. This method indicates that the client is no longer interested in the
/// operation result. It does not cancel the operation. If the server doesn't support this method, it returns
/// `google.rpc.Code.UNIMPLEMENTED`.
/// </summary>
public class DeleteRequest : CloudRuntimeConfigBaseServiceRequest<Google.Apis.CloudRuntimeConfig.v1.Data.Empty>
{
/// <summary>Constructs a new Delete request.</summary>
public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation resource to be deleted.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "delete";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "DELETE";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes Delete parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^operations/.*$",
});
}
}
/// <summary>
/// Lists operations that match the specified filter in the request. If the server doesn't support this method,
/// it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use
/// different resource name schemes, such as `users/*/operations`. To override the binding, API services can add
/// a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards
/// compatibility, the default name includes the operations collection id, however overriding users must ensure
/// the name binding is the parent resource, without the operations collection id.
/// </summary>
/// <param name="name">The name of the operation's parent resource.</param>
public virtual ListRequest List(string name)
{
return new ListRequest(service, name);
}
/// <summary>
/// Lists operations that match the specified filter in the request. If the server doesn't support this method,
/// it returns `UNIMPLEMENTED`. NOTE: the `name` binding allows API services to override the binding to use
/// different resource name schemes, such as `users/*/operations`. To override the binding, API services can add
/// a binding such as `"/v1/{name=users/*}/operations"` to their service configuration. For backwards
/// compatibility, the default name includes the operations collection id, however overriding users must ensure
/// the name binding is the parent resource, without the operations collection id.
/// </summary>
public class ListRequest : CloudRuntimeConfigBaseServiceRequest<Google.Apis.CloudRuntimeConfig.v1.Data.ListOperationsResponse>
{
/// <summary>Constructs a new List request.</summary>
public ListRequest(Google.Apis.Services.IClientService service, string name) : base(service)
{
Name = name;
InitParameters();
}
/// <summary>The name of the operation's parent resource.</summary>
[Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)]
public virtual string Name { get; private set; }
/// <summary>The standard list filter.</summary>
[Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Filter { get; set; }
/// <summary>The standard list page size.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<int> PageSize { get; set; }
/// <summary>The standard list page token.</summary>
[Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)]
public virtual string PageToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "list";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "v1/{+name}";
/// <summary>Initializes List parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("name", new Google.Apis.Discovery.Parameter
{
Name = "name",
IsRequired = true,
ParameterType = "path",
DefaultValue = null,
Pattern = @"^operations$",
});
RequestParameters.Add("filter", new Google.Apis.Discovery.Parameter
{
Name = "filter",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageSize", new Google.Apis.Discovery.Parameter
{
Name = "pageSize",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("pageToken", new Google.Apis.Discovery.Parameter
{
Name = "pageToken",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
}
}
namespace Google.Apis.CloudRuntimeConfig.v1.Data
{
/// <summary>The request message for Operations.CancelOperation.</summary>
public class CancelOperationRequest : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical
/// example is to use it as the request or the response type of an API method. For instance: service Foo { rpc
/// Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The JSON representation for `Empty` is empty JSON
/// object `{}`.
/// </summary>
public class Empty : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>The response message for Operations.ListOperations.</summary>
public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The standard List next-page token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")]
public virtual string NextPageToken { get; set; }
/// <summary>A list of operations that matches the specified filter in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("operations")]
public virtual System.Collections.Generic.IList<Operation> Operations { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>This resource represents a long-running operation that is the result of a network API call.</summary>
public class Operation : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>
/// If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed,
/// and either `error` or `response` is available.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("done")]
public virtual System.Nullable<bool> Done { get; set; }
/// <summary>The error result of the operation in case of failure or cancellation.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("error")]
public virtual Status Error { get; set; }
/// <summary>
/// Service-specific metadata associated with the operation. It typically contains progress information and
/// common metadata such as create time. Some services might not provide such metadata. Any method that returns
/// a long-running operation should document the metadata type, if any.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("metadata")]
public virtual System.Collections.Generic.IDictionary<string, object> Metadata { get; set; }
/// <summary>
/// The server-assigned name, which is only unique within the same service that originally returns it. If you
/// use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>
/// The normal response of the operation in case of success. If the original method returns no data on success,
/// such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard
/// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have
/// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name is
/// `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("response")]
public virtual System.Collections.Generic.IDictionary<string, object> Response { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
/// <summary>
/// The `Status` type defines a logical error model that is suitable for different programming environments,
/// including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains
/// three pieces of data: error code, error message, and error details. You can find out more about this error model
/// and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors).
/// </summary>
public class Status : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The status code, which should be an enum value of google.rpc.Code.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("code")]
public virtual System.Nullable<int> Code { get; set; }
/// <summary>
/// A list of messages that carry the error details. There is a common set of message types for APIs to use.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("details")]
public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string, object>> Details { get; set; }
/// <summary>
/// A developer-facing error message, which should be in English. Any user-facing error message should be
/// localized and sent in the google.rpc.Status.details field, or localized by the client.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("message")]
public virtual string Message { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Avalonia.VisualTree;
namespace Avalonia.Input.Navigation
{
/// <summary>
/// The implementation for default tab navigation.
/// </summary>
internal static class TabNavigation
{
/// <summary>
/// Gets the next control in the specified tab direction.
/// </summary>
/// <param name="element">The element.</param>
/// <param name="direction">The tab direction. Must be Next or Previous.</param>
/// <param name="outsideElement">
/// If true will not descend into <paramref name="element"/> to find next control.
/// </param>
/// <returns>
/// The next element in the specified direction, or null if <paramref name="element"/>
/// was the last in the requested direction.
/// </returns>
public static IInputElement? GetNextInTabOrder(
IInputElement element,
NavigationDirection direction,
bool outsideElement = false)
{
element = element ?? throw new ArgumentNullException(nameof(element));
if (direction != NavigationDirection.Next && direction != NavigationDirection.Previous)
{
throw new ArgumentException("Invalid direction: must be Next or Previous.");
}
var container = element.GetVisualParent<IInputElement>();
if (container != null)
{
var mode = KeyboardNavigation.GetTabNavigation((InputElement)container);
switch (mode)
{
case KeyboardNavigationMode.Continue:
return GetNextInContainer(element, container, direction, outsideElement) ??
GetFirstInNextContainer(element, element, direction);
case KeyboardNavigationMode.Cycle:
return GetNextInContainer(element, container, direction, outsideElement) ??
GetFocusableDescendant(container, direction);
case KeyboardNavigationMode.Contained:
return GetNextInContainer(element, container, direction, outsideElement);
default:
return GetFirstInNextContainer(element, container, direction);
}
}
else
{
return GetFocusableDescendants(element, direction).FirstOrDefault();
}
}
/// <summary>
/// Gets the first or last focusable descendant of the specified element.
/// </summary>
/// <param name="container">The element.</param>
/// <param name="direction">The direction to search.</param>
/// <returns>The element or null if not found.##</returns>
private static IInputElement GetFocusableDescendant(IInputElement container, NavigationDirection direction)
{
return direction == NavigationDirection.Next ?
GetFocusableDescendants(container, direction).FirstOrDefault() :
GetFocusableDescendants(container, direction).LastOrDefault();
}
/// <summary>
/// Gets the focusable descendants of the specified element.
/// </summary>
/// <param name="element">The element.</param>
/// <param name="direction">The tab direction. Must be Next or Previous.</param>
/// <returns>The element's focusable descendants.</returns>
private static IEnumerable<IInputElement> GetFocusableDescendants(IInputElement element,
NavigationDirection direction)
{
var mode = KeyboardNavigation.GetTabNavigation((InputElement)element);
if (mode == KeyboardNavigationMode.None)
{
yield break;
}
var children = element.GetVisualChildren().OfType<IInputElement>();
if (mode == KeyboardNavigationMode.Once)
{
var active = KeyboardNavigation.GetTabOnceActiveElement((InputElement)element);
if (active != null)
{
yield return active;
yield break;
}
else
{
children = children.Take(1);
}
}
foreach (var child in children)
{
var customNext = GetCustomNext(child, direction);
if (customNext.handled)
{
yield return customNext.next!;
}
else
{
if (child.CanFocus() && KeyboardNavigation.GetIsTabStop((InputElement)child))
{
yield return child;
}
if (child.CanFocusDescendants())
{
foreach (var descendant in GetFocusableDescendants(child, direction))
{
if (KeyboardNavigation.GetIsTabStop((InputElement)descendant))
{
yield return descendant;
}
}
}
}
}
}
/// <summary>
/// Gets the next item that should be focused in the specified container.
/// </summary>
/// <param name="element">The starting element/</param>
/// <param name="container">The container.</param>
/// <param name="direction">The direction.</param>
/// <param name="outsideElement">
/// If true will not descend into <paramref name="element"/> to find next control.
/// </param>
/// <returns>The next element, or null if the element is the last.</returns>
private static IInputElement? GetNextInContainer(
IInputElement element,
IInputElement container,
NavigationDirection direction,
bool outsideElement)
{
IInputElement? e = element;
if (direction == NavigationDirection.Next && !outsideElement)
{
var descendant = GetFocusableDescendants(element, direction).FirstOrDefault();
if (descendant != null)
{
return descendant;
}
}
if (container != null)
{
var navigable = container as INavigableContainer;
// TODO: Do a spatial search here if the container doesn't implement
// INavigableContainer.
if (navigable != null)
{
while (e != null)
{
e = navigable.GetControl(direction, e, false);
if (e != null &&
e.CanFocus() &&
KeyboardNavigation.GetIsTabStop((InputElement)e))
{
break;
}
}
}
else
{
// TODO: Do a spatial search here if the container doesn't implement
// INavigableContainer.
e = null;
}
if (e != null && direction == NavigationDirection.Previous)
{
var descendant = GetFocusableDescendants(e, direction).LastOrDefault();
if (descendant != null)
{
return descendant;
}
}
return e;
}
return null;
}
/// <summary>
/// Gets the first item that should be focused in the next container.
/// </summary>
/// <param name="element">The element being navigated away from.</param>
/// <param name="container">The container.</param>
/// <param name="direction">The direction of the search.</param>
/// <returns>The first element, or null if there are no more elements.</returns>
private static IInputElement? GetFirstInNextContainer(
IInputElement element,
IInputElement container,
NavigationDirection direction)
{
var parent = container.GetVisualParent<IInputElement>();
IInputElement? next = null;
if (parent != null)
{
if (direction == NavigationDirection.Previous &&
parent.CanFocus() &&
KeyboardNavigation.GetIsTabStop((InputElement) parent))
{
return parent;
}
var allSiblings = parent.GetVisualChildren()
.OfType<IInputElement>()
.Where(FocusExtensions.CanFocusDescendants);
var siblings = direction == NavigationDirection.Next ?
allSiblings.SkipWhile(x => x != container).Skip(1) :
allSiblings.TakeWhile(x => x != container).Reverse();
foreach (var sibling in siblings)
{
var customNext = GetCustomNext(sibling, direction);
if (customNext.handled)
{
return customNext.next;
}
if (sibling.CanFocus() && KeyboardNavigation.GetIsTabStop((InputElement) sibling))
{
return sibling;
}
next = direction == NavigationDirection.Next ?
GetFocusableDescendants(sibling, direction).FirstOrDefault() :
GetFocusableDescendants(sibling, direction).LastOrDefault();
if (next != null)
{
return next;
}
}
next = GetFirstInNextContainer(element, parent, direction);
}
else
{
next = direction == NavigationDirection.Next ?
GetFocusableDescendants(container, direction).FirstOrDefault() :
GetFocusableDescendants(container, direction).LastOrDefault();
}
return next;
}
private static (bool handled, IInputElement? next) GetCustomNext(IInputElement element,
NavigationDirection direction)
{
if (element is ICustomKeyboardNavigation custom)
{
return custom.GetNext(element, direction);
}
return (false, null);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Threading;
using System.IO;
using System.Text;
namespace NDeproxy
{
public class SocketServerConnector : ServerConnector
{
static readonly Logger log = new Logger("SocketServerConnector");
ListenerThread serverThread;
Socket serverSocket;
bool _stop = false;
List<Action> _shutdownActions = new List<Action>();
object _shutdownActionsLock = new object();
public readonly Endpoint endpoint;
public readonly int port;
public readonly string name;
public SocketServerConnector(Endpoint endpoint, string name, int port)
{
if (endpoint == null)
{
throw new ArgumentNullException("endpoint");
}
this.endpoint = endpoint;
this.name = name;
this.port = port;
serverSocket = SocketHelper.Server(port);
serverThread = new ListenerThread(this, serverSocket, string.Format("Thread-{0}", name));
}
public class ListenerThread
{
static readonly Logger log = new Logger("ListenerThread");
public SocketServerConnector parent;
public Socket socket;
public Thread thread;
ManualResetEvent _stopSignal = new ManualResetEvent(false);
public ListenerThread(SocketServerConnector parent, Socket socket, string name)
{
this.parent = parent;
parent.AddShutdownAction(this.Stop);
this.socket = socket;
thread = new Thread(this.Run);
thread.Name = name;
thread.IsBackground = true;
thread.Start();
}
public void Run()
{
var acceptedSignal = new ManualResetEvent(false);
var acceptedOrStop = new WaitHandle[2] { acceptedSignal, _stopSignal };
try
{
while (!_stopSignal.WaitOne(0))
{
Socket handlerSocket = null;
try
{
log.debug("calling BeginAccept");
acceptedSignal.Reset();
var ar = socket.BeginAccept((_ar) =>
{
log.debug("calling EndAccept");
try
{
handlerSocket = socket.EndAccept(_ar);
}
catch (Exception ex)
{
log.debug("Caught an exception in EndAccept: {0}", ex);
}
log.debug("returned from EndAccept, signalling completion");
acceptedSignal.Set();
}, null);
log.debug("returned from BeginAccept");
log.debug("waiting on the wait handles");
var signal = WaitHandle.WaitAny(acceptedOrStop);
if (acceptedOrStop[signal] == _stopSignal)
{
break;
}
log.debug("Accepted a new connection");
string connectionName = Guid.NewGuid().ToString();
log.debug("Starting the handler thread");
HandlerThread handlerThread = new HandlerThread(this.parent, handlerSocket, connectionName, thread.Name + "-connection-" + connectionName);
handlerSocket = null;
log.debug("Handler thread started");
}
catch (Exception e)
{
log.error("Exception caught in Run, in the second try-block: {0}", e);
throw;
}
finally
{
if (handlerSocket != null)
{
handlerSocket.Close();
}
}
}
}
finally
{
socket.Close();
}
}
public void Stop()
{
_stopSignal.Set();
if (thread.IsAlive)
{
int time = Environment.TickCount;
thread.Join(1000);
log.debug("while Stop()ing, joined for {0} ms", Environment.TickCount - time);
}
if (thread.IsAlive)
{
thread.Abort();
}
}
}
public delegate void ConnectionProcessor(Socket socket, string connectionName);
public class HandlerThread
{
static readonly Logger log = new Logger("HandlerThread");
public SocketServerConnector parent;
public Socket socket;
public string connectionName;
public Thread thread;
ManualResetEvent _stopSignal = new ManualResetEvent(false);
public HandlerThread(SocketServerConnector parent,
Socket socket,
string connectionName,
string threadName)
{
if (socket == null)
throw new ArgumentNullException("socket");
this.parent = parent;
parent.AddShutdownAction(this.Stop);
this.socket = socket;
this.connectionName = connectionName;
thread = new Thread(this.processNewConnection);
thread.Name = threadName;
thread.IsBackground = true;
thread.Start();
}
public void Stop()
{
_stopSignal.Set();
if (socket != null)
{
ShutdownSocket();
}
if (thread.IsAlive)
{
log.debug("thread is alive");
int time = Environment.TickCount;
log.debug("joining thread");
thread.Join(1000);
log.debug("while Stop()ing, joined for {0} ms", Environment.TickCount - time);
}
if (thread.IsAlive)
{
log.debug("thread is still alive");
thread.Abort();
log.debug("thread aborted");
}
}
void ShutdownSocket()
{
Socket s = Interlocked.Exchange(ref socket, null);
if (s != null)
{
log.debug("shutting down the socket");
s.Shutdown(SocketShutdown.Both);
log.debug("closing the socket");
s.Close();
}
}
void processNewConnection()
{
log.debug("processing new connection...");
Stream stream = new UnbufferedSocketStream(socket);
try
{
log.debug("starting loop");
bool persistConnection = true;
while (persistConnection && !_stopSignal.WaitOne(0))
{
log.debug("calling parseRequest");
var ret = parseRequest(stream);
log.debug("returned from parseRequest");
if (ret == null)
{
break;
}
Request request = ret.Item1;
persistConnection = ret.Item2;
if (persistConnection &&
request.headers.contains("Connection"))
{
foreach (var value in request.headers.findAll("Connection"))
{
if (value == "close")
{
persistConnection = false;
break;
}
}
}
log.debug("about to handle one request");
ResponseWithContext rwc = parent.endpoint.handleRequest(request, connectionName);
log.debug("handled one request");
log.debug("send the response");
sendResponse(stream, rwc.response, rwc.context);
if (persistConnection &&
rwc.response.headers.contains("Connection"))
{
foreach (var value in rwc.response.headers.findAll("Connection"))
{
if (value == "close")
{
persistConnection = false;
break;
}
}
}
}
log.debug("ending loop");
}
catch (Exception e)
{
log.error("there was an error: {0}", e);
if (_stopSignal.WaitOne(0) ||
(socket != null &&
socket.IsClosed()))
{
// do nothing
}
else
{
sendResponse(stream,
new Response(500, "Internal Server Error", null,
"The server encountered an unexpected condition which prevented it from fulfilling the request."));
}
}
finally
{
ShutdownSocket();
}
log.debug("done processing");
}
Tuple<Request, bool> parseRequest(Stream stream)
{
log.debug("reading request line");
var requestLine = LineReader.readLine(stream);
if (requestLine == null)
{
log.debug("request line is null: {0}", requestLine);
return null;
}
log.debug("request line is not null: {0}", requestLine);
var words = requestLine.Split(' ', '\t');
log.debug("{0}", words);
string version;
string method;
string path;
if (words.Length == 3)
{
method = words[0];
path = words[1];
version = words[2];
log.debug("{0}, {1}, {2}", method, path, version);
if (!version.StartsWith("HTTP/", StringComparison.Ordinal))
{
sendResponse(stream, new Response(400, null, null, string.Format("Bad request version \"{0}\"", version)));
return null;
}
}
else
{
sendResponse(stream, new Response(400));
return null;
}
log.debug("checking http protocol version: {0}", version);
if (version != "HTTP/1.1" &&
version != "HTTP/1.0" &&
version != "HTTP/0.9")
{
sendResponse(stream, new Response(505, null, null, string.Format("Invalid HTTP Version \"{0}\"}", version)));
return null;
}
HeaderCollection headers = HeaderReader.readHeaders(stream);
var persistentConnection = false;
if (version == "HTTP/1.1")
{
persistentConnection = true;
foreach (var value in headers.findAll("Connection"))
{
if (value == "close")
{
persistentConnection = false;
}
}
}
log.debug("reading the body");
var body = BodyReader.readBody(stream, headers);
int length;
if (body == null)
{
length = 0;
}
else if (body is byte[])
{
length = (body as byte[]).Length;
}
else
{
length = body.ToString().Length;
}
log.debug("Done reading body, length {0}", length);
log.debug("returning");
return new Tuple<Request, bool>(
new Request(method, path, headers, body),
persistentConnection
);
}
void sendResponse(Stream stream, Response response, HandlerContext context = null)
{
var writer = new StreamWriter(stream, Encoding.ASCII);
if (response.message == null)
{
response.message = "";
}
writer.Write("HTTP/1.1 {0} {1}", response.code, response.message);
writer.Write("\r\n");
writer.Flush();
HeaderWriter.writeHeaders(stream, response.headers);
BodyWriter.writeBody(response.body, stream,
(context != null && context.usedChunkedTransferEncoding));
log.debug("finished sending response");
}
}
public Socket createRawConnection()
{
return SocketHelper.Client("localhost", this.port);
}
public void shutdown()
{
_stop = true;
ExecuteShutdownActions();
if (serverThread != null)
{
// serverThread.interrupt();
// throw new NotImplementedException();
}
if (serverSocket != null)
{
serverSocket.Close();
}
}
private void AddShutdownAction(Action action)
{
lock (_shutdownActionsLock)
{
_shutdownActions.Add(action);
}
}
private void ExecuteShutdownActions()
{
lock (_shutdownActionsLock)
{
foreach (var action in _shutdownActions)
{
action();
}
_shutdownActions.Clear();
}
}
}
}
| |
/* New BSD License
-------------------------------------------------------------------------------
Copyright (c) 2006-2012, EntitySpaces, LLC
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the EntitySpaces, LLC nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL EntitySpaces, LLC BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-------------------------------------------------------------------------------
*/
using System;
using System.Collections.Generic;
using System.Data;
using Tiraggo.DynamicQuery;
using Tiraggo.Interfaces;
using VistaDB.Provider;
namespace Tiraggo.VistaDB4Provider
{
class QueryBuilder
{
public static VistaDBCommand PrepareCommand(tgDataRequest request)
{
StandardProviderParameters std = new StandardProviderParameters();
std.cmd = new VistaDBCommand();
std.pindex = NextParamIndex(std.cmd);
std.request = request;
string sql = BuildQuery(std, request.DynamicQuery);
std.cmd.CommandText = sql;
return (VistaDBCommand)std.cmd;
}
protected static string BuildQuery(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
string select = GetSelectStatement(std, query);
string from = GetFromStatement(std, query);
string join = GetJoinStatement(std, query);
string where = GetComparisonStatement(std, query, iQuery.InternalWhereItems, " WHERE ");
string groupBy = GetGroupByStatement(std, query);
string having = GetComparisonStatement(std, query, iQuery.InternalHavingItems, " HAVING ");
string orderBy = GetOrderByStatement(std, query);
string setOperation = GetSetOperationStatement(std, query);
string sql = String.Empty;
sql += "SELECT " + select + " FROM " + from + join + where + setOperation + groupBy + having + orderBy;
return sql;
}
protected static string GetFromStatement(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
string sql = String.Empty;
if (iQuery.InternalFromQuery == null)
{
sql = Shared.CreateFullName(query);
if (iQuery.JoinAlias != " ")
{
sql += " " + iQuery.JoinAlias;
}
}
else
{
IDynamicQuerySerializableInternal iSubQuery = iQuery.InternalFromQuery as IDynamicQuerySerializableInternal;
iSubQuery.IsInSubQuery = true;
sql += "(";
sql += BuildQuery(std, iQuery.InternalFromQuery);
sql += ")";
if (iSubQuery.SubQueryAlias != " ")
{
sql += " AS " + iSubQuery.SubQueryAlias;
}
iSubQuery.IsInSubQuery = false;
}
return sql;
}
protected static string GetSelectStatement(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
string sql = String.Empty;
string comma = String.Empty;
bool selectAll = true;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
if (query.tg.Distinct) sql += " DISTINCT ";
if (query.tg.Top >= 0) sql += " TOP " + query.tg.Top.ToString() + " ";
if (iQuery.InternalSelectColumns != null)
{
selectAll = false;
foreach (tgExpression expressionItem in iQuery.InternalSelectColumns)
{
if (expressionItem.Query != null)
{
IDynamicQuerySerializableInternal iSubQuery = expressionItem.Query as IDynamicQuerySerializableInternal;
sql += comma;
if (iSubQuery.SubQueryAlias == string.Empty)
{
sql += iSubQuery.JoinAlias + ".*";
}
else
{
iSubQuery.IsInSubQuery = true;
sql += " (" + BuildQuery(std, expressionItem.Query as tgDynamicQuerySerializable) + ") AS " + iSubQuery.SubQueryAlias;
iSubQuery.IsInSubQuery = false;
}
comma = ",";
}
else
{
sql += comma;
string columnName = expressionItem.Column.Name;
if (columnName != null && columnName[0] == '<')
sql += columnName.Substring(1, columnName.Length - 2);
else
sql += GetExpressionColumn(std, query, expressionItem, false, true);
comma = ",";
}
}
sql += " ";
}
if (query.tg.CountAll)
{
selectAll = false;
sql += comma;
sql += "COUNT(*)";
if (query.tg.CountAllAlias != null)
{
// Need DBMS string delimiter here
sql += " AS " + Delimiters.StringOpen + query.tg.CountAllAlias + Delimiters.StringClose;
}
}
if (selectAll)
{
sql += "*";
}
return sql;
}
protected static string GetJoinStatement(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
string sql = String.Empty;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
if (iQuery.InternalJoinItems != null)
{
foreach (tgJoinItem joinItem in iQuery.InternalJoinItems)
{
tgJoinItem.tgJoinItemData joinData = (tgJoinItem.tgJoinItemData)joinItem;
switch (joinData.JoinType)
{
case tgJoinType.InnerJoin:
sql += " INNER JOIN ";
break;
case tgJoinType.LeftJoin:
sql += " LEFT JOIN ";
break;
case tgJoinType.RightJoin:
sql += " RIGHT JOIN ";
break;
case tgJoinType.FullJoin:
sql += " FULL JOIN ";
break;
}
IDynamicQuerySerializableInternal iSubQuery = joinData.Query as IDynamicQuerySerializableInternal;
sql += Shared.CreateFullName((tgProviderSpecificMetadata)iSubQuery.ProviderMetadata);
sql += " " + iSubQuery.JoinAlias + " ON ";
sql += GetComparisonStatement(std, query, joinData.WhereItems, String.Empty);
}
}
return sql;
}
protected static string GetComparisonStatement(StandardProviderParameters std, tgDynamicQuerySerializable query, List<tgComparison> items, string prefix)
{
string sql = String.Empty;
string comma = String.Empty;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
//=======================================
// WHERE
//=======================================
if (items != null)
{
sql += prefix;
string compareTo = String.Empty;
foreach (tgComparison comparisonItem in items)
{
tgComparison.tgComparisonData comparisonData = (tgComparison.tgComparisonData)comparisonItem;
tgDynamicQuerySerializable subQuery = null;
bool requiresParam = true;
bool needsStringParameter = false;
if (comparisonData.IsParenthesis)
{
if (comparisonData.Parenthesis == tgParenthesis.Open)
sql += "(";
else
sql += ")";
continue;
}
if (comparisonData.IsConjunction)
{
switch (comparisonData.Conjunction)
{
case tgConjunction.And: sql += " AND "; break;
case tgConjunction.Or: sql += " OR "; break;
case tgConjunction.AndNot: sql += " AND NOT "; break;
case tgConjunction.OrNot: sql += " OR NOT "; break;
}
continue;
}
Dictionary<string, VistaDBParameter> types = null;
if (comparisonData.Column.Query != null)
{
IDynamicQuerySerializableInternal iLocalQuery = comparisonData.Column.Query as IDynamicQuerySerializableInternal;
types = Cache.GetParameters(iLocalQuery.DataID, (tgProviderSpecificMetadata)iLocalQuery.ProviderMetadata, (tgColumnMetadataCollection)iLocalQuery.Columns);
}
if (comparisonData.IsLiteral)
{
sql += comparisonData.Column.Name.Substring(1, comparisonData.Column.Name.Length - 2);
continue;
}
if (comparisonData.ComparisonColumn.Name == null)
{
subQuery = comparisonData.Value as tgDynamicQuerySerializable;
if (subQuery == null)
{
if (comparisonData.Column.Name != null)
{
IDynamicQuerySerializableInternal iColQuery = comparisonData.Column.Query as IDynamicQuerySerializableInternal;
tgColumnMetadataCollection columns = (tgColumnMetadataCollection)iColQuery.Columns;
compareTo = Delimiters.Param + columns[comparisonData.Column.Name].PropertyName + (++std.pindex).ToString();
}
else
{
compareTo = Delimiters.Param + "Expr" + (++std.pindex).ToString();
}
}
else
{
// It's a sub query
compareTo = GetSubquerySearchCondition(subQuery) + " (" + BuildQuery(std, subQuery) + ") ";
requiresParam = false;
}
}
else
{
compareTo = GetColumnName(comparisonData.ComparisonColumn);
requiresParam = false;
}
switch (comparisonData.Operand)
{
case tgComparisonOperand.Exists:
sql += " EXISTS" + compareTo;
break;
case tgComparisonOperand.NotExists:
sql += " NOT EXISTS" + compareTo;
break;
//-----------------------------------------------------------
// Comparison operators, left side vs right side
//-----------------------------------------------------------
case tgComparisonOperand.Equal:
if (comparisonData.ItemFirst)
sql += ApplyWhereSubOperations(std, query, comparisonData) + " = " + compareTo;
else
sql += compareTo + " = " + ApplyWhereSubOperations(std, query, comparisonData);
break;
case tgComparisonOperand.NotEqual:
if (comparisonData.ItemFirst)
sql += ApplyWhereSubOperations(std, query, comparisonData) + " <> " + compareTo;
else
sql += compareTo + " <> " + ApplyWhereSubOperations(std, query, comparisonData);
break;
case tgComparisonOperand.GreaterThan:
if (comparisonData.ItemFirst)
sql += ApplyWhereSubOperations(std, query, comparisonData) + " > " + compareTo;
else
sql += compareTo + " > " + ApplyWhereSubOperations(std, query, comparisonData);
break;
case tgComparisonOperand.LessThan:
if (comparisonData.ItemFirst)
sql += ApplyWhereSubOperations(std, query, comparisonData) + " < " + compareTo;
else
sql += compareTo + " < " + ApplyWhereSubOperations(std, query, comparisonData);
break;
case tgComparisonOperand.LessThanOrEqual:
if (comparisonData.ItemFirst)
sql += ApplyWhereSubOperations(std, query, comparisonData) + " <= " + compareTo;
else
sql += compareTo + " <= " + ApplyWhereSubOperations(std, query, comparisonData);
break;
case tgComparisonOperand.GreaterThanOrEqual:
if (comparisonData.ItemFirst)
sql += ApplyWhereSubOperations(std, query, comparisonData) + " >= " + compareTo;
else
sql += compareTo + " >= " + ApplyWhereSubOperations(std, query, comparisonData);
break;
case tgComparisonOperand.Like:
string esc = comparisonData.LikeEscape.ToString();
if (String.IsNullOrEmpty(esc) || esc == "\0")
{
sql += ApplyWhereSubOperations(std, query, comparisonData) + " LIKE " + compareTo;
needsStringParameter = true;
}
else
{
sql += ApplyWhereSubOperations(std, query, comparisonData) + " LIKE " + compareTo;
sql += " ESCAPE '" + esc + "'";
needsStringParameter = true;
}
break;
case tgComparisonOperand.NotLike:
esc = comparisonData.LikeEscape.ToString();
if (String.IsNullOrEmpty(esc) || esc == "\0")
{
sql += ApplyWhereSubOperations(std, query, comparisonData) + " NOT LIKE " + compareTo;
needsStringParameter = true;
}
else
{
sql += ApplyWhereSubOperations(std, query, comparisonData) + " NOT LIKE " + compareTo;
sql += " ESCAPE '" + esc + "'";
needsStringParameter = true;
}
break;
case tgComparisonOperand.Contains:
sql += " CONTAINS(" + GetColumnName(comparisonData.Column) +
", " + compareTo + ")";
needsStringParameter = true;
break;
case tgComparisonOperand.IsNull:
sql += ApplyWhereSubOperations(std, query, comparisonData) + " IS NULL";
requiresParam = false;
break;
case tgComparisonOperand.IsNotNull:
sql += ApplyWhereSubOperations(std, query, comparisonData) + " IS NOT NULL";
requiresParam = false;
break;
case tgComparisonOperand.In:
case tgComparisonOperand.NotIn:
{
if (subQuery != null)
{
// They used a subquery for In or Not
sql += ApplyWhereSubOperations(std, query, comparisonData);
sql += (comparisonData.Operand == tgComparisonOperand.In) ? " IN" : " NOT IN";
sql += compareTo;
}
else
{
comma = String.Empty;
if (comparisonData.Operand == tgComparisonOperand.In)
{
sql += ApplyWhereSubOperations(std, query, comparisonData) + " IN (";
}
else
{
sql += ApplyWhereSubOperations(std, query, comparisonData) + " NOT IN (";
}
foreach (object oin in comparisonData.Values)
{
string str = oin as string;
if (str != null)
{
// STRING
sql += comma + Delimiters.StringOpen + str + Delimiters.StringClose;
comma = ",";
}
else if (null != oin as System.Collections.IEnumerable)
{
// LIST OR COLLECTION OF SOME SORT
System.Collections.IEnumerable enumer = oin as System.Collections.IEnumerable;
if (enumer != null)
{
System.Collections.IEnumerator iter = enumer.GetEnumerator();
while (iter.MoveNext())
{
object o = iter.Current;
string soin = o as string;
if (soin != null)
sql += comma + Delimiters.StringOpen + soin + Delimiters.StringClose;
else
sql += comma + Convert.ToString(o);
comma = ",";
}
}
}
else
{
// NON STRING OR LIST
sql += comma + Convert.ToString(oin);
comma = ",";
}
}
sql += ")";
requiresParam = false;
}
}
break;
case tgComparisonOperand.Between:
VistaDBCommand sqlCommand = std.cmd as VistaDBCommand;
sql += ApplyWhereSubOperations(std, query, comparisonData) + " BETWEEN ";
sql += compareTo;
if (comparisonData.ComparisonColumn.Name == null)
{
sqlCommand.Parameters.Add(compareTo, comparisonData.BetweenBegin);
}
if (comparisonData.ComparisonColumn2.Name == null)
{
IDynamicQuerySerializableInternal iColQuery = comparisonData.Column.Query as IDynamicQuerySerializableInternal;
tgColumnMetadataCollection columns = (tgColumnMetadataCollection)iColQuery.Columns;
compareTo = Delimiters.Param + columns[comparisonData.Column.Name].PropertyName + (++std.pindex).ToString();
sql += " AND " + compareTo;
sqlCommand.Parameters.AddWithValue(compareTo, comparisonData.BetweenEnd);
}
else
{
sql += " AND " + Delimiters.ColumnOpen + comparisonData.ComparisonColumn2 + Delimiters.ColumnClose;
}
requiresParam = false;
break;
}
if (requiresParam)
{
VistaDBParameter p;
if (comparisonData.Column.Name != null)
{
p = types[comparisonData.Column.Name];
p = Cache.CloneParameter(p);
p.ParameterName = compareTo;
p.Value = comparisonData.Value;
if (needsStringParameter)
{
p.DbType = DbType.String;
}
}
else
{
p = new VistaDBParameter(compareTo, comparisonData.Value);
}
std.cmd.Parameters.Add(p);
}
}
}
return sql;
}
protected static string GetOrderByStatement(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
string sql = String.Empty;
string comma = String.Empty;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
if (iQuery.InternalOrderByItems != null)
{
sql += " ORDER BY ";
foreach (tgOrderByItem orderByItem in iQuery.InternalOrderByItems)
{
bool literal = false;
sql += comma;
string columnName = orderByItem.Expression.Column.Name;
if (columnName != null && columnName[0] == '<')
{
sql += columnName.Substring(1, columnName.Length - 2);
if (orderByItem.Direction == tgOrderByDirection.Unassigned)
{
literal = true; // They must provide the DESC/ASC in the literal string
}
}
else
{
sql += GetExpressionColumn(std, query, orderByItem.Expression, false, false);
}
if (!literal)
{
if (orderByItem.Direction == tgOrderByDirection.Ascending)
sql += " ASC";
else
sql += " DESC";
}
comma = ",";
}
}
return sql;
}
protected static string GetGroupByStatement(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
string sql = String.Empty;
string comma = String.Empty;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
if (iQuery.InternalGroupByItems != null)
{
sql += " GROUP BY ";
foreach (tgGroupByItem groupBy in iQuery.InternalGroupByItems)
{
sql += comma;
string columnName = groupBy.Expression.Column.Name;
if (columnName != null && columnName[0] == '<')
sql += columnName.Substring(1, columnName.Length - 2);
else
sql += GetExpressionColumn(std, query, groupBy.Expression, false, false);
comma = ",";
}
if (query.tg.WithRollup)
{
sql += " WITH ROLLUP";
}
}
return sql;
}
protected static string GetSetOperationStatement(StandardProviderParameters std, tgDynamicQuerySerializable query)
{
string sql = String.Empty;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
if (iQuery.InternalSetOperations != null)
{
foreach (tgSetOperation setOperation in iQuery.InternalSetOperations)
{
switch (setOperation.SetOperationType)
{
case tgSetOperationType.Union: sql += " UNION "; break;
case tgSetOperationType.UnionAll: sql += " UNION ALL "; break;
case tgSetOperationType.Intersect: sql += " INTERSECT "; break;
case tgSetOperationType.Except: sql += " EXCEPT "; break;
}
sql += BuildQuery(std, setOperation.Query);
}
}
return sql;
}
protected static string GetExpressionColumn(StandardProviderParameters std, tgDynamicQuerySerializable query, tgExpression expression, bool inExpression, bool useAlias)
{
string sql = String.Empty;
if (expression.CaseWhen != null)
{
return GetCaseWhenThenEnd(std, query, expression.CaseWhen);
}
if (expression.HasMathmaticalExpression)
{
sql += GetMathmaticalExpressionColumn(std, query, expression.MathmaticalExpression);
}
else
{
sql += GetColumnName(expression.Column);
}
if (expression.SubOperators != null)
{
if (expression.Column.Distinct)
{
sql = BuildSubOperationsSql(std, "DISTINCT " + sql, expression.SubOperators);
}
else
{
sql = BuildSubOperationsSql(std, sql, expression.SubOperators);
}
}
if (!inExpression && useAlias)
{
if (expression.SubOperators != null || expression.Column.HasAlias)
{
sql += " AS " + Delimiters.StringOpen + expression.Column.Alias + Delimiters.StringClose;
}
}
return sql;
}
protected static string GetCaseWhenThenEnd(StandardProviderParameters std, tgDynamicQuerySerializable query, tgCase caseWhenThen)
{
string sql = string.Empty;
Tiraggo.DynamicQuery.tgCase.tgSimpleCaseData caseStatement = caseWhenThen;
tgColumnItem column = caseStatement.QueryItem;
sql += "CASE ";
List<tgComparison> list = new List<tgComparison>();
foreach (Tiraggo.DynamicQuery.tgCase.tgSimpleCaseData.tgCaseClause caseClause in caseStatement.Cases)
{
sql += " WHEN ";
if (!caseClause.When.IsExpression)
{
sql += GetComparisonStatement(std, query, caseClause.When.Comparisons, string.Empty);
}
else
{
if (!caseClause.When.Expression.IsLiteralValue)
{
sql += GetExpressionColumn(std, query, caseClause.When.Expression, false, true);
}
else
{
if (caseClause.When.Expression.LiteralValue is string)
{
sql += Delimiters.StringOpen + caseClause.When.Expression.LiteralValue + Delimiters.StringClose;
}
else
{
sql += Convert.ToString(caseClause.When.Expression.LiteralValue);
}
}
}
sql += " THEN ";
if (!caseClause.Then.IsLiteralValue)
{
sql += GetExpressionColumn(std, query, caseClause.Then, false, true);
}
else
{
if (caseClause.Then.LiteralValue is string)
{
sql += Delimiters.StringOpen + caseClause.Then.LiteralValue + Delimiters.StringClose;
}
else
{
sql += Convert.ToString(caseClause.Then.LiteralValue);
}
}
}
if (caseStatement.Else != null)
{
sql += " ELSE ";
if (!caseStatement.Else.IsLiteralValue)
{
sql += GetExpressionColumn(std, query, caseStatement.Else, false, true);
}
else
{
if (caseStatement.Else.LiteralValue is string)
{
sql += Delimiters.StringOpen + caseStatement.Else.LiteralValue + Delimiters.StringClose;
}
else
{
sql += Convert.ToString(caseStatement.Else.LiteralValue);
}
}
}
sql += " END ";
sql += " AS " + Delimiters.ColumnOpen + column.Alias + Delimiters.ColumnClose;
return sql;
}
protected static string GetMathmaticalExpressionColumn(StandardProviderParameters std, tgDynamicQuerySerializable query, tgMathmaticalExpression mathmaticalExpression)
{
string sql = "(";
if (mathmaticalExpression.ItemFirst)
{
sql += GetExpressionColumn(std, query, mathmaticalExpression.SelectItem1, true, true);
sql += esArithmeticOperatorToString(mathmaticalExpression.Operator);
if (mathmaticalExpression.SelectItem2 != null)
{
sql += GetExpressionColumn(std, query, mathmaticalExpression.SelectItem2, true, true);
}
else
{
sql += GetMathmaticalExpressionLiteralType(std, mathmaticalExpression);
}
}
else
{
if (mathmaticalExpression.SelectItem2 != null)
{
sql += GetExpressionColumn(std, query, mathmaticalExpression.SelectItem2, true, true);
}
else
{
sql += GetMathmaticalExpressionLiteralType(std, mathmaticalExpression);
}
sql += esArithmeticOperatorToString(mathmaticalExpression.Operator);
sql += GetExpressionColumn(std, query, mathmaticalExpression.SelectItem1, true, true);
}
sql += ")";
return sql;
}
protected static string esArithmeticOperatorToString(tgArithmeticOperator arithmeticOperator)
{
switch (arithmeticOperator)
{
case tgArithmeticOperator.Add: return " + ";
case tgArithmeticOperator.Subtract: return " - ";
case tgArithmeticOperator.Multiply: return " * ";
case tgArithmeticOperator.Divide: return " / ";
case tgArithmeticOperator.Modulo: return " % ";
default: return "";
}
}
protected static string GetMathmaticalExpressionLiteralType(StandardProviderParameters std, tgMathmaticalExpression mathmaticalExpression)
{
switch (mathmaticalExpression.LiteralType)
{
case tgSystemType.String:
return Delimiters.StringOpen + (string)mathmaticalExpression.Literal + Delimiters.StringClose;
case tgSystemType.DateTime:
return Delimiters.StringOpen + ((DateTime)(mathmaticalExpression.Literal)).ToShortDateString() + Delimiters.StringClose;
default:
return Convert.ToString(mathmaticalExpression.Literal);
}
}
protected static string ApplyWhereSubOperations(StandardProviderParameters std, tgDynamicQuerySerializable query, tgComparison.tgComparisonData comparisonData)
{
string sql = string.Empty;
if (comparisonData.HasExpression)
{
sql += GetMathmaticalExpressionColumn(std, query, comparisonData.Expression);
if (comparisonData.SubOperators != null && comparisonData.SubOperators.Count > 0)
{
sql = BuildSubOperationsSql(std, sql, comparisonData.SubOperators);
}
return sql;
}
string delimitedColumnName = GetColumnName(comparisonData.Column);
if (comparisonData.SubOperators != null)
{
sql = BuildSubOperationsSql(std, delimitedColumnName, comparisonData.SubOperators);
}
else
{
sql = delimitedColumnName;
}
return sql;
}
protected static string BuildSubOperationsSql(StandardProviderParameters std, string columnName, List<tgQuerySubOperator> subOperators)
{
string sql = string.Empty;
subOperators.Reverse();
Stack<object> stack = new Stack<object>();
if (subOperators != null)
{
foreach (tgQuerySubOperator op in subOperators)
{
switch (op.SubOperator)
{
case tgQuerySubOperatorType.ToLower:
sql += "LOWER(";
stack.Push(")");
break;
case tgQuerySubOperatorType.ToUpper:
sql += "UPPER(";
stack.Push(")");
break;
case tgQuerySubOperatorType.LTrim:
sql += "LTRIM(";
stack.Push(")");
break;
case tgQuerySubOperatorType.RTrim:
sql += "RTRIM(";
stack.Push(")");
break;
case tgQuerySubOperatorType.Trim:
sql += "LTRIM(RTRIM(";
stack.Push("))");
break;
case tgQuerySubOperatorType.SubString:
sql += "SUBSTRING(";
stack.Push(")");
stack.Push(op.Parameters["length"]);
stack.Push(",");
if (op.Parameters.ContainsKey("start"))
{
stack.Push(op.Parameters["start"]);
stack.Push(",");
}
else
{
// They didn't pass in start so we start
// at the beginning
stack.Push(1);
stack.Push(",");
}
break;
case tgQuerySubOperatorType.Coalesce:
sql += "COALESCE(";
stack.Push(")");
stack.Push(op.Parameters["expressions"]);
stack.Push(",");
break;
case tgQuerySubOperatorType.Date:
sql += "CAST(DATEPART(yyyy, ";
stack.Push(") AS VARCHAR)");
stack.Push(columnName);
stack.Push(") AS VARCHAR) + '-' + CAST(DATEPART(dd, ");
stack.Push(columnName);
stack.Push(") AS VARCHAR) + '-' + CAST(DATEPART(mm, ");
break;
case tgQuerySubOperatorType.Length:
sql += "LEN(";
stack.Push(")");
break;
case tgQuerySubOperatorType.Round:
sql += "ROUND(";
stack.Push(")");
stack.Push(op.Parameters["SignificantDigits"]);
stack.Push(",");
break;
case tgQuerySubOperatorType.DatePart:
sql += "DATEPART(";
sql += op.Parameters["DatePart"];
sql += ",";
stack.Push(")");
break;
case tgQuerySubOperatorType.Avg:
sql += "AVG(";
stack.Push(")");
break;
case tgQuerySubOperatorType.Count:
sql += "COUNT(";
stack.Push(")");
break;
case tgQuerySubOperatorType.Max:
sql += "MAX(";
stack.Push(")");
break;
case tgQuerySubOperatorType.Min:
sql += "MIN(";
stack.Push(")");
break;
case tgQuerySubOperatorType.StdDev:
sql += "STDEV(";
stack.Push(")");
break;
case tgQuerySubOperatorType.Sum:
sql += "SUM(";
stack.Push(")");
break;
case tgQuerySubOperatorType.Var:
sql += "VAR(";
stack.Push(")");
break;
case tgQuerySubOperatorType.Cast:
sql += "CAST(";
stack.Push(")");
if (op.Parameters.Count > 1)
{
stack.Push(")");
if (op.Parameters.Count == 2)
{
stack.Push(op.Parameters["length"].ToString());
}
else
{
stack.Push(op.Parameters["scale"].ToString());
stack.Push(",");
stack.Push(op.Parameters["precision"].ToString());
}
stack.Push("(");
}
stack.Push(GetCastSql((tgCastType)op.Parameters["tgCastType"]));
stack.Push(" AS ");
break;
}
}
sql += columnName;
while (stack.Count > 0)
{
sql += stack.Pop().ToString();
}
}
return sql;
}
protected static string GetCastSql(tgCastType castType)
{
switch (castType)
{
case tgCastType.Boolean: return "Bit";
case tgCastType.Byte: return "TinyInt";
case tgCastType.Char: return "Char";
case tgCastType.DateTime: return "DateTime";
case tgCastType.Double: return "Float";
case tgCastType.Decimal: return "Decimal";
case tgCastType.Guid: return "UniqueIdentifier";
case tgCastType.Int16: return "SmallInt";
case tgCastType.Int32: return "Int";
case tgCastType.Int64: return "BigInt";
case tgCastType.Single: return "Real";
case tgCastType.String: return "NVarChar";
default: return "error";
}
}
protected static string GetColumnName(tgColumnItem column)
{
if (column.Query == null || column.Query.tg.JoinAlias == " ")
{
return Delimiters.ColumnOpen + column.Name + Delimiters.ColumnClose;
}
else
{
IDynamicQuerySerializableInternal iQuery = column.Query as IDynamicQuerySerializableInternal;
if (iQuery.IsInSubQuery)
{
return column.Query.tg.JoinAlias + "." + Delimiters.ColumnOpen + column.Name + Delimiters.ColumnClose;
}
else
{
string alias = iQuery.SubQueryAlias == string.Empty ? iQuery.JoinAlias : iQuery.SubQueryAlias;
return alias + "." + Delimiters.ColumnOpen + column.Name + Delimiters.ColumnClose;
}
}
}
private static int NextParamIndex(IDbCommand cmd)
{
return cmd.Parameters.Count;
}
private static string GetSubquerySearchCondition(tgDynamicQuerySerializable query)
{
string searchCondition = String.Empty;
IDynamicQuerySerializableInternal iQuery = query as IDynamicQuerySerializableInternal;
switch (iQuery.SubquerySearchCondition)
{
case tgSubquerySearchCondition.All: searchCondition = "ALL"; break;
case tgSubquerySearchCondition.Any: searchCondition = "ANY"; break;
case tgSubquerySearchCondition.Some: searchCondition = "SOME"; break;
}
return searchCondition;
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Web;
using Nop.Core;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Directory;
using Nop.Core.Domain.Messages;
using Nop.Services.Catalog;
using Nop.Services.Directory;
using Nop.Services.Media;
using Nop.Services.Messages;
using Nop.Services.Seo;
using OfficeOpenXml;
namespace Nop.Services.ExportImport
{
/// <summary>
/// Import manager
/// </summary>
public partial class ImportManager : IImportManager
{
#region Fields
private readonly IProductService _productService;
private readonly ICategoryService _categoryService;
private readonly IManufacturerService _manufacturerService;
private readonly IPictureService _pictureService;
private readonly IUrlRecordService _urlRecordService;
private readonly IStoreContext _storeContext;
private readonly INewsLetterSubscriptionService _newsLetterSubscriptionService;
private readonly ICountryService _countryService;
private readonly IStateProvinceService _stateProvinceService;
#endregion
#region Ctor
public ImportManager(IProductService productService,
ICategoryService categoryService,
IManufacturerService manufacturerService,
IPictureService pictureService,
IUrlRecordService urlRecordService,
IStoreContext storeContext,
INewsLetterSubscriptionService newsLetterSubscriptionService,
ICountryService countryService,
IStateProvinceService stateProvinceService)
{
this._productService = productService;
this._categoryService = categoryService;
this._manufacturerService = manufacturerService;
this._pictureService = pictureService;
this._urlRecordService = urlRecordService;
this._storeContext = storeContext;
this._newsLetterSubscriptionService = newsLetterSubscriptionService;
this._countryService = countryService;
this._stateProvinceService = stateProvinceService;
}
#endregion
#region Utilities
protected virtual int GetColumnIndex(string[] properties, string columnName)
{
if (properties == null)
throw new ArgumentNullException("properties");
if (columnName == null)
throw new ArgumentNullException("columnName");
for (int i = 0; i < properties.Length; i++)
if (properties[i].Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
return i + 1; //excel indexes start from 1
return 0;
}
protected virtual string ConvertColumnToString(object columnValue)
{
if (columnValue == null)
return null;
return Convert.ToString(columnValue);
}
protected virtual string GetMimeTypeFromFilePath(string filePath)
{
var mimeType = MimeMapping.GetMimeMapping(filePath);
//little hack here because MimeMapping does not contain all mappings (e.g. PNG)
if (mimeType == "application/octet-stream")
mimeType = "image/jpeg";
return mimeType;
}
#endregion
#region Methods
/// <summary>
/// Import products from XLSX file
/// </summary>
/// <param name="stream">Stream</param>
public virtual void ImportProductsFromXlsx(Stream stream)
{
// ok, we can run the real code of the sample now
using (var xlPackage = new ExcelPackage(stream))
{
// get the first worksheet in the workbook
var worksheet = xlPackage.Workbook.Worksheets.FirstOrDefault();
if (worksheet == null)
throw new NopException("No worksheet found");
//the columns
var properties = new []
{
"ProductTypeId",
"ParentGroupedProductId",
"VisibleIndividually",
"Name",
"ShortDescription",
"FullDescription",
"VendorId",
"ProductTemplateId",
"ShowOnHomePage",
"MetaKeywords",
"MetaDescription",
"MetaTitle",
"SeName",
"AllowCustomerReviews",
"Published",
"SKU",
"ManufacturerPartNumber",
"Gtin",
"IsGiftCard",
"GiftCardTypeId",
"OverriddenGiftCardAmount",
"RequireOtherProducts",
"RequiredProductIds",
"AutomaticallyAddRequiredProducts",
"IsDownload",
"DownloadId",
"UnlimitedDownloads",
"MaxNumberOfDownloads",
"DownloadActivationTypeId",
"HasSampleDownload",
"SampleDownloadId",
"HasUserAgreement",
"UserAgreementText",
"IsRecurring",
"RecurringCycleLength",
"RecurringCyclePeriodId",
"RecurringTotalCycles",
"IsRental",
"RentalPriceLength",
"RentalPricePeriodId",
"IsShipEnabled",
"IsFreeShipping",
"ShipSeparately",
"AdditionalShippingCharge",
"DeliveryDateId",
"IsTaxExempt",
"TaxCategoryId",
"IsTelecommunicationsOrBroadcastingOrElectronicServices",
"ManageInventoryMethodId",
"UseMultipleWarehouses",
"WarehouseId",
"StockQuantity",
"DisplayStockAvailability",
"DisplayStockQuantity",
"MinStockQuantity",
"LowStockActivityId",
"NotifyAdminForQuantityBelow",
"BackorderModeId",
"AllowBackInStockSubscriptions",
"OrderMinimumQuantity",
"OrderMaximumQuantity",
"AllowedQuantities",
"AllowAddingOnlyExistingAttributeCombinations",
"DisableBuyButton",
"DisableWishlistButton",
"AvailableForPreOrder",
"PreOrderAvailabilityStartDateTimeUtc",
"CallForPrice",
"Price",
"OldPrice",
"ProductCost",
"SpecialPrice",
"SpecialPriceStartDateTimeUtc",
"SpecialPriceEndDateTimeUtc",
"CustomerEntersPrice",
"MinimumCustomerEnteredPrice",
"MaximumCustomerEnteredPrice",
"BasepriceEnabled",
"BasepriceAmount",
"BasepriceUnitId",
"BasepriceBaseAmount",
"BasepriceBaseUnitId",
"MarkAsNew",
"MarkAsNewStartDateTimeUtc",
"MarkAsNewEndDateTimeUtc",
"Weight",
"Length",
"Width",
"Height",
"CreatedOnUtc",
"CategoryIds",
"ManufacturerIds",
"Picture1",
"Picture2",
"Picture3"
};
int iRow = 2;
while (true)
{
bool allColumnsAreEmpty = true;
for (var i = 1; i <= properties.Length; i++)
if (worksheet.Cells[iRow, i].Value != null && !String.IsNullOrEmpty(worksheet.Cells[iRow, i].Value.ToString()))
{
allColumnsAreEmpty = false;
break;
}
if (allColumnsAreEmpty)
break;
int productTypeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductTypeId")].Value);
int parentGroupedProductId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ParentGroupedProductId")].Value);
bool visibleIndividually = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "VisibleIndividually")].Value);
string name = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Name")].Value);
string shortDescription = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "ShortDescription")].Value);
string fullDescription = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "FullDescription")].Value);
int vendorId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "VendorId")].Value);
int productTemplateId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductTemplateId")].Value);
bool showOnHomePage = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "ShowOnHomePage")].Value);
string metaKeywords = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "MetaKeywords")].Value);
string metaDescription = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "MetaDescription")].Value);
string metaTitle = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "MetaTitle")].Value);
string seName = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "SeName")].Value);
bool allowCustomerReviews = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowCustomerReviews")].Value);
bool published = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "Published")].Value);
string sku = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "SKU")].Value);
string manufacturerPartNumber = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "ManufacturerPartNumber")].Value);
string gtin = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Gtin")].Value);
bool isGiftCard = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsGiftCard")].Value);
int giftCardTypeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "GiftCardTypeId")].Value);
decimal? overriddenGiftCardAmount = null;
var overriddenGiftCardAmountExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "OverriddenGiftCardAmount")].Value;
if (overriddenGiftCardAmountExcel != null)
overriddenGiftCardAmount = Convert.ToDecimal(overriddenGiftCardAmountExcel);
bool requireOtherProducts = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "RequireOtherProducts")].Value);
string requiredProductIds = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "RequiredProductIds")].Value);
bool automaticallyAddRequiredProducts = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AutomaticallyAddRequiredProducts")].Value);
bool isDownload = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsDownload")].Value);
int downloadId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DownloadId")].Value);
bool unlimitedDownloads = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "UnlimitedDownloads")].Value);
int maxNumberOfDownloads = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "MaxNumberOfDownloads")].Value);
int downloadActivationTypeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DownloadActivationTypeId")].Value);
bool hasSampleDownload = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "HasSampleDownload")].Value);
int sampleDownloadId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "SampleDownloadId")].Value);
bool hasUserAgreement = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "HasUserAgreement")].Value);
string userAgreementText = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "UserAgreementText")].Value);
bool isRecurring = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsRecurring")].Value);
int recurringCycleLength = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringCycleLength")].Value);
int recurringCyclePeriodId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringCyclePeriodId")].Value);
int recurringTotalCycles = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RecurringTotalCycles")].Value);
bool isRental = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsRental")].Value);
int rentalPriceLength = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RentalPriceLength")].Value);
int rentalPricePeriodId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "RentalPricePeriodId")].Value);
bool isShipEnabled = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsShipEnabled")].Value);
bool isFreeShipping = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsFreeShipping")].Value);
bool shipSeparately = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "ShipSeparately")].Value);
decimal additionalShippingCharge = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "AdditionalShippingCharge")].Value);
int deliveryDateId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "DeliveryDateId")].Value);
bool isTaxExempt = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsTaxExempt")].Value);
int taxCategoryId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "TaxCategoryId")].Value);
bool isTelecommunicationsOrBroadcastingOrElectronicServices = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "IsTelecommunicationsOrBroadcastingOrElectronicServices")].Value);
int manageInventoryMethodId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "ManageInventoryMethodId")].Value);
bool useMultipleWarehouses = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "UseMultipleWarehouses")].Value);
int warehouseId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "WarehouseId")].Value);
int stockQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "StockQuantity")].Value);
bool displayStockAvailability = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisplayStockAvailability")].Value);
bool displayStockQuantity = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisplayStockQuantity")].Value);
int minStockQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "MinStockQuantity")].Value);
int lowStockActivityId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "LowStockActivityId")].Value);
int notifyAdminForQuantityBelow = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "NotifyAdminForQuantityBelow")].Value);
int backorderModeId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "BackorderModeId")].Value);
bool allowBackInStockSubscriptions = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowBackInStockSubscriptions")].Value);
int orderMinimumQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "OrderMinimumQuantity")].Value);
int orderMaximumQuantity = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "OrderMaximumQuantity")].Value);
string allowedQuantities = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowedQuantities")].Value);
bool allowAddingOnlyExistingAttributeCombinations = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AllowAddingOnlyExistingAttributeCombinations")].Value);
bool disableBuyButton = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisableBuyButton")].Value);
bool disableWishlistButton = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "DisableWishlistButton")].Value);
bool availableForPreOrder = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "AvailableForPreOrder")].Value);
DateTime? preOrderAvailabilityStartDateTimeUtc = null;
var preOrderAvailabilityStartDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "PreOrderAvailabilityStartDateTimeUtc")].Value;
if (preOrderAvailabilityStartDateTimeUtcExcel != null)
preOrderAvailabilityStartDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(preOrderAvailabilityStartDateTimeUtcExcel));
bool callForPrice = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "CallForPrice")].Value);
decimal price = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Price")].Value);
decimal oldPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "OldPrice")].Value);
decimal productCost = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "ProductCost")].Value);
decimal? specialPrice = null;
var specialPriceExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPrice")].Value;
if (specialPriceExcel != null)
specialPrice = Convert.ToDecimal(specialPriceExcel);
DateTime? specialPriceStartDateTimeUtc = null;
var specialPriceStartDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPriceStartDateTimeUtc")].Value;
if (specialPriceStartDateTimeUtcExcel != null)
specialPriceStartDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(specialPriceStartDateTimeUtcExcel));
DateTime? specialPriceEndDateTimeUtc = null;
var specialPriceEndDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "SpecialPriceEndDateTimeUtc")].Value;
if (specialPriceEndDateTimeUtcExcel != null)
specialPriceEndDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(specialPriceEndDateTimeUtcExcel));
bool customerEntersPrice = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "CustomerEntersPrice")].Value);
decimal minimumCustomerEnteredPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "MinimumCustomerEnteredPrice")].Value);
decimal maximumCustomerEnteredPrice = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "MaximumCustomerEnteredPrice")].Value);
bool basepriceEnabled = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceEnabled")].Value);
decimal basepriceAmount = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceAmount")].Value);
int basepriceUnitId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceUnitId")].Value);
decimal basepriceBaseAmount = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceBaseAmount")].Value);
int basepriceBaseUnitId = Convert.ToInt32(worksheet.Cells[iRow, GetColumnIndex(properties, "BasepriceBaseUnitId")].Value);
bool markAsNew = Convert.ToBoolean(worksheet.Cells[iRow, GetColumnIndex(properties, "MarkAsNew")].Value);
DateTime? markAsNewStartDateTimeUtc = null;
var markAsNewStartDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "MarkAsNewStartDateTimeUtc")].Value;
if (markAsNewStartDateTimeUtcExcel != null)
markAsNewStartDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(markAsNewStartDateTimeUtcExcel));
DateTime? markAsNewEndDateTimeUtc = null;
var markAsNewEndDateTimeUtcExcel = worksheet.Cells[iRow, GetColumnIndex(properties, "MarkAsNewEndDateTimeUtc")].Value;
if (markAsNewEndDateTimeUtcExcel != null)
markAsNewEndDateTimeUtc = DateTime.FromOADate(Convert.ToDouble(markAsNewEndDateTimeUtcExcel));
decimal weight = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Weight")].Value);
decimal length = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Length")].Value);
decimal width = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Width")].Value);
decimal height = Convert.ToDecimal(worksheet.Cells[iRow, GetColumnIndex(properties, "Height")].Value);
DateTime createdOnUtc = DateTime.FromOADate(Convert.ToDouble(worksheet.Cells[iRow, GetColumnIndex(properties, "CreatedOnUtc")].Value));
string categoryIds = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "CategoryIds")].Value);
string manufacturerIds = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "ManufacturerIds")].Value);
string picture1 = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Picture1")].Value);
string picture2 = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Picture2")].Value);
string picture3 = ConvertColumnToString(worksheet.Cells[iRow, GetColumnIndex(properties, "Picture3")].Value);
var product = _productService.GetProductBySku(sku);
bool newProduct = false;
if (product == null)
{
product = new Product();
newProduct = true;
}
product.ProductTypeId = productTypeId;
product.ParentGroupedProductId = parentGroupedProductId;
product.VisibleIndividually = visibleIndividually;
product.Name = name;
product.ShortDescription = shortDescription;
product.FullDescription = fullDescription;
product.VendorId = vendorId;
product.ProductTemplateId = productTemplateId;
product.ShowOnHomePage = showOnHomePage;
product.MetaKeywords = metaKeywords;
product.MetaDescription = metaDescription;
product.MetaTitle = metaTitle;
product.AllowCustomerReviews = allowCustomerReviews;
product.Sku = sku;
product.ManufacturerPartNumber = manufacturerPartNumber;
product.Gtin = gtin;
product.IsGiftCard = isGiftCard;
product.GiftCardTypeId = giftCardTypeId;
product.OverriddenGiftCardAmount = overriddenGiftCardAmount;
product.RequireOtherProducts = requireOtherProducts;
product.RequiredProductIds = requiredProductIds;
product.AutomaticallyAddRequiredProducts = automaticallyAddRequiredProducts;
product.IsDownload = isDownload;
product.DownloadId = downloadId;
product.UnlimitedDownloads = unlimitedDownloads;
product.MaxNumberOfDownloads = maxNumberOfDownloads;
product.DownloadActivationTypeId = downloadActivationTypeId;
product.HasSampleDownload = hasSampleDownload;
product.SampleDownloadId = sampleDownloadId;
product.HasUserAgreement = hasUserAgreement;
product.UserAgreementText = userAgreementText;
product.IsRecurring = isRecurring;
product.RecurringCycleLength = recurringCycleLength;
product.RecurringCyclePeriodId = recurringCyclePeriodId;
product.RecurringTotalCycles = recurringTotalCycles;
product.IsRental = isRental;
product.RentalPriceLength = rentalPriceLength;
product.RentalPricePeriodId = rentalPricePeriodId;
product.IsShipEnabled = isShipEnabled;
product.IsFreeShipping = isFreeShipping;
product.ShipSeparately = shipSeparately;
product.AdditionalShippingCharge = additionalShippingCharge;
product.DeliveryDateId = deliveryDateId;
product.IsTaxExempt = isTaxExempt;
product.TaxCategoryId = taxCategoryId;
product.IsTelecommunicationsOrBroadcastingOrElectronicServices = isTelecommunicationsOrBroadcastingOrElectronicServices;
product.ManageInventoryMethodId = manageInventoryMethodId;
product.UseMultipleWarehouses = useMultipleWarehouses;
product.WarehouseId = warehouseId;
product.StockQuantity = stockQuantity;
product.DisplayStockAvailability = displayStockAvailability;
product.DisplayStockQuantity = displayStockQuantity;
product.MinStockQuantity = minStockQuantity;
product.LowStockActivityId = lowStockActivityId;
product.NotifyAdminForQuantityBelow = notifyAdminForQuantityBelow;
product.BackorderModeId = backorderModeId;
product.AllowBackInStockSubscriptions = allowBackInStockSubscriptions;
product.OrderMinimumQuantity = orderMinimumQuantity;
product.OrderMaximumQuantity = orderMaximumQuantity;
product.AllowedQuantities = allowedQuantities;
product.AllowAddingOnlyExistingAttributeCombinations = allowAddingOnlyExistingAttributeCombinations;
product.DisableBuyButton = disableBuyButton;
product.DisableWishlistButton = disableWishlistButton;
product.AvailableForPreOrder = availableForPreOrder;
product.PreOrderAvailabilityStartDateTimeUtc = preOrderAvailabilityStartDateTimeUtc;
product.CallForPrice = callForPrice;
product.Price = price;
product.OldPrice = oldPrice;
product.ProductCost = productCost;
product.SpecialPrice = specialPrice;
product.SpecialPriceStartDateTimeUtc = specialPriceStartDateTimeUtc;
product.SpecialPriceEndDateTimeUtc = specialPriceEndDateTimeUtc;
product.CustomerEntersPrice = customerEntersPrice;
product.MinimumCustomerEnteredPrice = minimumCustomerEnteredPrice;
product.MaximumCustomerEnteredPrice = maximumCustomerEnteredPrice;
product.BasepriceEnabled = basepriceEnabled;
product.BasepriceAmount = basepriceAmount;
product.BasepriceUnitId = basepriceUnitId;
product.BasepriceBaseAmount = basepriceBaseAmount;
product.BasepriceBaseUnitId = basepriceBaseUnitId;
product.MarkAsNew = markAsNew;
product.MarkAsNewStartDateTimeUtc = markAsNewStartDateTimeUtc;
product.MarkAsNewEndDateTimeUtc = markAsNewEndDateTimeUtc;
product.Weight = weight;
product.Length = length;
product.Width = width;
product.Height = height;
product.Published = published;
product.CreatedOnUtc = createdOnUtc;
product.UpdatedOnUtc = DateTime.UtcNow;
if (newProduct)
{
_productService.InsertProduct(product);
}
else
{
_productService.UpdateProduct(product);
}
//search engine name
_urlRecordService.SaveSlug(product, product.ValidateSeName(seName, product.Name, true), 0);
//category mappings
if (!String.IsNullOrEmpty(categoryIds))
{
foreach (var id in categoryIds.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim())))
{
if (product.ProductCategories.FirstOrDefault(x => x.CategoryId == id) == null)
{
//ensure that category exists
var category = _categoryService.GetCategoryById(id);
if (category != null)
{
var productCategory = new ProductCategory
{
ProductId = product.Id,
CategoryId = category.Id,
IsFeaturedProduct = false,
DisplayOrder = 1
};
_categoryService.InsertProductCategory(productCategory);
}
}
}
}
//manufacturer mappings
if (!String.IsNullOrEmpty(manufacturerIds))
{
foreach (var id in manufacturerIds.Split(new [] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(x => Convert.ToInt32(x.Trim())))
{
if (product.ProductManufacturers.FirstOrDefault(x => x.ManufacturerId == id) == null)
{
//ensure that manufacturer exists
var manufacturer = _manufacturerService.GetManufacturerById(id);
if (manufacturer != null)
{
var productManufacturer = new ProductManufacturer
{
ProductId = product.Id,
ManufacturerId = manufacturer.Id,
IsFeaturedProduct = false,
DisplayOrder = 1
};
_manufacturerService.InsertProductManufacturer(productManufacturer);
}
}
}
}
//pictures
foreach (var picturePath in new [] { picture1, picture2, picture3 })
{
if (String.IsNullOrEmpty(picturePath))
continue;
var mimeType = GetMimeTypeFromFilePath(picturePath);
var newPictureBinary = File.ReadAllBytes(picturePath);
var pictureAlreadyExists = false;
if (!newProduct)
{
//compare with existing product pictures
var existingPictures = _pictureService.GetPicturesByProductId(product.Id);
foreach (var existingPicture in existingPictures)
{
var existingBinary = _pictureService.LoadPictureBinary(existingPicture);
//picture binary after validation (like in database)
var validatedPictureBinary = _pictureService.ValidatePicture(newPictureBinary, mimeType);
if (existingBinary.SequenceEqual(validatedPictureBinary) || existingBinary.SequenceEqual(newPictureBinary))
{
//the same picture content
pictureAlreadyExists = true;
break;
}
}
}
if (!pictureAlreadyExists)
{
var newPicture = _pictureService.InsertPicture(newPictureBinary, mimeType , _pictureService.GetPictureSeName(name));
product.ProductPictures.Add(new ProductPicture
{
//EF has some weird issue if we set "Picture = newPicture" instead of "PictureId = newPicture.Id"
//pictures are duplicated
//maybe because entity size is too large
PictureId = newPicture.Id,
DisplayOrder = 1,
});
_productService.UpdateProduct(product);
}
}
//update "HasTierPrices" and "HasDiscountsApplied" properties
_productService.UpdateHasTierPricesProperty(product);
_productService.UpdateHasDiscountsApplied(product);
//next product
iRow++;
}
}
}
/// <summary>
/// Import newsletter subscribers from TXT file
/// </summary>
/// <param name="stream">Stream</param>
/// <returns>Number of imported subscribers</returns>
public virtual int ImportNewsletterSubscribersFromTxt(Stream stream)
{
int count = 0;
using (var reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (String.IsNullOrWhiteSpace(line))
continue;
string[] tmp = line.Split(',');
string email;
bool isActive = true;
int storeId = _storeContext.CurrentStore.Id;
//parse
if (tmp.Length == 1)
{
//"email" only
email = tmp[0].Trim();
}
else if (tmp.Length == 2)
{
//"email" and "active" fields specified
email = tmp[0].Trim();
isActive = Boolean.Parse(tmp[1].Trim());
}
else if (tmp.Length == 3)
{
//"email" and "active" and "storeId" fields specified
email = tmp[0].Trim();
isActive = Boolean.Parse(tmp[1].Trim());
storeId = Int32.Parse(tmp[2].Trim());
}
else
throw new NopException("Wrong file format");
//import
var subscription = _newsLetterSubscriptionService.GetNewsLetterSubscriptionByEmailAndStoreId(email, storeId);
if (subscription != null)
{
subscription.Email = email;
subscription.Active = isActive;
_newsLetterSubscriptionService.UpdateNewsLetterSubscription(subscription);
}
else
{
subscription = new NewsLetterSubscription
{
Active = isActive,
CreatedOnUtc = DateTime.UtcNow,
Email = email,
StoreId = storeId,
NewsLetterSubscriptionGuid = Guid.NewGuid()
};
_newsLetterSubscriptionService.InsertNewsLetterSubscription(subscription);
}
count++;
}
}
return count;
}
/// <summary>
/// Import states from TXT file
/// </summary>
/// <param name="stream">Stream</param>
/// <returns>Number of imported states</returns>
public virtual int ImportStatesFromTxt(Stream stream)
{
int count = 0;
using (var reader = new StreamReader(stream))
{
while (!reader.EndOfStream)
{
string line = reader.ReadLine();
if (String.IsNullOrWhiteSpace(line))
continue;
string[] tmp = line.Split(',');
if (tmp.Length != 5)
throw new NopException("Wrong file format");
//parse
var countryTwoLetterIsoCode = tmp[0].Trim();
var name = tmp[1].Trim();
var abbreviation = tmp[2].Trim();
bool published = Boolean.Parse(tmp[3].Trim());
int displayOrder = Int32.Parse(tmp[4].Trim());
var country = _countryService.GetCountryByTwoLetterIsoCode(countryTwoLetterIsoCode);
if (country == null)
{
//country cannot be loaded. skip
continue;
}
//import
var states = _stateProvinceService.GetStateProvincesByCountryId(country.Id, showHidden: true);
var state = states.FirstOrDefault(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase));
if (state != null)
{
state.Abbreviation = abbreviation;
state.Published = published;
state.DisplayOrder = displayOrder;
_stateProvinceService.UpdateStateProvince(state);
}
else
{
state = new StateProvince
{
CountryId = country.Id,
Name = name,
Abbreviation = abbreviation,
Published = published,
DisplayOrder = displayOrder,
};
_stateProvinceService.InsertStateProvince(state);
}
count++;
}
}
return count;
}
#endregion
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace LumiSoft.Net.IO
{
/// <summary>
/// This class implements base64 encoder/decoder. Defined in RFC 4648.
/// </summary>
public class Base64Stream : Stream,IDisposable
{
private readonly static byte[] BASE64_ENCODE_TABLE = new byte[]{
(byte)'A',(byte)'B',(byte)'C',(byte)'D',(byte)'E',(byte)'F',(byte)'G',(byte)'H',(byte)'I',(byte)'J',
(byte)'K',(byte)'L',(byte)'M',(byte)'N',(byte)'O',(byte)'P',(byte)'Q',(byte)'R',(byte)'S',(byte)'T',
(byte)'U',(byte)'V',(byte)'W',(byte)'X',(byte)'Y',(byte)'Z',(byte)'a',(byte)'b',(byte)'c',(byte)'d',
(byte)'e',(byte)'f',(byte)'g',(byte)'h',(byte)'i',(byte)'j',(byte)'k',(byte)'l',(byte)'m',(byte)'n',
(byte)'o',(byte)'p',(byte)'q',(byte)'r',(byte)'s',(byte)'t',(byte)'u',(byte)'v',(byte)'w',(byte)'x',
(byte)'y',(byte)'z',(byte)'0',(byte)'1',(byte)'2',(byte)'3',(byte)'4',(byte)'5',(byte)'6',(byte)'7',
(byte)'8',(byte)'9',(byte)'+',(byte)'/'
};
private readonly static short[] BASE64_DECODE_TABLE = new short[]{
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, // 0 - 9
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, //10 - 19
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, //20 - 29
-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, //30 - 39
-1,-1,-1,62,-1,-1,-1,63,52,53, //40 - 49
54,55,56,57,58,59,60,61,-1,-1, //50 - 59
-1,-1,-1,-1,-1, 0, 1, 2, 3, 4, //60 - 69
5, 6, 7, 8, 9,10,11,12,13,14, //70 - 79
15,16,17,18,19,20,21,22,23,24, //80 - 89
25,-1,-1,-1,-1,-1,-1,26,27,28, //90 - 99
29,30,31,32,33,34,35,36,37,38, //100 - 109
39,40,41,42,43,44,45,46,47,48, //110 - 119
49,50,51,-1,-1,-1,-1,-1 //120 - 127
};
private bool m_IsDisposed = false;
private bool m_IsFinished = false;
private Stream m_pStream = null;
private bool m_IsOwner = false;
private bool m_AddLineBreaks = true;
private FileAccess m_AccessMode = FileAccess.ReadWrite;
private int m_EncodeBufferOffset = 0;
private int m_OffsetInEncode3x8Block = 0;
private byte[] m_pEncode3x8Block = new byte[3];
private byte[] m_pEncodeBuffer = new byte[78];
private Queue<byte> m_pDecodeReminder = null;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="stream">Stream which to encode/decode.</param>
/// <param name="owner">Specifies if Base64Stream is owner of <b>stream</b>.</param>
/// <param name="addLineBreaks">Specifies if encoder inserts CRLF after each 76 bytes.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception>
public Base64Stream(Stream stream,bool owner,bool addLineBreaks) : this(stream,owner,addLineBreaks,FileAccess.ReadWrite)
{
}
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="stream">Stream which to encode/decode.</param>
/// <param name="owner">Specifies if Base64Stream is owner of <b>stream</b>.</param>
/// <param name="addLineBreaks">Specifies if encoder inserts CRLF after each 76 bytes.</param>
/// <param name="access">This stream access mode.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception>
public Base64Stream(Stream stream,bool owner,bool addLineBreaks,FileAccess access)
{
if(stream == null){
throw new ArgumentNullException("stream");
}
m_pStream = stream;
m_IsOwner = owner;
m_AddLineBreaks = addLineBreaks;
m_AccessMode = access;
m_pDecodeReminder = new Queue<byte>();
}
#region method Dispose
/// <summary>
/// Celans up any resources being used.
/// </summary>
public new void Dispose()
{
if(m_IsDisposed){
return;
}
try{
Finish();
}
catch{
}
m_IsDisposed = true;
if(m_IsOwner){
m_pStream.Close();
}
}
#endregion
#region override method Flush
/// <summary>
/// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
public override void Flush()
{
if(m_IsDisposed){
throw new ObjectDisposedException("Base64Stream");
}
}
#endregion
#region override method Seek
/// <summary>
/// Sets the position within the current stream. This method is not supported and always throws a NotSupportedException.
/// </summary>
/// <param name="offset">A byte offset relative to the <b>origin</b> parameter.</param>
/// <param name="origin">A value of type SeekOrigin indicating the reference point used to obtain the new position.</param>
/// <returns>The new position within the current stream.</returns>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
/// <exception cref="NotSupportedException">Is raised when this method is accessed.</exception>
public override long Seek(long offset,SeekOrigin origin)
{
if(m_IsDisposed){
throw new ObjectDisposedException("Base64Stream");
}
throw new NotSupportedException();
}
#endregion
#region override method SetLength
/// <summary>
/// Sets the length of the current stream. This method is not supported and always throws a NotSupportedException.
/// </summary>
/// <param name="value">The desired length of the current stream in bytes.</param>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
/// <exception cref="Seek">Is raised when this method is accessed.</exception>
public override void SetLength(long value)
{
if(m_IsDisposed){
throw new ObjectDisposedException("Base64Stream");
}
throw new NotSupportedException();
}
#endregion
#region override method Read
/// <summary>
/// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between offset and (offset + count - 1) replaced by the bytes read from the current source.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.</returns>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
/// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception>
/// <exception cref="NotSupportedException">Is raised when reading not supported.</exception>
public override int Read(byte[] buffer,int offset,int count)
{
if(m_IsDisposed){
throw new ObjectDisposedException("Base64Stream");
}
if(buffer == null){
throw new ArgumentNullException("buffer");
}
if((m_AccessMode & FileAccess.Read) == 0){
throw new NotSupportedException();
}
/* RFC 4648.
Base64 is processed from left to right by 4 6-bit byte block, 4 6-bit byte block
are converted to 3 8-bit bytes.
If base64 4 byte block doesn't have 3 8-bit bytes, missing bytes are marked with =.
Value Encoding Value Encoding Value Encoding Value Encoding
0 A 17 R 34 i 51 z
1 B 18 S 35 j 52 0
2 C 19 T 36 k 53 1
3 D 20 U 37 l 54 2
4 E 21 V 38 m 55 3
5 F 22 W 39 n 56 4
6 G 23 X 40 o 57 5
7 H 24 Y 41 p 58 6
8 I 25 Z 42 q 59 7
9 J 26 a 43 r 60 8
10 K 27 b 44 s 61 9
11 L 28 c 45 t 62 +
12 M 29 d 46 u 63 /
13 N 30 e 47 v
14 O 31 f 48 w (pad) =
15 P 32 g 49 x
16 Q 33 h 50 y
NOTE: 4 base64 6-bit bytes = 3 8-bit bytes
// | 6-bit | 6-bit | 6-bit | 6-bit |
// | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 |
// | 8-bit | 8-bit | 8-bit |
*/
int storedInBuffer = 0;
// If we have decoded-buffered bytes, use them first.
while(m_pDecodeReminder.Count > 0){
buffer[offset++] = m_pDecodeReminder.Dequeue();
storedInBuffer++;
count--;
// We filled whole "buffer", no more room.
if(count == 0){
return storedInBuffer;
}
}
// 1) Calculate as much we can decode to "buffer". !!! We need to read as 4x7-bit blocks.
int rawBytesToRead = (int)Math.Ceiling((double)count / 3.0) * 4;
byte[] readBuffer = new byte[rawBytesToRead];
short[] decodeBlock = new short[4];
byte[] decodedBlock = new byte[3];
int decodeBlockOffset = 0;
int paddedCount = 0;
// Decode while we have room in "buffer".
while(storedInBuffer < count){
int readedCount = m_pStream.Read(readBuffer,0,rawBytesToRead);
// We reached end of stream, no more data.
if(readedCount == 0){
// We have last block without padding 1 char.
if(decodeBlockOffset == 3){
buffer[offset + storedInBuffer++] = (byte)(decodeBlock[0] << 2 | decodeBlock[1] >> 4);
// See if "buffer" can accomodate 2 byte.
if(storedInBuffer < count){
buffer[offset + storedInBuffer++] = (byte)((decodeBlock[1] & 0xF) << 4 | decodeBlock[2] >> 2);
}
else{
m_pDecodeReminder.Enqueue((byte)((decodeBlock[1] & 0xF) << 4 | decodeBlock[2] >> 2));
}
}
// We have last block without padding 2 chars.
else if(decodeBlockOffset == 2){
buffer[offset + storedInBuffer++] = (byte)(decodeBlock[0] << 2 | decodeBlock[1] >> 4);
}
// We have invalid base64 data.
else if(decodeBlockOffset == 1){
throw new InvalidDataException("Incomplete base64 data..");
}
return storedInBuffer;
}
// Process readed bytes.
for(int i=0;i<readedCount;i++){
byte b = readBuffer[i];
// If padding char.
if(b == '='){
decodeBlock[decodeBlockOffset++] = (byte)'=';
paddedCount++;
rawBytesToRead--;
}
// If base64 char.
else if(BASE64_DECODE_TABLE[b] != -1){
decodeBlock[decodeBlockOffset++] = BASE64_DECODE_TABLE[b];
rawBytesToRead--;
}
// Non-base64 char, skip it.
else{
}
// Decode block full, decode bytes.
if(decodeBlockOffset == 4){
// Decode 3x8-bit block.
decodedBlock[0] = (byte)(decodeBlock[0] << 2 | decodeBlock[1] >> 4);
decodedBlock[1] = (byte)((decodeBlock[1] & 0xF) << 4 | decodeBlock[2] >> 2);
decodedBlock[2] = (byte)((decodeBlock[2] & 0x3) << 6 | decodeBlock[3] >> 0);
// Invalid base64 data. Base64 final quantum may have max 2 padding chars.
if(paddedCount > 2){
throw new InvalidDataException("Invalid base64 data, more than 2 padding chars(=).");
}
for(int n=0;n<(3 - paddedCount);n++){
// We have room in "buffer", store byte there.
if(storedInBuffer < count){
buffer[offset + storedInBuffer++] = decodedBlock[n];
}
//No room in "buffer", store reminder.
else{
m_pDecodeReminder.Enqueue(decodedBlock[n]);
}
}
decodeBlockOffset = 0;
paddedCount = 0;
}
}
}
return storedInBuffer;
}
#endregion
#region overide method Write
/// <summary>
/// Encodes a sequence of bytes, writes to the current stream and advances the current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current stream.</param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
/// <exception cref="InvalidOperationException">Is raised when this.Finish has been called and this method is accessed.</exception>
/// <exception cref="ArgumentNullException">Is raised when <b>buffer</b> is null reference.</exception>
/// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception>
/// <exception cref="NotSupportedException">Is raised when reading not supported.</exception>
public override void Write(byte[] buffer,int offset,int count)
{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
if(m_IsFinished){
throw new InvalidOperationException("Stream is marked as finished by calling Finish method.");
}
if(buffer == null){
throw new ArgumentNullException("buffer");
}
if(offset < 0 || offset > buffer.Length){
throw new ArgumentException("Invalid argument 'offset' value.");
}
if(count < 0 || count > (buffer.Length - offset)){
throw new ArgumentException("Invalid argument 'count' value.");
}
if((m_AccessMode & FileAccess.Write) == 0){
throw new NotSupportedException();
}
/* RFC 4648.
Base64 is processed from left to right by 4 6-bit byte block, 4 6-bit byte block
are converted to 3 8-bit bytes.
If base64 4 byte block doesn't have 3 8-bit bytes, missing bytes are marked with =.
Value Encoding Value Encoding Value Encoding Value Encoding
0 A 17 R 34 i 51 z
1 B 18 S 35 j 52 0
2 C 19 T 36 k 53 1
3 D 20 U 37 l 54 2
4 E 21 V 38 m 55 3
5 F 22 W 39 n 56 4
6 G 23 X 40 o 57 5
7 H 24 Y 41 p 58 6
8 I 25 Z 42 q 59 7
9 J 26 a 43 r 60 8
10 K 27 b 44 s 61 9
11 L 28 c 45 t 62 +
12 M 29 d 46 u 63 /
13 N 30 e 47 v
14 O 31 f 48 w (pad) =
15 P 32 g 49 x
16 Q 33 h 50 y
NOTE: 4 base64 6-bit bytes = 3 8-bit bytes
// | 6-bit | 6-bit | 6-bit | 6-bit |
// | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 | 1 2 3 4 5 6 |
// | 8-bit | 8-bit | 8-bit |
*/
int encodeBufSize = m_pEncodeBuffer.Length;
// Process all bytes.
for(int i=0;i<count;i++){
m_pEncode3x8Block[m_OffsetInEncode3x8Block++] = buffer[offset + i];
// 3x8-bit encode block is full, encode it.
if(m_OffsetInEncode3x8Block == 3){
m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[ m_pEncode3x8Block[0] >> 2];
m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[0] & 0x03) << 4 | m_pEncode3x8Block[1] >> 4];
m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[1] & 0x0F) << 2 | m_pEncode3x8Block[2] >> 6];
m_pEncodeBuffer[m_EncodeBufferOffset++] = BASE64_ENCODE_TABLE[(m_pEncode3x8Block[2] & 0x3F)];
// Encode buffer is full, write buffer to underlaying stream (we reserved 2 bytes for CRLF).
if(m_EncodeBufferOffset >= (encodeBufSize - 2)){
if(m_AddLineBreaks){
m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte)'\r';
m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte)'\n';
}
m_pStream.Write(m_pEncodeBuffer,0,m_EncodeBufferOffset);
m_EncodeBufferOffset = 0;
}
m_OffsetInEncode3x8Block = 0;
}
}
}
#endregion
#region method Finish
/// <summary>
/// Completes encoding. Call this method if all data has written and no more data.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this method is accessed.</exception>
public void Finish()
{
if(m_IsDisposed){
throw new ObjectDisposedException(this.GetType().Name);
}
if(m_IsFinished){
return;
}
m_IsFinished = true;
// PADD left-over, if any. Write encode buffer to underlaying stream.
if(m_OffsetInEncode3x8Block == 1){
m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte)BASE64_ENCODE_TABLE[m_pEncode3x8Block[0] >> 2];
m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte)BASE64_ENCODE_TABLE[(m_pEncode3x8Block[0] & 0x03) << 4];
m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte)'=';
m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte)'=';
}
else if(m_OffsetInEncode3x8Block == 2){
m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte)BASE64_ENCODE_TABLE[ m_pEncode3x8Block[0] >> 2];
m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte)BASE64_ENCODE_TABLE[(m_pEncode3x8Block[0] & 0x03) << 4 | m_pEncode3x8Block[1] >> 4];
m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte)BASE64_ENCODE_TABLE[(m_pEncode3x8Block[1] & 0x0F) << 2];
m_pEncodeBuffer[m_EncodeBufferOffset++] = (byte)'=';
}
if(m_EncodeBufferOffset > 0){
m_pStream.Write(m_pEncodeBuffer,0,m_EncodeBufferOffset);
}
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets if this object is disposed.
/// </summary>
public bool IsDisposed
{
get{ return m_IsDisposed; }
}
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public override bool CanRead
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
return true;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public override bool CanSeek
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
return false;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
public override bool CanWrite
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
return false;
}
}
/// <summary>
/// Gets the length in bytes of the stream. This method is not supported and always throws a NotSupportedException.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
/// <exception cref="NotSupportedException">Is raised when this property is accessed.</exception>
public override long Length
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
throw new NotSupportedException();
}
}
/// <summary>
/// Gets or sets the position within the current stream. This method is not supported and always throws a NotSupportedException.
/// </summary>
/// <exception cref="ObjectDisposedException">Is raised when this object is disposed and this property is accessed.</exception>
/// <exception cref="NotSupportedException">Is raised when this property is accessed.</exception>
public override long Position
{
get{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
throw new NotSupportedException();
}
set{
if(m_IsDisposed){
throw new ObjectDisposedException("SmartStream");
}
throw new NotSupportedException();
}
}
#endregion
}
}
| |
// MvxPictureChooserTask.cs
// (c) Copyright Cirrious Ltd. http://www.cirrious.com
// MvvmCross is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Stuart Lodge, @slodge, me@slodge.com
using System;
using System.IO;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Graphics;
using Android.Provider;
using MvvmCross.Platform.Droid;
using MvvmCross.Platform.Droid.Platform;
using MvvmCross.Platform.Droid.Views;
using MvvmCross.Platform.Exceptions;
using MvvmCross.Platform;
using MvvmCross.Platform.Platform;
using Uri = Android.Net.Uri;
namespace MvvmCross.Plugins.PictureChooser.Droid
{
public class MvxPictureChooserTask
: MvxAndroidTask
, IMvxPictureChooserTask
{
private Uri _cachedUriLocation;
private RequestParameters _currentRequestParameters;
#region IMvxPictureChooserTask Members
public void ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality, Action<Stream, string> pictureAvailable,
Action assumeCancelled)
{
var intent = new Intent(Intent.ActionGetContent);
intent.SetType("image/*");
ChoosePictureCommon(MvxIntentRequestCode.PickFromFile, intent, maxPixelDimension, percentQuality,
pictureAvailable, assumeCancelled);
}
public void ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable,
Action assumeCancelled)
{
this.ChoosePictureFromLibrary(maxPixelDimension, percentQuality, (stream, name) => pictureAvailable(stream), assumeCancelled);
}
public void TakePicture(int maxPixelDimension, int percentQuality, Action<Stream> pictureAvailable,
Action assumeCancelled)
{
var intent = new Intent(MediaStore.ActionImageCapture);
_cachedUriLocation = GetNewImageUri();
intent.PutExtra(MediaStore.ExtraOutput, _cachedUriLocation);
intent.PutExtra("outputFormat", Bitmap.CompressFormat.Jpeg.ToString());
intent.PutExtra("return-data", true);
ChoosePictureCommon(MvxIntentRequestCode.PickFromCamera, intent, maxPixelDimension, percentQuality,
(stream, name)=> pictureAvailable(stream), assumeCancelled);
}
public Task<Stream> ChoosePictureFromLibrary(int maxPixelDimension, int percentQuality)
{
var task = new TaskCompletionSource<Stream>();
ChoosePictureFromLibrary(maxPixelDimension, percentQuality, (stream, name) => task.SetResult(stream), () => task.SetResult(null));
return task.Task;
}
public Task<Stream> TakePicture(int maxPixelDimension, int percentQuality)
{
var task = new TaskCompletionSource<Stream>();
TakePicture(maxPixelDimension, percentQuality, task.SetResult, () => task.SetResult(null));
return task.Task;
}
public void ContinueFileOpenPicker(object args)
{
}
#endregion
private Uri GetNewImageUri()
{
// Optional - specify some metadata for the picture
var contentValues = new ContentValues();
//contentValues.Put(MediaStore.Images.ImageColumnsConsts.Description, "A camera photo");
// Specify where to put the image
return
Mvx.Resolve<IMvxAndroidGlobals>()
.ApplicationContext.ContentResolver.Insert(MediaStore.Images.Media.ExternalContentUri, contentValues);
}
public void ChoosePictureCommon(MvxIntentRequestCode pickId, Intent intent, int maxPixelDimension,
int percentQuality, Action<Stream, string> pictureAvailable, Action assumeCancelled)
{
if (_currentRequestParameters != null)
throw new MvxException("Cannot request a second picture while the first request is still pending");
_currentRequestParameters = new RequestParameters(maxPixelDimension, percentQuality, pictureAvailable,
assumeCancelled);
StartActivityForResult((int) pickId, intent);
}
protected override void ProcessMvxIntentResult(MvxIntentResultEventArgs result)
{
MvxTrace.Trace("ProcessMvxIntentResult started...");
Uri uri;
switch ((MvxIntentRequestCode) result.RequestCode)
{
case MvxIntentRequestCode.PickFromFile:
uri = result.Data?.Data;
break;
case MvxIntentRequestCode.PickFromCamera:
uri = _cachedUriLocation;
break;
default:
// ignore this result - it's not for us
MvxTrace.Trace("Unexpected request received from MvxIntentResult - request was {0}",
result.RequestCode);
return;
}
ProcessPictureUri(result, uri);
}
private void ProcessPictureUri(MvxIntentResultEventArgs result, Uri uri)
{
if (_currentRequestParameters == null)
{
MvxTrace.Error("Internal error - response received but _currentRequestParameters is null");
return; // we have not handled this - so we return null
}
var responseSent = false;
try
{
// Note for furture bug-fixing/maintenance - it might be better to use var outputFileUri = data.GetParcelableArrayExtra("outputFileuri") here?
if (result.ResultCode != Result.Ok)
{
MvxTrace.Trace("Non-OK result received from MvxIntentResult - {0} - request was {1}",
result.ResultCode, result.RequestCode);
return;
}
if (string.IsNullOrEmpty(uri?.Path))
{
MvxTrace.Trace("Empty uri or file path received for MvxIntentResult");
return;
}
MvxTrace.Trace("Loading InMemoryBitmap started...");
var memoryStream = LoadInMemoryBitmap(uri);
if (memoryStream == null)
{
MvxTrace.Trace("Loading InMemoryBitmap failed...");
return;
}
MvxTrace.Trace("Loading InMemoryBitmap complete...");
responseSent = true;
MvxTrace.Trace("Sending pictureAvailable...");
_currentRequestParameters.PictureAvailable(memoryStream, System.IO.Path.GetFileName(uri.Path));
MvxTrace.Trace("pictureAvailable completed...");
return;
}
finally
{
if (!responseSent)
_currentRequestParameters.AssumeCancelled();
_currentRequestParameters = null;
}
}
private MemoryStream LoadInMemoryBitmap(Uri uri)
{
var memoryStream = new MemoryStream();
var bitmap = LoadScaledBitmap(uri);
if (bitmap == null)
return null;
using (bitmap)
{
bitmap.Compress(Bitmap.CompressFormat.Jpeg, _currentRequestParameters.PercentQuality, memoryStream);
}
memoryStream.Seek(0L, SeekOrigin.Begin);
return memoryStream;
}
private Bitmap LoadScaledBitmap(Uri uri)
{
ContentResolver contentResolver = Mvx.Resolve<IMvxAndroidGlobals>().ApplicationContext.ContentResolver;
var maxDimensionSize = GetMaximumDimension(contentResolver, uri);
var sampleSize = (int) Math.Ceiling((maxDimensionSize)/
((double) _currentRequestParameters.MaxPixelDimension));
if (sampleSize < 1)
{
// this shouldn't happen, but if it does... then trace the error and set sampleSize to 1
MvxTrace.Trace(
"Warning - sampleSize of {0} was requested - how did this happen - based on requested {1} and returned image size {2}",
sampleSize,
_currentRequestParameters.MaxPixelDimension,
maxDimensionSize);
// following from https://github.com/MvvmCross/MvvmCross/issues/565 we return null in this case
// - it suggests that Android has returned a corrupt image uri
return null;
}
var sampled = LoadResampledBitmap(contentResolver, uri, sampleSize);
try
{
var rotated = ExifRotateBitmap(contentResolver, uri, sampled);
return rotated;
}
catch (Exception pokemon)
{
Mvx.Trace("Problem seem in Exit Rotate {0}", pokemon.ToLongString());
return sampled;
}
}
private Bitmap LoadResampledBitmap(ContentResolver contentResolver, Uri uri, int sampleSize)
{
using (var inputStream = contentResolver.OpenInputStream(uri))
{
var optionsDecode = new BitmapFactory.Options {InSampleSize = sampleSize};
return BitmapFactory.DecodeStream(inputStream, null, optionsDecode);
}
}
private static int GetMaximumDimension(ContentResolver contentResolver, Uri uri)
{
using (var inputStream = contentResolver.OpenInputStream(uri))
{
var optionsJustBounds = new BitmapFactory.Options
{
InJustDecodeBounds = true
};
var metadataResult = BitmapFactory.DecodeStream(inputStream, null, optionsJustBounds);
var maxDimensionSize = Math.Max(optionsJustBounds.OutWidth, optionsJustBounds.OutHeight);
return maxDimensionSize;
}
}
private Bitmap ExifRotateBitmap(ContentResolver contentResolver, Uri uri, Bitmap bitmap)
{
if (bitmap == null)
return null;
var exif = new Android.Media.ExifInterface(GetRealPathFromUri(contentResolver, uri));
var rotation = exif.GetAttributeInt(Android.Media.ExifInterface.TagOrientation, (Int32)Android.Media.Orientation.Normal);
var rotationInDegrees = ExifToDegrees(rotation);
if (rotationInDegrees == 0)
return bitmap;
using (var matrix = new Matrix())
{
matrix.PreRotate(rotationInDegrees);
return Bitmap.CreateBitmap(bitmap, 0, 0, bitmap.Width, bitmap.Height, matrix, true);
}
}
private String GetRealPathFromUri(ContentResolver contentResolver, Uri uri)
{
var proj = new String[] { MediaStore.Images.ImageColumns.Data };
using (var cursor = contentResolver.Query(uri, proj, null, null, null))
{
var columnIndex = cursor.GetColumnIndexOrThrow(MediaStore.Images.ImageColumns.Data);
cursor.MoveToFirst();
return cursor.GetString(columnIndex);
}
}
private static Int32 ExifToDegrees(Int32 exifOrientation)
{
switch (exifOrientation)
{
case (Int32)Android.Media.Orientation.Rotate90:
return 90;
case (Int32)Android.Media.Orientation.Rotate180:
return 180;
case (Int32)Android.Media.Orientation.Rotate270:
return 270;
}
return 0;
}
#region Nested type: RequestParameters
private class RequestParameters
{
public RequestParameters(int maxPixelDimension, int percentQuality, Action<Stream, string> pictureAvailable,
Action assumeCancelled)
{
PercentQuality = percentQuality;
MaxPixelDimension = maxPixelDimension;
AssumeCancelled = assumeCancelled;
PictureAvailable = pictureAvailable;
}
public Action<Stream, string> PictureAvailable { get; private set; }
public Action AssumeCancelled { get; private set; }
public int MaxPixelDimension { get; private set; }
public int PercentQuality { get; private set; }
}
#endregion
}
}
| |
#region MIT License
/*
* Copyright (c) 2005-2008 Jonathan Mark Porter. http://physics2d.googlepages.com/
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#endregion
#if UseDouble
using Scalar = System.Double;
#else
using Scalar = System.Single;
#endif
using System;
using System.Runtime.InteropServices;
using AdvanceMath.Design;
using System.Xml.Serialization;
namespace AdvanceMath
{
/// <summary>
/// A Vector with 4 dimensions.
/// </summary>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29"/></remarks>
//[StructLayout(LayoutKind.Sequential), Serializable]
[StructLayout(LayoutKind.Sequential, Size = Vector4D.Size)]
[AdvBrowsableOrder("X,Y,Z,W"), Serializable]
#if !CompactFramework && !WindowsCE && !PocketPC && !XBOX360 && !SILVERLIGHT
[System.ComponentModel.TypeConverter(typeof(AdvTypeConverter<Vector4D>))]
#endif
public struct Vector4D : IVector<Vector4D>
{
#region const fields
/// <summary>
/// The number of Scalar values in the class.
/// </summary>
public const int Count = 4;
/// <summary>
/// The Size of the class in bytes;
/// </summary>
public const int Size = sizeof(Scalar) * Count;
#endregion
#region readonly fields
/// <summary>
/// Vector4D(1,1,1,1)
/// </summary>
public static readonly Vector4D One = new Vector4D(1, 1, 1, 1);
/// <summary>
/// Vector4D(0,0,0,0)
/// </summary>
public static readonly Vector4D Zero = new Vector4D();
/// <summary>
/// Vector4D(1,0,0,0)
/// </summary>
public static readonly Vector4D XAxis = new Vector4D(1, 0, 0, 0);
/// <summary>
/// Vector4D(0,1,0,0)
/// </summary>
public static readonly Vector4D YAxis = new Vector4D(0, 1, 0, 0);
/// <summary>
/// Vector4D(0,0,1,0)
/// </summary>
public static readonly Vector4D ZAxis = new Vector4D(0, 0, 1, 0);
/// <summary>
/// Vector4D(0,0,0,1)
/// </summary>
public static readonly Vector4D WAxis = new Vector4D(0, 0, 0, 1);
private static readonly string FormatString = MatrixHelper.CreateVectorFormatString(Count);
private readonly static string FormatableString = MatrixHelper.CreateVectorFormatableString(Count);
#endregion
#region static methods
public static void Copy(ref Vector4D vector, Scalar[] destArray)
{
Copy(ref vector, destArray, 0);
}
public static void Copy(ref Vector4D vector, Scalar[] destArray, int index)
{
ThrowHelper.CheckCopy(destArray, index, Count);
destArray[index] = vector.X;
destArray[++index] = vector.Y;
destArray[++index] = vector.Z;
destArray[++index] = vector.W;
}
public static void Copy(Scalar[] sourceArray, out Vector4D result)
{
Copy(sourceArray, 0, out result);
}
public static void Copy(Scalar[] sourceArray, int index, out Vector4D result)
{
ThrowHelper.CheckCopy(sourceArray, index, Count);
result.X = sourceArray[index];
result.Y = sourceArray[++index];
result.Z = sourceArray[++index];
result.W = sourceArray[++index];
}
public static void Copy(ref Vector3D source, ref Vector4D dest)
{
dest.X = source.X;
dest.Y = source.Y;
dest.Z = source.Z;
}
public static void Copy(ref Vector2D source, ref Vector4D dest)
{
dest.X = source.X;
dest.Y = source.Y;
}
public static Vector4D Clamp(Vector4D value, Vector4D min, Vector4D max)
{
Vector4D result;
MathHelper.Clamp(ref value.X, ref min.X, ref max.X, out result.X);
MathHelper.Clamp(ref value.Y, ref min.Y, ref max.Y, out result.Y);
MathHelper.Clamp(ref value.Z, ref min.Z, ref max.Z, out result.Z);
MathHelper.Clamp(ref value.W, ref min.W, ref max.W, out result.W);
return result;
}
public static void Clamp(ref Vector4D value, ref Vector4D min, ref Vector4D max, out Vector4D result)
{
MathHelper.Clamp(ref value.X, ref min.X, ref max.X, out result.X);
MathHelper.Clamp(ref value.Y, ref min.Y, ref max.Y, out result.Y);
MathHelper.Clamp(ref value.Z, ref min.Z, ref max.Z, out result.Z);
MathHelper.Clamp(ref value.W, ref min.W, ref max.W, out result.W);
}
public static Vector4D Lerp(Vector4D left, Vector4D right, Scalar amount)
{
Vector4D result;
Lerp(ref left, ref right, ref amount, out result);
return result;
}
public static void Lerp(ref Vector4D left, ref Vector4D right, ref Scalar amount, out Vector4D result)
{
result.X = (right.X - left.X) * amount + left.X;
result.Y = (right.Y - left.Y) * amount + left.Y;
result.Z = (right.Z - left.Z) * amount + left.Z;
result.W = (right.W - left.W) * amount + left.W;
}
public static Vector4D Lerp(Vector4D left, Vector4D right, Vector4D amount)
{
Vector4D result;
Lerp(ref left, ref right, ref amount, out result);
return result;
}
public static void Lerp(ref Vector4D left, ref Vector4D right, ref Vector4D amount, out Vector4D result)
{
result.X = (right.X - left.X) * amount.X + left.X;
result.Y = (right.Y - left.Y) * amount.Y + left.Y;
result.Z = (right.Z - left.Z) * amount.Z + left.Z;
result.W = (right.W - left.W) * amount.W + left.W;
}
public static Scalar Distance(Vector4D left, Vector4D right)
{
Scalar result;
Distance(ref left, ref right, out result);
return result;
}
public static void Distance(ref Vector4D left, ref Vector4D right, out Scalar result)
{
Vector4D diff;
Subtract(ref left, ref right, out diff);
GetMagnitude(ref diff, out result);
}
public static Scalar DistanceSq(Vector4D left, Vector4D right)
{
Scalar result;
DistanceSq(ref left, ref right, out result);
return result;
}
public static void DistanceSq(ref Vector4D left, ref Vector4D right, out Scalar result)
{
Vector4D diff;
Subtract(ref left, ref right, out diff);
GetMagnitudeSq(ref diff, out result);
}
/// <summary>
/// Adds 2 Vectors2Ds.
/// </summary>
/// <param name="left">The left Vector4D operand.</param>
/// <param name="right">The right Vector4D operand.</param>
/// <returns>The Sum of the 2 Vector4Ds.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Vector_addition_and_subtraction"/></remarks>
public static Vector4D Add(Vector4D left, Vector4D right)
{
Vector4D result;
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
result.W = left.W + right.W;
return result;
}
public static void Add(ref Vector4D left, ref Vector4D right, out Vector4D result)
{
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
result.W = left.W + right.W;
}
public static Vector4D Add(Vector3D left, Vector4D right)
{
Vector4D result;
Add(ref left, ref right, out result);
return result;
}
public static void Add(ref Vector3D left, ref Vector4D right, out Vector4D result)
{
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
result.W = right.W;
}
public static Vector4D Add(Vector2D left, Vector4D right)
{
Vector4D result;
Add(ref left, ref right, out result);
return result;
}
public static void Add(ref Vector2D left, ref Vector4D right, out Vector4D result)
{
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = right.Z;
result.W = right.W;
}
public static Vector4D Add(Vector4D left, Vector3D right)
{
Vector4D result;
Add(ref left, ref right, out result);
return result;
}
public static void Add(ref Vector4D left, ref Vector3D right, out Vector4D result)
{
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
result.W = left.W;
}
public static Vector4D Add(Vector4D left, Vector2D right)
{
Vector4D result;
Add(ref left, ref right, out result);
return result;
}
public static void Add(ref Vector4D left, ref Vector2D right, out Vector4D result)
{
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z;
result.W = left.W;
}
/// <summary>
/// Subtracts 2 Vector4Ds.
/// </summary>
/// <param name="left">The left Vector4D operand.</param>
/// <param name="right">The right Vector4D operand.</param>
/// <returns>The Difference of the 2 Vector4Ds.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Vector_addition_and_subtraction"/></remarks>
public static Vector4D Subtract(Vector4D left, Vector4D right)
{
Vector4D result;
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
result.W = left.W - right.W;
return result;
}
public static void Subtract(ref Vector4D left, ref Vector4D right, out Vector4D result)
{
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
result.W = left.W - right.W;
}
public static Vector4D Subtract(Vector3D left, Vector4D right)
{
Vector4D result;
Subtract(ref left, ref right, out result);
return result;
}
public static void Subtract(ref Vector3D left, ref Vector4D right, out Vector4D result)
{
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
result.W = -right.W;
}
public static Vector4D Subtract(Vector2D left, Vector4D right)
{
Vector4D result;
Subtract(ref left, ref right, out result);
return result;
}
public static void Subtract(ref Vector2D left, ref Vector4D right, out Vector4D result)
{
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = -right.Z;
result.W = -right.W;
}
public static Vector4D Subtract(Vector4D left, Vector3D right)
{
Vector4D result;
Subtract(ref left, ref right, out result);
return result;
}
public static void Subtract(ref Vector4D left, ref Vector3D right, out Vector4D result)
{
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
result.W = left.W;
}
public static Vector4D Subtract(Vector4D left, Vector2D right)
{
Vector4D result;
Subtract(ref left, ref right, out result);
return result;
}
public static void Subtract(ref Vector4D left, ref Vector2D right, out Vector4D result)
{
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z;
result.W = left.W;
}
/// <summary>
/// Does Scaler Multiplication on a Vector4D.
/// </summary>
/// <param name="source">The Vector4D to be multiplied.</param>
/// <param name="scalar">The scalar value that will multiply the Vector4D.</param>
/// <returns>The Product of the Scaler Multiplication.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Scalar_multiplication"/></remarks>
public static Vector4D Multiply(Vector4D source, Scalar scalar)
{
Vector4D result;
result.X = source.X * scalar;
result.Y = source.Y * scalar;
result.Z = source.Z * scalar;
result.W = source.W * scalar;
return result;
}
public static void Multiply(ref Vector4D source, ref Scalar scalar, out Vector4D result)
{
result.X = source.X * scalar;
result.Y = source.Y * scalar;
result.Z = source.Z * scalar;
result.W = source.W * scalar;
}
/// <summary>
/// Does Scaler Multiplication on a Vector4D.
/// </summary>
/// <param name="scalar">The scalar value that will multiply the Vector4D.</param>
/// <param name="source">The Vector4D to be multiplied.</param>
/// <returns>The Product of the Scaler Multiplication.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Scalar_multiplication"/></remarks>
public static Vector4D Multiply(Scalar scalar, Vector4D source)
{
Vector4D result;
result.X = scalar * source.X;
result.Y = scalar * source.Y;
result.Z = scalar * source.Z;
result.W = scalar * source.W;
return result;
}
public static void Multiply(ref Scalar scalar, ref Vector4D source, out Vector4D result)
{
result.X = scalar * source.X;
result.Y = scalar * source.Y;
result.Z = scalar * source.Z;
result.W = scalar * source.W;
}
public static Vector4D Transform(Matrix4x4 matrix, Vector4D vector)
{
Vector4D result;
result.X = vector.X * matrix.m00 + vector.Y * matrix.m01 + vector.Z * matrix.m02 + vector.W * matrix.m03;
result.Y = vector.X * matrix.m10 + vector.Y * matrix.m11 + vector.Z * matrix.m12 + vector.W * matrix.m13;
result.Z = vector.X * matrix.m20 + vector.Y * matrix.m21 + vector.Z * matrix.m22 + vector.W * matrix.m23;
result.W = vector.X * matrix.m30 + vector.Y * matrix.m31 + vector.Z * matrix.m32 + vector.W * matrix.m33;
return result;
}
public static void Transform(ref Matrix4x4 matrix, ref Vector4D vector, out Vector4D result)
{
Scalar X = vector.X;
Scalar Y = vector.Y;
Scalar Z = vector.Z;
result.X = X * matrix.m00 + Y * matrix.m01 + Z * matrix.m02 + vector.W * matrix.m03;
result.Y = X * matrix.m10 + Y * matrix.m11 + Z * matrix.m12 + vector.W * matrix.m13;
result.Z = X * matrix.m20 + Y * matrix.m21 + Z * matrix.m22 + vector.W * matrix.m23;
result.W = X * matrix.m30 + Y * matrix.m31 + Z * matrix.m32 + vector.W * matrix.m33;
}
public static Vector4D Transform(Vector4D vector, Matrix4x4 matrix)
{
Vector4D result;
result.X = vector.X * matrix.m00 + vector.Y * matrix.m10 + vector.Z * matrix.m20 + vector.W * matrix.m30;
result.Y = vector.X * matrix.m01 + vector.Y * matrix.m11 + vector.Z * matrix.m21 + vector.W * matrix.m31;
result.Z = vector.X * matrix.m02 + vector.Y * matrix.m12 + vector.Z * matrix.m22 + vector.W * matrix.m32;
result.W = vector.X * matrix.m03 + vector.Y * matrix.m13 + vector.Z * matrix.m23 + vector.W * matrix.m33;
return result;
}
public static void Transform(ref Vector4D vector, ref Matrix4x4 matrix, out Vector4D result)
{
Scalar X = vector.X;
Scalar Y = vector.Y;
Scalar Z = vector.Z;
result.X = X * matrix.m00 + Y * matrix.m10 + Z * matrix.m20 + vector.W * matrix.m30;
result.Y = X * matrix.m01 + Y * matrix.m11 + Z * matrix.m21 + vector.W * matrix.m31;
result.Z = X * matrix.m02 + Y * matrix.m12 + Z * matrix.m22 + vector.W * matrix.m32;
result.W = X * matrix.m03 + Y * matrix.m13 + Z * matrix.m23 + vector.W * matrix.m33;
}
/// <summary>
/// Does a Dot Operation Also know as an Inner Product.
/// </summary>
/// <param name="left">The left Vector4D operand.</param>
/// <param name="right">The right Vector4D operand.</param>
/// <returns>The Dot Product (Inner Product).</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Dot_product"/></remarks>
public static Scalar Dot(Vector4D left, Vector4D right)
{
return left.Y * right.Y + left.X * right.X + left.Z * right.Z + left.W * right.W;
}
public static void Dot(ref Vector4D left, ref Vector4D right, out Scalar result)
{
result = left.Y * right.Y + left.X * right.X + left.Z * right.Z + left.W * right.W;
}
/// <summary>
/// Gets the Squared <see cref="Magnitude"/> of the Vector4D that is passed.
/// </summary>
/// <param name="source">The Vector4D whos Squared Magnitude is te be returned.</param>
/// <returns>The Squared Magnitude.</returns>
public static Scalar GetMagnitudeSq(Vector4D source)
{
return source.X * source.X + source.Y * source.Y + source.Z * source.Z + source.W * source.W;
}
public static void GetMagnitudeSq(ref Vector4D source, out Scalar result)
{
result = source.X * source.X + source.Y * source.Y + source.Z * source.Z + source.W * source.W;
}
/// <summary>
/// Gets the <see cref="Magnitude"/> of the Vector4D that is passed.
/// </summary>
/// <param name="source">The Vector4D whos Magnitude is te be returned.</param>
/// <returns>The Magnitude.</returns>
public static Scalar GetMagnitude(Vector4D source)
{
return MathHelper.Sqrt(source.X * source.X + source.Y * source.Y + source.Z * source.Z + source.W * source.W);
}
public static void GetMagnitude(ref Vector4D source, out Scalar result)
{
result = MathHelper.Sqrt(source.X * source.X + source.Y * source.Y + source.Z * source.Z + source.W * source.W);
}
/// <summary>
/// Sets the <see cref="Magnitude"/> of a Vector4D.
/// </summary>
/// <param name="source">The Vector4D whose Magnitude is to be changed.</param>
/// <param name="magnitude">The Magnitude.</param>
/// <returns>A Vector4D with the new Magnitude</returns>
public static Vector4D SetMagnitude(Vector4D source, Scalar magnitude)
{
Vector4D result;
SetMagnitude(ref source, ref magnitude, out result);
return result;
}
public static void SetMagnitude(ref Vector4D source, ref Scalar magnitude, out Vector4D result)
{
Scalar oldmagnitude;
GetMagnitude(ref source, out oldmagnitude);
if (oldmagnitude > 0 && magnitude != 0)
{
oldmagnitude = (magnitude / oldmagnitude);
Multiply(ref source, ref oldmagnitude, out result);
}
else
{
result = Zero;
}
}
/// <summary>
/// Negates a Vector4D.
/// </summary>
/// <param name="source">The Vector4D to be Negated.</param>
/// <returns>The Negated Vector4D.</returns>
public static Vector4D Negate(Vector4D source)
{
Vector4D result;
result.X = -source.X;
result.Y = -source.Y;
result.Z = -source.Z;
result.W = -source.W;
return result;
}
[CLSCompliant(false)]
public static void Negate(ref Vector4D source)
{
Negate(ref source, out source);
}
public static void Negate(ref Vector4D source, out Vector4D result)
{
result.X = -source.X;
result.Y = -source.Y;
result.Z = -source.Z;
result.W = -source.W;
}
/// <summary>
/// This returns the Normalized Vector4D that is passed. This is also known as a Unit Vector.
/// </summary>
/// <param name="source">The Vector4D to be Normalized.</param>
/// <returns>The Normalized Vector4D. (Unit Vector)</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Unit_vector"/></remarks>
public static Vector4D Normalize(Vector4D source)
{
Scalar oldmagnitude;
GetMagnitude(ref source, out oldmagnitude);
if (oldmagnitude == 0) { return Zero; }
oldmagnitude = (1 / oldmagnitude);
Vector4D result;
result.X = source.X * oldmagnitude;
result.Y = source.Y * oldmagnitude;
result.Z = source.Z * oldmagnitude;
result.W = source.W * oldmagnitude;
return result;
}
public static void Normalize(ref Vector4D source, out Vector4D result)
{
Scalar oldmagnitude;
GetMagnitude(ref source, out oldmagnitude);
if (oldmagnitude == 0) { result = Zero; return; }
oldmagnitude = (1 / oldmagnitude);
result.X = source.X * oldmagnitude;
result.Y = source.Y * oldmagnitude;
result.Z = source.Z * oldmagnitude;
result.W = source.W * oldmagnitude;
}
[CLSCompliant(false)]
public static void Normalize(ref Vector4D source)
{
Normalize(ref source, out source);
}
/// <summary>
/// Thie Projects the left Vector4D onto the Right Vector4D.
/// </summary>
/// <param name="left">The left Vector4D operand.</param>
/// <param name="right">The right Vector4D operand.</param>
/// <returns>The Projected Vector4D.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Projection_%28linear_algebra%29"/></remarks>
public static Vector4D Project(Vector4D left, Vector4D right)
{
Vector4D result;
Project(ref left, ref right, out result);
return result;
}
public static void Project(ref Vector4D left, ref Vector4D right, out Vector4D result)
{
Scalar tmp, magsq;
Dot(ref left, ref right, out tmp);
GetMagnitudeSq(ref right, out magsq);
tmp /= magsq;
Multiply(ref right, ref tmp, out result);
}
public static Vector4D TripleCross(Vector4D top, Vector4D middle, Vector4D bottom)
{
Vector4D result;
result.X = Matrix3x3.GetDeterminant(
top.Y, top.Z, top.W,
middle.Y, middle.Z, middle.W,
bottom.Y, bottom.Z, bottom.W);
result.Y = -Matrix3x3.GetDeterminant(
top.X, top.Z, top.W,
middle.X, middle.Z, middle.W,
bottom.X, bottom.Z, bottom.W);
result.Z = Matrix3x3.GetDeterminant(
top.X, top.Y, top.W,
middle.X, middle.Y, middle.W,
bottom.X, bottom.Y, bottom.W);
result.W = -Matrix3x3.GetDeterminant(
top.X, top.Y, top.Z,
middle.X, middle.Y, middle.Z,
bottom.X, bottom.Y, bottom.Z);
return result;
}
public static Vector4D CatmullRom( Vector4D value1, Vector4D value2, Vector4D value3, Vector4D value4, Scalar amount)
{
Vector4D result;
CatmullRom(ref value1, ref value2, ref value3, ref value4, amount, out result);
return result;
}
public static void CatmullRom(ref Vector4D value1, ref Vector4D value2, ref Vector4D value3, ref Vector4D value4, Scalar amount, out Vector4D result)
{
Scalar amountSq = amount * amount;
Scalar amountCu = amountSq * amount;
result.X =
0.5f * ((2 * value2.X) +
(-value1.X + value3.X) * amount +
(2 * value1.X - 5 * value2.X + 4 * value3.X - value4.X) * amountSq +
(-value1.X + 3 * value2.X - 3 * value3.X + value4.X) * amountCu);
result.Y =
0.5f * ((2 * value2.Y) +
(-value1.Y + value3.Y) * amount +
(2 * value1.Y - 5 * value2.Y + 4 * value3.Y - value4.Y) * amountSq +
(-value1.Y + 3 * value2.Y - 3 * value3.Y + value4.Y) * amountCu);
result.Z =
0.5f * ((2 * value2.Z) +
(-value1.Z + value3.Z) * amount +
(2 * value1.Z - 5 * value2.Z + 4 * value3.Z - value4.Z) * amountSq +
(-value1.Z + 3 * value2.Z - 3 * value3.Z + value4.Z) * amountCu);
result.W =
0.5f * ((2 * value2.W) +
(-value1.W + value3.W) * amount +
(2 * value1.W - 5 * value2.W + 4 * value3.W - value4.W) * amountSq +
(-value1.W + 3 * value2.W - 3 * value3.W + value4.W) * amountCu);
}
public static Vector4D Max(Vector4D value1, Vector4D value2)
{
Vector4D result;
Max(ref value1, ref value2, out result);
return result;
}
public static void Max(ref Vector4D value1,ref Vector4D value2,out Vector4D result)
{
result.X = (value1.X < value2.X) ? (value2.X) : (value1.X);
result.Y = (value1.Y < value2.Y) ? (value2.Y) : (value1.Y);
result.Z = (value1.Z < value2.Z) ? (value2.Z) : (value1.Z);
result.W = (value1.W < value2.W) ? (value2.W) : (value1.W);
}
public static Vector4D Min(Vector4D value1, Vector4D value2)
{
Vector4D result;
Min(ref value1, ref value2, out result);
return result;
}
public static void Min(ref Vector4D value1, ref Vector4D value2, out Vector4D result)
{
result.X = (value1.X > value2.X) ? (value2.X) : (value1.X);
result.Y = (value1.Y > value2.Y) ? (value2.Y) : (value1.Y);
result.Z = (value1.Z > value2.Z) ? (value2.Z) : (value1.Z);
result.W = (value1.W > value2.W) ? (value2.W) : (value1.W);
}
public static Vector4D Hermite(Vector4D value1, Vector4D tangent1, Vector4D value2, Vector4D tangent2, Scalar amount)
{
Vector4D result;
Hermite(ref value1, ref tangent1, ref value2, ref tangent2, amount, out result);
return result;
}
public static void Hermite(ref Vector4D value1, ref Vector4D tangent1, ref Vector4D value2, ref Vector4D tangent2, Scalar amount, out Vector4D result)
{
Scalar h1, h2, h3, h4;
MathHelper.HermiteHelper(amount, out h1, out h2, out h3, out h4);
result.X = h1 * value1.X + h2 * value2.X + h3 * tangent1.X + h4 * tangent2.X;
result.Y = h1 * value1.Y + h2 * value2.Y + h3 * tangent1.Y + h4 * tangent2.Y;
result.Z = h1 * value1.Z + h2 * value2.Z + h3 * tangent1.Z + h4 * tangent2.Z;
result.W = h1 * value1.W + h2 * value2.W + h3 * tangent1.W + h4 * tangent2.W;
}
#endregion
#region fields
/// <summary>
/// This is the X value.
/// </summary>
[AdvBrowsable]
[XmlAttribute]
[System.ComponentModel.Description("The Magnitude on the X-Axis")]
public Scalar X;
/// <summary>
/// This is the Y value.
/// </summary>
[AdvBrowsable]
[XmlAttribute]
[System.ComponentModel.Description("The Magnitude on the Y-Axis")]
public Scalar Y;
/// <summary>
/// This is the Z value.
/// </summary>
[AdvBrowsable]
[XmlAttribute]
[System.ComponentModel.Description("The Magnitude on the Z-Axis")]
public Scalar Z;
/// <summary>
/// This is the W value.
/// </summary>
[AdvBrowsable]
[XmlAttribute]
[System.ComponentModel.Description("The Magnitude on the W-Axis")]
public Scalar W;
#endregion
#region constructors
/// <summary>
/// Creates a New Vector4D Instance on the Stack.
/// </summary>
/// <param name="X">The X value.</param>
/// <param name="Y">The Y value.</param>
/// <param name="Z">The Z value.</param>
/// <param name="W">The W value.</param>
[InstanceConstructor("X,Y,Z,W")]
public Vector4D(Scalar X, Scalar Y, Scalar Z, Scalar W)
{
this.X = X;
this.Y = Y;
this.Z = Z;
this.W = W;
}
public Vector4D(Scalar[] vals) : this(vals, 0) { }
public Vector4D(Scalar[] vals, int index)
{
Copy(vals, index, out this);
}
#endregion
#region indexers
#if UNSAFE
/// <summary>
/// Allows the Vector to be accessed linearly (v[0] -> v[Count-1]).
/// </summary>
/// <remarks>
/// This indexer is only provided as a convenience, and is <b>not</b> recommended for use in
/// intensive applications.
/// </remarks>
public Scalar this[int index]
{
get
{
ThrowHelper.CheckIndex("index", index, Count);
unsafe
{
fixed (Scalar* ptr = &this.X)
{
return ptr[index];
}
}
}
set
{
ThrowHelper.CheckIndex("index", index, Count);
unsafe
{
fixed (Scalar* ptr = &this.X)
{
ptr[index] = value;
}
}
}
}
#endif
#endregion
#region properties
/// <summary>
/// Gets or Sets the Magnitude (Length) of the Vector4D.
/// </summary>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Length_of_a_vector"/></remarks>
[XmlIgnore]
public Scalar Magnitude
{
get
{
return MathHelper.Sqrt(this.X * this.X + this.Y * this.Y + this.Z * this.Z + this.W * this.W);
}
set
{
this = SetMagnitude(this, value);
}
}
/// <summary>
/// Gets the Squared Magnitude of the Vector4D.
/// </summary>
public Scalar MagnitudeSq
{
get
{
return this.X * this.X + this.Y * this.Y + this.Z * this.Z + this.W * this.W;
}
}
/// <summary>
/// Gets the Normalized Vector4D. (Unit Vector)
/// </summary>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Unit_vector"/></remarks>
public Vector4D Normalized
{
get
{
return Normalize(this);
}
}
/// <summary>
/// The Number of Variables accesable though the indexer.
/// </summary>
int IAdvanceValueType.Count { get { return Count; } }
#endregion
#region public methods
public Scalar[] ToArray()
{
Scalar[] array = new Scalar[Count];
Copy(ref this, array, 0);
return array;
}
public void CopyFrom(Scalar[] array, int index)
{
Copy(array, index, out this);
}
public void CopyTo(Scalar[] array, int index)
{
Copy(ref this, array, index);
}
#endregion
#region operators
/// <summary>
/// Adds 2 Vectors2Ds.
/// </summary>
/// <param name="left">The left Vector4D operand.</param>
/// <param name="right">The right Vector4D operand.</param>
/// <returns>The Sum of the 2 Vector4Ds.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Vector_addition_and_subtraction"/></remarks>
public static Vector4D operator +(Vector4D left, Vector4D right)
{
Vector4D result;
result.X = left.X + right.X;
result.Y = left.Y + right.Y;
result.Z = left.Z + right.Z;
result.W = left.W + right.W;
return result;
}
public static Vector4D operator +(Vector3D left, Vector4D right)
{
Vector4D result;
Add(ref left, ref right, out result);
return result;
}
public static Vector4D operator +(Vector2D left, Vector4D right)
{
Vector4D result;
Add(ref left, ref right, out result);
return result;
}
public static Vector4D operator +(Vector4D left, Vector3D right)
{
Vector4D result;
Add(ref left, ref right, out result);
return result;
}
public static Vector4D operator +(Vector4D left, Vector2D right)
{
Vector4D result;
Add(ref left, ref right, out result);
return result;
}
/// <summary>
/// Subtracts 2 Vector4Ds.
/// </summary>
/// <param name="left">The left Vector4D operand.</param>
/// <param name="right">The right Vector4D operand.</param>
/// <returns>The Difference of the 2 Vector4Ds.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Vector_addition_and_subtraction"/></remarks>
public static Vector4D operator -(Vector4D left, Vector4D right)
{
Vector4D result;
result.X = left.X - right.X;
result.Y = left.Y - right.Y;
result.Z = left.Z - right.Z;
result.W = left.W - right.W;
return result;
}
public static Vector4D operator -(Vector3D left, Vector4D right)
{
Vector4D result;
Subtract(ref left, ref right, out result);
return result;
}
public static Vector4D operator -(Vector2D left, Vector4D right)
{
Vector4D result;
Subtract(ref left, ref right, out result);
return result;
}
public static Vector4D operator -(Vector4D left, Vector3D right)
{
Vector4D result;
Subtract(ref left, ref right, out result);
return result;
}
public static Vector4D operator -(Vector4D left, Vector2D right)
{
Vector4D result;
Subtract(ref left, ref right, out result);
return result;
}
/// <summary>
/// Does Scaler Multiplication on a Vector4D.
/// </summary>
/// <param name="source">The Vector4D to be multiplied.</param>
/// <param name="scalar">The scalar value that will multiply the Vector4D.</param>
/// <returns>The Product of the Scaler Multiplication.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Scalar_multiplication"/></remarks>
public static Vector4D operator *(Vector4D source, Scalar scalar)
{
Vector4D result;
result.X = source.X * scalar;
result.Y = source.Y * scalar;
result.Z = source.Z * scalar;
result.W = source.W * scalar;
return result;
}
/// <summary>
/// Does Scaler Multiplication on a Vector4D.
/// </summary>
/// <param name="scalar">The scalar value that will multiply the Vector4D.</param>
/// <param name="source">The Vector4D to be multiplied.</param>
/// <returns>The Product of the Scaler Multiplication.</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Vector_%28spatial%29#Scalar_multiplication"/></remarks>
public static Vector4D operator *(Scalar scalar, Vector4D source)
{
Vector4D result;
result.X = scalar * source.X;
result.Y = scalar * source.Y;
result.Z = scalar * source.Z;
result.W = scalar * source.W;
return result;
}
/// <summary>
/// Does a Dot Operation Also know as an Inner Product.
/// </summary>
/// <param name="left">The left Vector4D operand.</param>
/// <param name="right">The right Vector4D operand.</param>
/// <returns>The Dot Product (Inner Product).</returns>
/// <remarks><seealso href="http://en.wikipedia.org/wiki/Dot_product"/></remarks>
public static Scalar operator *(Vector4D left, Vector4D right)
{
return left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W;
}
public static Vector4D operator *(Matrix4x4 matrix, Vector4D vector)
{
Vector4D result;
result.X = vector.X * matrix.m00 + vector.Y * matrix.m01 + vector.Z * matrix.m02 + vector.W * matrix.m03;
result.Y = vector.X * matrix.m10 + vector.Y * matrix.m11 + vector.Z * matrix.m12 + vector.W * matrix.m13;
result.Z = vector.X * matrix.m20 + vector.Y * matrix.m21 + vector.Z * matrix.m22 + vector.W * matrix.m23;
result.W = vector.X * matrix.m30 + vector.Y * matrix.m31 + vector.Z * matrix.m32 + vector.W * matrix.m33;
return result;
}
public static Vector4D operator *(Vector4D vector, Matrix4x4 matrix)
{
Vector4D result;
result.X = vector.X * matrix.m00 + vector.Y * matrix.m10 + vector.Z * matrix.m20 + vector.W * matrix.m30;
result.Y = vector.X * matrix.m01 + vector.Y * matrix.m11 + vector.Z * matrix.m21 + vector.W * matrix.m31;
result.Z = vector.X * matrix.m02 + vector.Y * matrix.m12 + vector.Z * matrix.m22 + vector.W * matrix.m32;
result.W = vector.X * matrix.m03 + vector.Y * matrix.m13 + vector.Z * matrix.m23 + vector.W * matrix.m33;
return result;
}
/// <summary>
/// Negates a Vector4D.
/// </summary>
/// <param name="source">The Vector4D to be Negated.</param>
/// <returns>The Negated Vector4D.</returns>
public static Vector4D operator -(Vector4D source)
{
Vector4D result;
result.X = -source.X;
result.Y = -source.Y;
result.Z = -source.Z;
result.W = -source.W;
return result;
}
/// <summary>
/// Specifies whether the Vector4Ds contain the same coordinates.
/// </summary>
/// <param name="left">The left Vector4D to test.</param>
/// <param name="right">The right Vector4D to test.</param>
/// <returns>true if the Vector4Ds have the same coordinates; otherwise false</returns>
public static bool operator ==(Vector4D left, Vector4D right)
{
return left.X == right.X && left.Y == right.Y && left.Z == right.Z && left.W == right.W;
}
/// <summary>
/// Specifies whether the Vector4Ds do not contain the same coordinates.
/// </summary>
/// <param name="left">The left Vector4D to test.</param>
/// <param name="right">The right Vector4D to test.</param>
/// <returns>true if the Vector4Ds do not have the same coordinates; otherwise false</returns>
public static bool operator !=(Vector4D left, Vector4D right)
{
return !(left.X == right.X && left.Y == right.Y && left.Z == right.Z && left.W == right.W);
}
public static explicit operator Vector4D(Vector3D source)
{
Vector4D result;
result.X = source.X;
result.Y = source.Y;
result.Z = source.Z;
result.W = 1;
return result;
}
#endregion
#region overrides
private string ToStringInternal(string FormatString)
{
return string.Format(FormatString, X, Y, Z, W);
}
public string ToString(string format)
{
return ToStringInternal(string.Format(FormatableString, format));
}
public override string ToString()
{
return ToStringInternal(FormatString);
}
#if !CompactFramework && !WindowsCE && !PocketPC && !XBOX360 && !SILVERLIGHT
public static bool TryParse(string s, out Vector4D result)
{
if (s == null)
{
result = Zero;
return false;
}
string[] vals = ParseHelper.SplitStringVector(s);
if (vals.Length != Count)
{
result = Zero;
return false;
}
if (Scalar.TryParse(vals[0], out result.X) &&
Scalar.TryParse(vals[1], out result.Y) &&
Scalar.TryParse(vals[2], out result.Z) &&
Scalar.TryParse(vals[3], out result.W))
{
return true;
}
else
{
result = Zero;
return false;
}
}
#endif
[ParseMethod]
public static Vector4D Parse(string s)
{
if (s == null)
{
throw new ArgumentNullException("s");
}
string[] vals = ParseHelper.SplitStringVector(s);
if (vals.Length != Count)
{
ThrowHelper.ThrowVectorFormatException(s, Count, FormatString);
}
Vector4D value;
value.X = Scalar.Parse(vals[0]);
value.Y = Scalar.Parse(vals[1]);
value.Z = Scalar.Parse(vals[2]);
value.W = Scalar.Parse(vals[3]);
return value;
}
/// <summary>
/// Provides a unique hash code based on the member variables of this
/// class. This should be done because the equality operators (==, !=)
/// have been overriden by this class.
/// <p/>
/// The standard implementation is a simple XOR operation between all local
/// member variables.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return X.GetHashCode() ^ Y.GetHashCode() ^ Z.GetHashCode() ^ W.GetHashCode();
}
/// <summary>
/// Compares this Vector to another object. This should be done because the
/// equality operators (==, !=) have been overriden by this class.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
return (obj is Vector4D) && Equals((Vector4D)obj);
}
public bool Equals(Vector4D other)
{
return Equals(ref this, ref other);
}
public static bool Equals(Vector4D left, Vector4D right)
{
return
left.X == right.X &&
left.Y == right.Y &&
left.Z == right.Z &&
left.W == right.W;
}
[CLSCompliant(false)]
public static bool Equals(ref Vector4D left, ref Vector4D right)
{
return
left.X == right.X &&
left.Y == right.Y &&
left.Z == right.Z &&
left.W == right.W;
}
#endregion
}
}
| |
/* Copyright (C) 2008-2018 Peter Palotas, Jeffrey Jangli, Alexandr Normuradov
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
using System.Diagnostics.CodeAnalysis;
namespace Alphaleonis.Win32.Network
{
/// <summary>Contains operating statistics for the Workstation service.</summary>
[Serializable]
public sealed class WorkstationStatisticsInfo : IEquatable<WorkstationStatisticsInfo>
{
#region Fields
[NonSerialized] private NativeMethods.STAT_WORKSTATION_0 _workstationStat;
#endregion // Fields
#region Constructors
/// <summary>Create a WorkstationStatisticsInfo instance from the local host.</summary>
public WorkstationStatisticsInfo() : this(Environment.MachineName, null)
{
}
/// <summary>Create a WorkstationStatisticsInfo instance from the specified host name.</summary>
/// <param name="hostName">The host name.</param>
public WorkstationStatisticsInfo(string hostName) : this(hostName, null)
{
}
/// <summary>Create a ServerStatisticsInfo instance from the specified host name.</summary>
internal WorkstationStatisticsInfo(string hostName, NativeMethods.STAT_WORKSTATION_0? workstationStat)
{
HostName = !Utils.IsNullOrWhiteSpace(hostName) ? hostName : Environment.MachineName;
if (workstationStat.HasValue)
_workstationStat = (NativeMethods.STAT_WORKSTATION_0) workstationStat;
else
Refresh();
}
#endregion // Constructors
#region Properties
/// <summary>The total number of bytes received by the workstation.</summary>
public long BytesReceived
{
get { return _workstationStat.BytesReceived; }
}
/// <summary>The total number of bytes received by the workstation, formatted as a unit size.</summary>
public string BytesReceivedUnitSize
{
get { return Utils.UnitSizeToText(BytesReceived); }
}
/// <summary>The total number of bytes transmitted by the workstation.</summary>
public long BytesTransmitted
{
get { return _workstationStat.BytesTransmitted; }
}
/// <summary>The total number of bytes transmitted by the workstation, formatted as a unit size.</summary>
public string BytesTransmittedUnitSize
{
get { return Utils.UnitSizeToText(BytesTransmitted); }
}
/// <summary>The total number of bytes that have been read by cache I/O requests.</summary>
public long CacheReadBytesRequested
{
get { return _workstationStat.CacheReadBytesRequested; }
}
/// <summary>The total number of bytes that have been read by cache I/O requests, formatted as a unit size.</summary>
public string CacheReadBytesRequestedUnitSize
{
get { return Utils.UnitSizeToText(CacheReadBytesRequested); }
}
/// <summary>The total number of bytes that have been written by cache I/O requests.</summary>
public long CacheWriteBytesRequested
{
get { return _workstationStat.CacheWriteBytesRequested; }
}
/// <summary>The total number of bytes that have been written by cache I/O requests, formatted as a unit size.</summary>
public string CacheWriteBytesRequestedUnitSize
{
get { return Utils.UnitSizeToText(CacheWriteBytesRequested); }
}
/// <summary>The total number of connections to servers supporting the PCNET dialect that have succeeded.</summary>
public int CoreConnects
{
get { return (int) _workstationStat.CoreConnects; }
}
/// <summary>The number of current requests that have not been completed.</summary>
public int CurrentCommands
{
get { return (int) _workstationStat.CurrentCommands; }
}
/// <summary>The total number of network operations that failed to complete.</summary>
public int FailedCompletionOperations
{
get { return (int) _workstationStat.FailedCompletionOperations; }
}
/// <summary>The number of times the workstation attempted to create a session but failed.</summary>
public int FailedSessions
{
get { return (int) _workstationStat.FailedSessions; }
}
/// <summary>The total number of failed network connections for the workstation.</summary>
public int FailedUseCount
{
get { return (int) _workstationStat.FailedUseCount; }
}
/// <summary>The host name from where the statistics are gathered.</summary>
public string HostName { get; private set; }
/// <summary>The total number of network operations that failed to begin.</summary>
public int InitiallyFailedOperations
{
get { return (int) _workstationStat.InitiallyFailedOperations; }
}
/// <summary>The total number of sessions that have expired on the workstation.</summary>
public int HungSessions
{
get { return (int) _workstationStat.HungSessions; }
}
/// <summary>The total number of connections to servers supporting the LanManager 2.0 dialect that have succeeded.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lanman")]
public int Lanman20Connects
{
get { return (int) _workstationStat.Lanman20Connects; }
}
/// <summary>The total number of connections to servers supporting the LanManager 2.1 dialect that have succeeded.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lanman")]
public int Lanman21Connects
{
get { return (int) _workstationStat.Lanman21Connects; }
}
/// <summary>The total number of connections to servers supporting the NTLM dialect that have succeeded.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Nt")]
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Lanman")]
[SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Nt")]
public int LanmanNtConnects
{
get { return (int) _workstationStat.LanmanNtConnects; }
}
/// <summary>The total number of read requests the workstation has sent to servers that are greater than twice the size of the server's negotiated buffer size.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
public int LargeReadSmbs
{
get { return (int) _workstationStat.LargeReadSmbs; }
}
/// <summary>The total number of write requests the workstation has sent to servers that are greater than twice the size of the server's negotiated buffer size.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
public int LargeWriteSmbs
{
get { return (int) _workstationStat.LargeWriteSmbs; }
}
/// <summary>The total number of network errors received by the workstation.</summary>
public int NetworkErrors
{
get { return (int) _workstationStat.NetworkErrors; }
}
/// <summary>The total amount of bytes that have been read by disk I/O requests.</summary>
public long NetworkReadBytesRequested
{
get { return _workstationStat.NetworkReadBytesRequested; }
}
/// <summary>The total amount of bytes that have been read by disk I/O requests, formatted as a unit size.</summary>
public string NetworkReadBytesRequestedUnitSize
{
get { return Utils.UnitSizeToText(NetworkReadBytesRequested); }
}
/// <summary>The total number of bytes that have been written by disk I/O requests.</summary>
public long NetworkWriteBytesRequested
{
get { return _workstationStat.NetworkWriteBytesRequested; }
}
/// <summary>The total number of bytes that have been written by disk I/O requests, formatted as a unit size.</summary>
public string NetworkWriteBytesRequestedUnitSize
{
get { return Utils.UnitSizeToText(NetworkWriteBytesRequested); }
}
/// <summary>The total number of bytes that have been read by non-paging I/O requests.</summary>
public long NonPagingReadBytesRequested
{
get { return _workstationStat.NonPagingReadBytesRequested; }
}
/// <summary>The total number of bytes that have been read by non-paging I/O requests, formatted as a unit size.</summary>
public string NonPagingReadBytesRequestedUnitSize
{
get { return Utils.UnitSizeToText(NonPagingReadBytesRequested); }
}
/// <summary>The total number of bytes that have been written by non-paging I/O requests.</summary>
public long NonPagingWriteBytesRequested
{
get { return _workstationStat.NonPagingWriteBytesRequested; }
}
/// <summary>The total number of bytes that have been written by non-paging I/O requests, formatted as a unit size.</summary>
public string NonPagingWriteBytesRequestedUnitSize
{
get { return Utils.UnitSizeToText(NonPagingWriteBytesRequested); }
}
/// <summary>The total number of bytes that have been read by paging I/O requests.</summary>
public long PagingReadBytesRequested
{
get { return _workstationStat.PagingReadBytesRequested; }
}
/// <summary>The total number of bytes that have been read by paging I/O requests, formatted as a unit size.</summary>
public string PagingReadBytesRequestedUnitSize
{
get { return Utils.UnitSizeToText(PagingReadBytesRequested); }
}
/// <summary>The total number of bytes that have been written by paging I/O requests.</summary>
public long PagingWriteBytesRequested
{
get { return _workstationStat.PagingWriteBytesRequested; }
}
/// <summary>The total number of bytes that have been written by paging I/O requests, formatted as a unit size.</summary>
public string PagingWriteBytesRequestedUnitSize
{
get { return Utils.UnitSizeToText(PagingWriteBytesRequested); }
}
/// <summary>The total number of random access reads initiated by the workstation.</summary>
public int RandomReadOperations
{
get { return (int) _workstationStat.RandomReadOperations; }
}
/// <summary>The total number of random access writes initiated by the workstation.</summary>
public int RandomWriteOperations
{
get { return (int) _workstationStat.RandomWriteOperations; }
}
/// <summary>The total number of raw read requests made by the workstation that have been denied.</summary>
public int RawReadsDenied
{
get { return (int) _workstationStat.RawReadsDenied; }
}
/// <summary>The total number of raw write requests made by the workstation that have been denied.</summary>
public int RawWritesDenied
{
get { return (int) _workstationStat.RawWritesDenied; }
}
/// <summary>The total number of read operations initiated by the workstation.</summary>
public int ReadOperations
{
get { return (int) _workstationStat.ReadOperations; }
}
/// <summary>The total number of read requests the workstation has sent to servers.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
public int ReadSmbs
{
get { return (int) _workstationStat.ReadSmbs; }
}
/// <summary>The total number of connections that have failed.</summary>
public int Reconnects
{
get { return (int) _workstationStat.Reconnects; }
}
/// <summary>The number of times the workstation was disconnected by a network server.</summary>
public int ServerDisconnects
{
get { return (int) _workstationStat.ServerDisconnects; }
}
/// <summary>The total number of workstation sessions that were established.</summary>
public int Sessions
{
get { return (int) _workstationStat.Sessions; }
}
/// <summary>The total number of read requests the workstation has sent to servers that are less than 1/4 of the size of the server's negotiated buffer size.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
public int SmallReadSmbs
{
get { return (int) _workstationStat.SmallReadSmbs; }
}
/// <summary>The total number of write requests the workstation has sent to servers that are less than 1/4 of the size of the server's negotiated buffer size.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
public int SmallWriteSmbs
{
get { return (int) _workstationStat.SmallWriteSmbs; }
}
/// <summary>The local time statistics collection started. This member also indicates when statistics for the workstations were last cleared.</summary>
public DateTime StatisticsStartTime
{
get { return StatisticsStartTimeUtc.ToLocalTime(); }
}
/// <summary>The time statistics collection started. This member also indicates when statistics for the workstations were last cleared.</summary>
public DateTime StatisticsStartTimeUtc
{
get { return DateTime.FromFileTimeUtc(_workstationStat.StatisticsStartTime); }
}
/// <summary>The total number of server message blocks (SMBs) received by the workstation.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
public long SmbsReceived
{
get { return _workstationStat.SmbsReceived; }
}
/// <summary>The total number of SMBs transmitted by the workstation.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
public long SmbsTransmitted
{
get { return _workstationStat.SmbsTransmitted; }
}
/// <summary>The total number of network connections established by the workstation.</summary>
public int UseCount
{
get { return (int) _workstationStat.UseCount; }
}
/// <summary>The total number of write operations initiated by the workstation.</summary>
public int WriteOperations
{
get { return (int) _workstationStat.WriteOperations; }
}
/// <summary>The total number of write requests the workstation has sent to servers.</summary>
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Smbs")]
public int WriteSmbs
{
get { return (int) _workstationStat.WriteSmbs; }
}
#endregion // Properties
#region Methods
/// <summary>Refreshes the state of the object.</summary>
public void Refresh()
{
_workstationStat = Host.GetNetStatisticsNative<NativeMethods.STAT_WORKSTATION_0>(false, HostName);
}
/// <summary>Returns the local time when statistics collection started or when the statistics were last cleared.</summary>
/// <returns>A string that represents this instance.</returns>
public override string ToString()
{
return HostName;
}
/// <summary>Serves as a hash function for a particular type.</summary>
/// <returns>A hash code for the current Object.</returns>
public override int GetHashCode()
{
return Utils.CombineHashCodesOf(HostName, BytesTransmitted, StatisticsStartTime);
}
/// <summary>Determines whether the specified Object is equal to the current Object.</summary>
/// <param name="other">Another <see cref="WorkstationStatisticsInfo"/> instance to compare to.</param>
/// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
public bool Equals(WorkstationStatisticsInfo other)
{
return null != other && GetType() == other.GetType() &&
Equals(HostName, other.HostName) &&
Equals(BytesTransmitted, other.BytesTransmitted) &&
Equals(BytesReceived, other.BytesReceived) &&
Equals(StatisticsStartTimeUtc, other.StatisticsStartTimeUtc);
}
/// <summary>Determines whether the specified Object is equal to the current Object.</summary>
/// <param name="obj">Another object to compare to.</param>
/// <returns><c>true</c> if the specified Object is equal to the current Object; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
var other = obj as WorkstationStatisticsInfo;
return null != other && Equals(other);
}
/// <summary>Implements the operator ==</summary>
/// <param name="left">A.</param>
/// <param name="right">B.</param>
/// <returns>The result of the operator.</returns>
public static bool operator ==(WorkstationStatisticsInfo left, WorkstationStatisticsInfo right)
{
return ReferenceEquals(left, null) && ReferenceEquals(right, null) ||
!ReferenceEquals(left, null) && !ReferenceEquals(right, null) && left.Equals(right);
}
/// <summary>Implements the operator !=</summary>
/// <param name="left">A.</param>
/// <param name="right">B.</param>
/// <returns>The result of the operator.</returns>
public static bool operator !=(WorkstationStatisticsInfo left, WorkstationStatisticsInfo right)
{
return !(left == right);
}
#endregion // Methods
}
}
| |
// 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.Xml;
using System.Xml.Schema;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Security;
namespace System.Runtime.Serialization
{
#if USE_REFEMIT || NET_NATIVE
public delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract);
public delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract);
#else
internal delegate void XmlFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract dataContract);
internal delegate void XmlFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, CollectionDataContract dataContract);
internal sealed class XmlFormatWriterGenerator
{
[SecurityCritical]
/// <SecurityNote>
/// Critical - holds instance of CriticalHelper which keeps state that was produced within an assert
/// </SecurityNote>
private CriticalHelper _helper;
/// <SecurityNote>
/// Critical - initializes SecurityCritical field 'helper'
/// </SecurityNote>
[SecurityCritical]
public XmlFormatWriterGenerator()
{
_helper = new CriticalHelper();
}
/// <SecurityNote>
/// Critical - accesses SecurityCritical helper class 'CriticalHelper'
/// </SecurityNote>
[SecurityCritical]
internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract)
{
return _helper.GenerateClassWriter(classContract);
}
/// <SecurityNote>
/// Critical - accesses SecurityCritical helper class 'CriticalHelper'
/// </SecurityNote>
[SecurityCritical]
internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract)
{
return _helper.GenerateCollectionWriter(collectionContract);
}
/// <SecurityNote>
/// Review - handles all aspects of IL generation including initializing the DynamicMethod.
/// changes to how IL generated could affect how data is serialized and what gets access to data,
/// therefore we mark it for review so that changes to generation logic are reviewed.
/// </SecurityNote>
private class CriticalHelper
{
private CodeGenerator _ilg;
private ArgBuilder _xmlWriterArg;
private ArgBuilder _contextArg;
private ArgBuilder _dataContractArg;
private LocalBuilder _objectLocal;
// Used for classes
private LocalBuilder _contractNamespacesLocal;
private LocalBuilder _memberNamesLocal;
private LocalBuilder _childElementNamespacesLocal;
private int _typeIndex = 1;
private int _childElementIndex = 0;
private bool _useReflection = true;
internal XmlFormatClassWriterDelegate GenerateClassWriter(ClassDataContract classContract)
{
if (_useReflection)
{
return new ReflectionXmlFormatWriter().ReflectionWriteClass;
}
else
{
_ilg = new CodeGenerator();
bool memberAccessFlag = classContract.RequiresMemberAccessForWrite(null);
try
{
_ilg.BeginMethod("Write" + classContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatClassWriterDelegate, memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
classContract.RequiresMemberAccessForWrite(securityException);
}
else
{
throw;
}
}
InitArgs(classContract.UnderlyingType);
WriteClass(classContract);
return (XmlFormatClassWriterDelegate)_ilg.EndMethod();
}
}
internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDataContract collectionContract)
{
if (_useReflection)
{
return new ReflectionXmlFormatWriter().ReflectionWriteCollection;
}
else
{
_ilg = new CodeGenerator();
bool memberAccessFlag = collectionContract.RequiresMemberAccessForWrite(null);
try
{
_ilg.BeginMethod("Write" + collectionContract.StableName.Name + "ToXml", Globals.TypeOfXmlFormatCollectionWriterDelegate, memberAccessFlag);
}
catch (SecurityException securityException)
{
if (memberAccessFlag)
{
collectionContract.RequiresMemberAccessForWrite(securityException);
}
else
{
throw;
}
}
InitArgs(collectionContract.UnderlyingType);
WriteCollection(collectionContract);
return (XmlFormatCollectionWriterDelegate)_ilg.EndMethod();
}
}
private void InitArgs(Type objType)
{
_xmlWriterArg = _ilg.GetArg(0);
_contextArg = _ilg.GetArg(2);
_dataContractArg = _ilg.GetArg(3);
_objectLocal = _ilg.DeclareLocal(objType, "objSerialized");
ArgBuilder objectArg = _ilg.GetArg(1);
_ilg.Load(objectArg);
// Copy the data from the DataTimeOffset object passed in to the DateTimeOffsetAdapter.
// DateTimeOffsetAdapter is used here for serialization purposes to bypass the ISerializable implementation
// on DateTimeOffset; which does not work in partial trust.
if (objType == Globals.TypeOfDateTimeOffsetAdapter)
{
_ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfDateTimeOffset);
_ilg.Call(XmlFormatGeneratorStatics.GetDateTimeOffsetAdapterMethod);
}
//Copy the KeyValuePair<K,T> to a KeyValuePairAdapter<K,T>.
else if (objType.GetTypeInfo().IsGenericType && objType.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter)
{
ClassDataContract dc = (ClassDataContract)DataContract.GetDataContract(objType);
_ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments));
_ilg.New(dc.KeyValuePairAdapterConstructorInfo);
}
else
{
_ilg.ConvertValue(objectArg.ArgType, objType);
}
_ilg.Stloc(_objectLocal);
}
private void InvokeOnSerializing(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnSerializing(classContract.BaseContract);
if (classContract.OnSerializing != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnSerializing);
}
}
private void InvokeOnSerialized(ClassDataContract classContract)
{
if (classContract.BaseContract != null)
InvokeOnSerialized(classContract.BaseContract);
if (classContract.OnSerialized != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.GetStreamingContextMethod);
_ilg.Call(classContract.OnSerialized);
}
}
private void WriteClass(ClassDataContract classContract)
{
InvokeOnSerializing(classContract);
{
if (classContract.ContractNamespaces.Length > 1)
{
_contractNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "contractNamespaces");
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.ContractNamespacesField);
_ilg.Store(_contractNamespacesLocal);
}
_memberNamesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "memberNames");
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.MemberNamesField);
_ilg.Store(_memberNamesLocal);
for (int i = 0; i < classContract.ChildElementNamespaces.Length; i++)
{
if (classContract.ChildElementNamespaces[i] != null)
{
_childElementNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "childElementNamespaces");
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespacesProperty);
_ilg.Store(_childElementNamespacesLocal);
}
}
WriteMembers(classContract, null, classContract);
}
InvokeOnSerialized(classContract);
}
private int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract)
{
int memberCount = (classContract.BaseContract == null) ? 0 :
WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract);
LocalBuilder namespaceLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString), "ns");
if (_contractNamespacesLocal == null)
{
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty);
}
else
_ilg.LoadArrayElement(_contractNamespacesLocal, _typeIndex - 1);
_ilg.Store(namespaceLocal);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classContract.Members.Count);
for (int i = 0; i < classContract.Members.Count; i++, memberCount++)
{
DataMember member = classContract.Members[i];
Type memberType = member.MemberType;
LocalBuilder memberValue = null;
if (member.IsGetOnlyCollection)
{
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.StoreIsGetOnlyCollectionMethod);
}
if (!member.EmitDefaultValue)
{
memberValue = LoadMemberValue(member);
_ilg.IfNotDefaultValue(memberValue);
}
bool writeXsiType = CheckIfMemberHasConflict(member, classContract, derivedMostClassContract);
if (writeXsiType || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, null /*arrayItemIndex*/, namespaceLocal, null /*nameLocal*/, i + _childElementIndex))
{
WriteStartElement(memberType, classContract.Namespace, namespaceLocal, null /*nameLocal*/, i + _childElementIndex);
if (classContract.ChildElementNamespaces[i + _childElementIndex] != null)
{
_ilg.Load(_xmlWriterArg);
_ilg.LoadArrayElement(_childElementNamespacesLocal, i + _childElementIndex);
_ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod);
}
if (memberValue == null)
memberValue = LoadMemberValue(member);
WriteValue(memberValue, writeXsiType);
WriteEndElement();
}
if (!member.EmitDefaultValue)
{
if (member.IsRequired)
{
_ilg.Else();
_ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMustBeEmittedMethod, member.Name, classContract.UnderlyingType);
}
_ilg.EndIf();
}
}
_typeIndex++;
_childElementIndex += classContract.Members.Count;
return memberCount;
}
private LocalBuilder LoadMemberValue(DataMember member)
{
_ilg.LoadAddress(_objectLocal);
_ilg.LoadMember(member.MemberInfo);
LocalBuilder memberValue = _ilg.DeclareLocal(member.MemberType, member.Name + "Value");
_ilg.Stloc(memberValue);
return memberValue;
}
private void WriteCollection(CollectionDataContract collectionContract)
{
LocalBuilder itemNamespace = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemNamespace");
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.NamespaceProperty);
_ilg.Store(itemNamespace);
LocalBuilder itemName = _ilg.DeclareLocal(typeof(XmlDictionaryString), "itemName");
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.CollectionItemNameProperty);
_ilg.Store(itemName);
if (collectionContract.ChildElementNamespace != null)
{
_ilg.Load(_xmlWriterArg);
_ilg.Load(_dataContractArg);
_ilg.LoadMember(XmlFormatGeneratorStatics.ChildElementNamespaceProperty);
_ilg.Call(XmlFormatGeneratorStatics.WriteNamespaceDeclMethod);
}
if (collectionContract.Kind == CollectionKind.Array)
{
Type itemType = collectionContract.ItemType;
LocalBuilder i = _ilg.DeclareLocal(Globals.TypeOfInt, "i");
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementArrayCountMethod, _xmlWriterArg, _objectLocal);
if (!TryWritePrimitiveArray(collectionContract.UnderlyingType, itemType, _objectLocal, itemName, itemNamespace))
{
_ilg.For(i, 0, _objectLocal);
if (!TryWritePrimitive(itemType, null /*value*/, null /*memberInfo*/, i /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/))
{
WriteStartElement(itemType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/);
_ilg.LoadArrayElement(_objectLocal, i);
LocalBuilder memberValue = _ilg.DeclareLocal(itemType, "memberValue");
_ilg.Stloc(memberValue);
WriteValue(memberValue, false /*writeXsiType*/);
WriteEndElement();
}
_ilg.EndFor();
}
}
else
{
MethodInfo incrementCollectionCountMethod = null;
switch (collectionContract.Kind)
{
case CollectionKind.Collection:
case CollectionKind.List:
case CollectionKind.Dictionary:
incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountMethod;
break;
case CollectionKind.GenericCollection:
case CollectionKind.GenericList:
incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(collectionContract.ItemType);
break;
case CollectionKind.GenericDictionary:
incrementCollectionCountMethod = XmlFormatGeneratorStatics.IncrementCollectionCountGenericMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(collectionContract.ItemType.GetGenericArguments()));
break;
}
if (incrementCollectionCountMethod != null)
{
_ilg.Call(_contextArg, incrementCollectionCountMethod, _xmlWriterArg, _objectLocal);
}
bool isDictionary = false, isGenericDictionary = false;
Type enumeratorType = null;
Type[] keyValueTypes = null;
if (collectionContract.Kind == CollectionKind.GenericDictionary)
{
isGenericDictionary = true;
keyValueTypes = collectionContract.ItemType.GetGenericArguments();
enumeratorType = Globals.TypeOfGenericDictionaryEnumerator.MakeGenericType(keyValueTypes);
}
else if (collectionContract.Kind == CollectionKind.Dictionary)
{
isDictionary = true;
keyValueTypes = new Type[] { Globals.TypeOfObject, Globals.TypeOfObject };
enumeratorType = Globals.TypeOfDictionaryEnumerator;
}
else
{
enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType;
}
MethodInfo moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty<Type>());
if (moveNextMethod == null || getCurrentMethod == null)
{
if (enumeratorType.GetTypeInfo().IsInterface)
{
if (moveNextMethod == null)
moveNextMethod = XmlFormatGeneratorStatics.MoveNextMethod;
if (getCurrentMethod == null)
getCurrentMethod = XmlFormatGeneratorStatics.GetCurrentMethod;
}
else
{
Type ienumeratorInterface = Globals.TypeOfIEnumerator;
CollectionKind kind = collectionContract.Kind;
if (kind == CollectionKind.GenericDictionary || kind == CollectionKind.GenericCollection || kind == CollectionKind.GenericEnumerable)
{
Type[] interfaceTypes = enumeratorType.GetInterfaces();
foreach (Type interfaceType in interfaceTypes)
{
if (interfaceType.GetTypeInfo().IsGenericType
&& interfaceType.GetGenericTypeDefinition() == Globals.TypeOfIEnumeratorGeneric
&& interfaceType.GetGenericArguments()[0] == collectionContract.ItemType)
{
ienumeratorInterface = interfaceType;
break;
}
}
}
if (moveNextMethod == null)
moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface);
if (getCurrentMethod == null)
getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface);
}
}
Type elementType = getCurrentMethod.ReturnType;
LocalBuilder currentValue = _ilg.DeclareLocal(elementType, "currentValue");
LocalBuilder enumerator = _ilg.DeclareLocal(enumeratorType, "enumerator");
_ilg.Call(_objectLocal, collectionContract.GetEnumeratorMethod);
if (isDictionary)
{
_ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, Globals.TypeOfIDictionaryEnumerator);
_ilg.New(XmlFormatGeneratorStatics.DictionaryEnumeratorCtor);
}
else if (isGenericDictionary)
{
Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes));
ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam });
_ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam);
_ilg.New(dictEnumCtor);
}
_ilg.Stloc(enumerator);
_ilg.ForEach(currentValue, elementType, enumeratorType, enumerator, getCurrentMethod);
if (incrementCollectionCountMethod == null)
{
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, 1);
}
if (!TryWritePrimitive(elementType, currentValue, null /*memberInfo*/, null /*arrayItemIndex*/, itemNamespace, itemName, 0 /*nameIndex*/))
{
WriteStartElement(elementType, collectionContract.Namespace, itemNamespace, itemName, 0 /*nameIndex*/);
if (isGenericDictionary || isDictionary)
{
_ilg.Call(_dataContractArg, XmlFormatGeneratorStatics.GetItemContractMethod);
_ilg.Load(_xmlWriterArg);
_ilg.Load(currentValue);
_ilg.ConvertValue(currentValue.LocalType, Globals.TypeOfObject);
_ilg.Load(_contextArg);
_ilg.Call(XmlFormatGeneratorStatics.WriteXmlValueMethod);
}
else
{
WriteValue(currentValue, false /*writeXsiType*/);
}
WriteEndElement();
}
_ilg.EndForEach(moveNextMethod);
}
}
private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberInfo, LocalBuilder arrayItemIndex, LocalBuilder ns, LocalBuilder name, int nameIndex)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type);
if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject)
return false;
// load xmlwriter
if (type.GetTypeInfo().IsValueType)
{
_ilg.Load(_xmlWriterArg);
}
else
{
_ilg.Load(_contextArg);
_ilg.Load(_xmlWriterArg);
}
// load primitive value
if (value != null)
{
_ilg.Load(value);
}
else if (memberInfo != null)
{
_ilg.LoadAddress(_objectLocal);
_ilg.LoadMember(memberInfo);
}
else
{
_ilg.LoadArrayElement(_objectLocal, arrayItemIndex);
}
// load name
if (name != null)
{
_ilg.Load(name);
}
else
{
_ilg.LoadArrayElement(_memberNamesLocal, nameIndex);
}
// load namespace
_ilg.Load(ns);
// call method to write primitive
_ilg.Call(primitiveContract.XmlFormatWriterMethod);
return true;
}
private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName, LocalBuilder itemNamespace)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType);
if (primitiveContract == null)
return false;
string writeArrayMethod = null;
switch (itemType.GetTypeCode())
{
case TypeCode.Boolean:
writeArrayMethod = "WriteBooleanArray";
break;
case TypeCode.DateTime:
writeArrayMethod = "WriteDateTimeArray";
break;
case TypeCode.Decimal:
writeArrayMethod = "WriteDecimalArray";
break;
case TypeCode.Int32:
writeArrayMethod = "WriteInt32Array";
break;
case TypeCode.Int64:
writeArrayMethod = "WriteInt64Array";
break;
case TypeCode.Single:
writeArrayMethod = "WriteSingleArray";
break;
case TypeCode.Double:
writeArrayMethod = "WriteDoubleArray";
break;
default:
break;
}
if (writeArrayMethod != null)
{
_ilg.Load(_xmlWriterArg);
_ilg.Load(value);
_ilg.Load(itemName);
_ilg.Load(itemNamespace);
_ilg.Call(typeof(XmlWriterDelegator).GetMethod(writeArrayMethod, Globals.ScanAllMembers, new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }));
return true;
}
return false;
}
private void WriteValue(LocalBuilder memberValue, bool writeXsiType)
{
Type memberType = memberValue.LocalType;
bool isNullableOfT = (memberType.GetTypeInfo().IsGenericType &&
memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable);
if (memberType.GetTypeInfo().IsValueType && !isNullableOfT)
{
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
if (primitiveContract != null && !writeXsiType)
_ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue);
else
InternalSerialize(XmlFormatGeneratorStatics.InternalSerializeMethod, memberValue, memberType, writeXsiType);
}
else
{
if (isNullableOfT)
{
memberValue = UnwrapNullableObject(memberValue);//Leaves !HasValue on stack
memberType = memberValue.LocalType;
}
else
{
_ilg.Load(memberValue);
_ilg.Load(null);
_ilg.Ceq();
}
_ilg.If();
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType));
_ilg.Else();
PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType);
if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType)
{
if (isNullableOfT)
{
_ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue);
}
else
{
_ilg.Call(_contextArg, primitiveContract.XmlFormatContentWriterMethod, _xmlWriterArg, memberValue);
}
}
else
{
if (memberType == Globals.TypeOfObject ||//boxed Nullable<T>
memberType == Globals.TypeOfValueType ||
((IList)Globals.TypeOfNullable.GetInterfaces()).Contains(memberType))
{
_ilg.Load(memberValue);
_ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject);
memberValue = _ilg.DeclareLocal(Globals.TypeOfObject, "unwrappedMemberValue");
memberType = memberValue.LocalType;
_ilg.Stloc(memberValue);
_ilg.If(memberValue, Cmp.EqualTo, null);
_ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType));
_ilg.Else();
}
InternalSerialize((isNullableOfT ? XmlFormatGeneratorStatics.InternalSerializeMethod : XmlFormatGeneratorStatics.InternalSerializeReferenceMethod),
memberValue, memberType, writeXsiType);
if (memberType == Globals.TypeOfObject) //boxed Nullable<T>
_ilg.EndIf();
}
_ilg.EndIf();
}
}
private void InternalSerialize(MethodInfo methodInfo, LocalBuilder memberValue, Type memberType, bool writeXsiType)
{
_ilg.Load(_contextArg);
_ilg.Load(_xmlWriterArg);
_ilg.Load(memberValue);
_ilg.ConvertValue(memberValue.LocalType, Globals.TypeOfObject);
//In SL GetTypeHandle throws MethodAccessException as its internal and extern.
//So as a workaround, call XmlObjectSerializerWriteContext.IsMemberTypeSameAsMemberValue that
//does the actual comparison and returns the bool value we care.
_ilg.Call(null, XmlFormatGeneratorStatics.IsMemberTypeSameAsMemberValue, memberValue, memberType);
_ilg.Load(writeXsiType);
_ilg.Load(DataContract.GetId(memberType.TypeHandle));
_ilg.Ldtoken(memberType);
_ilg.Call(methodInfo);
}
private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !HasValue on stack
{
Type memberType = memberValue.LocalType;
Label onNull = _ilg.DefineLabel();
Label end = _ilg.DefineLabel();
_ilg.Load(memberValue);
while (memberType.GetTypeInfo().IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable)
{
Type innerType = memberType.GetGenericArguments()[0];
_ilg.Dup();
_ilg.Call(XmlFormatGeneratorStatics.GetHasValueMethod.MakeGenericMethod(innerType));
_ilg.Brfalse(onNull);
_ilg.Call(XmlFormatGeneratorStatics.GetNullableValueMethod.MakeGenericMethod(innerType));
memberType = innerType;
}
memberValue = _ilg.DeclareLocal(memberType, "nullableUnwrappedMemberValue");
_ilg.Stloc(memberValue);
_ilg.Load(false); //isNull
_ilg.Br(end);
_ilg.MarkLabel(onNull);
_ilg.Pop();
_ilg.Call(XmlFormatGeneratorStatics.GetDefaultValueMethod.MakeGenericMethod(memberType));
_ilg.Stloc(memberValue);
_ilg.Load(true);//isNull
_ilg.MarkLabel(end);
return memberValue;
}
private bool NeedsPrefix(Type type, XmlDictionaryString ns)
{
return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0);
}
private void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder namespaceLocal, LocalBuilder nameLocal, int nameIndex)
{
bool needsPrefix = NeedsPrefix(type, ns);
_ilg.Load(_xmlWriterArg);
// prefix
if (needsPrefix)
_ilg.Load(Globals.ElementPrefix);
// localName
if (nameLocal == null)
_ilg.LoadArrayElement(_memberNamesLocal, nameIndex);
else
_ilg.Load(nameLocal);
// namespace
_ilg.Load(namespaceLocal);
_ilg.Call(needsPrefix ? XmlFormatGeneratorStatics.WriteStartElementMethod3 : XmlFormatGeneratorStatics.WriteStartElementMethod2);
}
private void WriteEndElement()
{
_ilg.Call(_xmlWriterArg, XmlFormatGeneratorStatics.WriteEndElementMethod);
}
private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract classContract, ClassDataContract derivedMostClassContract)
{
// Check for conflict with base type members
if (CheckIfConflictingMembersHaveDifferentTypes(member))
return true;
// Check for conflict with derived type members
string name = member.Name;
string ns = classContract.StableName.Namespace;
ClassDataContract currentContract = derivedMostClassContract;
while (currentContract != null && currentContract != classContract)
{
if (ns == currentContract.StableName.Namespace)
{
List<DataMember> members = currentContract.Members;
for (int j = 0; j < members.Count; j++)
{
if (name == members[j].Name)
return CheckIfConflictingMembersHaveDifferentTypes(members[j]);
}
}
currentContract = currentContract.BaseContract;
}
return false;
}
private bool CheckIfConflictingMembersHaveDifferentTypes(DataMember member)
{
while (member.ConflictingMember != null)
{
if (member.MemberType != member.ConflictingMember.MemberType)
return true;
member = member.ConflictingMember;
}
return false;
}
}
}
#endif
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.Lambda.Core;
using HoneyBear.Alexa.Kodi.Commands;
using HoneyBear.Alexa.Kodi.Models;
using HoneyBear.Alexa.Kodi.Queries;
using Slight.Alexa.Framework.Models.Requests.RequestTypes;
using Slight.Alexa.Framework.Models.Responses;
using JsonSerializer = Amazon.Lambda.Serialization.Json.JsonSerializer;
using HoneyBear.Alexa.Kodi.Proxies.Alexa;
// Assembly attribute to enable the Lambda function's JSON input to be converted into a .NET class.
[assembly: LambdaSerializer(typeof(JsonSerializer))]
namespace HoneyBear.Alexa.Kodi
{
public sealed class Function
{
private ILambdaLogger _log;
private readonly SongQueueReader _queueReader;
private readonly SongQueueWriter _queueWriter;
private readonly LibraryWriter _library;
private readonly SongReader _songs;
private static Song _currentSong;
private static int _currentOffsetInMilliseconds;
public Function()
{
_queueReader = new SongQueueReader();
_queueWriter = new SongQueueWriter();
_library = new LibraryWriter();
_songs = new SongReader();
}
public AudioSkillResponse Handle(AudioSkillRequest input, ILambdaContext context)
{
_log = context.Logger;
_log.LogLine($"Request type={input.GetRequestType()}.");
if (input.GetRequestType() == typeof(ILaunchRequest))
return HandleLaunchRequest();
if (input.GetRequestType() == typeof(IIntentRequest))
return HandleIntentRequest(input.Request);
if (input.GetRequestType() == typeof(IAudioPlayerPlaybackNearlyFinishedRequest))
return HandlePlaybackNearlyFinishedRequest(input.Request);
if (input.GetRequestType() == typeof(IAudioPlayerPlaybackStartedRequest))
return HandlePlaybackStartedRequest(input.Request);
if (input.GetRequestType() == typeof(IAudioPlayerPlaybackStoppedRequest))
return HandlePlaybackStoppedRequest(input.Request);
if (input.GetRequestType() == typeof(IAudioPlayerPlaybackFailedRequest))
{
_log.LogLine($"Request: {input.Request}");
return Failed("Failed to play song.");
}
return DefaultResponse(input.Request);
}
private AudioSkillResponse HandleLaunchRequest()
{
_log.LogLine("Default LaunchRequest made");
return new AudioSkillResponse
{
Response = new AudioResponse
{
ShouldEndSession = false,
OutputSpeech = new PlainTextOutputSpeech {Text = "Please select music to play."}
},
Version = "1.0"
};
}
private AudioSkillResponse HandleIntentRequest(IIntentRequest request)
{
_log.LogLine($"Intent Requested {request.Intent.Name}");
switch (request.Intent.Name)
{
case "RequestPlayAlbumByArtistIntent":
case "RequestPlayAlbumIntent":
case "RequestPlayArtistIntent":
case "RequestPlaySongByArtistIntent":
case "RequestPlaySongOnAlbumIntent":
case "RequestPlaySongIntent":
return HandlePlayMusicRequest(request);
case "AMAZON.PauseIntent":
return StopPlaying();
case "AMAZON.CancelIntent":
return StopPlaying();
case "AMAZON.ResumeIntent":
return HandleResumeRequest();
case "AMAZON.NextIntent":
return HandleNextRequest();
case "AMAZON.PreviousIntent":
return HandlePreviousRequest();
default:
throw new Exception($"Failed to handle request {request.Intent.Name}");
}
}
private AudioSkillResponse HandlePlayMusicRequest(IIntentRequest request)
{
var slots = request.Intent.Slots;
var intent = request.Intent.Name;
var requestedArtist = slots.ContainsKey("requestedArtist") ? slots["requestedArtist"].Value : null;
var requestedAlbum = slots.ContainsKey("requestedAlbum") ? slots["requestedAlbum"].Value : null;
var requestedSong = slots.ContainsKey("requestedSong") ? slots["requestedSong"].Value : null;
var hasArtist = !string.IsNullOrEmpty(requestedArtist);
var hasAlbum = !string.IsNullOrEmpty(requestedAlbum);
var hasSong = !string.IsNullOrEmpty(requestedSong);
var artistIsRequired = intent.Contains("Artist");
var albumIsRequired = intent.Contains("Album");
var songIsRequired = intent.Contains("Song");
if (artistIsRequired && !hasArtist)
return Failed("Artist input was empty");
if (albumIsRequired && !hasAlbum)
return Failed("Album input was empty");
if (songIsRequired && !hasSong)
return Failed("Song input was empty");
var artist = new Artist(requestedArtist);
var album = new Album(requestedAlbum);
switch (intent)
{
case "RequestPlayAlbumByArtistIntent":
return PlayMusic(artist, album);
case "RequestPlayAlbumIntent":
return PlayMusic(album);
case "RequestPlayArtistIntent":
return PlayMusic(artist);
case "RequestPlaySongByArtistIntent":
return PlayMusic(artist, requestedSong);
case "RequestPlaySongOnAlbumIntent":
return PlayMusic(album, requestedSong);
case "RequestPlaySongIntent":
return PlayMusic(requestedSong);
default:
throw new Exception($"Failed to handle request {intent}");
}
}
private AudioSkillResponse PlayMusic(Artist artist, Album album)
{
_log.LogLine($"Searching for songs by artist {artist} on album {album}...");
var songs = _songs.FindFor(artist, album);
return
songs.Any()
? PlaySong(songs.First(), songs, true)
: Failed($"Failed to find any songs for artist {artist} on album {album}");
}
private AudioSkillResponse PlayMusic(Artist artist, string requestedSong)
{
_log.LogLine($"Searching for song {requestedSong} by artist {artist}...");
return
_songs.TryFind(requestedSong, artist, out Song song)
? PlaySong(song)
: Failed($"Failed to find song {requestedSong} by artist {artist}.");
}
private AudioSkillResponse PlayMusic(Album album, string requestedSong)
{
_log.LogLine($"Searching for song {requestedSong} on album {album}...");
return
_songs.TryFind(requestedSong, album, out Song song)
? PlaySong(song)
: Failed($"Failed to find song {requestedSong} on album {album}.");
}
private AudioSkillResponse PlayMusic(Artist artist)
{
_log.LogLine($"Searching for songs by artist {artist}...");
var songs = _songs.FindFor(artist);
return
songs.Any()
? PlaySong(songs.First(), songs, true)
: Failed($"Failed to find any songs by artist {artist}");
}
private AudioSkillResponse PlayMusic(Album album)
{
_log.LogLine($"Searching for songs on album {album}...");
var songs = _songs.FindFor(album);
return
songs.Any()
? PlaySong(songs.First(), songs, true)
: Failed($"Failed to find any songs on album {album}");
}
private AudioSkillResponse PlayMusic(string requestedSong)
{
_log.LogLine($"Searching for song {requestedSong}...");
return
_songs.TryFind(requestedSong, out Song song)
? PlaySong(song)
: Failed($"Failed to find song {requestedSong}.");
}
private AudioSkillResponse HandlePlaybackNearlyFinishedRequest(AudioRequestBundle request)
{
_log.LogLine($"Handle PlaybackNearlyFinished request (token={request.Token}).");
Guid.TryParse(request.Token, out Guid songRef);
var songs = _queueReader.QueuedSongs();
var current = songs.FirstOrDefault(s => s.SongRef == songRef);
if (current == null)
return Failed($"Failed to find current song for token={songRef}");
var index = songs.IndexOf(current);
if (index + 1 < songs.Count)
{
var next = songs[index + 1];
return PlaySong(next, songs, false);
}
_log.LogLine("No songs left in queue.");
return DefaultResponse(request);
}
private AudioSkillResponse HandlePlaybackStartedRequest(AudioRequestBundle request)
{
_log.LogLine($"Handle PlaybackStarted request (token={request.Token}).");
Guid.TryParse(request.Token, out Guid songRef);
var songs = _queueReader.QueuedSongs();
var current = songs.FirstOrDefault(s => s.SongRef == songRef);
if (current == null)
return Failed($"Failed to find current song for token={songRef}");
_currentSong = current;
return DefaultResponse(request);
}
private AudioSkillResponse HandlePlaybackStoppedRequest(AudioRequestBundle request)
{
_log.LogLine($"Handle PlaybackStopped request (token={request.Token} | offset={request.OffsetInMilliseconds}).");
_currentOffsetInMilliseconds = request.OffsetInMilliseconds;
return DefaultResponse(request);
}
private AudioSkillResponse HandleResumeRequest()
{
_log.LogLine($"Handle AMAZON.ResumeIntent (current song={_currentSong}).");
if (_currentSong == null)
return Failed("Resume failed; no current song stored in session.");
var songs = _queueReader.QueuedSongs();
var index = songs.IndexOf(_currentSong);
return PlaySong(_currentSong, true, songs.Count - index - 1, _currentOffsetInMilliseconds);
}
private AudioSkillResponse HandleNextRequest()
{
_log.LogLine($"Handle AMAZON.NextIntent (current song={_currentSong}).");
if (_currentSong == null)
return Failed("Next failed; no current song stored in session.");
var songs = _queueReader.QueuedSongs();
var index = songs.IndexOf(_currentSong);
return
index + 1 >= songs.Count
? Failed("Next failed; no more songs in queue.")
: PlaySong(songs[index + 1], true, songs.Count - index);
}
private AudioSkillResponse HandlePreviousRequest()
{
_log.LogLine($"Handle AMAZON.PreviousIntent (current song={_currentSong}).");
if (_currentSong == null)
return Failed("Previous failed; no current song stored in session.");
var songs = _queueReader.QueuedSongs();
var index = songs.IndexOf(_currentSong);
return
index == 0
? Failed("Previous failed; no previous songs in queue.")
: PlaySong(songs[index - 1], true, songs.Count - index + 1);
}
private AudioSkillResponse PlaySong(Song next)
{
_queueWriter.Save(new[] {next});
return PlaySong(next, true, 0);
}
private AudioSkillResponse PlaySong(Song next, IList<Song> songs, bool firstSong)
{
var index = songs.IndexOf(next);
var remaining = songs.Count - index - 1;
if (firstSong)
{
_log.LogLine($"Adding {songs.Count} songs to the queue.");
_queueWriter.Save(songs);
}
return PlaySong(next, firstSong, remaining);
}
private AudioSkillResponse PlaySong(Song next, bool firstSong, int remaining) =>
PlaySong(next, firstSong, remaining, 0);
private AudioSkillResponse PlaySong(Song next, bool firstSong, int remaining, int offset)
{
_log.LogLine($"Play song: {next} | Remaining: {remaining} | URL: {next.Url}");
_library.Save(next);
var behavior = "ENQUEUE";
PlainTextOutputSpeech speech = null;
var token = next.SongRef.ToString();
var previousToken = _currentSong?.SongRef.ToString();
if (firstSong)
{
speech = new PlainTextOutputSpeech
{
Text = $"Playing song: {next}. {remaining} song{(remaining == 1 ? "" : "s")} remaining in the queue."
};
behavior = "REPLACE_ALL";
previousToken = null;
}
return new AudioSkillResponse
{
Response = new AudioResponse
{
ShouldEndSession = true,
OutputSpeech = speech,
Directives = new[]
{
new Directive
{
Type = "AudioPlayer.Play",
PlayBehavior = behavior,
AudioItem = new AudioItem
{
Stream = new AudioStream
{
Token = token,
ExpectedPreviousToken = previousToken,
Url = next.Url,
OffsetInMilliseconds = offset
}
}
}
}
},
Version = "1.0"
};
}
private AudioSkillResponse StopPlaying()
{
_log.LogLine("Stopping the player.");
return new AudioSkillResponse
{
Response = new AudioResponse
{
ShouldEndSession = true,
Directives = new[] {new Directive {Type = "AudioPlayer.Stop"}}
},
Version = "1.0"
};
}
private AudioSkillResponse Failed(string message)
{
_log.LogLine(message);
return new AudioSkillResponse
{
Response = new AudioResponse
{
ShouldEndSession = false,
OutputSpeech = new PlainTextOutputSpeech {Text = $"{message} Please try again."}
},
Version = "1.0"
};
}
private AudioSkillResponse DefaultResponse(IRequest request)
{
_log.LogLine($"Request: {request}");
return new AudioSkillResponse
{
Response = new AudioResponse {ShouldEndSession = true},
Version = "1.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.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
namespace System
{
[Serializable]
[CLSCompliant(false)]
[StructLayout(LayoutKind.Sequential)]
[TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
public readonly struct UInt32 : IComparable, IConvertible, IFormattable, IComparable<uint>, IEquatable<uint>, ISpanFormattable
{
private readonly uint m_value; // Do not rename (binary serialization)
public const uint MaxValue = (uint)0xffffffff;
public const uint MinValue = 0U;
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this object
// null is considered to be less than any instance.
// If object is not of type UInt32, this method throws an ArgumentException.
//
public int CompareTo(object value)
{
if (value == null)
{
return 1;
}
if (value is uint)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
uint i = (uint)value;
if (m_value < i) return -1;
if (m_value > i) return 1;
return 0;
}
throw new ArgumentException(SR.Arg_MustBeUInt32);
}
public int CompareTo(uint value)
{
// Need to use compare because subtraction will wrap
// to positive for very large neg numbers, etc.
if (m_value < value) return -1;
if (m_value > value) return 1;
return 0;
}
public override bool Equals(object obj)
{
if (!(obj is uint))
{
return false;
}
return m_value == ((uint)obj).m_value;
}
[NonVersionable]
public bool Equals(uint obj)
{
return m_value == obj;
}
// The absolute value of the int contained.
public override int GetHashCode()
{
return ((int)m_value);
}
// The base 10 representation of the number with no extra padding.
public override string ToString()
{
return Number.FormatUInt32(m_value, null, null);
}
public string ToString(IFormatProvider provider)
{
return Number.FormatUInt32(m_value, null, provider);
}
public string ToString(string format)
{
return Number.FormatUInt32(m_value, format, null);
}
public string ToString(string format, IFormatProvider provider)
{
return Number.FormatUInt32(m_value, format, provider);
}
public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)
{
return Number.TryFormatUInt32(m_value, format, provider, destination, out charsWritten);
}
[CLSCompliant(false)]
public static uint Parse(string s)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static uint Parse(string s, NumberStyles style)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt32(s, style, NumberFormatInfo.CurrentInfo);
}
[CLSCompliant(false)]
public static uint Parse(string s, IFormatProvider provider)
{
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt32(s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static uint Parse(string s, NumberStyles style, IFormatProvider provider)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static uint Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider provider = null)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.ParseUInt32(s, style, NumberFormatInfo.GetInstance(provider));
}
[CLSCompliant(false)]
public static bool TryParse(string s, out uint result)
{
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseUInt32IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK;
}
[CLSCompliant(false)]
public static bool TryParse(ReadOnlySpan<char> s, out uint result)
{
return Number.TryParseUInt32IntegerStyle(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result) == Number.ParsingStatus.OK;
}
[CLSCompliant(false)]
public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out uint result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
if (s == null)
{
result = 0;
return false;
}
return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
}
[CLSCompliant(false)]
public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out uint result)
{
NumberFormatInfo.ValidateParseStyleInteger(style);
return Number.TryParseUInt32(s, style, NumberFormatInfo.GetInstance(provider), out result) == Number.ParsingStatus.OK;
}
//
// IConvertible implementation
//
public TypeCode GetTypeCode()
{
return TypeCode.UInt32;
}
bool IConvertible.ToBoolean(IFormatProvider provider)
{
return Convert.ToBoolean(m_value);
}
char IConvertible.ToChar(IFormatProvider provider)
{
return Convert.ToChar(m_value);
}
sbyte IConvertible.ToSByte(IFormatProvider provider)
{
return Convert.ToSByte(m_value);
}
byte IConvertible.ToByte(IFormatProvider provider)
{
return Convert.ToByte(m_value);
}
short IConvertible.ToInt16(IFormatProvider provider)
{
return Convert.ToInt16(m_value);
}
ushort IConvertible.ToUInt16(IFormatProvider provider)
{
return Convert.ToUInt16(m_value);
}
int IConvertible.ToInt32(IFormatProvider provider)
{
return Convert.ToInt32(m_value);
}
uint IConvertible.ToUInt32(IFormatProvider provider)
{
return m_value;
}
long IConvertible.ToInt64(IFormatProvider provider)
{
return Convert.ToInt64(m_value);
}
ulong IConvertible.ToUInt64(IFormatProvider provider)
{
return Convert.ToUInt64(m_value);
}
float IConvertible.ToSingle(IFormatProvider provider)
{
return Convert.ToSingle(m_value);
}
double IConvertible.ToDouble(IFormatProvider provider)
{
return Convert.ToDouble(m_value);
}
decimal IConvertible.ToDecimal(IFormatProvider provider)
{
return Convert.ToDecimal(m_value);
}
DateTime IConvertible.ToDateTime(IFormatProvider provider)
{
throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt32", "DateTime"));
}
object IConvertible.ToType(Type type, IFormatProvider provider)
{
return Convert.DefaultToType((IConvertible)this, type, provider);
}
}
}
| |
// ***********************************************************************
// Copyright (c) 2007 Charlie Poole
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using NUnit.Framework.Api;
using NUnit.Framework.Internal;
using NUnit.TestUtilities;
using NUnit.TestData.ExpectedExceptionData;
#if !NETCF
using System.Runtime.Serialization;
#endif
namespace NUnit.Framework.Attributes
{
/// <summary>
///
/// </summary>
[TestFixture]
public class ExpectedExceptionTests
{
[Test, ExpectedException]
public void CanExpectUnspecifiedException()
{
throw new ArgumentException();
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void TestSucceedsWithSpecifiedExceptionType()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException(ExpectedException=typeof(ArgumentException))]
public void TestSucceedsWithSpecifiedExceptionTypeAsNamedParameter()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException("System.ArgumentException")]
public void TestSucceedsWithSpecifiedExceptionName()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException(ExpectedExceptionName="System.ArgumentException")]
public void TestSucceedsWithSpecifiedExceptionNameAsNamedParameter()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException(typeof(ArgumentException),ExpectedMessage="argument exception")]
public void TestSucceedsWithSpecifiedExceptionTypeAndMessage()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage="argument exception", MatchType=MessageMatch.Exact)]
public void TestSucceedsWithSpecifiedExceptionTypeAndExactMatch()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException(typeof(ArgumentException),ExpectedMessage="invalid", MatchType=MessageMatch.Contains)]
public void TestSucceedsWithSpecifiedExceptionTypeAndContainsMatch()
{
throw new ArgumentException("argument invalid exception");
}
[Test]
[ExpectedException(typeof(ArgumentException),ExpectedMessage="exception$", MatchType=MessageMatch.Regex)]
public void TestSucceedsWithSpecifiedExceptionTypeAndRegexMatch()
{
throw new ArgumentException("argument invalid exception");
}
[Test]
[ExpectedException(typeof(ArgumentException), ExpectedMessage = "argument invalid", MatchType = MessageMatch.StartsWith)]
public void TestSucceedsWithSpecifiedExceptionTypeAndStartsWithMatch()
{
throw new ArgumentException("argument invalid exception");
}
// [Test]
// [ExpectedException("System.ArgumentException", "argument exception")]
// public void TestSucceedsWithSpecifiedExceptionNameAndMessage_OldFormat()
// {
// throw new ArgumentException("argument exception");
// }
[Test]
[ExpectedException("System.ArgumentException", ExpectedMessage = "argument exception")]
public void TestSucceedsWithSpecifiedExceptionNameAndMessage_NewFormat()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException("System.ArgumentException",ExpectedMessage="argument exception",MatchType=MessageMatch.Exact)]
public void TestSucceedsWithSpecifiedExceptionNameAndExactMatch()
{
throw new ArgumentException("argument exception");
}
[Test]
[ExpectedException("System.ArgumentException",ExpectedMessage="invalid", MatchType=MessageMatch.Contains)]
public void TestSucceedsWhenSpecifiedExceptionNameAndContainsMatch()
{
throw new ArgumentException("argument invalid exception");
}
[Test]
[ExpectedException("System.ArgumentException",ExpectedMessage="exception$", MatchType=MessageMatch.Regex)]
public void TestSucceedsWhenSpecifiedExceptionNameAndRegexMatch()
{
throw new ArgumentException("argument invalid exception");
}
[Test]
public void TestFailsWhenBaseExceptionIsThrown()
{
Type fixtureType = typeof(BaseException);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "BaseExceptionTest" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "BaseExceptionTest should have failed");
Assert.That(result.Message, Is.StringStarting(
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.ArgumentException" + Env.NewLine +
" but was: System.Exception"));
}
[Test]
public void TestFailsWhenDerivedExceptionIsThrown()
{
Type fixtureType = typeof(DerivedException);
ITestResult result = TestBuilder.RunTestCase(fixtureType, "DerivedExceptionTest");
Assert.IsTrue(result.ResultState == ResultState.Failure, "DerivedExceptionTest should have failed");
Assert.That(result.Message, Is.StringStarting(
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.Exception" + Env.NewLine +
" but was: System.ArgumentException"));
}
[Test]
public void TestMismatchedExceptionType()
{
Type fixtureType = typeof(MismatchedException);
ITestResult result = TestBuilder.RunTestCase(fixtureType, "MismatchedExceptionType");
Assert.IsTrue(result.ResultState == ResultState.Failure, "MismatchedExceptionType should have failed");
Assert.That(result.Message, Is.StringStarting(
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.ArgumentException" + Env.NewLine +
" but was: System.ArgumentOutOfRangeException"));
}
[Test]
public void TestMismatchedExceptionTypeAsNamedParameter()
{
Type fixtureType = typeof(MismatchedException);
ITestResult result = TestBuilder.RunTestCase(fixtureType, "MismatchedExceptionTypeAsNamedParameter");
Assert.IsTrue(result.ResultState == ResultState.Failure, "MismatchedExceptionType should have failed");
Assert.That(result.Message, Is.StringStarting(
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.ArgumentException" + Env.NewLine +
" but was: System.ArgumentOutOfRangeException"));
}
[Test]
public void TestMismatchedExceptionTypeWithUserMessage()
{
Type fixtureType = typeof(MismatchedException);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "MismatchedExceptionTypeWithUserMessage" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.That(result.Message, Is.StringStarting(
"custom message" + Env.NewLine +
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.ArgumentException" + Env.NewLine +
" but was: System.ArgumentOutOfRangeException"));
}
[Test]
public void TestMismatchedExceptionName()
{
Type fixtureType = typeof(MismatchedException);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "MismatchedExceptionName" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "MismatchedExceptionName should have failed");
Assert.That(result.Message, Is.StringStarting(
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.ArgumentException" + Env.NewLine +
" but was: System.ArgumentOutOfRangeException"));
}
[Test]
public void TestMismatchedExceptionNameWithUserMessage()
{
Type fixtureType = typeof(MismatchedException);
ITestResult result = TestBuilder.RunTestCase(fixtureType, "MismatchedExceptionNameWithUserMessage");
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.That(result.Message, Is.StringStarting(
"custom message" + Env.NewLine +
"An unexpected exception type was thrown" + Env.NewLine +
"Expected: System.ArgumentException" + Env.NewLine +
" but was: System.ArgumentOutOfRangeException"));
}
[Test]
public void TestMismatchedExceptionMessage()
{
Type fixtureType = typeof(TestThrowsExceptionWithWrongMessage);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestThrow" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "TestThrow should have failed");
Assert.AreEqual(
"The exception message text was incorrect" + Env.NewLine +
"Expected: not the message" + Env.NewLine +
" but was: the message",
result.Message);
}
[Test]
public void TestMismatchedExceptionMessageWithUserMessage()
{
Type fixtureType = typeof(TestThrowsExceptionWithWrongMessage);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestThrowWithUserMessage" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "TestThrow should have failed");
Assert.AreEqual(
"custom message" + Env.NewLine +
"The exception message text was incorrect" + Env.NewLine +
"Expected: not the message" + Env.NewLine +
" but was: the message",
result.Message);
}
[Test]
public void TestUnspecifiedExceptionNotThrown()
{
Type fixtureType = typeof(TestDoesNotThrowExceptionFixture);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowUnspecifiedException" );
Assert.AreEqual(ResultState.Failure, result.ResultState);
Assert.AreEqual("An Exception was expected", result.Message);
}
[Test]
public void TestUnspecifiedExceptionNotThrownWithUserMessage()
{
Type fixtureType = typeof(TestDoesNotThrowExceptionFixture);
ITestResult result = TestBuilder.RunTestCase(fixtureType, "TestDoesNotThrowUnspecifiedExceptionWithUserMessage");
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.AreEqual("custom message" + Env.NewLine + "An Exception was expected", result.Message);
}
[Test]
public void TestExceptionTypeNotThrown()
{
Type fixtureType = typeof(TestDoesNotThrowExceptionFixture);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowExceptionType" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.AreEqual("System.ArgumentException was expected", result.Message);
}
[Test]
public void TestExceptionTypeNotThrownWithUserMessage()
{
Type fixtureType = typeof(TestDoesNotThrowExceptionFixture);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowExceptionTypeWithUserMessage" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.AreEqual("custom message" + Env.NewLine + "System.ArgumentException was expected", result.Message);
}
[Test]
public void TestExceptionNameNotThrown()
{
Type fixtureType = typeof(TestDoesNotThrowExceptionFixture);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowExceptionName" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.AreEqual("System.ArgumentException was expected", result.Message);
}
[Test]
public void TestExceptionNameNotThrownWithUserMessage()
{
Type fixtureType = typeof(TestDoesNotThrowExceptionFixture);
ITestResult result = TestBuilder.RunTestCase( fixtureType, "TestDoesNotThrowExceptionNameWithUserMessage" );
Assert.IsTrue(result.ResultState == ResultState.Failure, "Test method should have failed");
Assert.AreEqual("custom message" + Env.NewLine + "System.ArgumentException was expected", result.Message);
}
[Test]
public void MethodThrowsException()
{
TestResult result = TestBuilder.RunTestFixture( typeof( TestThrowsExceptionFixture ) );
Assert.AreEqual(true, result.ResultState == ResultState.Failure);
}
[Test]
public void MethodThrowsRightExceptionMessage()
{
TestResult result = TestBuilder.RunTestFixture( typeof( TestThrowsExceptionWithRightMessage ) );
Assert.AreEqual(true, result.ResultState == ResultState.Success);
}
[Test]
public void MethodThrowsArgumentOutOfRange()
{
TestResult result = TestBuilder.RunTestFixture( typeof( TestThrowsArgumentOutOfRangeException ) );
Assert.AreEqual(true, result.ResultState == ResultState.Success);
}
[Test]
public void MethodThrowsWrongExceptionMessage()
{
TestResult result = TestBuilder.RunTestFixture( typeof( TestThrowsExceptionWithWrongMessage ) );
Assert.AreEqual(true, result.ResultState == ResultState.Failure);
}
[Test]
public void SetUpThrowsSameException()
{
TestResult result = TestBuilder.RunTestFixture( typeof( SetUpExceptionTests ) );
Assert.AreEqual(true, result.ResultState == ResultState.Failure);
}
[Test]
public void TearDownThrowsSameException()
{
TestResult result = TestBuilder.RunTestFixture( typeof( TearDownExceptionTests ) );
Assert.AreEqual(true, result.ResultState == ResultState.Failure);
}
[Test]
public void AssertFailBeforeException()
{
TestResult suiteResult = TestBuilder.RunTestFixture( typeof (TestAssertsBeforeThrowingException) );
Assert.AreEqual( ResultState.Failure, suiteResult.ResultState );
TestResult result = (TestResult)suiteResult.Children[0];
Assert.AreEqual( "private message", result.Message );
}
internal class MyAppException : System.Exception
{
public MyAppException (string message) : base(message)
{}
public MyAppException(string message, Exception inner) :
base(message, inner)
{}
#if !NETCF && !SILVERLIGHT
protected MyAppException(SerializationInfo info,
StreamingContext context) : base(info,context)
{}
#endif
}
[Test]
[ExpectedException(typeof(MyAppException))]
public void ThrowingMyAppException()
{
throw new MyAppException("my app");
}
[Test]
[ExpectedException(typeof(MyAppException), ExpectedMessage="my app")]
public void ThrowingMyAppExceptionWithMessage()
{
throw new MyAppException("my app");
}
[Test]
[ExpectedException(typeof(NUnitException))]
public void ThrowNUnitException()
{
throw new NUnitException("Nunit exception");
}
[Test]
public void ExceptionHandlerIsCalledWhenExceptionMatches_AlternateHandler()
{
ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass();
TestBuilder.RunTestCase( fixture, "ThrowsArgumentException_AlternateHandler" );
Assert.IsFalse(fixture.HandlerCalled, "Base Handler should not be called" );
Assert.IsTrue(fixture.AlternateHandlerCalled, "Alternate Handler should be called" );
}
[Test]
public void ExceptionHandlerIsCalledWhenExceptionMatches()
{
ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass();
TestBuilder.RunTestCase( fixture, "ThrowsArgumentException" );
Assert.IsTrue(fixture.HandlerCalled, "Base Handler should be called");
Assert.IsFalse(fixture.AlternateHandlerCalled, "Alternate Handler should not be called");
}
[Test]
public void ExceptionHandlerIsNotCalledWhenExceptionDoesNotMatch()
{
ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass();
TestBuilder.RunTestCase( fixture, "ThrowsCustomException" );
Assert.IsFalse( fixture.HandlerCalled, "Base Handler should not be called" );
Assert.IsFalse( fixture.AlternateHandlerCalled, "Alternate Handler should not be called" );
}
[Test]
public void ExceptionHandlerIsNotCalledWhenExceptionDoesNotMatch_AlternateHandler()
{
ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass();
TestBuilder.RunTestCase(fixture, "ThrowsCustomException_AlternateHandler");
Assert.IsFalse(fixture.HandlerCalled, "Base Handler should not be called");
Assert.IsFalse(fixture.AlternateHandlerCalled, "Alternate Handler should not be called");
}
[Test]
public void TestIsNotRunnableWhenAlternateHandlerIsNotFound()
{
ExceptionHandlerCalledClass fixture = new ExceptionHandlerCalledClass();
Test test = TestBuilder.MakeTestCase( fixture, "MethodWithBadHandler" );
Assert.AreEqual( RunState.NotRunnable, test.RunState );
Assert.AreEqual(
"The specified exception handler DeliberatelyMissingHandler was not found",
test.Properties.Get(PropertyNames.SkipReason) );
}
#if CLR_2_0 || CLR_4_0
[Test]
public void TestSucceedsInStaticClass()
{
ITestResult result = TestBuilder.RunTestCase(typeof(StaticClassWithExpectedExceptions), "TestSucceedsInStaticClass");
Assert.That(result.ResultState, Is.EqualTo(ResultState.Success));
}
[Test]
public void TestFailsInStaticClass_NoExceptionThrown()
{
ITestResult result = TestBuilder.RunTestCase(typeof(StaticClassWithExpectedExceptions), "TestFailsInStaticClass_NoExceptionThrown");
Assert.That(result.ResultState, Is.EqualTo(ResultState.Failure));
}
[Test]
public void TestFailsInStaticClass_WrongExceptionThrown()
{
ITestResult result = TestBuilder.RunTestCase(typeof(StaticClassWithExpectedExceptions), "TestFailsInStaticClass_WrongExceptionThrown");
Assert.That(result.ResultState, Is.EqualTo(ResultState.Failure));
}
#endif
}
}
| |
// 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.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//------------------------------------------------------------------------------
using System.Data.Common;
using System.Globalization;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace System.Data.SqlTypes
{
// Options that are used in comparison
[Flags]
public enum SqlCompareOptions
{
None = 0x00000000,
IgnoreCase = 0x00000001,
IgnoreNonSpace = 0x00000002,
IgnoreKanaType = 0x00000008, // ignore kanatype
IgnoreWidth = 0x00000010, // ignore width
BinarySort = 0x00008000, // binary sorting
BinarySort2 = 0x00004000, // binary sorting 2
}
/// <devdoc>
/// <para>
/// Represents a variable-length stream of characters to be stored in or retrieved from the database.
/// </para>
/// </devdoc>
[StructLayout(LayoutKind.Sequential)]
public struct SqlString : INullable, IComparable
{
private String _value;
private CompareInfo _cmpInfo;
private int _lcid; // Locale Id
private SqlCompareOptions _flag; // Compare flags
private bool _fNotNull; // false if null
/// <devdoc>
/// <para>
/// Represents a null value that can be assigned to the <see cref='System.Data.SqlTypes.SqlString.Value'/> property of an instance of
/// the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public static readonly SqlString Null = new SqlString(true);
internal static readonly UnicodeEncoding x_UnicodeEncoding = new UnicodeEncoding();
/// <devdoc>
/// </devdoc>
public static readonly int IgnoreCase = 0x1;
/// <devdoc>
/// </devdoc>
public static readonly int IgnoreWidth = 0x10;
/// <devdoc>
/// </devdoc>
public static readonly int IgnoreNonSpace = 0x2;
/// <devdoc>
/// </devdoc>
public static readonly int IgnoreKanaType = 0x8;
/// <devdoc>
/// </devdoc>
public static readonly int BinarySort = 0x8000;
/// <devdoc>
/// </devdoc>
public static readonly int BinarySort2 = 0x4000;
private static readonly SqlCompareOptions s_iDefaultFlag =
SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreKanaType |
SqlCompareOptions.IgnoreWidth;
private static readonly CompareOptions s_iValidCompareOptionMask =
CompareOptions.IgnoreCase | CompareOptions.IgnoreWidth |
CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreKanaType;
internal static readonly SqlCompareOptions x_iValidSqlCompareOptionMask =
SqlCompareOptions.IgnoreCase | SqlCompareOptions.IgnoreWidth |
SqlCompareOptions.IgnoreNonSpace | SqlCompareOptions.IgnoreKanaType |
SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2;
internal static readonly int x_lcidUSEnglish = 0x00000409;
private static readonly int s_lcidBinary = 0x00008200;
// constructor
// construct a Null
private SqlString(bool fNull)
{
_value = null;
_cmpInfo = null;
_lcid = 0;
_flag = SqlCompareOptions.None;
_fNotNull = false;
}
// Constructor: Construct from both Unicode and NonUnicode data, according to fUnicode
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, int index, int count, bool fUnicode)
{
_lcid = lcid;
ValidateSqlCompareOptions(compareOptions);
_flag = compareOptions;
if (data == null)
{
_fNotNull = false;
_value = null;
_cmpInfo = null;
}
else
{
_fNotNull = true;
// m_cmpInfo is set lazily, so that we don't need to pay the cost
// unless the string is used in comparison.
_cmpInfo = null;
if (fUnicode)
{
_value = x_UnicodeEncoding.GetString(data, index, count);
}
else
{
Encoding cpe = Locale.GetEncodingForLcid(_lcid);
_value = cpe.GetString(data, index, count);
}
}
}
// Constructor: Construct from both Unicode and NonUnicode data, according to fUnicode
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, bool fUnicode)
: this(lcid, compareOptions, data, 0, data.Length, fUnicode)
{
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data, int index, int count)
: this(lcid, compareOptions, data, index, count, true)
{
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(int lcid, SqlCompareOptions compareOptions, byte[] data)
: this(lcid, compareOptions, data, 0, data.Length, true)
{
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(String data, int lcid, SqlCompareOptions compareOptions)
{
_lcid = lcid;
ValidateSqlCompareOptions(compareOptions);
_flag = compareOptions;
_cmpInfo = null;
if (data == null)
{
_fNotNull = false;
_value = null;
}
else
{
_fNotNull = true;
_value = data; // PERF: do not String.Copy
}
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(String data, int lcid) : this(data, lcid, s_iDefaultFlag)
{
}
/// <devdoc>
/// <para>
/// Initializes a new instance of the <see cref='System.Data.SqlTypes.SqlString'/> class.
/// </para>
/// </devdoc>
public SqlString(String data) : this(data, Locale.GetCurrentCultureLcid(), s_iDefaultFlag)
{
}
private SqlString(int lcid, SqlCompareOptions compareOptions, String data, CompareInfo cmpInfo)
{
_lcid = lcid;
ValidateSqlCompareOptions(compareOptions);
_flag = compareOptions;
if (data == null)
{
_fNotNull = false;
_value = null;
_cmpInfo = null;
}
else
{
_value = data;
_cmpInfo = cmpInfo;
_fNotNull = true;
}
}
// INullable
/// <devdoc>
/// <para>
/// Gets whether the <see cref='System.Data.SqlTypes.SqlString.Value'/> of the <see cref='System.Data.SqlTypes.SqlString'/> is <see cref='System.Data.SqlTypes.SqlString.Null'/>.
/// </para>
/// </devdoc>
public bool IsNull
{
get { return !_fNotNull; }
}
// property: Value
/// <devdoc>
/// <para>
/// Gets the string that is to be stored.
/// </para>
/// </devdoc>
public String Value
{
get
{
if (!IsNull)
return _value;
else
throw new SqlNullValueException();
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int LCID
{
get
{
if (!IsNull)
return _lcid;
else
throw new SqlNullValueException();
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public CultureInfo CultureInfo
{
get
{
if (!IsNull)
return new CultureInfo(Locale.GetLocaleNameForLcid(_lcid));
else
throw new SqlNullValueException();
}
}
private void SetCompareInfo()
{
Debug.Assert(!IsNull);
if (_cmpInfo == null)
_cmpInfo = (new CultureInfo(Locale.GetLocaleNameForLcid(_lcid))).CompareInfo;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public CompareInfo CompareInfo
{
get
{
if (!IsNull)
{
SetCompareInfo();
return _cmpInfo;
}
else
throw new SqlNullValueException();
}
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SqlCompareOptions SqlCompareOptions
{
get
{
if (!IsNull)
return _flag;
else
throw new SqlNullValueException();
}
}
// Implicit conversion from String to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static implicit operator SqlString(String x)
{
return new SqlString(x);
}
// Explicit conversion from SqlString to String. Throw exception if x is Null.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator String(SqlString x)
{
return x.Value;
}
/// <devdoc>
/// <para>
/// Converts a <see cref='System.Data.SqlTypes.SqlString'/> object to a string.
/// </para>
/// </devdoc>
public override String ToString()
{
return IsNull ? SQLResource.NullString : _value;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public byte[] GetUnicodeBytes()
{
if (IsNull)
return null;
return x_UnicodeEncoding.GetBytes(_value);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public byte[] GetNonUnicodeBytes()
{
if (IsNull)
return null;
// Get the CultureInfo
Encoding cpe = Locale.GetEncodingForLcid(_lcid);
return cpe.GetBytes(_value);
}
/*
internal int GetSQLCID() {
if (IsNull)
throw new SqlNullValueException();
return MAKECID(m_lcid, m_flag);
}
*/
// Binary operators
// Concatenation
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlString operator +(SqlString x, SqlString y)
{
if (x.IsNull || y.IsNull)
return SqlString.Null;
if (x._lcid != y._lcid || x._flag != y._flag)
throw new SqlTypeException(SQLResource.ConcatDiffCollationMessage);
return new SqlString(x._lcid, x._flag, x._value + y._value,
(x._cmpInfo == null) ? y._cmpInfo : x._cmpInfo);
}
// StringCompare: Common compare function which is used by Compare and CompareTo
// In the case of Compare (used by comparison operators) the int result needs to be converted to SqlBoolean type
// while CompareTo needs the result in int type
// Pre-requisite: the null condition of the both string needs to be checked and handled by the caller of this function
private static int StringCompare(SqlString x, SqlString y)
{
Debug.Assert(!x.IsNull && !y.IsNull, "Null condition should be handled by the caller of StringCompare method");
if (x._lcid != y._lcid || x._flag != y._flag)
throw new SqlTypeException(SQLResource.CompareDiffCollationMessage);
x.SetCompareInfo();
y.SetCompareInfo();
Debug.Assert(x.FBinarySort() || (x._cmpInfo != null && y._cmpInfo != null));
int iCmpResult;
if ((x._flag & SqlCompareOptions.BinarySort) != 0)
iCmpResult = CompareBinary(x, y);
else if ((x._flag & SqlCompareOptions.BinarySort2) != 0)
iCmpResult = CompareBinary2(x, y);
else
{
// SqlString can be padded with spaces (Padding is turn on by default in SQL Server 2008
// Trim the trailing space for comparison
// Avoid using String.TrimEnd function to avoid extra string allocations
string rgchX = x._value;
string rgchY = y._value;
int cwchX = rgchX.Length;
int cwchY = rgchY.Length;
while (cwchX > 0 && rgchX[cwchX - 1] == ' ')
cwchX--;
while (cwchY > 0 && rgchY[cwchY - 1] == ' ')
cwchY--;
CompareOptions options = CompareOptionsFromSqlCompareOptions(x._flag);
iCmpResult = x._cmpInfo.Compare(x._value, 0, cwchX, y._value, 0, cwchY, options);
}
return iCmpResult;
}
// Comparison operators
private static SqlBoolean Compare(SqlString x, SqlString y, EComparison ecExpectedResult)
{
if (x.IsNull || y.IsNull)
return SqlBoolean.Null;
int iCmpResult = StringCompare(x, y);
bool fResult = false;
switch (ecExpectedResult)
{
case EComparison.EQ:
fResult = (iCmpResult == 0);
break;
case EComparison.LT:
fResult = (iCmpResult < 0);
break;
case EComparison.LE:
fResult = (iCmpResult <= 0);
break;
case EComparison.GT:
fResult = (iCmpResult > 0);
break;
case EComparison.GE:
fResult = (iCmpResult >= 0);
break;
default:
Debug.Assert(false, "Invalid ecExpectedResult");
return SqlBoolean.Null;
}
return new SqlBoolean(fResult);
}
// Implicit conversions
// Explicit conversions
// Explicit conversion from SqlBoolean to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlBoolean x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString());
}
// Explicit conversion from SqlByte to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlByte x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlInt16 to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlInt16 x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlInt32 to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlInt32 x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlInt64 to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlInt64 x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlSingle to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlSingle x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlDouble to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlDouble x)
{
return x.IsNull ? Null : new SqlString((x.Value).ToString((IFormatProvider)null));
}
// Explicit conversion from SqlDecimal to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlDecimal x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
// Explicit conversion from SqlMoney to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlMoney x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
// Explicit conversion from SqlDateTime to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlDateTime x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
// Explicit conversion from SqlGuid to SqlString
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static explicit operator SqlString(SqlGuid x)
{
return x.IsNull ? Null : new SqlString(x.ToString());
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public SqlString Clone()
{
if (IsNull)
return new SqlString(true);
else
{
SqlString ret = new SqlString(_value, _lcid, _flag);
return ret;
}
}
// Overloading comparison operators
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator ==(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.EQ);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator !=(SqlString x, SqlString y)
{
return !(x == y);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator <(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.LT);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator >(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.GT);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator <=(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.LE);
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public static SqlBoolean operator >=(SqlString x, SqlString y)
{
return Compare(x, y, EComparison.GE);
}
//--------------------------------------------------
// Alternative methods for overloaded operators
//--------------------------------------------------
// Alternative method for operator +
public static SqlString Concat(SqlString x, SqlString y)
{
return x + y;
}
public static SqlString Add(SqlString x, SqlString y)
{
return x + y;
}
// Alternative method for operator ==
public static SqlBoolean Equals(SqlString x, SqlString y)
{
return (x == y);
}
// Alternative method for operator !=
public static SqlBoolean NotEquals(SqlString x, SqlString y)
{
return (x != y);
}
// Alternative method for operator <
public static SqlBoolean LessThan(SqlString x, SqlString y)
{
return (x < y);
}
// Alternative method for operator >
public static SqlBoolean GreaterThan(SqlString x, SqlString y)
{
return (x > y);
}
// Alternative method for operator <=
public static SqlBoolean LessThanOrEqual(SqlString x, SqlString y)
{
return (x <= y);
}
// Alternative method for operator >=
public static SqlBoolean GreaterThanOrEqual(SqlString x, SqlString y)
{
return (x >= y);
}
// Alternative method for conversions.
public SqlBoolean ToSqlBoolean()
{
return (SqlBoolean)this;
}
public SqlByte ToSqlByte()
{
return (SqlByte)this;
}
public SqlDateTime ToSqlDateTime()
{
return (SqlDateTime)this;
}
public SqlDouble ToSqlDouble()
{
return (SqlDouble)this;
}
public SqlInt16 ToSqlInt16()
{
return (SqlInt16)this;
}
public SqlInt32 ToSqlInt32()
{
return (SqlInt32)this;
}
public SqlInt64 ToSqlInt64()
{
return (SqlInt64)this;
}
public SqlMoney ToSqlMoney()
{
return (SqlMoney)this;
}
public SqlDecimal ToSqlDecimal()
{
return (SqlDecimal)this;
}
public SqlSingle ToSqlSingle()
{
return (SqlSingle)this;
}
public SqlGuid ToSqlGuid()
{
return (SqlGuid)this;
}
// Utility functions and constants
private static void ValidateSqlCompareOptions(SqlCompareOptions compareOptions)
{
if ((compareOptions & x_iValidSqlCompareOptionMask) != compareOptions)
throw new ArgumentOutOfRangeException(nameof(compareOptions));
}
public static CompareOptions CompareOptionsFromSqlCompareOptions(SqlCompareOptions compareOptions)
{
CompareOptions options = CompareOptions.None;
ValidateSqlCompareOptions(compareOptions);
if ((compareOptions & (SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2)) != 0)
throw ADP.ArgumentOutOfRange(nameof(compareOptions));
else
{
if ((compareOptions & SqlCompareOptions.IgnoreCase) != 0)
options |= CompareOptions.IgnoreCase;
if ((compareOptions & SqlCompareOptions.IgnoreNonSpace) != 0)
options |= CompareOptions.IgnoreNonSpace;
if ((compareOptions & SqlCompareOptions.IgnoreKanaType) != 0)
options |= CompareOptions.IgnoreKanaType;
if ((compareOptions & SqlCompareOptions.IgnoreWidth) != 0)
options |= CompareOptions.IgnoreWidth;
}
return options;
}
/*
private static SqlCompareOptions SqlCompareOptionsFromCompareOptions(CompareOptions compareOptions) {
SqlCompareOptions sqlOptions = SqlCompareOptions.None;
if ((compareOptions & x_iValidCompareOptionMask) != compareOptions)
throw new ArgumentOutOfRangeException ("compareOptions");
else {
if ((compareOptions & CompareOptions.IgnoreCase) != 0)
sqlOptions |= SqlCompareOptions.IgnoreCase;
if ((compareOptions & CompareOptions.IgnoreNonSpace) != 0)
sqlOptions |= SqlCompareOptions.IgnoreNonSpace;
if ((compareOptions & CompareOptions.IgnoreKanaType) != 0)
sqlOptions |= SqlCompareOptions.IgnoreKanaType;
if ((compareOptions & CompareOptions.IgnoreWidth) != 0)
sqlOptions |= SqlCompareOptions.IgnoreWidth;
}
return sqlOptions;
}
*/
private bool FBinarySort()
{
return (!IsNull && (_flag & (SqlCompareOptions.BinarySort | SqlCompareOptions.BinarySort2)) != 0);
}
// Wide-character string comparison for Binary Unicode Collation
// Return values:
// -1 : wstr1 < wstr2
// 0 : wstr1 = wstr2
// 1 : wstr1 > wstr2
//
// Does a memory comparison.
private static int CompareBinary(SqlString x, SqlString y)
{
byte[] rgDataX = x_UnicodeEncoding.GetBytes(x._value);
byte[] rgDataY = x_UnicodeEncoding.GetBytes(y._value);
int cbX = rgDataX.Length;
int cbY = rgDataY.Length;
int cbMin = cbX < cbY ? cbX : cbY;
int i;
Debug.Assert(cbX % 2 == 0);
Debug.Assert(cbY % 2 == 0);
for (i = 0; i < cbMin; i++)
{
if (rgDataX[i] < rgDataY[i])
return -1;
else if (rgDataX[i] > rgDataY[i])
return 1;
}
i = cbMin;
int iCh;
int iSpace = (int)' ';
if (cbX < cbY)
{
for (; i < cbY; i += 2)
{
iCh = ((int)rgDataY[i + 1]) << 8 + rgDataY[i];
if (iCh != iSpace)
return (iSpace > iCh) ? 1 : -1;
}
}
else
{
for (; i < cbX; i += 2)
{
iCh = ((int)rgDataX[i + 1]) << 8 + rgDataX[i];
if (iCh != iSpace)
return (iCh > iSpace) ? 1 : -1;
}
}
return 0;
}
// Wide-character string comparison for Binary2 Unicode Collation
// Return values:
// -1 : wstr1 < wstr2
// 0 : wstr1 = wstr2
// 1 : wstr1 > wstr2
//
// Does a wchar comparison (different from memcmp of BinarySort).
private static int CompareBinary2(SqlString x, SqlString y)
{
Debug.Assert(!x.IsNull && !y.IsNull);
string rgDataX = x._value;
string rgDataY = y._value;
int cwchX = rgDataX.Length;
int cwchY = rgDataY.Length;
int cwchMin = cwchX < cwchY ? cwchX : cwchY;
int i;
for (i = 0; i < cwchMin; i++)
{
if (rgDataX[i] < rgDataY[i])
return -1;
else if (rgDataX[i] > rgDataY[i])
return 1;
}
// If compares equal up to one of the string terminates,
// pad it with spaces and compare with the rest of the other one.
//
char chSpace = ' ';
if (cwchX < cwchY)
{
for (i = cwchMin; i < cwchY; i++)
{
if (rgDataY[i] != chSpace)
return (chSpace > rgDataY[i]) ? 1 : -1;
}
}
else
{
for (i = cwchMin; i < cwchX; i++)
{
if (rgDataX[i] != chSpace)
return (rgDataX[i] > chSpace) ? 1 : -1;
}
}
return 0;
}
/*
private void Print() {
Debug.WriteLine("SqlString - ");
Debug.WriteLine("\tlcid = " + m_lcid.ToString());
Debug.Write("\t");
if ((m_flag & SqlCompareOptions.IgnoreCase) != 0)
Debug.Write("IgnoreCase, ");
if ((m_flag & SqlCompareOptions.IgnoreNonSpace) != 0)
Debug.Write("IgnoreNonSpace, ");
if ((m_flag & SqlCompareOptions.IgnoreKanaType) != 0)
Debug.Write("IgnoreKanaType, ");
if ((m_flag & SqlCompareOptions.IgnoreWidth) != 0)
Debug.Write("IgnoreWidth, ");
Debug.WriteLine("");
Debug.WriteLine("\tvalue = " + m_value);
Debug.WriteLine("\tcmpinfo = " + m_cmpInfo);
}
*/
// IComparable
// Compares this object to another object, returning an integer that
// indicates the relationship.
// Returns a value less than zero if this < object, zero if this = object,
// or a value greater than zero if this > object.
// null is considered to be less than any instance.
// If object is not of same type, this method throws an ArgumentException.
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public int CompareTo(Object value)
{
if (value is SqlString)
{
SqlString i = (SqlString)value;
return CompareTo(i);
}
throw ADP.WrongType(value.GetType(), typeof(SqlString));
}
public int CompareTo(SqlString value)
{
// If both Null, consider them equal.
// Otherwise, Null is less than anything.
if (IsNull)
return value.IsNull ? 0 : -1;
else if (value.IsNull)
return 1;
int returnValue = StringCompare(this, value);
// Convert the result into -1, 0, or 1 as this method never returned any other values
// This is to ensure the backcompat
if (returnValue < 0)
{
return -1;
}
if (returnValue > 0)
{
return 1;
}
return 0;
}
// Compares this instance with a specified object
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override bool Equals(Object value)
{
if (!(value is SqlString))
{
return false;
}
SqlString i = (SqlString)value;
if (i.IsNull || IsNull)
return (i.IsNull && IsNull);
else
return (this == i).Value;
}
// For hashing purpose
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
public override int GetHashCode()
{
if (IsNull)
return 0;
byte[] rgbSortKey;
if (FBinarySort())
rgbSortKey = x_UnicodeEncoding.GetBytes(_value.TrimEnd());
else
{
// VSDevDiv 479660
// GetHashCode should not throw just because this instance has an invalid LCID or compare options.
CompareInfo cmpInfo;
CompareOptions options;
try
{
SetCompareInfo();
cmpInfo = _cmpInfo;
options = CompareOptionsFromSqlCompareOptions(_flag);
}
catch (ArgumentException)
{
// SetCompareInfo throws this when instance's LCID is unsupported
// CompareOptionsFromSqlCompareOptions throws this when instance's options are invalid
cmpInfo = CultureInfo.InvariantCulture.CompareInfo;
options = CompareOptions.None;
}
return cmpInfo.GetHashCode(_value.TrimEnd(), options);
}
return SqlBinary.HashByteArray(rgbSortKey, rgbSortKey.Length);
}
} // SqlString
/*
internal struct SLocaleMapItem {
public int lcid; // the primary key, not nullable
public String name; // unique, nullable
public int idCodePage; // the ANSI default code page of the locale
public SLocaleMapItem(int lid, String str, int cpid) {
lcid = lid;
name = str;
idCodePage = cpid;
}
}
// Struct to map lcid to ordinal
internal struct SLcidOrdMapItem {
internal int lcid;
internal int uiOrd;
};
// Class to store map of lcids to ordinal
internal class CBuildLcidOrdMap {
internal SLcidOrdMapItem[] m_rgLcidOrdMap;
internal int m_cValidLocales;
internal int m_uiPosEnglish; // Start binary searches here - this is index in array, not ordinal
// Constructor builds the array sorted by lcid
// We use a simple n**2 sort because the array is mostly sorted anyway
// and objects of this class will be const, hence this will be called
// only by VC compiler
public CBuildLcidOrdMap() {
int i,j;
m_rgLcidOrdMap = new SLcidOrdMapItem[SqlString.x_cLocales];
// Compact the array
for (i=0,j=0; i < SqlString.x_cLocales; i++) {
if (SqlString.x_rgLocaleMap[i].lcid != SqlString.x_lcidUnused) {
m_rgLcidOrdMap[j].lcid = SqlString.x_rgLocaleMap[i].lcid;
m_rgLcidOrdMap[j].uiOrd = i;
j++;
}
}
m_cValidLocales = j;
// Set the rest to invalid
while (j < SqlString.x_cLocales) {
m_rgLcidOrdMap[j].lcid = SqlString.x_lcidUnused;
m_rgLcidOrdMap[j].uiOrd = 0;
j++;
}
// Now sort in place
// Algorithm:
// Start from 1, assume list before i is sorted, if next item
// violates this assumption, exchange with prev items until the
// item is in its correct place
for (i=1; i<m_cValidLocales; i++) {
for (j=i; j>0 &&
m_rgLcidOrdMap[j].lcid < m_rgLcidOrdMap[j-1].lcid; j--) {
// Swap with prev element
int lcidTemp = m_rgLcidOrdMap[j-1].lcid;
int uiOrdTemp = m_rgLcidOrdMap[j-1].uiOrd;
m_rgLcidOrdMap[j-1].lcid = m_rgLcidOrdMap[j].lcid;
m_rgLcidOrdMap[j-1].uiOrd = m_rgLcidOrdMap[j].uiOrd;
m_rgLcidOrdMap[j].lcid = lcidTemp;
m_rgLcidOrdMap[j].uiOrd = uiOrdTemp;
}
}
// Set the position of the US_English LCID (Latin1_General)
for (i=0; i<m_cValidLocales && m_rgLcidOrdMap[i].lcid != SqlString.x_lcidUSEnglish; i++)
; // Deliberately empty
SQLDebug.Check(i<m_cValidLocales); // Latin1_General better be present
m_uiPosEnglish = i; // This is index in array, not ordinal
}
} // CBuildLcidOrdMap
*/
} // namespace System.Data.SqlTypes
| |
namespace GImpactTestDemo
{
static class TorusMesh
{
public static float[] Vertices = new float[]
{
2.5f, 0f, 0f,
2.405f, 0.294f, 0f,
2.155f, 0.476f, 0f,
1.845f, 0.476f, 0f,
1.595f, 0.294f, 0f,
1.5f, 0f, 0f,
1.595f, -0.294f, 0f,
1.845f, -0.476f, 0f,
2.155f, -0.476f, 0f,
2.405f, -0.294f, 0f,
2.445f, 0f, 0.52f,
2.352f, 0.294f, 0.5f,
2.107f, 0.476f, 0.448f,
1.805f, 0.476f, 0.384f,
1.561f, 0.294f, 0.332f,
1.467f, 0f, 0.312f,
1.561f, -0.294f, 0.332f,
1.805f, -0.476f, 0.384f,
2.107f, -0.476f, 0.448f,
2.352f, -0.294f, 0.5f,
2.284f, 0f, 1.017f,
2.197f, 0.294f, 0.978f,
1.968f, 0.476f, 0.876f,
1.686f, 0.476f, 0.751f,
1.458f, 0.294f, 0.649f,
1.37f, 0f, 0.61f,
1.458f, -0.294f, 0.649f,
1.686f, -0.476f, 0.751f,
1.968f, -0.476f, 0.876f,
2.197f, -0.294f, 0.978f,
2.023f, 0f, 1.469f,
1.945f, 0.294f, 1.413f,
1.743f, 0.476f, 1.266f,
1.493f, 0.476f, 1.085f,
1.291f, 0.294f, 0.938f,
1.214f, 0f, 0.882f,
1.291f, -0.294f, 0.938f,
1.493f, -0.476f, 1.085f,
1.743f, -0.476f, 1.266f,
1.945f, -0.294f, 1.413f,
1.673f, 0f, 1.858f,
1.609f, 0.294f, 1.787f,
1.442f, 0.476f, 1.601f,
1.235f, 0.476f, 1.371f,
1.068f, 0.294f, 1.186f,
1.004f, 0f, 1.115f,
1.068f, -0.294f, 1.186f,
1.235f, -0.476f, 1.371f,
1.442f, -0.476f, 1.601f,
1.609f, -0.294f, 1.787f,
1.25f, 0f, 2.165f,
1.202f, 0.294f, 2.082f,
1.077f, 0.476f, 1.866f,
0.923f, 0.476f, 1.598f,
0.798f, 0.294f, 1.382f,
0.75f, 0f, 1.299f,
0.798f, -0.294f, 1.382f,
0.923f, -0.476f, 1.598f,
1.077f, -0.476f, 1.866f,
1.202f, -0.294f, 2.082f,
0.773f, 0f, 2.378f,
0.743f, 0.294f, 2.287f,
0.666f, 0.476f, 2.049f,
0.57f, 0.476f, 1.755f,
0.493f, 0.294f, 1.517f,
0.464f, 0f, 1.427f,
0.493f, -0.294f, 1.517f,
0.57f, -0.476f, 1.755f,
0.666f, -0.476f, 2.049f,
0.743f, -0.294f, 2.287f,
0.261f, 0f, 2.486f,
0.251f, 0.294f, 2.391f,
0.225f, 0.476f, 2.143f,
0.193f, 0.476f, 1.835f,
0.167f, 0.294f, 1.587f,
0.157f, 0f, 1.492f,
0.167f, -0.294f, 1.587f,
0.193f, -0.476f, 1.835f,
0.225f, -0.476f, 2.143f,
0.251f, -0.294f, 2.391f,
-0.261f, 0f, 2.486f,
-0.251f, 0.294f, 2.391f,
-0.225f, 0.476f, 2.143f,
-0.193f, 0.476f, 1.835f,
-0.167f, 0.294f, 1.587f,
-0.157f, 0f, 1.492f,
-0.167f, -0.294f, 1.587f,
-0.193f, -0.476f, 1.835f,
-0.225f, -0.476f, 2.143f,
-0.251f, -0.294f, 2.391f,
-0.773f, 0f, 2.378f,
-0.743f, 0.294f, 2.287f,
-0.666f, 0.476f, 2.049f,
-0.57f, 0.476f, 1.755f,
-0.493f, 0.294f, 1.517f,
-0.464f, 0f, 1.427f,
-0.493f, -0.294f, 1.517f,
-0.57f, -0.476f, 1.755f,
-0.666f, -0.476f, 2.049f,
-0.743f, -0.294f, 2.287f,
-1.25f, 0f, 2.165f,
-1.202f, 0.294f, 2.082f,
-1.077f, 0.476f, 1.866f,
-0.923f, 0.476f, 1.598f,
-0.798f, 0.294f, 1.382f,
-0.75f, 0f, 1.299f,
-0.798f, -0.294f, 1.382f,
-0.923f, -0.476f, 1.598f,
-1.077f, -0.476f, 1.866f,
-1.202f, -0.294f, 2.082f,
-1.673f, 0f, 1.858f,
-1.609f, 0.294f, 1.787f,
-1.442f, 0.476f, 1.601f,
-1.235f, 0.476f, 1.371f,
-1.068f, 0.294f, 1.186f,
-1.004f, 0f, 1.115f,
-1.068f, -0.294f, 1.186f,
-1.235f, -0.476f, 1.371f,
-1.442f, -0.476f, 1.601f,
-1.609f, -0.294f, 1.787f,
-2.023f, 0f, 1.469f,
-1.945f, 0.294f, 1.413f,
-1.743f, 0.476f, 1.266f,
-1.493f, 0.476f, 1.085f,
-1.291f, 0.294f, 0.938f,
-1.214f, 0f, 0.882f,
-1.291f, -0.294f, 0.938f,
-1.493f, -0.476f, 1.085f,
-1.743f, -0.476f, 1.266f,
-1.945f, -0.294f, 1.413f,
-2.284f, 0f, 1.017f,
-2.197f, 0.294f, 0.978f,
-1.968f, 0.476f, 0.876f,
-1.686f, 0.476f, 0.751f,
-1.458f, 0.294f, 0.649f,
-1.37f, 0f, 0.61f,
-1.458f, -0.294f, 0.649f,
-1.686f, -0.476f, 0.751f,
-1.968f, -0.476f, 0.876f,
-2.197f, -0.294f, 0.978f,
-2.445f, 0f, 0.52f,
-2.352f, 0.294f, 0.5f,
-2.107f, 0.476f, 0.448f,
-1.805f, 0.476f, 0.384f,
-1.561f, 0.294f, 0.332f,
-1.467f, 0f, 0.312f,
-1.561f, -0.294f, 0.332f,
-1.805f, -0.476f, 0.384f,
-2.107f, -0.476f, 0.448f,
-2.352f, -0.294f, 0.5f,
-2.5f, 0f, 0f,
-2.405f, 0.294f, 0f,
-2.155f, 0.476f, 0f,
-1.845f, 0.476f, 0f,
-1.595f, 0.294f, 0f,
-1.5f, 0f, 0f,
-1.595f, -0.294f, 0f,
-1.845f, -0.476f, 0f,
-2.155f, -0.476f, 0f,
-2.405f, -0.294f, 0f,
-2.445f, 0f, -0.52f,
-2.352f, 0.294f, -0.5f,
-2.107f, 0.476f, -0.448f,
-1.805f, 0.476f, -0.384f,
-1.561f, 0.294f, -0.332f,
-1.467f, 0f, -0.312f,
-1.561f, -0.294f, -0.332f,
-1.805f, -0.476f, -0.384f,
-2.107f, -0.476f, -0.448f,
-2.352f, -0.294f, -0.5f,
-2.284f, 0f, -1.017f,
-2.197f, 0.294f, -0.978f,
-1.968f, 0.476f, -0.876f,
-1.686f, 0.476f, -0.751f,
-1.458f, 0.294f, -0.649f,
-1.37f, 0f, -0.61f,
-1.458f, -0.294f, -0.649f,
-1.686f, -0.476f, -0.751f,
-1.968f, -0.476f, -0.876f,
-2.197f, -0.294f, -0.978f,
-2.023f, 0f, -1.469f,
-1.945f, 0.294f, -1.413f,
-1.743f, 0.476f, -1.266f,
-1.493f, 0.476f, -1.085f,
-1.291f, 0.294f, -0.938f,
-1.214f, 0f, -0.882f,
-1.291f, -0.294f, -0.938f,
-1.493f, -0.476f, -1.085f,
-1.743f, -0.476f, -1.266f,
-1.945f, -0.294f, -1.413f,
-1.673f, 0f, -1.858f,
-1.609f, 0.294f, -1.787f,
-1.442f, 0.476f, -1.601f,
-1.235f, 0.476f, -1.371f,
-1.068f, 0.294f, -1.186f,
-1.004f, 0f, -1.115f,
-1.068f, -0.294f, -1.186f,
-1.235f, -0.476f, -1.371f,
-1.442f, -0.476f, -1.601f,
-1.609f, -0.294f, -1.787f,
-1.25f, 0f, -2.165f,
-1.202f, 0.294f, -2.082f,
-1.077f, 0.476f, -1.866f,
-0.923f, 0.476f, -1.598f,
-0.798f, 0.294f, -1.382f,
-0.75f, 0f, -1.299f,
-0.798f, -0.294f, -1.382f,
-0.923f, -0.476f, -1.598f,
-1.077f, -0.476f, -1.866f,
-1.202f, -0.294f, -2.082f,
-0.773f, 0f, -2.378f,
-0.743f, 0.294f, -2.287f,
-0.666f, 0.476f, -2.049f,
-0.57f, 0.476f, -1.755f,
-0.493f, 0.294f, -1.517f,
-0.464f, 0f, -1.427f,
-0.493f, -0.294f, -1.517f,
-0.57f, -0.476f, -1.755f,
-0.666f, -0.476f, -2.049f,
-0.743f, -0.294f, -2.287f,
-0.261f, 0f, -2.486f,
-0.251f, 0.294f, -2.391f,
-0.225f, 0.476f, -2.143f,
-0.193f, 0.476f, -1.835f,
-0.167f, 0.294f, -1.587f,
-0.157f, 0f, -1.492f,
-0.167f, -0.294f, -1.587f,
-0.193f, -0.476f, -1.835f,
-0.225f, -0.476f, -2.143f,
-0.251f, -0.294f, -2.391f,
0.261f, 0f, -2.486f,
0.251f, 0.294f, -2.391f,
0.225f, 0.476f, -2.143f,
0.193f, 0.476f, -1.835f,
0.167f, 0.294f, -1.587f,
0.157f, 0f, -1.492f,
0.167f, -0.294f, -1.587f,
0.193f, -0.476f, -1.835f,
0.225f, -0.476f, -2.143f,
0.251f, -0.294f, -2.391f,
0.773f, 0f, -2.378f,
0.743f, 0.294f, -2.287f,
0.666f, 0.476f, -2.049f,
0.57f, 0.476f, -1.755f,
0.493f, 0.294f, -1.517f,
0.464f, 0f, -1.427f,
0.493f, -0.294f, -1.517f,
0.57f, -0.476f, -1.755f,
0.666f, -0.476f, -2.049f,
0.743f, -0.294f, -2.287f,
1.25f, 0f, -2.165f,
1.202f, 0.294f, -2.082f,
1.077f, 0.476f, -1.866f,
0.923f, 0.476f, -1.598f,
0.798f, 0.294f, -1.382f,
0.75f, 0f, -1.299f,
0.798f, -0.294f, -1.382f,
0.923f, -0.476f, -1.598f,
1.077f, -0.476f, -1.866f,
1.202f, -0.294f, -2.082f,
1.673f, 0f, -1.858f,
1.609f, 0.294f, -1.787f,
1.442f, 0.476f, -1.601f,
1.235f, 0.476f, -1.371f,
1.068f, 0.294f, -1.186f,
1.004f, 0f, -1.115f,
1.068f, -0.294f, -1.186f,
1.235f, -0.476f, -1.371f,
1.442f, -0.476f, -1.601f,
1.609f, -0.294f, -1.787f,
2.023f, 0f, -1.469f,
1.945f, 0.294f, -1.413f,
1.743f, 0.476f, -1.266f,
1.493f, 0.476f, -1.085f,
1.291f, 0.294f, -0.938f,
1.214f, 0f, -0.882f,
1.291f, -0.294f, -0.938f,
1.493f, -0.476f, -1.085f,
1.743f, -0.476f, -1.266f,
1.945f, -0.294f, -1.413f,
2.284f, 0f, -1.017f,
2.197f, 0.294f, -0.978f,
1.968f, 0.476f, -0.876f,
1.686f, 0.476f, -0.751f,
1.458f, 0.294f, -0.649f,
1.37f, 0f, -0.61f,
1.458f, -0.294f, -0.649f,
1.686f, -0.476f, -0.751f,
1.968f, -0.476f, -0.876f,
2.197f, -0.294f, -0.978f,
2.445f, 0f, -0.52f,
2.352f, 0.294f, -0.5f,
2.107f, 0.476f, -0.448f,
1.805f, 0.476f, -0.384f,
1.561f, 0.294f, -0.332f,
1.467f, 0f, -0.312f,
1.561f, -0.294f, -0.332f,
1.805f, -0.476f, -0.384f,
2.107f, -0.476f, -0.448f,
2.352f, -0.294f, -0.5f
};
public static int[] Indices = new int[]
{
0, 1, 11,
1, 2, 12,
2, 3, 13,
3, 4, 14,
4, 5, 15,
5, 6, 16,
6, 7, 17,
7, 8, 18,
8, 9, 19,
9, 0, 10,
10, 11, 21,
11, 12, 22,
12, 13, 23,
13, 14, 24,
14, 15, 25,
15, 16, 26,
16, 17, 27,
17, 18, 28,
18, 19, 29,
19, 10, 20,
20, 21, 31,
21, 22, 32,
22, 23, 33,
23, 24, 34,
24, 25, 35,
25, 26, 36,
26, 27, 37,
27, 28, 38,
28, 29, 39,
29, 20, 30,
30, 31, 41,
31, 32, 42,
32, 33, 43,
33, 34, 44,
34, 35, 45,
35, 36, 46,
36, 37, 47,
37, 38, 48,
38, 39, 49,
39, 30, 40,
40, 41, 51,
41, 42, 52,
42, 43, 53,
43, 44, 54,
44, 45, 55,
45, 46, 56,
46, 47, 57,
47, 48, 58,
48, 49, 59,
49, 40, 50,
50, 51, 61,
51, 52, 62,
52, 53, 63,
53, 54, 64,
54, 55, 65,
55, 56, 66,
56, 57, 67,
57, 58, 68,
58, 59, 69,
59, 50, 60,
60, 61, 71,
61, 62, 72,
62, 63, 73,
63, 64, 74,
64, 65, 75,
65, 66, 76,
66, 67, 77,
67, 68, 78,
68, 69, 79,
69, 60, 70,
70, 71, 81,
71, 72, 82,
72, 73, 83,
73, 74, 84,
74, 75, 85,
75, 76, 86,
76, 77, 87,
77, 78, 88,
78, 79, 89,
79, 70, 80,
80, 81, 91,
81, 82, 92,
82, 83, 93,
83, 84, 94,
84, 85, 95,
85, 86, 96,
86, 87, 97,
87, 88, 98,
88, 89, 99,
89, 80, 90,
90, 91, 101,
91, 92, 102,
92, 93, 103,
93, 94, 104,
94, 95, 105,
95, 96, 106,
96, 97, 107,
97, 98, 108,
98, 99, 109,
99, 90, 100,
100, 101, 111,
101, 102, 112,
102, 103, 113,
103, 104, 114,
104, 105, 115,
105, 106, 116,
106, 107, 117,
107, 108, 118,
108, 109, 119,
109, 100, 110,
110, 111, 121,
111, 112, 122,
112, 113, 123,
113, 114, 124,
114, 115, 125,
115, 116, 126,
116, 117, 127,
117, 118, 128,
118, 119, 129,
119, 110, 120,
120, 121, 131,
121, 122, 132,
122, 123, 133,
123, 124, 134,
124, 125, 135,
125, 126, 136,
126, 127, 137,
127, 128, 138,
128, 129, 139,
129, 120, 130,
130, 131, 141,
131, 132, 142,
132, 133, 143,
133, 134, 144,
134, 135, 145,
135, 136, 146,
136, 137, 147,
137, 138, 148,
138, 139, 149,
139, 130, 140,
140, 141, 151,
141, 142, 152,
142, 143, 153,
143, 144, 154,
144, 145, 155,
145, 146, 156,
146, 147, 157,
147, 148, 158,
148, 149, 159,
149, 140, 150,
150, 151, 161,
151, 152, 162,
152, 153, 163,
153, 154, 164,
154, 155, 165,
155, 156, 166,
156, 157, 167,
157, 158, 168,
158, 159, 169,
159, 150, 160,
160, 161, 171,
161, 162, 172,
162, 163, 173,
163, 164, 174,
164, 165, 175,
165, 166, 176,
166, 167, 177,
167, 168, 178,
168, 169, 179,
169, 160, 170,
170, 171, 181,
171, 172, 182,
172, 173, 183,
173, 174, 184,
174, 175, 185,
175, 176, 186,
176, 177, 187,
177, 178, 188,
178, 179, 189,
179, 170, 180,
180, 181, 191,
181, 182, 192,
182, 183, 193,
183, 184, 194,
184, 185, 195,
185, 186, 196,
186, 187, 197,
187, 188, 198,
188, 189, 199,
189, 180, 190,
190, 191, 201,
191, 192, 202,
192, 193, 203,
193, 194, 204,
194, 195, 205,
195, 196, 206,
196, 197, 207,
197, 198, 208,
198, 199, 209,
199, 190, 200,
200, 201, 211,
201, 202, 212,
202, 203, 213,
203, 204, 214,
204, 205, 215,
205, 206, 216,
206, 207, 217,
207, 208, 218,
208, 209, 219,
209, 200, 210,
210, 211, 221,
211, 212, 222,
212, 213, 223,
213, 214, 224,
214, 215, 225,
215, 216, 226,
216, 217, 227,
217, 218, 228,
218, 219, 229,
219, 210, 220,
220, 221, 231,
221, 222, 232,
222, 223, 233,
223, 224, 234,
224, 225, 235,
225, 226, 236,
226, 227, 237,
227, 228, 238,
228, 229, 239,
229, 220, 230,
230, 231, 241,
231, 232, 242,
232, 233, 243,
233, 234, 244,
234, 235, 245,
235, 236, 246,
236, 237, 247,
237, 238, 248,
238, 239, 249,
239, 230, 240,
240, 241, 251,
241, 242, 252,
242, 243, 253,
243, 244, 254,
244, 245, 255,
245, 246, 256,
246, 247, 257,
247, 248, 258,
248, 249, 259,
249, 240, 250,
250, 251, 261,
251, 252, 262,
252, 253, 263,
253, 254, 264,
254, 255, 265,
255, 256, 266,
256, 257, 267,
257, 258, 268,
258, 259, 269,
259, 250, 260,
260, 261, 271,
261, 262, 272,
262, 263, 273,
263, 264, 274,
264, 265, 275,
265, 266, 276,
266, 267, 277,
267, 268, 278,
268, 269, 279,
269, 260, 270,
270, 271, 281,
271, 272, 282,
272, 273, 283,
273, 274, 284,
274, 275, 285,
275, 276, 286,
276, 277, 287,
277, 278, 288,
278, 279, 289,
279, 270, 280,
280, 281, 291,
281, 282, 292,
282, 283, 293,
283, 284, 294,
284, 285, 295,
285, 286, 296,
286, 287, 297,
287, 288, 298,
288, 289, 299,
289, 280, 290,
290, 291, 1,
291, 292, 2,
292, 293, 3,
293, 294, 4,
294, 295, 5,
295, 296, 6,
296, 297, 7,
297, 298, 8,
298, 299, 9,
299, 290, 0,
0, 11, 10,
1, 12, 11,
2, 13, 12,
3, 14, 13,
4, 15, 14,
5, 16, 15,
6, 17, 16,
7, 18, 17,
8, 19, 18,
9, 10, 19,
10, 21, 20,
11, 22, 21,
12, 23, 22,
13, 24, 23,
14, 25, 24,
15, 26, 25,
16, 27, 26,
17, 28, 27,
18, 29, 28,
19, 20, 29,
20, 31, 30,
21, 32, 31,
22, 33, 32,
23, 34, 33,
24, 35, 34,
25, 36, 35,
26, 37, 36,
27, 38, 37,
28, 39, 38,
29, 30, 39,
30, 41, 40,
31, 42, 41,
32, 43, 42,
33, 44, 43,
34, 45, 44,
35, 46, 45,
36, 47, 46,
37, 48, 47,
38, 49, 48,
39, 40, 49,
40, 51, 50,
41, 52, 51,
42, 53, 52,
43, 54, 53,
44, 55, 54,
45, 56, 55,
46, 57, 56,
47, 58, 57,
48, 59, 58,
49, 50, 59,
50, 61, 60,
51, 62, 61,
52, 63, 62,
53, 64, 63,
54, 65, 64,
55, 66, 65,
56, 67, 66,
57, 68, 67,
58, 69, 68,
59, 60, 69,
60, 71, 70,
61, 72, 71,
62, 73, 72,
63, 74, 73,
64, 75, 74,
65, 76, 75,
66, 77, 76,
67, 78, 77,
68, 79, 78,
69, 70, 79,
70, 81, 80,
71, 82, 81,
72, 83, 82,
73, 84, 83,
74, 85, 84,
75, 86, 85,
76, 87, 86,
77, 88, 87,
78, 89, 88,
79, 80, 89,
80, 91, 90,
81, 92, 91,
82, 93, 92,
83, 94, 93,
84, 95, 94,
85, 96, 95,
86, 97, 96,
87, 98, 97,
88, 99, 98,
89, 90, 99,
90, 101, 100,
91, 102, 101,
92, 103, 102,
93, 104, 103,
94, 105, 104,
95, 106, 105,
96, 107, 106,
97, 108, 107,
98, 109, 108,
99, 100, 109,
100, 111, 110,
101, 112, 111,
102, 113, 112,
103, 114, 113,
104, 115, 114,
105, 116, 115,
106, 117, 116,
107, 118, 117,
108, 119, 118,
109, 110, 119,
110, 121, 120,
111, 122, 121,
112, 123, 122,
113, 124, 123,
114, 125, 124,
115, 126, 125,
116, 127, 126,
117, 128, 127,
118, 129, 128,
119, 120, 129,
120, 131, 130,
121, 132, 131,
122, 133, 132,
123, 134, 133,
124, 135, 134,
125, 136, 135,
126, 137, 136,
127, 138, 137,
128, 139, 138,
129, 130, 139,
130, 141, 140,
131, 142, 141,
132, 143, 142,
133, 144, 143,
134, 145, 144,
135, 146, 145,
136, 147, 146,
137, 148, 147,
138, 149, 148,
139, 140, 149,
140, 151, 150,
141, 152, 151,
142, 153, 152,
143, 154, 153,
144, 155, 154,
145, 156, 155,
146, 157, 156,
147, 158, 157,
148, 159, 158,
149, 150, 159,
150, 161, 160,
151, 162, 161,
152, 163, 162,
153, 164, 163,
154, 165, 164,
155, 166, 165,
156, 167, 166,
157, 168, 167,
158, 169, 168,
159, 160, 169,
160, 171, 170,
161, 172, 171,
162, 173, 172,
163, 174, 173,
164, 175, 174,
165, 176, 175,
166, 177, 176,
167, 178, 177,
168, 179, 178,
169, 170, 179,
170, 181, 180,
171, 182, 181,
172, 183, 182,
173, 184, 183,
174, 185, 184,
175, 186, 185,
176, 187, 186,
177, 188, 187,
178, 189, 188,
179, 180, 189,
180, 191, 190,
181, 192, 191,
182, 193, 192,
183, 194, 193,
184, 195, 194,
185, 196, 195,
186, 197, 196,
187, 198, 197,
188, 199, 198,
189, 190, 199,
190, 201, 200,
191, 202, 201,
192, 203, 202,
193, 204, 203,
194, 205, 204,
195, 206, 205,
196, 207, 206,
197, 208, 207,
198, 209, 208,
199, 200, 209,
200, 211, 210,
201, 212, 211,
202, 213, 212,
203, 214, 213,
204, 215, 214,
205, 216, 215,
206, 217, 216,
207, 218, 217,
208, 219, 218,
209, 210, 219,
210, 221, 220,
211, 222, 221,
212, 223, 222,
213, 224, 223,
214, 225, 224,
215, 226, 225,
216, 227, 226,
217, 228, 227,
218, 229, 228,
219, 220, 229,
220, 231, 230,
221, 232, 231,
222, 233, 232,
223, 234, 233,
224, 235, 234,
225, 236, 235,
226, 237, 236,
227, 238, 237,
228, 239, 238,
229, 230, 239,
230, 241, 240,
231, 242, 241,
232, 243, 242,
233, 244, 243,
234, 245, 244,
235, 246, 245,
236, 247, 246,
237, 248, 247,
238, 249, 248,
239, 240, 249,
240, 251, 250,
241, 252, 251,
242, 253, 252,
243, 254, 253,
244, 255, 254,
245, 256, 255,
246, 257, 256,
247, 258, 257,
248, 259, 258,
249, 250, 259,
250, 261, 260,
251, 262, 261,
252, 263, 262,
253, 264, 263,
254, 265, 264,
255, 266, 265,
256, 267, 266,
257, 268, 267,
258, 269, 268,
259, 260, 269,
260, 271, 270,
261, 272, 271,
262, 273, 272,
263, 274, 273,
264, 275, 274,
265, 276, 275,
266, 277, 276,
267, 278, 277,
268, 279, 278,
269, 270, 279,
270, 281, 280,
271, 282, 281,
272, 283, 282,
273, 284, 283,
274, 285, 284,
275, 286, 285,
276, 287, 286,
277, 288, 287,
278, 289, 288,
279, 280, 289,
280, 291, 290,
281, 292, 291,
282, 293, 292,
283, 294, 293,
284, 295, 294,
285, 296, 295,
286, 297, 296,
287, 298, 297,
288, 299, 298,
289, 290, 299,
290, 1, 0,
291, 2, 1,
292, 3, 2,
293, 4, 3,
294, 5, 4,
295, 6, 5,
296, 7, 6,
297, 8, 7,
298, 9, 8,
299, 0, 9
};
}
}
| |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Hyak.Common;
using Microsoft.Azure.Management.Resources;
using Microsoft.Azure.Management.Resources.Models;
using Newtonsoft.Json.Linq;
namespace Microsoft.Azure.Management.Resources
{
/// <summary>
/// Operations for managing preview features.
/// </summary>
internal partial class Features : IServiceOperations<FeatureClient>, IFeatures
{
/// <summary>
/// Initializes a new instance of the Features class.
/// </summary>
/// <param name='client'>
/// Reference to the service client.
/// </param>
internal Features(FeatureClient client)
{
this._client = client;
}
private FeatureClient _client;
/// <summary>
/// Gets a reference to the
/// Microsoft.Azure.Management.Resources.FeatureClient.
/// </summary>
public FeatureClient Client
{
get { return this._client; }
}
/// <summary>
/// Get all features under the subscription.
/// </summary>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <param name='featureName'>
/// Required. Previewed feature name in the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Previewed feature information.
/// </returns>
public async Task<FeatureResponse> GetAsync(string resourceProviderNamespace, string featureName, CancellationToken cancellationToken)
{
// Validate
if (resourceProviderNamespace == null)
{
throw new ArgumentNullException("resourceProviderNamespace");
}
if (featureName == null)
{
throw new ArgumentNullException("featureName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
tracingParameters.Add("featureName", featureName);
TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.Features/providers/";
url = url + Uri.EscapeDataString(resourceProviderNamespace);
url = url + "/features/";
url = url + Uri.EscapeDataString(featureName);
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-12-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
FeatureResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new FeatureResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
result.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
FeatureProperties propertiesInstance = new FeatureProperties();
result.Properties = propertiesInstance;
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
result.Id = idInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
result.Type = typeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a list of previewed features of a resource provider.
/// </summary>
/// <param name='resourceProviderNamespace'>
/// Required. The namespace of the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of previewed features.
/// </returns>
public async Task<FeatureOperationsListResult> ListAsync(string resourceProviderNamespace, CancellationToken cancellationToken)
{
// Validate
if (resourceProviderNamespace == null)
{
throw new ArgumentNullException("resourceProviderNamespace");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.Features/providers/";
url = url + Uri.EscapeDataString(resourceProviderNamespace);
url = url + "/features";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-12-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
FeatureOperationsListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new FeatureOperationsListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
FeatureResponse featureResponseInstance = new FeatureResponse();
result.Features.Add(featureResponseInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
featureResponseInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
FeatureProperties propertiesInstance = new FeatureProperties();
featureResponseInstance.Properties = propertiesInstance;
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
featureResponseInstance.Id = idInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
featureResponseInstance.Type = typeInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a list of previewed features for all the providers in the
/// current subscription.
/// </summary>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of previewed features.
/// </returns>
public async Task<FeatureOperationsListResult> ListAllAsync(CancellationToken cancellationToken)
{
// Validate
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
TracingAdapter.Enter(invocationId, this, "ListAllAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.Features/features";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-12-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
FeatureOperationsListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new FeatureOperationsListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
FeatureResponse featureResponseInstance = new FeatureResponse();
result.Features.Add(featureResponseInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
featureResponseInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
FeatureProperties propertiesInstance = new FeatureProperties();
featureResponseInstance.Properties = propertiesInstance;
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
featureResponseInstance.Id = idInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
featureResponseInstance.Type = typeInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a list of previewed features of a subscription.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of previewed features.
/// </returns>
public async Task<FeatureOperationsListResult> ListAllNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListAllNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
FeatureOperationsListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new FeatureOperationsListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
FeatureResponse featureResponseInstance = new FeatureResponse();
result.Features.Add(featureResponseInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
featureResponseInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
FeatureProperties propertiesInstance = new FeatureProperties();
featureResponseInstance.Properties = propertiesInstance;
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
featureResponseInstance.Id = idInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
featureResponseInstance.Type = typeInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Gets a list of previewed features of a resource provider.
/// </summary>
/// <param name='nextLink'>
/// Required. NextLink from the previous successful call to List
/// operation.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// List of previewed features.
/// </returns>
public async Task<FeatureOperationsListResult> ListNextAsync(string nextLink, CancellationToken cancellationToken)
{
// Validate
if (nextLink == null)
{
throw new ArgumentNullException("nextLink");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("nextLink", nextLink);
TracingAdapter.Enter(invocationId, this, "ListNextAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + nextLink;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Get;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
FeatureOperationsListResult result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new FeatureOperationsListResult();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken valueArray = responseDoc["value"];
if (valueArray != null && valueArray.Type != JTokenType.Null)
{
foreach (JToken valueValue in ((JArray)valueArray))
{
FeatureResponse featureResponseInstance = new FeatureResponse();
result.Features.Add(featureResponseInstance);
JToken nameValue = valueValue["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
featureResponseInstance.Name = nameInstance;
}
JToken propertiesValue = valueValue["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
FeatureProperties propertiesInstance = new FeatureProperties();
featureResponseInstance.Properties = propertiesInstance;
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
}
JToken idValue = valueValue["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
featureResponseInstance.Id = idInstance;
}
JToken typeValue = valueValue["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
featureResponseInstance.Type = typeInstance;
}
}
}
JToken nextLinkValue = responseDoc["nextLink"];
if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null)
{
string nextLinkInstance = ((string)nextLinkValue);
result.NextLink = nextLinkInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
/// <summary>
/// Registers for a previewed feature of a resource provider.
/// </summary>
/// <param name='resourceProviderNamespace'>
/// Required. Namespace of the resource provider.
/// </param>
/// <param name='featureName'>
/// Required. Previewed feature name in the resource provider.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// Previewed feature information.
/// </returns>
public async Task<FeatureResponse> RegisterAsync(string resourceProviderNamespace, string featureName, CancellationToken cancellationToken)
{
// Validate
if (resourceProviderNamespace == null)
{
throw new ArgumentNullException("resourceProviderNamespace");
}
if (featureName == null)
{
throw new ArgumentNullException("featureName");
}
// Tracing
bool shouldTrace = TracingAdapter.IsEnabled;
string invocationId = null;
if (shouldTrace)
{
invocationId = TracingAdapter.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("resourceProviderNamespace", resourceProviderNamespace);
tracingParameters.Add("featureName", featureName);
TracingAdapter.Enter(invocationId, this, "RegisterAsync", tracingParameters);
}
// Construct URL
string url = "";
url = url + "/subscriptions/";
if (this.Client.Credentials.SubscriptionId != null)
{
url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId);
}
url = url + "/providers/Microsoft.Features/providers/";
url = url + Uri.EscapeDataString(resourceProviderNamespace);
url = url + "/features/";
url = url + Uri.EscapeDataString(featureName);
url = url + "/register";
List<string> queryParameters = new List<string>();
queryParameters.Add("api-version=2015-12-01");
if (queryParameters.Count > 0)
{
url = url + "?" + string.Join("&", queryParameters);
}
string baseUrl = this.Client.BaseUri.AbsoluteUri;
// Trim '/' character from the end of baseUrl and beginning of url.
if (baseUrl[baseUrl.Length - 1] == '/')
{
baseUrl = baseUrl.Substring(0, baseUrl.Length - 1);
}
if (url[0] == '/')
{
url = url.Substring(1);
}
url = baseUrl + "/" + url;
url = url.Replace(" ", "%20");
// Create HTTP transport objects
HttpRequestMessage httpRequest = null;
try
{
httpRequest = new HttpRequestMessage();
httpRequest.Method = HttpMethod.Post;
httpRequest.RequestUri = new Uri(url);
// Set Headers
// Set Credentials
cancellationToken.ThrowIfCancellationRequested();
await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false);
// Send Request
HttpResponseMessage httpResponse = null;
try
{
if (shouldTrace)
{
TracingAdapter.SendRequest(invocationId, httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false);
if (shouldTrace)
{
TracingAdapter.ReceiveResponse(invocationId, httpResponse);
}
HttpStatusCode statusCode = httpResponse.StatusCode;
if (statusCode != HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false));
if (shouldTrace)
{
TracingAdapter.Error(invocationId, ex);
}
throw ex;
}
// Create Result
FeatureResponse result = null;
// Deserialize Response
if (statusCode == HttpStatusCode.OK)
{
cancellationToken.ThrowIfCancellationRequested();
string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
result = new FeatureResponse();
JToken responseDoc = null;
if (string.IsNullOrEmpty(responseContent) == false)
{
responseDoc = JToken.Parse(responseContent);
}
if (responseDoc != null && responseDoc.Type != JTokenType.Null)
{
JToken nameValue = responseDoc["name"];
if (nameValue != null && nameValue.Type != JTokenType.Null)
{
string nameInstance = ((string)nameValue);
result.Name = nameInstance;
}
JToken propertiesValue = responseDoc["properties"];
if (propertiesValue != null && propertiesValue.Type != JTokenType.Null)
{
FeatureProperties propertiesInstance = new FeatureProperties();
result.Properties = propertiesInstance;
JToken stateValue = propertiesValue["state"];
if (stateValue != null && stateValue.Type != JTokenType.Null)
{
string stateInstance = ((string)stateValue);
propertiesInstance.State = stateInstance;
}
}
JToken idValue = responseDoc["id"];
if (idValue != null && idValue.Type != JTokenType.Null)
{
string idInstance = ((string)idValue);
result.Id = idInstance;
}
JToken typeValue = responseDoc["type"];
if (typeValue != null && typeValue.Type != JTokenType.Null)
{
string typeInstance = ((string)typeValue);
result.Type = typeInstance;
}
}
}
result.StatusCode = statusCode;
if (httpResponse.Headers.Contains("x-ms-request-id"))
{
result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault();
}
if (shouldTrace)
{
TracingAdapter.Exit(invocationId, result);
}
return result;
}
finally
{
if (httpResponse != null)
{
httpResponse.Dispose();
}
}
}
finally
{
if (httpRequest != null)
{
httpRequest.Dispose();
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Text;
using System.Threading;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Diagnostics.Tests
{
//Complex types are not supported on EventSource for .NET 4.5
public class DiagnosticSourceEventSourceBridgeTests
{
// To avoid interactions between tests when they are run in parallel, we run all these tests in their
// own sub-process using RemoteExecutor.Invoke() However this makes it very inconvinient to debug the test.
// By seting this #if to true you stub out RemoteInvoke and the code will run in-proc which is useful
// in debugging.
#if false
class NullDispose : IDisposable
{
public void Dispose()
{
}
}
static IDisposable RemoteExecutor.Invoke(Action a)
{
a();
return new NullDispose();
}
#endif
/// <summary>
/// Tests the basic functionality of turning on specific EventSources and specifying
/// the events you want.
/// </summary>
[Fact]
public void TestSpecificEvents()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestSpecificEventsSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// Turn on events with both implicit and explicit types You can have whitespace
// before and after each spec.
eventSourceListener.Enable(
" TestSpecificEventsSource/TestEvent1:cls_Point_X=cls.Point.X;cls_Point_Y=cls.Point.Y\r\n" +
" TestSpecificEventsSource/TestEvent2:cls_Url=cls.Url\r\n"
);
/***************************************************************************************/
// Emit an event that matches the first pattern.
MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestSpecificEventsSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(5, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]);
Assert.Equal("3", eventSourceListener.LastEvent.Arguments["cls_Point_X"]);
Assert.Equal("5", eventSourceListener.LastEvent.Arguments["cls_Point_Y"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an event that matches the second pattern.
if (diagnosticSourceListener.IsEnabled("TestEvent2"))
diagnosticSourceListener.Write("TestEvent2", new { prop2Str = "hello", prop2Int = 8, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestSpecificEventsSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName);
Assert.Equal(4, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hello", eventSourceListener.LastEvent.Arguments["prop2Str"]);
Assert.Equal("8", eventSourceListener.LastEvent.Arguments["prop2Int"]);
Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["cls_Url"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Emit an event that does not match either pattern. (thus will be filtered out)
if (diagnosticSourceListener.IsEnabled("TestEvent3"))
diagnosticSourceListener.Write("TestEvent3", new { propStr = "prop3", });
Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired.
/***************************************************************************************/
// Emit an event from another diagnostic source with the same event name.
// It will be filtered out.
using (var diagnosticSourceListener2 = new DiagnosticListener("TestSpecificEventsSource2"))
{
if (diagnosticSourceListener2.IsEnabled("TestEvent1"))
diagnosticSourceListener2.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
}
Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired.
// Disable all the listener and insure that no more events come through.
eventSourceListener.Disable();
diagnosticSourceListener.Write("TestEvent1", null);
diagnosticSourceListener.Write("TestEvent2", null);
Assert.Equal(0, eventSourceListener.EventCount); // No Event should be received.
}
// Make sure that there are no Diagnostic Listeners left over.
DiagnosticListener.AllListeners.Subscribe(DiagnosticSourceTest.MakeObserver(delegate (DiagnosticListener listen)
{
Assert.True(!listen.Name.StartsWith("BuildTestSource"));
}));
}).Dispose();
}
/// <summary>
/// Test that things work properly for Linux newline conventions.
/// </summary>
[Fact]
public void LinuxNewLineConventions()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("LinuxNewLineConventionsSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// Turn on events with both implicit and explicit types You can have whitespace
// before and after each spec. Use \n rather than \r\n
eventSourceListener.Enable(
" LinuxNewLineConventionsSource/TestEvent1:-cls_Point_X=cls.Point.X\n" +
" LinuxNewLineConventionsSource/TestEvent2:-cls_Url=cls.Url\n"
);
/***************************************************************************************/
// Emit an event that matches the first pattern.
MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("LinuxNewLineConventionsSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("3", eventSourceListener.LastEvent.Arguments["cls_Point_X"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an event that matches the second pattern.
if (diagnosticSourceListener.IsEnabled("TestEvent2"))
diagnosticSourceListener.Write("TestEvent2", new { prop2Str = "hello", prop2Int = 8, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("LinuxNewLineConventionsSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["cls_Url"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Emit an event that does not match either pattern. (thus will be filtered out)
if (diagnosticSourceListener.IsEnabled("TestEvent3"))
diagnosticSourceListener.Write("TestEvent3", new { propStr = "prop3", });
Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired.
}
// Make sure that there are no Diagnostic Listeners left over.
DiagnosticListener.AllListeners.Subscribe(DiagnosticSourceTest.MakeObserver(delegate (DiagnosticListener listen)
{
Assert.True(!listen.Name.StartsWith("BuildTestSource"));
}));
}).Dispose();
}
/// <summary>
/// Tests what happens when you wildcard the source name (empty string)
/// </summary>
[Fact]
public void TestWildCardSourceName()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener1 = new DiagnosticListener("TestWildCardSourceName1"))
using (var diagnosticSourceListener2 = new DiagnosticListener("TestWildCardSourceName2"))
{
eventSourceListener.Filter = (DiagnosticSourceEvent evnt) => evnt.SourceName.StartsWith("TestWildCardSourceName");
// Turn On Everything. Note that because of concurrent testing, we may get other sources as well.
// but we filter them out because we set eventSourceListener.Filter.
eventSourceListener.Enable("");
Assert.True(diagnosticSourceListener1.IsEnabled("TestEvent1"));
Assert.True(diagnosticSourceListener1.IsEnabled("TestEvent2"));
Assert.True(diagnosticSourceListener2.IsEnabled("TestEvent1"));
Assert.True(diagnosticSourceListener2.IsEnabled("TestEvent2"));
Assert.Equal(0, eventSourceListener.EventCount);
diagnosticSourceListener1.Write("TestEvent1", new { prop111 = "prop111Val", prop112 = 112 });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardSourceName1", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("prop111Val", eventSourceListener.LastEvent.Arguments["prop111"]);
Assert.Equal("112", eventSourceListener.LastEvent.Arguments["prop112"]);
eventSourceListener.ResetEventCountAndLastEvent();
diagnosticSourceListener1.Write("TestEvent2", new { prop121 = "prop121Val", prop122 = 122 });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardSourceName1", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("prop121Val", eventSourceListener.LastEvent.Arguments["prop121"]);
Assert.Equal("122", eventSourceListener.LastEvent.Arguments["prop122"]);
eventSourceListener.ResetEventCountAndLastEvent();
diagnosticSourceListener2.Write("TestEvent1", new { prop211 = "prop211Val", prop212 = 212 });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardSourceName2", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("prop211Val", eventSourceListener.LastEvent.Arguments["prop211"]);
Assert.Equal("212", eventSourceListener.LastEvent.Arguments["prop212"]);
eventSourceListener.ResetEventCountAndLastEvent();
diagnosticSourceListener2.Write("TestEvent2", new { prop221 = "prop221Val", prop222 = 122 });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardSourceName2", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent2", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("prop221Val", eventSourceListener.LastEvent.Arguments["prop221"]);
Assert.Equal("122", eventSourceListener.LastEvent.Arguments["prop222"]);
eventSourceListener.ResetEventCountAndLastEvent();
}
}).Dispose();
}
/// <summary>
/// Tests what happens when you wildcard event name (but not the source name)
/// </summary>
[Fact]
public void TestWildCardEventName()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestWildCardEventNameSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// Turn on events with both implicit and explicit types
eventSourceListener.Enable("TestWildCardEventNameSource");
/***************************************************************************************/
// Emit an event, check that all implicit properties are generated
MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit the same event, with a different set of implicit properties
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr2 = "hi2", cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hi2", eventSourceListener.LastEvent.Arguments["propStr2"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an event with the same schema as the first event. (uses first-event cache)
val = new MyClass() { };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr = "hiThere", propInt = 5, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hiThere", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("5", eventSourceListener.LastEvent.Arguments["propInt"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an event with the same schema as the second event. (uses dictionary cache)
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr2 = "hi3", cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestWildCardEventNameSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hi3", eventSourceListener.LastEvent.Arguments["propStr2"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an event from another diagnostic source with the same event name.
// It will be filtered out.
using (var diagnosticSourceListener2 = new DiagnosticListener("TestWildCardEventNameSource2"))
{
if (diagnosticSourceListener2.IsEnabled("TestEvent1"))
diagnosticSourceListener2.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
}
Assert.Equal(0, eventSourceListener.EventCount); // No Event should be fired.
}
}).Dispose();
}
/// <summary>
/// Test what happens when there are nulls passed in the event payloads
/// Basically strings get turned into empty strings and other nulls are typically
/// ignored.
/// </summary>
[Fact]
public void TestNulls()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestNullsTestSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// Turn on events with both implicit and explicit types
eventSourceListener.Enable("TestNullsTestSource/TestEvent1:cls.Url;cls_Point_X=cls.Point.X");
/***************************************************************************************/
// Emit a null arguments object.
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", null);
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(0, eventSourceListener.LastEvent.Arguments.Count);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an arguments object with nulls in it.
MyClass val = null;
string strVal = null;
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { cls = val, propStr = "propVal1", propStrNull = strVal });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("", eventSourceListener.LastEvent.Arguments["cls"]); // Tostring() on a null end up as an empty string.
Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("", eventSourceListener.LastEvent.Arguments["propStrNull"]); // null strings get turned into empty strings
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an arguments object that points at null things
MyClass val1 = new MyClass() { Url = "myUrlVal", Point = null };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { cls = val1, propStr = "propVal1" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val1.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("myUrlVal", eventSourceListener.LastEvent.Arguments["Url"]);
eventSourceListener.ResetEventCountAndLastEvent();
/***************************************************************************************/
// Emit an arguments object that points at null things (variation 2)
MyClass val2 = new MyClass() { Url = null, Point = new MyPoint() { X = 8, Y = 9 } };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { cls = val2, propStr = "propVal1" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestNullsTestSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val2.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("propVal1", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("8", eventSourceListener.LastEvent.Arguments["cls_Point_X"]);
eventSourceListener.ResetEventCountAndLastEvent();
}
}).Dispose();
}
/// <summary>
/// Tests the feature that suppresses the implicit inclusion of serialable properties
/// of the payload object.
/// </summary>
[Fact]
public void TestNoImplicitTransforms()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestNoImplicitTransformsSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// use the - prefix to suppress the implicit properties. Thus you should only get propStr and Url.
eventSourceListener.Enable("TestNoImplicitTransformsSource/TestEvent1:-propStr;cls.Url");
/***************************************************************************************/
// Emit an event that matches the first pattern.
MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val, propStr2 = "there" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestNoImplicitTransformsSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(2, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("MyUrl", eventSourceListener.LastEvent.Arguments["Url"]);
eventSourceListener.ResetEventCountAndLastEvent();
}
}).Dispose();
}
/// <summary>
/// Tests what happens when wacky characters are used in property specs.
/// </summary>
[Fact]
public void TestBadProperties()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestBadPropertiesSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// This has a syntax error in the Url case, so it should be ignored.
eventSourceListener.Enable("TestBadPropertiesSource/TestEvent1:cls.Ur-+l");
/***************************************************************************************/
// Emit an event that matches the first pattern.
MyClass val = new MyClass() { Url = "MyUrl", Point = new MyPoint() { X = 3, Y = 5 } };
if (diagnosticSourceListener.IsEnabled("TestEvent1"))
diagnosticSourceListener.Write("TestEvent1", new { propStr = "hi", propInt = 4, cls = val });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("TestBadPropertiesSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent1", eventSourceListener.LastEvent.EventName);
Assert.Equal(3, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal(val.GetType().FullName, eventSourceListener.LastEvent.Arguments["cls"]); // ToString on cls is the class name
Assert.Equal("hi", eventSourceListener.LastEvent.Arguments["propStr"]);
Assert.Equal("4", eventSourceListener.LastEvent.Arguments["propInt"]);
eventSourceListener.ResetEventCountAndLastEvent();
}
}).Dispose();
}
// Tests that messages about DiagnosticSourceEventSource make it out.
[Fact]
public void TestMessages()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestMessagesSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
// This is just to make debugging easier.
var messages = new List<string>();
eventSourceListener.OtherEventWritten += delegate (EventWrittenEventArgs evnt)
{
if (evnt.EventName == "Message")
{
var message = (string)evnt.Payload[0];
messages.Add(message);
}
};
// This has a syntax error in the Url case, so it should be ignored.
eventSourceListener.Enable("TestMessagesSource/TestEvent1:-cls.Url");
Assert.Equal(0, eventSourceListener.EventCount);
Assert.True(3 <= messages.Count);
}
}).Dispose();
}
/// <summary>
/// Tests the feature to send the messages as EventSource Activities.
/// </summary>
[Fact]
public void TestActivities()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
using (var diagnosticSourceListener = new DiagnosticListener("TestActivitiesSource"))
{
Assert.Equal(0, eventSourceListener.EventCount);
eventSourceListener.Enable(
"TestActivitiesSource/TestActivity1Start@Activity1Start\r\n" +
"TestActivitiesSource/TestActivity1Stop@Activity1Stop\r\n" +
"TestActivitiesSource/TestActivity2Start@Activity2Start\r\n" +
"TestActivitiesSource/TestActivity2Stop@Activity2Stop\r\n" +
"TestActivitiesSource/TestEvent\r\n"
);
// Start activity 1
diagnosticSourceListener.Write("TestActivity1Start", new { propStr = "start" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity1Start", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestActivity1Start", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("start", eventSourceListener.LastEvent.Arguments["propStr"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Start nested activity 2
diagnosticSourceListener.Write("TestActivity2Start", new { propStr = "start" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity2Start", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestActivity2Start", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("start", eventSourceListener.LastEvent.Arguments["propStr"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Send a normal event
diagnosticSourceListener.Write("TestEvent", new { propStr = "event" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Event", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestEvent", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("event", eventSourceListener.LastEvent.Arguments["propStr"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Stop nested activity 2
diagnosticSourceListener.Write("TestActivity2Stop", new { propStr = "stop" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity2Stop", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestActivity2Stop", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("stop", eventSourceListener.LastEvent.Arguments["propStr"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Stop activity 1
diagnosticSourceListener.Write("TestActivity1Stop", new { propStr = "stop" });
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity1Stop", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("TestActivitiesSource", eventSourceListener.LastEvent.SourceName);
Assert.Equal("TestActivity1Stop", eventSourceListener.LastEvent.EventName);
Assert.Equal(1, eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("stop", eventSourceListener.LastEvent.Arguments["propStr"]);
eventSourceListener.ResetEventCountAndLastEvent();
}
}).Dispose();
}
/// <summary>
/// Tests that keywords that define shortcuts work.
/// </summary>
[Fact]
public void TestShortcutKeywords()
{
RemoteExecutor.Invoke(() =>
{
using (var eventSourceListener = new TestDiagnosticSourceEventListener())
// These are look-alikes for the real ones.
using (var aspNetCoreSource = new DiagnosticListener("Microsoft.AspNetCore"))
using (var entityFrameworkCoreSource = new DiagnosticListener("Microsoft.EntityFrameworkCore"))
{
// Sadly we have a problem where if something else has turned on Microsoft-Diagnostics-DiagnosticSource then
// its keywords are ORed with our and because the shortcuts require that IgnoreShortCutKeywords is OFF
// Something outside this test (the debugger seems to do this), will cause the test to fail.
// Currently we simply give up in that case (but it really is a deeper problem.
var IgnoreShortCutKeywords = (EventKeywords)0x0800;
foreach (var eventSource in EventSource.GetSources())
{
if (eventSource.Name == "Microsoft-Diagnostics-DiagnosticSource")
{
if (eventSource.IsEnabled(EventLevel.Informational, IgnoreShortCutKeywords))
return; // Don't do the testing.
}
}
// These are from DiagnosticSourceEventListener.
var Messages = (EventKeywords)0x1;
var Events = (EventKeywords)0x2;
var AspNetCoreHosting = (EventKeywords)0x1000;
var EntityFrameworkCoreCommands = (EventKeywords)0x2000;
// Turn on listener using just the keywords
eventSourceListener.Enable(null, Messages | Events | AspNetCoreHosting | EntityFrameworkCoreCommands);
Assert.Equal(0, eventSourceListener.EventCount);
// Start a ASP.NET Request
aspNetCoreSource.Write("Microsoft.AspNetCore.Hosting.BeginRequest",
new
{
httpContext = new
{
Request = new
{
Method = "Get",
Host = "MyHost",
Path = "MyPath",
QueryString = "MyQuery"
}
}
});
// Check that the morphs work as expected.
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity1Start", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("Microsoft.AspNetCore", eventSourceListener.LastEvent.SourceName);
Assert.Equal("Microsoft.AspNetCore.Hosting.BeginRequest", eventSourceListener.LastEvent.EventName);
Assert.True(4 <= eventSourceListener.LastEvent.Arguments.Count);
Debug.WriteLine("Arg Keys = " + string.Join(" ", eventSourceListener.LastEvent.Arguments.Keys));
Debug.WriteLine("Arg Values = " + string.Join(" ", eventSourceListener.LastEvent.Arguments.Values));
Assert.Equal("Get", eventSourceListener.LastEvent.Arguments["Method"]);
Assert.Equal("MyHost", eventSourceListener.LastEvent.Arguments["Host"]);
Assert.Equal("MyPath", eventSourceListener.LastEvent.Arguments["Path"]);
Assert.Equal("MyQuery", eventSourceListener.LastEvent.Arguments["QueryString"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Start a SQL command
entityFrameworkCoreSource.Write("Microsoft.EntityFrameworkCore.BeforeExecuteCommand",
new
{
Command = new
{
Connection = new
{
DataSource = "MyDataSource",
Database = "MyDatabase",
},
CommandText = "MyCommand"
}
});
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity2Start", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("Microsoft.EntityFrameworkCore", eventSourceListener.LastEvent.SourceName);
Assert.Equal("Microsoft.EntityFrameworkCore.BeforeExecuteCommand", eventSourceListener.LastEvent.EventName);
Assert.True(3 <= eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("MyDataSource", eventSourceListener.LastEvent.Arguments["DataSource"]);
Assert.Equal("MyDatabase", eventSourceListener.LastEvent.Arguments["Database"]);
Assert.Equal("MyCommand", eventSourceListener.LastEvent.Arguments["CommandText"]);
eventSourceListener.ResetEventCountAndLastEvent();
// Stop the SQL command
entityFrameworkCoreSource.Write("Microsoft.EntityFrameworkCore.AfterExecuteCommand", null);
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity2Stop", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("Microsoft.EntityFrameworkCore", eventSourceListener.LastEvent.SourceName);
Assert.Equal("Microsoft.EntityFrameworkCore.AfterExecuteCommand", eventSourceListener.LastEvent.EventName);
eventSourceListener.ResetEventCountAndLastEvent();
// Stop the ASP.NET request.
aspNetCoreSource.Write("Microsoft.AspNetCore.Hosting.EndRequest",
new
{
httpContext = new
{
Response = new
{
StatusCode = "200"
},
TraceIdentifier = "MyTraceId"
}
});
Assert.Equal(1, eventSourceListener.EventCount); // Exactly one more event has been emitted.
Assert.Equal("Activity1Stop", eventSourceListener.LastEvent.EventSourceEventName);
Assert.Equal("Microsoft.AspNetCore", eventSourceListener.LastEvent.SourceName);
Assert.Equal("Microsoft.AspNetCore.Hosting.EndRequest", eventSourceListener.LastEvent.EventName);
Assert.True(2 <= eventSourceListener.LastEvent.Arguments.Count);
Assert.Equal("MyTraceId", eventSourceListener.LastEvent.Arguments["TraceIdentifier"]);
Assert.Equal("200", eventSourceListener.LastEvent.Arguments["StatusCode"]);
eventSourceListener.ResetEventCountAndLastEvent();
}
}).Dispose();
}
[OuterLoop("Runs for several seconds")]
[Fact]
public void Stress_WriteConcurrently_DoesntCrash()
{
const int StressTimeSeconds = 4;
RemoteExecutor.Invoke(() =>
{
using (new TurnOnAllEventListener())
using (var source = new DiagnosticListener("testlistener"))
{
var ce = new CountdownEvent(Environment.ProcessorCount * 2);
for (int i = 0; i < ce.InitialCount; i++)
{
new Thread(() =>
{
DateTime end = DateTime.UtcNow.Add(TimeSpan.FromSeconds(StressTimeSeconds));
while (DateTime.UtcNow < end)
{
source.Write("event1", Tuple.Create(1));
source.Write("event2", Tuple.Create(1, 2));
source.Write("event3", Tuple.Create(1, 2, 3));
source.Write("event4", Tuple.Create(1, 2, 3, 4));
source.Write("event5", Tuple.Create(1, 2, 3, 4, 5));
}
ce.Signal();
})
{ IsBackground = true }.Start();
}
ce.Wait();
}
}).Dispose();
}
[Fact]
public void IndexGetters_DontThrow()
{
RemoteExecutor.Invoke(() =>
{
using (var eventListener = new TestDiagnosticSourceEventListener())
using (var diagnosticListener = new DiagnosticListener("MySource"))
{
eventListener.Enable(
"MySource/MyEvent"
);
// The type MyEvent only declares 3 Properties, but actually
// has 4 due to the implicit Item property from having the index
// operator implemented. The Getter for this Item property
// is unusual for Property getters because it takes
// an int32 as an input. This test ensures that this
// implicit Property isn't implicitly serialized by
// DiagnosticSourceEventSource.
diagnosticListener.Write(
"MyEvent",
new MyEvent
{
Number = 1,
OtherNumber = 2
}
);
Assert.Equal(1, eventListener.EventCount);
Assert.Equal("MySource", eventListener.LastEvent.SourceName);
Assert.Equal("MyEvent", eventListener.LastEvent.EventName);
Assert.True(eventListener.LastEvent.Arguments.Count <= 3);
Assert.Equal("1", eventListener.LastEvent.Arguments["Number"]);
Assert.Equal("2", eventListener.LastEvent.Arguments["OtherNumber"]);
Assert.Equal("2", eventListener.LastEvent.Arguments["Count"]);
}
}).Dispose();
}
[Fact]
public void ActivityObjectsAreInspectable()
{
RemoteExecutor.Invoke(() =>
{
using (var eventListener = new TestDiagnosticSourceEventListener())
using (var diagnosticListener = new DiagnosticListener("MySource"))
{
string activityProps =
"-DummyProp" +
";ActivityId=*Activity.Id" +
";ActivityStartTime=*Activity.StartTimeUtc.Ticks" +
";ActivityDuration=*Activity.Duration.Ticks" +
";ActivityOperationName=*Activity.OperationName" +
";ActivityIdFormat=*Activity.IdFormat" +
";ActivityParentId=*Activity.ParentId" +
";ActivityTags=*Activity.Tags.*Enumerate" +
";ActivityTraceId=*Activity.TraceId" +
";ActivitySpanId=*Activity.SpanId" +
";ActivityTraceStateString=*Activity.TraceStateString" +
";ActivityParentSpanId=*Activity.ParentSpanId";
eventListener.Enable(
"MySource/TestActivity1.Start@Activity1Start:" + activityProps + "\r\n" +
"MySource/TestActivity1.Stop@Activity1Stop:" + activityProps + "\r\n" +
"MySource/TestActivity2.Start@Activity2Start:" + activityProps + "\r\n" +
"MySource/TestActivity2.Stop@Activity2Stop:" + activityProps + "\r\n"
);
Activity activity1 = new Activity("TestActivity1");
activity1.SetIdFormat(ActivityIdFormat.W3C);
activity1.TraceStateString = "hi_there";
activity1.AddTag("one", "1");
activity1.AddTag("two", "2");
diagnosticListener.StartActivity(activity1, new { DummyProp = "val" });
Assert.Equal(1, eventListener.EventCount);
AssertActivityMatchesEvent(activity1, eventListener.LastEvent, isStart: true);
Activity activity2 = new Activity("TestActivity2");
diagnosticListener.StartActivity(activity2, new { DummyProp = "val" });
Assert.Equal(2, eventListener.EventCount);
AssertActivityMatchesEvent(activity2, eventListener.LastEvent, isStart: true);
diagnosticListener.StopActivity(activity2, new { DummyProp = "val" });
Assert.Equal(3, eventListener.EventCount);
AssertActivityMatchesEvent(activity2, eventListener.LastEvent, isStart: false);
diagnosticListener.StopActivity(activity1, new { DummyProp = "val" });
Assert.Equal(4, eventListener.EventCount);
AssertActivityMatchesEvent(activity1, eventListener.LastEvent, isStart: false);
}
}).Dispose();
}
private void AssertActivityMatchesEvent(Activity a, DiagnosticSourceEvent e, bool isStart)
{
Assert.Equal("MySource", e.SourceName);
Assert.Equal(a.OperationName + (isStart ? ".Start" : ".Stop"), e.EventName);
Assert.Equal("val", e.Arguments["DummyProp"]);
Assert.Equal(a.Id, e.Arguments["ActivityId"]);
Assert.Equal(a.StartTimeUtc.Ticks.ToString(), e.Arguments["ActivityStartTime"]);
if (!isStart)
{
Assert.Equal(a.Duration.Ticks.ToString(), e.Arguments["ActivityDuration"]);
}
Assert.Equal(a.OperationName, e.Arguments["ActivityOperationName"]);
if (a.ParentId == null)
{
Assert.True(!e.Arguments.ContainsKey("ActivityParentId"));
}
else
{
Assert.Equal(a.ParentId, e.Arguments["ActivityParentId"]);
}
Assert.Equal(a.IdFormat.ToString(), e.Arguments["ActivityIdFormat"]);
if (a.IdFormat == ActivityIdFormat.W3C)
{
Assert.Equal(a.TraceId.ToString(), e.Arguments["ActivityTraceId"]);
Assert.Equal(a.SpanId.ToString(), e.Arguments["ActivitySpanId"]);
Assert.Equal(a.TraceStateString, e.Arguments["ActivityTraceStateString"]);
if(a.ParentSpanId != default)
{
Assert.Equal(a.ParentSpanId.ToString(), e.Arguments["ActivityParentSpanId"]);
}
}
Assert.Equal(string.Join(',', a.Tags), e.Arguments["ActivityTags"]);
}
}
/****************************************************************************/
// classes to make up data for the tests.
/// <summary>
/// classes for test data.
/// </summary>
internal class MyClass
{
public string Url { get; set; }
public MyPoint Point { get; set; }
}
/// <summary>
/// classes for test data.
/// </summary>
internal class MyPoint
{
public int X { get; set; }
public int Y { get; set; }
}
/// <summary>
/// classes for test data
/// </summary>
internal class MyEvent
{
public int Number { get; set; }
public int OtherNumber { get; set; }
public int Count => 2;
public KeyValuePair<string, object> this[int index] => index switch
{
0 => new KeyValuePair<string, object>(nameof(Number), Number),
1 => new KeyValuePair<string, object>(nameof(OtherNumber), OtherNumber),
_ => throw new IndexOutOfRangeException()
};
}
/****************************************************************************/
// Harness infrastructure
/// <summary>
/// TestDiagnosticSourceEventListener installs a EventWritten callback that updates EventCount and LastEvent.
/// </summary>
internal sealed class TestDiagnosticSourceEventListener : DiagnosticSourceEventListener
{
public TestDiagnosticSourceEventListener()
{
EventWritten += UpdateLastEvent;
}
public int EventCount;
public DiagnosticSourceEvent LastEvent;
#if DEBUG
// Here just for debugging. Lets you see the last 3 events that were sent.
public DiagnosticSourceEvent SecondLast;
public DiagnosticSourceEvent ThirdLast;
#endif
/// <summary>
/// Sets the EventCount to 0 and LastEvent to null
/// </summary>
public void ResetEventCountAndLastEvent()
{
EventCount = 0;
LastEvent = null;
#if DEBUG
SecondLast = null;
ThirdLast = null;
#endif
}
/// <summary>
/// If present, will ignore events that don't cause this filter predicate to return true.
/// </summary>
public Predicate<DiagnosticSourceEvent> Filter;
#region private
private void UpdateLastEvent(DiagnosticSourceEvent anEvent)
{
if (Filter != null && !Filter(anEvent))
return;
#if DEBUG
ThirdLast = SecondLast;
SecondLast = LastEvent;
#endif
EventCount++;
LastEvent = anEvent;
}
#endregion
}
/// <summary>
/// Represents a single DiagnosticSource event.
/// </summary>
internal sealed class DiagnosticSourceEvent
{
public string SourceName;
public string EventName;
public Dictionary<string, string> Arguments;
// Not typically important.
public string EventSourceEventName; // This is the name of the EventSourceEvent that carried the data. Only important for activities.
public override string ToString()
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("{");
sb.Append(" SourceName: \"").Append(SourceName ?? "").Append("\",").AppendLine();
sb.Append(" EventName: \"").Append(EventName ?? "").Append("\",").AppendLine();
sb.Append(" Arguments: ").Append("[").AppendLine();
bool first = true;
foreach (var keyValue in Arguments)
{
if (!first)
sb.Append(",").AppendLine();
first = false;
sb.Append(" ").Append(keyValue.Key).Append(": \"").Append(keyValue.Value).Append("\"");
}
sb.AppendLine().AppendLine(" ]");
sb.AppendLine("}");
return sb.ToString();
}
}
/// <summary>
/// A helper class that listens to Diagnostic sources and send events to the 'EventWritten'
/// callback. Standard use is to create the class set up the events of interested and
/// use 'Enable'. .
/// </summary>
internal class DiagnosticSourceEventListener : EventListener
{
public DiagnosticSourceEventListener() { }
/// <summary>
/// Will be called when a DiagnosticSource event is fired.
/// </summary>
public new event Action<DiagnosticSourceEvent> EventWritten;
/// <summary>
/// It is possible that there are other events besides those that are being forwarded from
/// the DiagnosticSources. These come here.
/// </summary>
public event Action<EventWrittenEventArgs> OtherEventWritten;
public void Enable(string filterAndPayloadSpecs, EventKeywords keywords = EventKeywords.All)
{
var args = new Dictionary<string, string>();
if (filterAndPayloadSpecs != null)
args.Add("FilterAndPayloadSpecs", filterAndPayloadSpecs);
EnableEvents(_diagnosticSourceEventSource, EventLevel.Verbose, keywords, args);
}
public void Disable()
{
DisableEvents(_diagnosticSourceEventSource);
}
/// <summary>
/// Cleans this class up. Among other things disables the DiagnosticSources being listened to.
/// </summary>
public override void Dispose()
{
if (_diagnosticSourceEventSource != null)
{
Disable();
_diagnosticSourceEventSource = null;
}
}
#region private
protected override void OnEventWritten(EventWrittenEventArgs eventData)
{
bool wroteEvent = false;
var eventWritten = EventWritten;
if (eventWritten != null)
{
if (eventData.Payload.Count == 3 && (eventData.EventName == "Event" || eventData.EventName.Contains("Activity")))
{
Debug.Assert(eventData.PayloadNames[0] == "SourceName");
Debug.Assert(eventData.PayloadNames[1] == "EventName");
Debug.Assert(eventData.PayloadNames[2] == "Arguments");
var anEvent = new DiagnosticSourceEvent();
anEvent.EventSourceEventName = eventData.EventName;
anEvent.SourceName = eventData.Payload[0].ToString();
anEvent.EventName = eventData.Payload[1].ToString();
anEvent.Arguments = new Dictionary<string, string>();
var asKeyValueList = eventData.Payload[2] as IEnumerable<object>;
if (asKeyValueList != null)
{
foreach (IDictionary<string, object> keyvalue in asKeyValueList)
{
object key;
keyvalue.TryGetValue("Key", out key);
object value;
keyvalue.TryGetValue("Value", out value);
if (key != null && value != null)
anEvent.Arguments[key.ToString()] = value.ToString();
}
}
eventWritten(anEvent);
wroteEvent = true;
}
}
if (eventData.EventName == "EventSourceMessage" && 0 < eventData.Payload.Count)
System.Diagnostics.Debug.WriteLine("EventSourceMessage: " + eventData.Payload[0].ToString());
var otherEventWritten = OtherEventWritten;
if (otherEventWritten != null && !wroteEvent)
otherEventWritten(eventData);
}
protected override void OnEventSourceCreated(EventSource eventSource)
{
if (eventSource.Name == "Microsoft-Diagnostics-DiagnosticSource")
_diagnosticSourceEventSource = eventSource;
}
EventSource _diagnosticSourceEventSource;
#endregion
}
internal sealed class TurnOnAllEventListener : EventListener
{
protected override void OnEventSourceCreated(EventSource eventSource) => EnableEvents(eventSource, EventLevel.LogAlways);
protected override void OnEventWritten(EventWrittenEventArgs eventData) { }
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="CookielessHelper.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
/*
* CookielessHelper class
*
* Copyright (c) 1999 Microsoft Corporation
*/
namespace System.Web.Security {
using System;
using System.Web;
using System.Text;
using System.Web.Configuration;
using System.Web.Caching;
using System.Collections;
using System.Web.Util;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Threading;
using System.Globalization;
using System.Security.Permissions;
internal sealed class CookielessHelperClass {
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
internal CookielessHelperClass(HttpContext context) {
_Context = context;
}
private void Init()
{
if (_Headers != null)
return;
if (_Headers == null)
GetCookielessValuesFromHeader();
if (_Headers == null)
RemoveCookielessValuesFromPath();
if (_Headers == null)
_Headers = String.Empty;
_OriginalHeaders = _Headers;
}
private void GetCookielessValuesFromHeader()
{
_Headers = _Context.Request.Headers[COOKIELESS_SESSION_FILTER_HEADER];
// Dev10 775061 Regression: FormsAuthentication.SignOut does not redirect if cookieless forms authentication is enabled.
// HttpContext.Init calls RemoveCookielessValues directly so we need to also store the OriginalHeaders for Redirect
// calling Init directly causes regressions
_OriginalHeaders = _Headers;
if (!String.IsNullOrEmpty(_Headers)) {
// QFE 4512: Ignore old V1.1 Session ids for cookieless in V2.0
if (_Headers.Length == 24 && !_Headers.Contains("(")) {
_Headers = null;
}
else {
_Context.Response.SetAppPathModifier("(" + _Headers + ")");
}
}
}
// This function is called for all requests -- it must be performant.
// In the common case (i.e. value not present in the URI, it must not
// look at the headers collection
internal void RemoveCookielessValuesFromPath()
{
// See if the path contains "/(XXXXX)/"
string path = _Context.Request.ClientFilePath.VirtualPathString;
// Optimize for the common case where there is no cookie
if (path.IndexOf('(') == -1) {
return;
}
int endPos = path.LastIndexOf(")/", StringComparison.Ordinal);
int startPos = (endPos > 2 ? path.LastIndexOf("/(", endPos - 1, endPos, StringComparison.Ordinal) : -1);
if (startPos < 0) // pattern not found: common case, exit immediately
return;
if (_Headers == null) // Header should always be processed first
GetCookielessValuesFromHeader();
// if the path contains a cookie, remove it
if (IsValidHeader(path, startPos + 2, endPos))
{
// only set _Headers if not already set
if (_Headers == null) {
_Headers = path.Substring(startPos + 2, endPos - startPos - 2);
}
// Rewrite the path
path = path.Substring(0, startPos) + path.Substring(endPos+1);
// remove cookie from ClientFilePath
_Context.Request.ClientFilePath = VirtualPath.CreateAbsolute(path);
// get and append query string to path if it exists
string rawUrl = _Context.Request.RawUrl;
int qsIndex = rawUrl.IndexOf('?');
if (qsIndex > -1) {
path = path + rawUrl.Substring(qsIndex);
}
// remove cookie from RawUrl
_Context.Request.RawUrl = path;
if (!String.IsNullOrEmpty(_Headers)) {
_Context.Request.ValidateCookielessHeaderIfRequiredByConfig(_Headers); // ensure that the path doesn't contain invalid chars
_Context.Response.SetAppPathModifier("(" + _Headers + ")");
// For Cassini and scenarios where aspnet_filter.dll is not used,
// HttpRequest.FilePath also needs to have the cookie removed.
string filePath = _Context.Request.FilePath;
string newFilePath = _Context.Response.RemoveAppPathModifier(filePath);
if (!Object.ReferenceEquals(filePath, newFilePath)) {
_Context.RewritePath(VirtualPath.CreateAbsolute(newFilePath),
_Context.Request.PathInfoObject,
null /*newQueryString*/,
false /*setClientFilePath*/);
}
}
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Get the cookie value from the header/path based on the identifying char
internal string GetCookieValue(char identifier) {
int startPos = 0;
int endPos = 0;
string returnValue;
Init();
////////////////////////////////////////////////////////////
// Step 1: Get the positions
if (!GetValueStartAndEnd(_Headers, identifier, out startPos, out endPos))
return null;
returnValue = _Headers.Substring(startPos, endPos-startPos); // get the substring
return returnValue;
}
internal bool DoesCookieValueExistInOriginal(char identifier) {
int startPos = 0;
int endPos = 0;
Init();
return GetValueStartAndEnd(_OriginalHeaders, identifier, out startPos, out endPos);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Add/Change/Delete a cookie value, given the tag
internal void SetCookieValue(char identifier, string cookieValue) {
int startPos = 0;
int endPos = 0;
Init();
////////////////////////////////////////////////////////////
// Step 1: Remove old values
while (GetValueStartAndEnd(_Headers, identifier, out startPos, out endPos)) { // find old value position
_Headers = _Headers.Substring(0, startPos-2) + _Headers.Substring(endPos+1); // Remove old value
}
////////////////////////////////////////////////////////////
// Step 2: Add new Value if value is specified
if (!String.IsNullOrEmpty(cookieValue)) {
_Headers += new string(new char[] {identifier, '('}) + cookieValue + ")";
}
////////////////////////////////////////////////////////////
// Step 3: Set path for redirection
if (_Headers.Length > 0)
_Context.Response.SetAppPathModifier("(" + _Headers + ")");
else
_Context.Response.SetAppPathModifier(null);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Get the position (start & end) of cookie value given the identifier
private static bool GetValueStartAndEnd(string headers, char identifier, out int startPos, out int endPos) {
////////////////////////////////////////////////////////////
// Step 1: Check if the header is non-empty
if (String.IsNullOrEmpty(headers)) {
startPos = endPos = -1;
return false;
}
////////////////////////////////////////////////////////////
// Step 2: Get the start pos
string tag = new string(new char[] {identifier, '('}); // Tag is: "X("
startPos = headers.IndexOf(tag, StringComparison.Ordinal); // Search for "X("
if (startPos < 0) { // Not Found
startPos = endPos = -1;
return false;
}
startPos += 2;
////////////////////////////////////////////////////////////
// Step 3: Find the end position
endPos = headers.IndexOf(')', startPos);
if (endPos < 0) {
startPos = endPos = -1;
return false;
}
return true;
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Look at config (<httpCookies>) and (maybe) current request, and return
// whether to use cookie-less feature
internal static bool UseCookieless(HttpContext context, bool doRedirect, HttpCookieMode cookieMode) {
////////////////////////////////////////////////////////////
// Step 2: Look at config
switch(cookieMode)
{
case HttpCookieMode.UseUri: // Use cookieless always
return true;
case HttpCookieMode.UseCookies: // Never use cookieless
return false;
case HttpCookieMode.UseDeviceProfile: // Use browser config
if (context == null)
context = HttpContext.Current;
if (context == null)
return false;
bool fRet = (!context.Request.Browser.Cookies ||
!context.Request.Browser.SupportsRedirectWithCookie);
return fRet;
case HttpCookieMode.AutoDetect: // Detect based on whether the client supports cookieless
if (context == null)
context = HttpContext.Current;
if (context == null)
return false;
if (!context.Request.Browser.Cookies || !context.Request.Browser.SupportsRedirectWithCookie) {
return true;
}
//////////////////////////////////////////////////////////////////
// Look in the header
string cookieDetectHeader = context.CookielessHelper.GetCookieValue('X');
if (cookieDetectHeader != null && cookieDetectHeader == "1") {
return true;
}
//////////////////////////////////////////////////
// Step 3a: See if the client sent any (request) cookies
string cookieHeader = context.Request.Headers["Cookie"];
if (!String.IsNullOrEmpty(cookieHeader)) { // Yes, client sent request cookies
return false;
}
//////////////////////////////////////////////////
// Step 3b: See if we have done a challenge-response to detect cookie support
string qs = context.Request.QueryString[s_AutoDetectName];
if (qs != null && qs == s_AutoDetectValue) { // Yes, we have done a challenge-response: No cookies present => no cookie support
context.CookielessHelper.SetCookieValue('X', "1");
return true;
}
//////////////////////////////////////////////////
// Step 3c: Do a challenge-response (redirect) to detect cookie support
if (doRedirect) {
context.CookielessHelper.RedirectWithDetection(null);
}
// Note: if doRedirect==true, execution won't reach here
return false;
default: // Config broken?
return false;
}
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Do a redirect to figure out cookies are supported or not.
/// The way we do it: write the cookie and in the query-string,
// write the cookie-name value pair.
internal void RedirectWithDetection(string redirectPath) {
Init();
////////////////////////////////////////////////////////////
// Step 1: If URL to redirect to, has not been specified,
// the use the current URL
if (String.IsNullOrEmpty(redirectPath)) {
redirectPath = _Context.Request.RawUrl;
}
////////////////////////////////////////////////////////////
// Step 2: Add cookie name and value to query-string
if (redirectPath.IndexOf("?", StringComparison.Ordinal) > 0)
redirectPath += "&" + s_AutoDetectName + "=" + s_AutoDetectValue;
else
redirectPath += "?" + s_AutoDetectName + "=" + s_AutoDetectValue;
////////////////////////////////////////////////////////////
// Step 3: Add cookie
_Context.Response.Cookies.Add(new HttpCookie(s_AutoDetectName, s_AutoDetectValue));
////////////////////////////////////////////////////////////
// Step 4: Do redirect
_Context.Response.Redirect(redirectPath, true);
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// RedirectWithDetection if we need to
internal void RedirectWithDetectionIfRequired(string redirectPath, HttpCookieMode cookieMode) {
Init();
////////////////////////////////////////////////////////////
// Step 1: Check if config wants us to do a challenge-reponse
if (cookieMode != HttpCookieMode.AutoDetect) {
return;
}
////////////////////////////////////////////////////////////
// Step 2: Check browser caps
if (!_Context.Request.Browser.Cookies || !_Context.Request.Browser.SupportsRedirectWithCookie) {
return;
}
////////////////////////////////////////////////////////////
// Step 3: Check header
string cookieDetectHeader = GetCookieValue('X');
if (cookieDetectHeader != null && cookieDetectHeader == "1") {
return;
}
////////////////////////////////////////////////////////////
// Step 4: see if the client sent any cookies
string cookieHeader = _Context.Request.Headers["Cookie"];
if (!String.IsNullOrEmpty(cookieHeader)) {
return;
}
////////////////////////////////////////////////////////////
// Step 5: See if we already did a challenge-reponse
string qs = _Context.Request.QueryString[s_AutoDetectName];
if (qs != null && qs == s_AutoDetectValue) { // Yes, we have done a challenge-response
// No cookies present => no cookie support
SetCookieValue('X', "1");
return;
}
////////////////////////////////////////////////////////////
// Do a challenge response
RedirectWithDetection(redirectPath);
}
///////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////
// Make sure sub-string if of the pattern: A(XXXX)N(XXXXX)P(XXXXX) and so on.
static private bool IsValidHeader(string path, int startPos, int endPos)
{
if (endPos - startPos < 3) // Minimum len is "X()"
return false;
while (startPos <= endPos - 3) { // Each iteration deals with one "A(XXXX)" pattern
if (path[startPos] < 'A' || path[startPos] > 'Z') // Make sure pattern starts with a capital letter
return false;
if (path[startPos + 1] != '(') // Make sure next char is '('
return false;
startPos += 2;
bool found = false;
for (; startPos < endPos; startPos++) { // Find the ending ')'
if (path[startPos] == ')') { // found it!
startPos++; // Set position for the next pattern
found = true;
break; // Break out of this for-loop.
}
if (path[startPos] == '/') { // Can't contain path separaters
return false;
}
}
if (!found) {
return false; // Ending ')' not found!
}
}
if (startPos < endPos) // All chars consumed?
return false;
return true;
}
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////
// Static data
internal const String COOKIELESS_SESSION_FILTER_HEADER = "AspFilterSessionId";
const string s_AutoDetectName = "AspxAutoDetectCookieSupport";
const string s_AutoDetectValue = "1";
// Private instance data
private HttpContext _Context;
private string _Headers;
private string _OriginalHeaders;
}
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
internal enum CookiesSupported {
Supported, NotSupported, Unknown
}
}
| |
//
// RoundedFrame.cs
//
// Authors:
// Aaron Bockover <abockover@novell.com>
// Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Cairo;
using Hyena.Gui;
using Hyena.Gui.Theming;
namespace Hyena.Widgets
{
public class RoundedFrame : Bin
{
private Theme theme;
protected Theme Theme {
get { return theme; }
}
private int frame_width = 3;
private Widget child;
private Gdk.Rectangle child_allocation;
private bool fill_color_set;
private Cairo.Color fill_color;
private bool draw_border = true;
private Pattern fill_pattern;
// Ugh, this is to avoid the GLib.MissingIntPtrCtorException seen by some; BGO #552169
protected RoundedFrame (IntPtr ptr) : base (ptr)
{
}
public RoundedFrame ()
{
}
public void SetFillColor (Cairo.Color color)
{
fill_color = color;
fill_color_set = true;
QueueDraw ();
}
public void UnsetFillColor ()
{
fill_color_set = false;
QueueDraw ();
}
public Pattern FillPattern {
get { return fill_pattern; }
set {
fill_pattern = value;
QueueDraw ();
}
}
public bool DrawBorder {
get { return draw_border; }
set { draw_border = value; QueueDraw (); }
}
#region Gtk.Widget Overrides
protected override void OnRealized ()
{
base.OnRealized ();
theme = Hyena.Gui.Theming.ThemeEngine.CreateTheme (this);
}
protected override void OnSizeRequested (ref Requisition requisition)
{
if (child != null && child.Visible) {
// Add the child's width/height
Requisition child_requisition = child.SizeRequest ();
requisition.Width = Math.Max (0, child_requisition.Width);
requisition.Height = child_requisition.Height;
} else {
requisition.Width = 0;
requisition.Height = 0;
}
// Add the frame border
requisition.Width += ((int)BorderWidth + frame_width) * 2;
requisition.Height += ((int)BorderWidth + frame_width) * 2;
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
base.OnSizeAllocated (allocation);
child_allocation = new Gdk.Rectangle ();
if (child == null || !child.Visible) {
return;
}
child_allocation.X = (int)BorderWidth + frame_width;
child_allocation.Y = (int)BorderWidth + frame_width;
child_allocation.Width = (int)Math.Max (1, Allocation.Width - child_allocation.X * 2);
child_allocation.Height = (int)Math.Max (1, Allocation.Height - child_allocation.Y -
(int)BorderWidth - frame_width);
child_allocation.X += Allocation.X;
child_allocation.Y += Allocation.Y;
child.SizeAllocate (child_allocation);
}
protected override void OnSetScrollAdjustments (Adjustment hadj, Adjustment vadj)
{
// This is to satisfy the gtk_widget_set_scroll_adjustments
// inside of GtkScrolledWindow so it doesn't complain about
// its child not being scrollable.
}
protected override bool OnExposeEvent (Gdk.EventExpose evnt)
{
if (!IsDrawable) {
return false;
}
Cairo.Context cr = Gdk.CairoHelper.Create (evnt.Window);
try {
DrawFrame (cr, evnt.Area);
if (child != null) {
PropagateExpose (child, evnt);
}
return false;
} finally {
CairoExtensions.DisposeContext (cr);
}
}
private void DrawFrame (Cairo.Context cr, Gdk.Rectangle clip)
{
int x = child_allocation.X - frame_width;
int y = child_allocation.Y - frame_width;
int width = child_allocation.Width + 2 * frame_width;
int height = child_allocation.Height + 2 * frame_width;
Gdk.Rectangle rect = new Gdk.Rectangle (x, y, width, height);
theme.Context.ShowStroke = draw_border;
if (fill_color_set) {
theme.DrawFrameBackground (cr, rect, fill_color);
} else if (fill_pattern != null) {
theme.DrawFrameBackground (cr, rect, fill_pattern);
} else {
theme.DrawFrameBackground (cr, rect, true);
theme.DrawFrameBorder (cr, rect);
}
}
#endregion
#region Gtk.Container Overrides
protected override void OnAdded (Widget widget)
{
child = widget;
base.OnAdded (widget);
}
protected override void OnRemoved (Widget widget)
{
if (child == widget) {
child = null;
}
base.OnRemoved (widget);
}
#endregion
}
}
| |
//! \file ArcSec5.cs
//! \date Fri Oct 23 18:10:06 2015
//! \brief Sas5 engine resource index file.
//
// Copyright (C) 2015 by morkt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.IO;
using GameRes.Utility;
using System.Text;
namespace GameRes.Formats.Sas5
{
[Export(typeof(ArchiveFormat))]
public class Sec5Opener : ArchiveFormat
{
public override string Tag { get { return "SEC5"; } }
public override string Description { get { return "SAS5 engine resource index file"; } }
public override uint Signature { get { return 0x35434553; } } // 'SEC5'
public override bool IsHierarchic { get { return false; } }
public override bool CanCreate { get { return false; } }
public override ArcFile TryOpen (ArcView file)
{
uint offset = 8;
var dir = new List<Entry>();
while (offset < file.MaxOffset)
{
string name = file.View.ReadString (offset, 4, Encoding.ASCII);
if ("ENDS" == name)
break;
uint section_size = file.View.ReadUInt32 (offset+4);
offset += 8;
var entry = new Entry {
Name = name,
Offset = offset,
Size = section_size,
};
dir.Add (entry);
offset += section_size;
}
if (dir.Count > 0)
return new ArcFile (file, this, dir);
return null;
}
public override Stream OpenEntry (ArcFile arc, Entry entry)
{
if ("CODE" != entry.Name)
return arc.File.CreateStream (entry.Offset, entry.Size);
var code = new byte[entry.Size];
arc.File.View.Read (entry.Offset, code, 0, entry.Size);
DecryptCodeSection (code);
return new MemoryStream (code);
}
static void DecryptCodeSection (byte[] code)
{
byte key = 0;
for (int i = 0; i < code.Length; ++i)
{
int x = code[i] + 18;
code[i] ^= key;
key += (byte)x;
}
}
static internal Dictionary<string, Dictionary<int, Entry>> CurrentIndex;
static internal Dictionary<int, Entry> LookupIndex (string filename)
{
if (null == CurrentIndex)
CurrentIndex = FindSec5Resr (filename);
if (null == CurrentIndex)
return null;
Dictionary<int, Entry> arc_map = null;
CurrentIndex.TryGetValue (Path.GetFileName (filename), out arc_map);
return arc_map;
}
static internal Dictionary<string, Dictionary<int, Entry>> FindSec5Resr (string arc_name)
{
string dir_name = Path.GetDirectoryName (arc_name);
var match = Directory.GetFiles (dir_name, "*.sec5");
if (0 == match.Length)
{
string parent = Path.GetDirectoryName (dir_name);
if (!string.IsNullOrEmpty (parent))
match = Directory.GetFiles (parent, "*.sec5");
}
if (0 == match.Length)
return null;
using (var sec5 = new ArcView (match[0]))
{
if (!sec5.View.AsciiEqual (0, "SEC5"))
return null;
uint offset = 8;
while (offset < sec5.MaxOffset)
{
string id = sec5.View.ReadString (offset, 4, Encoding.ASCII);
if ("ENDS" == id)
break;
uint section_size = sec5.View.ReadUInt32 (offset+4);
offset += 8;
if ("RESR" == id)
{
using (var resr = sec5.CreateStream (offset, section_size))
return ReadResrSection (resr);
}
if ("RES2" == id)
{
using (var res2 = sec5.CreateStream (offset, section_size))
return ReadRes2Section (res2);
}
offset += section_size;
}
}
return null;
}
static internal Dictionary<string, Dictionary<int, Entry>> ReadResrSection (Stream input)
{
using (var resr = new BinaryReader (input, Encodings.cp932, true))
{
int count = resr.ReadInt32();
if (0 == count)
return null;
var map = new Dictionary<string, Dictionary<int, Entry>> (StringComparer.InvariantCultureIgnoreCase);
for (int i = 0; i < count; ++i)
{
string name = resr.BaseStream.ReadCString();
string type = resr.BaseStream.ReadCString();
string arc_type = resr.BaseStream.ReadCString();
int res_length = resr.ReadInt32();
var next_pos = resr.BaseStream.Position + res_length;
if (arc_type == "file-war" || arc_type == "file-iar")
{
string arc_name = resr.BaseStream.ReadCString();
int id = resr.ReadInt32();
var base_arc_name = Path.GetFileName (arc_name);
if (!map.ContainsKey (base_arc_name))
map[base_arc_name] = new Dictionary<int, Entry>();
var entry = new Entry
{
Name = name,
Type = type,
};
map[base_arc_name][id] = entry;
}
resr.BaseStream.Position = next_pos;
}
return map.Count > 0 ? map : null;
}
}
static internal Dictionary<string, Dictionary<int, Entry>> ReadRes2Section (Stream input)
{
using (var resr = new Res2Reader (input))
return resr.Read();
}
}
internal sealed class Res2Reader : IDisposable
{
BinaryReader m_resr;
byte[] m_strings;
Dictionary<int, string> m_string_cache = new Dictionary<int, string>();
public Res2Reader (Stream input)
{
m_resr = new BinaryReader (input, Encodings.cp932, true);
}
public Dictionary<string, Dictionary<int, Entry>> Read ()
{
int section_size = m_resr.ReadInt32();
m_strings = m_resr.ReadBytes (section_size);
if (m_strings.Length != section_size)
return null;
var map = new Dictionary<string, Dictionary<int, Entry>> (StringComparer.InvariantCultureIgnoreCase);
int count = m_resr.ReadInt32();
for (int i = 0; i < count; ++i)
{
string name = ReadString();
string type = ReadString();
string arc_type = ReadString();
int param_count = ReadInteger();
string arc_name = null;
int? arc_index = null;
for (int j = 0; j < param_count; ++j)
{
string param_name = ReadString();
if ("path" == param_name)
arc_name = ReadString();
else if ("arc-index" == param_name)
arc_index = ReadInteger();
else
SkipObject();
}
if (!string.IsNullOrEmpty (arc_name) && arc_index != null)
{
arc_name = Path.GetFileName (arc_name);
if (!map.ContainsKey (arc_name))
map[arc_name] = new Dictionary<int, Entry>();
var entry = new Entry
{
Name = name,
Type = type,
};
map[arc_name][arc_index.Value] = entry;
}
}
return map.Count > 0 ? map : null;
}
string ReadString ()
{
int n = m_resr.ReadByte();
if (0x90 != (n & 0xF8))
throw new InvalidFormatException ("[ReadString] SEC5 deserialization error");
int offset = ReadNumber (n);
if (offset >= m_strings.Length)
throw new InvalidFormatException ("[ReadString] SEC5 deserialization error");
string s;
if (!m_string_cache.TryGetValue (offset, out s))
{
int str_length = LittleEndian.ToInt32 (m_strings, offset);
s = Encodings.cp932.GetString (m_strings, offset+4, str_length);
m_string_cache[offset] = s;
}
return s;
}
int ReadInteger ()
{
int n = m_resr.ReadByte();
if (0 != (n & 0xE0))
{
if (0x80 != (n & 0xF8))
throw new InvalidFormatException ("[ReadInteger] SEC5 deserialization error");
n = ReadNumber (n);
}
else
{
n = (n & 0xF) - (n & 0x10);
}
return n;
}
void SkipObject ()
{
int n = m_resr.ReadByte();
if (0 != (n & 0xE0))
ReadNumber (n);
}
int ReadNumber (int length_code)
{
int count = (length_code & 7) + 1;
if (count > 4)
throw new InvalidFormatException ("[ReadNumber] SEC5 deserialization error");
int n = 0;
int rank = 0;
for (int i = 0; i < count; ++i)
{
int b = m_resr.ReadByte();
n |= b << rank;
rank += 8;
}
if (count <= 3)
{
int sign = n & (1 << (8 * count - 1));
if (sign != 0)
n -= sign << 1;
}
return n;
}
#region IDisposable Members
bool _disposed = false;
public void Dispose ()
{
if (!_disposed)
{
m_resr.Dispose();
_disposed = true;
}
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Portions derived from React Native:
// Copyright (c) 2015-present, Facebook, Inc.
// Licensed under the MIT License.
using ImagePipeline.Core;
using Newtonsoft.Json.Linq;
using ReactNative.Collections;
using ReactNative.Modules.Image;
using ReactNative.UIManager;
using ReactNative.UIManager.Annotations;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
using Windows.ApplicationModel.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;
namespace ReactNative.Views.Image
{
/// <summary>
/// The view manager responsible for rendering native images.
/// </summary>
public class ReactImageManager : SimpleViewManager<Border>
{
private readonly ViewKeyedDictionary<Border, List<KeyValuePair<string, double>>> _imageSources =
new ViewKeyedDictionary<Border, List<KeyValuePair<string, double>>>();
private readonly ViewKeyedDictionary<Border, CornerRadiusManager> _borderToRadii =
new ViewKeyedDictionary<Border, CornerRadiusManager>();
private readonly ViewKeyedDictionary<Border, ThicknessManager> _borderToThickness =
new ViewKeyedDictionary<Border, ThicknessManager>();
private readonly ThreadLocal<ScaleTransform> _rtlScaleTransform = new ThreadLocal<ScaleTransform>(() => new ScaleTransform
{
CenterX = 0.5,
ScaleX = -1
});
/// <summary>
/// The view manager name.
/// </summary>
public override string Name
{
get
{
return "RCTImageView";
}
}
/// <summary>
/// The view manager event constants.
/// </summary>
public override JObject CustomDirectEventTypeConstants
{
get
{
return new JObject
{
{
"topLoadStart",
new JObject
{
{ "registrationName", "onLoadStart" }
}
},
{
"topLoad",
new JObject
{
{ "registrationName", "onLoad" }
}
},
{
"topLoadEnd",
new JObject
{
{ "registrationName", "onLoadEnd" }
}
},
{
"topError",
new JObject
{
{ "registrationName", "onError" }
}
},
};
}
}
/// <summary>
/// Set the scaling mode of the image.
/// </summary>
/// <param name="view">The image view instance.</param>
/// <param name="resizeMode">The scaling mode.</param>
[ReactProp(ViewProps.ResizeMode)]
public void SetResizeMode(Border view, string resizeMode)
{
if (resizeMode != null)
{
var imageBrush = (ImageBrush)view.Background;
if (resizeMode.Equals("cover"))
{
imageBrush.Stretch = Stretch.UniformToFill;
}
else if (resizeMode.Equals("contain"))
{
imageBrush.Stretch = Stretch.Uniform;
}
else
{
imageBrush.Stretch = Stretch.Fill;
}
}
}
/// <summary>
/// Set the source URI of the image.
/// </summary>
/// <param name="view">The image view instance.</param>
/// <param name="sources">The source URI.</param>
[ReactProp("src")]
public void SetSource(Border view, JArray sources)
{
var count = sources.Count;
// There is no image source
if (count == 0)
{
throw new ArgumentException("Sources must not be empty.", nameof(sources));
}
// Optimize for the case where we have just one uri, case in which we don't need the sizes
else if (count == 1)
{
var uri = ((JObject)sources[0]).Value<string>("uri");
SetUriFromSingleSource(view, uri);
}
else
{
if (_imageSources.TryGetValue(view, out var viewSources))
{
viewSources.Clear();
}
else
{
viewSources = new List<KeyValuePair<string, double>>(count);
_imageSources.AddOrUpdate(view, viewSources);
}
foreach (var source in sources)
{
var sourceData = (JObject)source;
viewSources.Add(
new KeyValuePair<string, double>(
sourceData.Value<string>("uri"),
sourceData.Value<double>("width") * sourceData.Value<double>("height")));
}
viewSources.Sort((p1, p2) => p1.Value.CompareTo(p2.Value));
if (double.IsNaN(view.Width) || double.IsNaN(view.Height))
{
// If we need to choose from multiple URIs but the size is not yet set, wait for layout pass
return;
}
SetUriFromMultipleSources(view);
}
}
/// <summary>
/// Enum values correspond to positions of prop names in ReactPropGroup attribute
/// applied to <see cref="SetBorderRadius(Border, int, double?)"/>
/// </summary>
private enum Radius
{
All,
TopLeft,
TopRight,
BottomLeft,
BottomRight,
}
/// <summary>
/// The border radius of the <see cref="ReactRootView"/>.
/// </summary>
/// <param name="view">The image view instance.</param>
/// <param name="index">The prop index.</param>
/// <param name="radius">The border radius value.</param>
[ReactPropGroup(
ViewProps.BorderRadius,
ViewProps.BorderTopLeftRadius,
ViewProps.BorderTopRightRadius,
ViewProps.BorderBottomLeftRadius,
ViewProps.BorderBottomRightRadius)]
public void SetBorderRadius(Border view, int index, double? radius)
{
if (!_borderToRadii.TryGetValue(view, out var cornerRadiusManager))
{
cornerRadiusManager = new CornerRadiusManager();
_borderToRadii.AddOrUpdate(view, cornerRadiusManager);
}
switch ((Radius)index)
{
case Radius.All:
cornerRadiusManager.Set(CornerRadiusManager.All, radius);
break;
case Radius.TopLeft:
cornerRadiusManager.Set(CornerRadiusManager.TopLeft, radius);
break;
case Radius.TopRight:
cornerRadiusManager.Set(CornerRadiusManager.TopRight, radius);
break;
case Radius.BottomLeft:
cornerRadiusManager.Set(CornerRadiusManager.BottomLeft, radius);
break;
case Radius.BottomRight:
cornerRadiusManager.Set(CornerRadiusManager.BottomRight, radius);
break;
}
view.CornerRadius = cornerRadiusManager.AsCornerRadius();
}
/// <summary>
/// Set the border color of the image view.
/// </summary>
/// <param name="view">The image view instance.</param>
/// <param name="color">The masked color value.</param>
[ReactProp(ViewProps.BorderColor, CustomType = "Color")]
public void SetBorderColor(Border view, uint? color)
{
view.BorderBrush = color.HasValue
? new SolidColorBrush(ColorHelpers.Parse(color.Value))
: null;
}
/// <summary>
/// Enum values correspond to positions of prop names in ReactPropGroup attribute
/// applied to <see cref="SetBorderWidth(Border, int, double?)"/>
/// </summary>
private enum Width
{
All,
Left,
Right,
Top,
Bottom,
}
/// <summary>
/// Sets the border thickness of the image view.
/// </summary>
/// <param name="view">The image view instance.</param>
/// <param name="index">The prop index.</param>
/// <param name="width">The border width in pixels.</param>
[ReactPropGroup(
ViewProps.BorderWidth,
ViewProps.BorderLeftWidth,
ViewProps.BorderRightWidth,
ViewProps.BorderTopWidth,
ViewProps.BorderBottomWidth)]
public void SetBorderWidth(Border view, int index, double? width)
{
if (!_borderToThickness.TryGetValue(view, out var thicknessManager))
{
thicknessManager = new ThicknessManager();
_borderToThickness.AddOrUpdate(view, thicknessManager);
}
switch ((Width)index)
{
case Width.All:
thicknessManager.Set(ThicknessManager.All, width);
break;
case Width.Left:
thicknessManager.Set(ThicknessManager.Left, width);
break;
case Width.Right:
thicknessManager.Set(ThicknessManager.Right, width);
break;
case Width.Top:
thicknessManager.Set(ThicknessManager.Top, width);
break;
case Width.Bottom:
thicknessManager.Set(ThicknessManager.Bottom, width);
break;
}
view.BorderThickness = thicknessManager.AsThickness();
}
/// <summary>
/// Called when view is detached from view hierarchy and allows for
/// additional cleanup.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The view.</param>
public override void OnDropViewInstance(ThemedReactContext reactContext, Border view)
{
base.OnDropViewInstance(reactContext, view);
_imageSources.Remove(view);
_borderToRadii.Remove(view);
_borderToThickness.Remove(view);
}
/// <summary>
/// Creates the image view instance.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <returns>The image view instance.</returns>
protected override Border CreateViewInstance(ThemedReactContext reactContext)
{
var border = new Border
{
Background = new ImageBrush
{
Stretch = Stretch.UniformToFill
},
};
border.Loaded += OnLoaded;
return border;
}
private void OnLoaded(object sender, RoutedEventArgs e)
{
// Using a Border instead of a native Image has its advantages (round corner support, etc.), but
// we have to take into account the automatic flipping that happens in RTL mode. We use a transform
// to negate that flipping.
var border = (Border)sender;
border.RegisterPropertyChangedCallback(FrameworkElement.FlowDirectionProperty, FlowDirectionChanged);
FlowDirectionChanged(border, null);
}
private void FlowDirectionChanged(DependencyObject sender, DependencyProperty dp)
{
var border = (Border)sender;
if (border.FlowDirection == FlowDirection.RightToLeft)
{
border.Background.RelativeTransform = _rtlScaleTransform.Value;
}
else
{
border.Background.ClearValue(Brush.RelativeTransformProperty);
}
}
/// <summary>
/// Sets the dimensions of the view.
/// </summary>
/// <param name="view">The view.</param>
/// <param name="dimensions">The output buffer.</param>
public override void SetDimensions(Border view, Dimensions dimensions)
{
base.SetDimensions(view, dimensions);
SetUriFromMultipleSources(view);
}
private void OnImageFailed(Border view, Exception e)
{
if (!view.HasTag())
{
// View may have been unmounted, ignore.
return;
}
var eventDispatcher = view.GetReactContext()
.GetNativeModule<UIManagerModule>()
.EventDispatcher;
eventDispatcher.DispatchEvent(
new ReactImageLoadEvent(
view.GetTag(),
e.Message));
eventDispatcher.DispatchEvent(
new ReactImageLoadEvent(
view.GetTag(),
ReactImageLoadEvent.OnLoadEnd));
}
private void OnImageStatusUpdate(Border view, ImageLoadStatus status, ImageMetadata metadata)
{
if (!view.HasTag())
{
// View may have been unmounted, ignore.
return;
}
var eventDispatcher = view.GetReactContext()
.GetNativeModule<UIManagerModule>()
.EventDispatcher;
eventDispatcher.DispatchEvent(
new ReactImageLoadEvent(
view.GetTag(),
(int)status,
metadata.Uri,
metadata.Width,
metadata.Height));
}
/// <summary>
/// Set the source URI of the image.
/// </summary>
/// <param name="view">The image view instance.</param>
/// <param name="source">The source URI.</param>
private async void SetUriFromSingleSource(Border view, string source)
{
var imageBrush = (ImageBrush)view.Background;
OnImageStatusUpdate(view, ImageLoadStatus.OnLoadStart, default(ImageMetadata));
try
{
var imagePipeline = ImagePipelineFactory.Instance.GetImagePipeline();
var dispatcher = CoreApplication.GetCurrentView().Dispatcher;
var image = await imagePipeline.FetchEncodedBitmapImageAsync(new Uri(source), default(CancellationToken), dispatcher);
var metadata = new ImageMetadata(source, image.PixelWidth, image.PixelHeight);
OnImageStatusUpdate(view, ImageLoadStatus.OnLoad, metadata);
imageBrush.ImageSource = image;
OnImageStatusUpdate(view, ImageLoadStatus.OnLoadEnd, metadata);
}
catch (Exception e)
{
OnImageFailed(view, e);
}
}
/// <summary>
/// Chooses the uri with the size closest to the target image size. Must be called only after the
/// layout pass when the sizes of the target image have been computed, and when there are at least
/// two sources to choose from.
/// </summary>
/// <param name="view">The image view instance.</param>
private void SetUriFromMultipleSources(Border view)
{
if (_imageSources.TryGetValue(view, out var sources))
{
var targetImageSize = view.Width * view.Height;
var bestResult = sources.LocalMin((s) => Math.Abs(s.Value - targetImageSize));
SetUriFromSingleSource(view, bestResult.Key);
}
}
}
}
| |
// 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.Diagnostics.Contracts;
namespace System.Globalization
{
public partial class CompareInfo
{
internal static unsafe int InvariantIndexOf(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(startIndex >= 0 && startIndex < source.Length);
fixed (char* pSource = source) fixed (char* pValue = value)
{
char* pSrc = &pSource[startIndex];
int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, start : true);
if (index >= 0)
{
return index + startIndex;
}
return -1;
}
}
internal static unsafe int InvariantLastIndexOf(string source, string value, int startIndex, int count, bool ignoreCase)
{
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(startIndex >= 0 && startIndex < source.Length);
fixed (char* pSource = source) fixed (char* pValue = value)
{
char* pSrc = &pSource[startIndex - count + 1];
int index = InvariantFindString(pSrc, count, pValue, value.Length, ignoreCase, start : false);
if (index >= 0)
{
return index + startIndex - count + 1;
}
return -1;
}
}
private static unsafe int InvariantFindString(char* source, int sourceCount, char* value, int valueCount, bool ignoreCase, bool start)
{
int ctrSource = 0; // index value into source
int ctrValue = 0; // index value into value
char sourceChar; // Character for case lookup in source
char valueChar; // Character for case lookup in value
int lastSourceStart;
Debug.Assert(source != null);
Debug.Assert(value != null);
Debug.Assert(sourceCount >= 0);
Debug.Assert(valueCount >= 0);
if (valueCount == 0)
{
return start ? 0 : sourceCount - 1;
}
if (sourceCount < valueCount)
{
return -1;
}
if (start)
{
lastSourceStart = sourceCount - valueCount;
if (ignoreCase)
{
char firstValueChar = InvariantToUpper(value[0]);
for (ctrSource = 0; ctrSource <= lastSourceStart; ctrSource++)
{
sourceChar = InvariantToUpper(source[ctrSource]);
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = InvariantToUpper(source[ctrSource + ctrValue]);
valueChar = InvariantToUpper(value[ctrValue]);
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
else
{
char firstValueChar = value[0];
for (ctrSource = 0; ctrSource <= lastSourceStart; ctrSource++)
{
sourceChar = source[ctrSource];
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = source[ctrSource + ctrValue];
valueChar = value[ctrValue];
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
}
else
{
lastSourceStart = sourceCount - valueCount;
if (ignoreCase)
{
char firstValueChar = InvariantToUpper(value[0]);
for (ctrSource = lastSourceStart; ctrSource >= 0; ctrSource--)
{
sourceChar = InvariantToUpper(source[ctrSource]);
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = InvariantToUpper(source[ctrSource + ctrValue]);
valueChar = InvariantToUpper(value[ctrValue]);
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
else
{
char firstValueChar = value[0];
for (ctrSource = lastSourceStart; ctrSource >= 0; ctrSource--)
{
sourceChar = source[ctrSource];
if (sourceChar != firstValueChar)
{
continue;
}
for (ctrValue = 1; ctrValue < valueCount; ctrValue++)
{
sourceChar = source[ctrSource + ctrValue];
valueChar = value[ctrValue];
if (sourceChar != valueChar)
{
break;
}
}
if (ctrValue == valueCount)
{
return ctrSource;
}
}
}
}
return -1;
}
private static char InvariantToUpper(char c)
{
return (uint)(c - 'a') <= (uint)('z' - 'a') ? (char)(c - 0x20) : c;
}
private unsafe SortKey InvariantCreateSortKey(string source, CompareOptions options)
{
if (source == null) { throw new ArgumentNullException(nameof(source)); }
Contract.EndContractBlock();
if ((options & ValidSortkeyCtorMaskOffFlags) != 0)
{
throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options));
}
byte [] keyData;
if (source.Length == 0)
{
keyData = Array.Empty<byte>();
}
else
{
// In the invariant mode, all string comparisons are done as ordinal so when generating the sort keys we generate it according to this fact
keyData = new byte[source.Length * sizeof(char)];
fixed (char* pChar = source) fixed (byte* pByte = keyData)
{
if ((options & (CompareOptions.IgnoreCase | CompareOptions.OrdinalIgnoreCase)) != 0)
{
short *pShort = (short *) pByte;
for (int i=0; i<source.Length; i++)
{
pShort[i] = (short) InvariantToUpper(source[i]);
}
}
else
{
Buffer.MemoryCopy(pChar, pByte, keyData.Length, keyData.Length);
}
}
}
return new SortKey(Name, source, options, keyData);
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Contracts;
using System.Net;
using System.Runtime;
using System.ServiceModel.Channels;
using System.ServiceModel.Security;
using System.Xml;
namespace System.ServiceModel.Dispatcher
{
[SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Compat", Justification = "Compat is an accepted abbreviation")]
[EditorBrowsable(EditorBrowsableState.Never)]
public class ClientRuntimeCompatBase
{
internal ClientRuntimeCompatBase() { }
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
public IList<IClientMessageInspector> MessageInspectors
{
get
{
return this.messageInspectors;
}
}
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
public KeyedCollection<string, ClientOperation> Operations
{
get
{
return this.compatOperations;
}
}
internal SynchronizedCollection<IClientMessageInspector> messageInspectors;
internal SynchronizedKeyedCollection<string, ClientOperation> operations;
internal KeyedCollection<string, ClientOperation> compatOperations;
}
public sealed class ClientRuntime : ClientRuntimeCompatBase
{
private bool _addTransactionFlowProperties = true;
private Type _callbackProxyType;
private ProxyBehaviorCollection<IChannelInitializer> _channelInitializers;
private string _contractName;
private string _contractNamespace;
private Type _contractProxyType;
private DispatchRuntime _dispatchRuntime;
private IdentityVerifier _identityVerifier;
private ProxyBehaviorCollection<IInteractiveChannelInitializer> _interactiveChannelInitializers;
private IClientOperationSelector _operationSelector;
private ImmutableClientRuntime _runtime;
private ClientOperation _unhandled;
private bool _useSynchronizationContext = true;
private Uri _via;
private SharedRuntimeState _shared;
private int _maxFaultSize;
private bool _messageVersionNoneFaultsEnabled;
internal ClientRuntime(DispatchRuntime dispatchRuntime, SharedRuntimeState shared)
: this(dispatchRuntime.EndpointDispatcher.ContractName,
dispatchRuntime.EndpointDispatcher.ContractNamespace,
shared)
{
if (dispatchRuntime == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("dispatchRuntime");
_dispatchRuntime = dispatchRuntime;
_shared = shared;
Fx.Assert(shared.IsOnServer, "Server constructor called on client?");
}
internal ClientRuntime(string contractName, string contractNamespace)
: this(contractName, contractNamespace, new SharedRuntimeState(false))
{
Fx.Assert(!_shared.IsOnServer, "Client constructor called on server?");
}
private ClientRuntime(string contractName, string contractNamespace, SharedRuntimeState shared)
{
_contractName = contractName;
_contractNamespace = contractNamespace;
_shared = shared;
OperationCollection operations = new OperationCollection(this);
this.operations = operations;
this.compatOperations = new OperationCollectionWrapper(operations);
_channelInitializers = new ProxyBehaviorCollection<IChannelInitializer>(this);
this.messageInspectors = new ProxyBehaviorCollection<IClientMessageInspector>(this);
_interactiveChannelInitializers = new ProxyBehaviorCollection<IInteractiveChannelInitializer>(this);
_unhandled = new ClientOperation(this, "*", MessageHeaders.WildcardAction, MessageHeaders.WildcardAction);
_unhandled.InternalFormatter = new MessageOperationFormatter();
_maxFaultSize = TransportDefaults.MaxFaultSize;
}
internal bool AddTransactionFlowProperties
{
get { return _addTransactionFlowProperties; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_addTransactionFlowProperties = value;
}
}
}
public Type CallbackClientType
{
get { return _callbackProxyType; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_callbackProxyType = value;
}
}
}
public SynchronizedCollection<IChannelInitializer> ChannelInitializers
{
get { return _channelInitializers; }
}
public string ContractName
{
get { return _contractName; }
}
public string ContractNamespace
{
get { return _contractNamespace; }
}
public Type ContractClientType
{
get { return _contractProxyType; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_contractProxyType = value;
}
}
}
internal IdentityVerifier IdentityVerifier
{
get
{
if (_identityVerifier == null)
{
_identityVerifier = IdentityVerifier.CreateDefault();
}
return _identityVerifier;
}
set
{
if (value == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value");
}
this.InvalidateRuntime();
_identityVerifier = value;
}
}
public Uri Via
{
get { return _via; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_via = value;
}
}
}
public bool ValidateMustUnderstand
{
get { return _shared.ValidateMustUnderstand; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_shared.ValidateMustUnderstand = value;
}
}
}
public bool MessageVersionNoneFaultsEnabled
{
get
{
return _messageVersionNoneFaultsEnabled;
}
set
{
this.InvalidateRuntime();
_messageVersionNoneFaultsEnabled = value;
}
}
public DispatchRuntime DispatchRuntime
{
get { return _dispatchRuntime; }
}
public DispatchRuntime CallbackDispatchRuntime
{
get
{
if (_dispatchRuntime == null)
_dispatchRuntime = new DispatchRuntime(this, _shared);
return _dispatchRuntime;
}
}
internal bool EnableFaults
{
get
{
if (this.IsOnServer)
{
return _dispatchRuntime.EnableFaults;
}
else
{
return _shared.EnableFaults;
}
}
set
{
lock (this.ThisLock)
{
if (this.IsOnServer)
{
string text = SR.SFxSetEnableFaultsOnChannelDispatcher0;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(text));
}
else
{
this.InvalidateRuntime();
_shared.EnableFaults = value;
}
}
}
}
public SynchronizedCollection<IInteractiveChannelInitializer> InteractiveChannelInitializers
{
get { return _interactiveChannelInitializers; }
}
public int MaxFaultSize
{
get
{
return _maxFaultSize;
}
set
{
this.InvalidateRuntime();
_maxFaultSize = value;
}
}
internal bool IsOnServer
{
get { return _shared.IsOnServer; }
}
public bool ManualAddressing
{
get
{
if (this.IsOnServer)
{
return _dispatchRuntime.ManualAddressing;
}
else
{
return _shared.ManualAddressing;
}
}
set
{
lock (this.ThisLock)
{
if (this.IsOnServer)
{
string text = SR.SFxSetManualAddresssingOnChannelDispatcher0;
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(text));
}
else
{
this.InvalidateRuntime();
_shared.ManualAddressing = value;
}
}
}
}
internal int MaxParameterInspectors
{
get
{
lock (this.ThisLock)
{
int max = 0;
for (int i = 0; i < this.operations.Count; i++)
max = System.Math.Max(max, this.operations[i].ParameterInspectors.Count);
return max;
}
}
}
public ICollection<IClientMessageInspector> ClientMessageInspectors
{
get { return this.MessageInspectors; }
}
[EditorBrowsable(EditorBrowsableState.Never)]
public new SynchronizedCollection<IClientMessageInspector> MessageInspectors
{
get { return this.messageInspectors; }
}
public ICollection<ClientOperation> ClientOperations
{
get { return this.Operations; }
}
[EditorBrowsable(EditorBrowsableState.Never)]
public new SynchronizedKeyedCollection<string, ClientOperation> Operations
{
get { return this.operations; }
}
public IClientOperationSelector OperationSelector
{
get { return _operationSelector; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_operationSelector = value;
}
}
}
internal object ThisLock
{
get { return _shared; }
}
public ClientOperation UnhandledClientOperation
{
get { return _unhandled; }
}
internal bool UseSynchronizationContext
{
get { return _useSynchronizationContext; }
set
{
lock (this.ThisLock)
{
this.InvalidateRuntime();
_useSynchronizationContext = value;
}
}
}
internal T[] GetArray<T>(SynchronizedCollection<T> collection)
{
lock (collection.SyncRoot)
{
if (collection.Count == 0)
{
return Array.Empty<T>();
}
else
{
T[] array = new T[collection.Count];
collection.CopyTo(array, 0);
return array;
}
}
}
internal ImmutableClientRuntime GetRuntime()
{
lock (this.ThisLock)
{
if (_runtime == null)
_runtime = new ImmutableClientRuntime(this);
return _runtime;
}
}
internal void InvalidateRuntime()
{
lock (this.ThisLock)
{
_shared.ThrowIfImmutable();
_runtime = null;
}
}
internal void LockDownProperties()
{
_shared.LockDownProperties();
}
internal SynchronizedCollection<T> NewBehaviorCollection<T>()
{
return new ProxyBehaviorCollection<T>(this);
}
internal bool IsFault(ref Message reply)
{
if (reply == null)
{
return false;
}
if (reply.IsFault)
{
return true;
}
if (this.MessageVersionNoneFaultsEnabled && IsMessageVersionNoneFault(ref reply, this.MaxFaultSize))
{
return true;
}
return false;
}
internal static bool IsMessageVersionNoneFault(ref Message message, int maxFaultSize)
{
if (message.Version != MessageVersion.None || message.IsEmpty)
{
return false;
}
HttpResponseMessageProperty prop = message.Properties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty;
if (prop == null || prop.StatusCode != HttpStatusCode.InternalServerError)
{
return false;
}
using (MessageBuffer buffer = message.CreateBufferedCopy(maxFaultSize))
{
message.Close();
message = buffer.CreateMessage();
using (Message copy = buffer.CreateMessage())
{
using (XmlDictionaryReader reader = copy.GetReaderAtBodyContents())
{
return reader.IsStartElement(XD.MessageDictionary.Fault, MessageVersion.None.Envelope.DictionaryNamespace);
}
}
}
}
internal class ProxyBehaviorCollection<T> : SynchronizedCollection<T>
{
private ClientRuntime _outer;
internal ProxyBehaviorCollection(ClientRuntime outer)
: base(outer.ThisLock)
{
_outer = outer;
}
protected override void ClearItems()
{
_outer.InvalidateRuntime();
base.ClearItems();
}
protected override void InsertItem(int index, T item)
{
if (item == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
}
_outer.InvalidateRuntime();
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
_outer.InvalidateRuntime();
base.RemoveItem(index);
}
protected override void SetItem(int index, T item)
{
if (item == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
}
_outer.InvalidateRuntime();
base.SetItem(index, item);
}
}
internal class OperationCollection : SynchronizedKeyedCollection<string, ClientOperation>
{
private ClientRuntime _outer;
internal OperationCollection(ClientRuntime outer)
: base(outer.ThisLock)
{
_outer = outer;
}
protected override void ClearItems()
{
_outer.InvalidateRuntime();
base.ClearItems();
}
protected override string GetKeyForItem(ClientOperation item)
{
return item.Name;
}
protected override void InsertItem(int index, ClientOperation item)
{
if (item == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
if (item.Parent != _outer)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.SFxMismatchedOperationParent);
_outer.InvalidateRuntime();
base.InsertItem(index, item);
}
protected override void RemoveItem(int index)
{
_outer.InvalidateRuntime();
base.RemoveItem(index);
}
protected override void SetItem(int index, ClientOperation item)
{
if (item == null)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
if (item.Parent != _outer)
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.SFxMismatchedOperationParent);
_outer.InvalidateRuntime();
base.SetItem(index, item);
}
internal void InternalClearItems() { this.ClearItems(); }
internal string InternalGetKeyForItem(ClientOperation item) { return this.GetKeyForItem(item); }
internal void InternalInsertItem(int index, ClientOperation item) { this.InsertItem(index, item); }
internal void InternalRemoveItem(int index) { this.RemoveItem(index); }
internal void InternalSetItem(int index, ClientOperation item) { this.SetItem(index, item); }
}
internal class OperationCollectionWrapper : KeyedCollection<string, ClientOperation>
{
private OperationCollection _inner;
internal OperationCollectionWrapper(OperationCollection inner) { _inner = inner; }
protected override void ClearItems() { _inner.InternalClearItems(); }
protected override string GetKeyForItem(ClientOperation item) { return _inner.InternalGetKeyForItem(item); }
protected override void InsertItem(int index, ClientOperation item) { _inner.InternalInsertItem(index, item); }
protected override void RemoveItem(int index) { _inner.InternalRemoveItem(index); }
protected override void SetItem(int index, ClientOperation item) { _inner.InternalSetItem(index, item); }
}
}
}
| |
//-----------------------------------------------------------------------
// <copyright file="BasicTests.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: http://www.lhotka.net/cslanet/
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#endif
namespace Csla.Test.Basic
{
[TestClass]
public class BasicTests
{
[TestMethod]
public void TestNotUndoableField()
{
Csla.ApplicationContext.GlobalContext.Clear();
Csla.Test.DataBinding.ParentEntity p = Csla.Test.DataBinding.ParentEntity.NewParentEntity();
p.NotUndoable = "something";
p.Data = "data";
p.BeginEdit();
p.NotUndoable = "something else";
p.Data = "new data";
p.CancelEdit();
//NotUndoable property points to a private field marked with [NotUndoable()]
//so its state is never copied when BeginEdit() is called
Assert.AreEqual("something else", p.NotUndoable);
//the Data property points to a field that is undoable, so it reverts
Assert.AreEqual("data", p.Data);
}
[TestMethod]
public void TestReadOnlyList()
{
//ReadOnlyList list = ReadOnlyList.GetReadOnlyList();
// Assert.AreEqual("Fetched", Csla.ApplicationContext.GlobalContext["ReadOnlyList"]);
}
[TestMethod]
public void TestNameValueList()
{
NameValueListObj nvList = NameValueListObj.GetNameValueListObj();
Assert.AreEqual("Fetched", Csla.ApplicationContext.GlobalContext["NameValueListObj"]);
Assert.AreEqual("element_1", nvList[1].Value);
//won't work, because IsReadOnly is set to true after object is populated in the for
//loop in DataPortal_Fetch
//NameValueListObj.NameValuePair newPair = new NameValueListObj.NameValuePair(45, "something");
//nvList.Add(newPair);
//Assert.AreEqual("something", nvList[45].Value);
}
[TestMethod]
public void TestCommandBase()
{
Csla.ApplicationContext.GlobalContext.Clear();
CommandObject obj = new CommandObject();
Assert.AreEqual("Executed", obj.ExecuteServerCode().AProperty);
}
[TestMethod]
public void CreateGenRoot()
{
Csla.ApplicationContext.GlobalContext.Clear();
GenRoot root;
root = GenRoot.NewRoot();
Assert.IsNotNull(root);
Assert.AreEqual("<new>", root.Data);
Assert.AreEqual("Created", Csla.ApplicationContext.GlobalContext["GenRoot"]);
Assert.AreEqual(true, root.IsNew);
Assert.AreEqual(false, root.IsDeleted);
Assert.AreEqual(true, root.IsDirty);
}
[TestMethod]
public void InheritanceUndo()
{
Csla.ApplicationContext.GlobalContext.Clear();
GenRoot root;
root = GenRoot.NewRoot();
root.BeginEdit();
root.Data = "abc";
root.CancelEdit();
Csla.ApplicationContext.GlobalContext.Clear();
root = GenRoot.NewRoot();
root.BeginEdit();
root.Data = "abc";
root.ApplyEdit();
}
[TestMethod]
public void CreateRoot()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root;
root = Csla.Test.Basic.Root.NewRoot();
Assert.IsNotNull(root);
Assert.AreEqual("<new>", root.Data);
Assert.AreEqual("Created", Csla.ApplicationContext.GlobalContext["Root"]);
Assert.AreEqual(true, root.IsNew);
Assert.AreEqual(false, root.IsDeleted);
Assert.AreEqual(true, root.IsDirty);
}
[TestMethod]
public void AddChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
Assert.AreEqual(1, root.Children.Count);
Assert.AreEqual("1", root.Children[0].Data);
}
[TestMethod]
public void AddRemoveChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
root.Children.Remove(root.Children[0]);
Assert.AreEqual(0, root.Children.Count);
}
[TestMethod]
public void AddRemoveAddChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
root.BeginEdit();
root.Children.Remove(root.Children[0]);
root.Children.Add("2");
root.CancelEdit();
Assert.AreEqual(1, root.Children.Count);
Assert.AreEqual("1", root.Children[0].Data);
}
[TestMethod]
public void AddGrandChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
Child child = root.Children[0];
child.GrandChildren.Add("1");
Assert.AreEqual(1, child.GrandChildren.Count);
Assert.AreEqual("1", child.GrandChildren[0].Data);
}
[TestMethod]
public void AddRemoveGrandChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
Child child = root.Children[0];
child.GrandChildren.Add("1");
child.GrandChildren.Remove(child.GrandChildren[0]);
Assert.AreEqual(0, child.GrandChildren.Count);
}
///<remarks>"the non-generic method AreEqual cannot be used with type arguments" - though
///it is used with type arguments in BasicTests.vb
///</remarks>
//[TestMethod]
//public void CloneGraph()
//{
// Csla.ApplicationContext.GlobalContext.Clear();
// Root root = Csla.Test.Basic.Root.NewRoot();
// FormSimulator form = new FormSimulator(root);
// SerializableListener listener = new SerializableListener(root);
// root.Children.Add("1");
// Child child = root.Children[0];
// Child.GrandChildren.Add("1");
// Assert.AreEqual<int>(1, child.GrandChildren.Count);
// Assert.AreEqual<string>("1", child.GrandChildren[0].Data);
// Root clone = ((Root)(root.Clone()));
// child = clone.Children[0];
// Assert.AreEqual<int>(1, child.GrandChildren.Count);
// Assert.AreEqual<string>("1", child.GrandChildren[0].Data);
// Assert.AreEqual<string>("root Deserialized", ((string)(Csla.ApplicationContext.GlobalContext["Deserialized"])));
// Assert.AreEqual<string>("GC Deserialized", ((string)(Csla.ApplicationContext.GlobalContext["GCDeserialized"])));
//}
[TestMethod]
public void ClearChildList()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("A");
root.Children.Add("B");
root.Children.Add("C");
root.Children.Clear();
Assert.AreEqual(0, root.Children.Count, "Count should be 0");
Assert.AreEqual(3, root.Children.DeletedCount, "Deleted count should be 3");
}
[TestMethod]
public void NestedAddAcceptchild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.BeginEdit();
root.Children.Add("A");
root.BeginEdit();
root.Children.Add("B");
root.BeginEdit();
root.Children.Add("C");
root.ApplyEdit();
root.ApplyEdit();
root.ApplyEdit();
Assert.AreEqual(3, root.Children.Count);
}
[TestMethod]
public void NestedAddDeleteAcceptChild()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.BeginEdit();
root.Children.Add("A");
root.BeginEdit();
root.Children.Add("B");
root.BeginEdit();
root.Children.Add("C");
Child childC = root.Children[2];
Assert.AreEqual(true, root.Children.Contains(childC), "Child should be in collection");
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
Assert.AreEqual(false, root.Children.Contains(childC), "Child should not be in collection");
Assert.AreEqual(true, root.Children.ContainsDeleted(childC), "Deleted child should be in deleted collection");
root.ApplyEdit();
Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after first applyedit");
root.ApplyEdit();
Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after ApplyEdit");
root.ApplyEdit();
Assert.AreEqual(0, root.Children.Count, "No children should remain");
Assert.AreEqual(false, root.Children.ContainsDeleted(childC), "Deleted child should not be in deleted collection after third applyedit");
}
[TestMethod]
public void BasicEquality()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root r1 = Root.NewRoot();
r1.Data = "abc";
Assert.AreEqual(true, r1.Equals(r1), "objects should be equal on instance compare");
Assert.AreEqual(true, Equals(r1, r1), "objects should be equal on static compare");
Csla.ApplicationContext.GlobalContext.Clear();
Root r2 = Root.NewRoot();
r2.Data = "xyz";
Assert.AreEqual(false, r1.Equals(r2), "objects should not be equal");
Assert.AreEqual(false, Equals(r1, r2), "objects should not be equal");
Assert.AreEqual(false, r1.Equals(null), "Objects should not be equal");
Assert.AreEqual(false, Equals(r1, null), "Objects should not be equal");
Assert.AreEqual(false, Equals(null, r2), "Objects should not be equal");
}
[TestMethod]
public void ChildEquality()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Root.NewRoot();
root.Children.Add("abc");
root.Children.Add("xyz");
root.Children.Add("123");
Child c1 = root.Children[0];
Child c2 = root.Children[1];
Child c3 = root.Children[2];
root.Children.Remove(c3);
Assert.AreEqual(true, c1.Equals(c1), "objects should be equal");
Assert.AreEqual(true, Equals(c1, c1), "objects should be equal");
Assert.AreEqual(false, c1.Equals(c2), "objects should not be equal");
Assert.AreEqual(false, Equals(c1, c2), "objects should not be equal");
Assert.AreEqual(false, c1.Equals(null), "objects should not be equal");
Assert.AreEqual(false, Equals(c1, null), "objects should not be equal");
Assert.AreEqual(false, Equals(null, c2), "objects should not be equal");
Assert.AreEqual(true, root.Children.Contains(c1), "Collection should contain c1");
Assert.AreEqual(true, root.Children.Contains(c2), "collection should contain c2");
Assert.AreEqual(false, root.Children.Contains(c3), "collection should not contain c3");
Assert.AreEqual(true, root.Children.ContainsDeleted(c3), "Deleted collection should contain c3");
}
[TestMethod]
public void DeletedListTest()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
root.Children.Add("2");
root.Children.Add("3");
root.BeginEdit();
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
root.ApplyEdit();
Root copy = root.Clone();
var deleted = copy.Children.GetDeletedList();
Assert.AreEqual(2, deleted.Count);
Assert.AreEqual("1", deleted[0].Data);
Assert.AreEqual("2", deleted[1].Data);
Assert.AreEqual(1, root.Children.Count);
}
[TestMethod]
public void DeletedListTestWithCancel()
{
Csla.ApplicationContext.GlobalContext.Clear();
Root root = Csla.Test.Basic.Root.NewRoot();
root.Children.Add("1");
root.Children.Add("2");
root.Children.Add("3");
root.BeginEdit();
root.Children.Remove(root.Children[0]);
root.Children.Remove(root.Children[0]);
Root copy = root.Clone();
var deleted = copy.Children.GetDeletedList();
Assert.AreEqual(2, deleted.Count);
Assert.AreEqual("1", deleted[0].Data);
Assert.AreEqual("2", deleted[1].Data);
Assert.AreEqual(1, root.Children.Count);
root.CancelEdit();
deleted = root.Children.GetDeletedList();
Assert.AreEqual(0, deleted.Count);
Assert.AreEqual(3, root.Children.Count);
}
[TestMethod]
public void SuppressListChangedEventsDoNotRaiseCollectionChanged()
{
bool changed = false;
var obj = new RootList();
obj.ListChanged += (o, e) =>
{
changed = true;
};
var child = new RootListChild(); // object is marked as child
Assert.IsTrue(obj.RaiseListChangedEvents);
using (obj.SuppressListChangedEvents)
{
Assert.IsFalse(obj.RaiseListChangedEvents);
obj.Add(child);
}
Assert.IsFalse(changed, "Should not raise ListChanged event");
Assert.IsTrue(obj.RaiseListChangedEvents);
Assert.AreEqual(child, obj[0]);
}
[TestCleanup]
public void ClearContextsAfterEachTest() {
Csla.ApplicationContext.GlobalContext.Clear();
}
}
public class FormSimulator
{
private Core.BusinessBase _obj;
public FormSimulator(Core.BusinessBase obj)
{
this._obj.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(obj_IsDirtyChanged);
this._obj = obj;
}
private void obj_IsDirtyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{}
}
[Serializable()]
public class SerializableListener
{
private Core.BusinessBase _obj;
public SerializableListener(Core.BusinessBase obj)
{
this._obj.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(obj_IsDirtyChanged);
this._obj = obj;
}
public void obj_IsDirtyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{ }
}
}
| |
//---------------------------------------------------------------------
// <copyright file="CellQuery.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner [....]
// @backupOwner [....]
//---------------------------------------------------------------------
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common.Utils;
using System.Data.Mapping.ViewGeneration.CqlGeneration;
using System.Data.Mapping.ViewGeneration.Utils;
using System.Data.Mapping.ViewGeneration.Validation;
using System.Data.Metadata.Edm;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace System.Data.Mapping.ViewGeneration.Structures
{
using System.Data.Entity;
using AttributeSet = Set<MemberPath>;
/// <summary>
/// This class stores the C or S query. For example,
/// (C) SELECT (p type Person) AS D1, p.pid, p.name FROM p in P WHERE D1
/// (S) SELECT True AS D1, pid, name FROM SPerson WHERE D1
///
/// The cell query is stored in a "factored" manner for ease of
/// cell-merging and cell manipulation. It contains:
/// * Projection: A sequence of slots and a sequence of boolean slots (one
/// for each cell in the extent)
/// * A From part represented as a Join tree
/// * A where clause
/// </summary>
internal class CellQuery : InternalBase
{
#region Fields
/// <summary>
/// Whether query has a 'SELECT DISTINCT' on top.
/// </summary>
internal enum SelectDistinct
{
Yes,
No
}
// The boolean expressions that essentially capture the type information
// Fixed-size list; NULL in the list means 'unused'
private List<BoolExpression> m_boolExprs;
// The fields including the key fields
// May contain NULLs - means 'not in the projection'
private ProjectedSlot[] m_projectedSlots;
// where clause: An expression formed using the boolExprs
private BoolExpression m_whereClause;
private BoolExpression m_originalWhereClause; // m_originalWhereClause is not changed
private SelectDistinct m_selectDistinct;
// The from part of the query
private MemberPath m_extentMemberPath;
// The basic cell relation for all slots in this
private BasicCellRelation m_basicCellRelation;
#endregion
#region Constructors
// effects: Creates a cell query with the given projection (slots),
// from part (joinTreeRoot) and the predicate (whereClause)
// Used for cell creation
internal CellQuery(List<ProjectedSlot> slots, BoolExpression whereClause, MemberPath rootMember, SelectDistinct eliminateDuplicates)
: this(slots.ToArray(), whereClause, new List<BoolExpression>(), eliminateDuplicates, rootMember)
{
}
// effects: Given all the fields, just sets them.
internal CellQuery(ProjectedSlot[] projectedSlots,
BoolExpression whereClause,
List<BoolExpression> boolExprs,
SelectDistinct elimDupl, MemberPath rootMember)
{
m_boolExprs = boolExprs;
m_projectedSlots = projectedSlots;
m_whereClause = whereClause;
m_originalWhereClause = whereClause;
m_selectDistinct = elimDupl;
m_extentMemberPath = rootMember;
}
/// <summary>
/// Copy Constructor
/// </summary>
internal CellQuery(CellQuery source)
{
this.m_basicCellRelation = source.m_basicCellRelation;
this.m_boolExprs = source.m_boolExprs;
this.m_selectDistinct = source.m_selectDistinct;
this.m_extentMemberPath = source.m_extentMemberPath;
this.m_originalWhereClause = source.m_originalWhereClause;
this.m_projectedSlots = source.m_projectedSlots;
this.m_whereClause = source.m_whereClause;
}
// effects: Given an existing cellquery, makes a new one based on it
// but uses the slots as specified with newSlots
private CellQuery(CellQuery existing, ProjectedSlot[] newSlots) :
this(newSlots, existing.m_whereClause, existing.m_boolExprs,
existing.m_selectDistinct, existing.m_extentMemberPath)
{
}
#endregion
#region Properties
internal SelectDistinct SelectDistinctFlag
{
get { return m_selectDistinct; }
}
// effects: Returns the top levelextent corresponding to this cell query
internal EntitySetBase Extent
{
get
{
EntitySetBase extent = m_extentMemberPath.Extent as EntitySetBase;
Debug.Assert(extent != null, "JoinTreeRoot in cellquery must be an extent");
return extent;
}
}
// effects: Returns the number of slots projected in the query
internal int NumProjectedSlots
{
get { return m_projectedSlots.Length; }
}
internal ProjectedSlot[] ProjectedSlots
{
get { return m_projectedSlots; }
}
internal List<BoolExpression> BoolVars
{
get { return m_boolExprs; }
}
// effects: Returns the number of boolean expressions projected in the query
internal int NumBoolVars
{
get { return m_boolExprs.Count; }
}
internal BoolExpression WhereClause
{
get { return m_whereClause; }
}
// effects: Returns the root of the join tree
internal MemberPath SourceExtentMemberPath
{
get { return m_extentMemberPath; }
}
// effects: Returns the relation that contains all the slots present
// in this cell query
internal BasicCellRelation BasicCellRelation
{
get
{
Debug.Assert(m_basicCellRelation != null, "BasicCellRelation must be created first");
return m_basicCellRelation;
}
}
/// <summary>
/// [WARNING}
/// After cell merging boolean expression can (most likely) have disjunctions (OR node)
/// to represent the condition that a tuple came from either of the merged cells.
/// In this case original where clause IS MERGED CLAUSE with OR!!!
/// So don't call this after merging. It'll throw or debug assert from within GetConjunctsFromWC()
/// </summary>
internal IEnumerable<MemberRestriction> Conditions
{
get { return GetConjunctsFromOriginalWhereClause(); }
}
#endregion
#region ProjectedSlots related methods
// effects: Returns the slotnum projected slot
internal ProjectedSlot ProjectedSlotAt(int slotNum)
{
Debug.Assert(slotNum < m_projectedSlots.Length, "Slot number too high");
return m_projectedSlots[slotNum];
}
// requires: All slots in this are join tree slots
// This method is called for an S-side query
// cQuery is the corresponding C-side query in the cell
// sourceCell is the original cell for "this" and cQuery
// effects: Checks if any of the columns in "this" are mapped to multiple properties in cQuery. If so,
// returns an error record about the duplicated slots
internal ErrorLog.Record CheckForDuplicateFields(CellQuery cQuery, Cell sourceCell)
{
// slotMap stores the slots on the S-side and the
// C-side properties that it maps to
KeyToListMap<MemberProjectedSlot, int> slotMap = new KeyToListMap<MemberProjectedSlot, int>(ProjectedSlot.EqualityComparer);
// Note that this does work for self-association. In the manager
// employee example, ManagerId and EmployeeId from the SEmployee
// table map to the two ends -- Manager.ManagerId and
// Employee.EmployeeId in the C Space
for (int i = 0; i < m_projectedSlots.Length; i++)
{
ProjectedSlot projectedSlot = m_projectedSlots[i];
MemberProjectedSlot slot = projectedSlot as MemberProjectedSlot;
Debug.Assert(slot != null, "All slots for this method must be JoinTreeSlots");
slotMap.Add(slot, i);
}
StringBuilder builder = null;
// Now determine the entries that have more than one integer per slot
bool isErrorSituation = false;
foreach (MemberProjectedSlot slot in slotMap.Keys)
{
ReadOnlyCollection<int> indexes = slotMap.ListForKey(slot);
Debug.Assert(indexes.Count >= 1, "Each slot must have one index at least");
if (indexes.Count > 1 &&
cQuery.AreSlotsEquivalentViaRefConstraints(indexes) == false)
{
// The column is mapped to more than one property and it
// failed the "association corresponds to referential
// constraints" check
isErrorSituation = true;
if (builder == null)
{
builder = new StringBuilder(System.Data.Entity.Strings.ViewGen_Duplicate_CProperties(Extent.Name));
builder.AppendLine();
}
StringBuilder tmpBuilder = new StringBuilder();
for (int i = 0; i < indexes.Count; i++)
{
int index = indexes[i];
if (i != 0)
{
tmpBuilder.Append(", ");
}
// The slot must be a JoinTreeSlot. If it isn't it is an internal error
MemberProjectedSlot cSlot = (MemberProjectedSlot)cQuery.m_projectedSlots[index];
tmpBuilder.Append(cSlot.ToUserString());
}
builder.AppendLine(Strings.ViewGen_Duplicate_CProperties_IsMapped(slot.ToUserString(), tmpBuilder.ToString()));
}
}
if (false == isErrorSituation)
{
return null;
}
ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.DuplicateCPropertiesMapped, builder.ToString(), sourceCell, String.Empty);
return record;
}
// requires: "this" is a query on the C-side
// and cSideSlotIndexes corresponds to the indexes
// (into "this") that the slot is being mapped into
// cSideSlotIndexes.Count > 1 - that is, a particular column in "this"'s corresponding S-Query
// has been mapped to more than one property in "this"
//
// effects: Checks that the multiple mappings on the C-side are
// backed by an appropriate Referential constraint
// If a column is mapped to two properties <A, B> in a single cell:
// (a) Must be an association
// (b) The two properties must be on opposite ends of the association
// (c) The association must have a RI constraint
// (d) Ordinal[A] == Ordinal[B] in the RI constraint
// (c) and (d) can be stated as - the slots are equivalent, i.e.,
// kept equal via an RI constraint
private bool AreSlotsEquivalentViaRefConstraints(ReadOnlyCollection<int> cSideSlotIndexes)
{
// Check (a): Must be an association
AssociationSet assocSet = Extent as AssociationSet;
if (assocSet == null)
{
return false;
}
// Check (b): The two properties must be on opposite ends of the association
// There better be exactly two properties!
Debug.Assert(cSideSlotIndexes.Count > 1, "Method called when no duplicate mapping");
if (cSideSlotIndexes.Count > 2)
{
return false;
}
// They better be join tree slots (if they are mapped!) and map to opposite ends
MemberProjectedSlot slot0 = (MemberProjectedSlot)m_projectedSlots[cSideSlotIndexes[0]];
MemberProjectedSlot slot1 = (MemberProjectedSlot)m_projectedSlots[cSideSlotIndexes[1]];
return slot0.MemberPath.IsEquivalentViaRefConstraint(slot1.MemberPath);
}
// requires: The Where clause satisfies the same requirements a GetConjunctsFromWhereClause
// effects: For each slot that has a NotNull condition in the where
// clause, checks if it is projected. If all such slots are
// projected, returns null. Else returns an error record
internal ErrorLog.Record CheckForProjectedNotNullSlots(Cell sourceCell, IEnumerable<Cell> associationSets)
{
StringBuilder builder = new StringBuilder();
bool foundError = false;
foreach (MemberRestriction restriction in Conditions)
{
if (restriction.Domain.ContainsNotNull())
{
MemberProjectedSlot slot = MemberProjectedSlot.GetSlotForMember(m_projectedSlots, restriction.RestrictedMemberSlot.MemberPath);
if (slot == null) //member with not null condition is not mapped in this extent
{
bool missingMapping = true;
if(Extent is EntitySet)
{
bool isCQuery = sourceCell.CQuery == this;
ViewTarget target = isCQuery ? ViewTarget.QueryView : ViewTarget.UpdateView;
CellQuery rightCellQuery = isCQuery? sourceCell.SQuery : sourceCell.CQuery;
//Find out if there is an association mapping but only if the current Not Null condition is on an EntitySet
EntitySet rightExtent = rightCellQuery.Extent as EntitySet;
if (rightExtent != null)
{
List<AssociationSet> associations = MetadataHelper.GetAssociationsForEntitySet(rightCellQuery.Extent as EntitySet);
foreach (var association in associations.Where(association => association.AssociationSetEnds.Any(end => ( end.CorrespondingAssociationEndMember.RelationshipMultiplicity == RelationshipMultiplicity.One &&
(MetadataHelper.GetOppositeEnd(end).EntitySet.EdmEquals(rightExtent))))))
{
foreach (var associationCell in associationSets.Where(c => c.GetRightQuery(target).Extent.EdmEquals(association)))
{
if (MemberProjectedSlot.GetSlotForMember(associationCell.GetLeftQuery(target).ProjectedSlots, restriction.RestrictedMemberSlot.MemberPath) != null)
{
missingMapping = false;
}
}
}
}
}
if (missingMapping)
{
// condition of NotNull and slot not being projected
builder.AppendLine(System.Data.Entity.Strings.ViewGen_NotNull_No_Projected_Slot(
restriction.RestrictedMemberSlot.MemberPath.PathToString(false)));
foundError = true;
}
}
}
}
if (false == foundError)
{
return null;
}
ErrorLog.Record record = new ErrorLog.Record(true, ViewGenErrorCode.NotNullNoProjectedSlot, builder.ToString(), sourceCell, String.Empty);
return record;
}
internal void FixMissingSlotAsDefaultConstant(int slotNumber, ConstantProjectedSlot slot)
{
Debug.Assert(m_projectedSlots[slotNumber] == null, "Another attempt to plug in a default value");
m_projectedSlots[slotNumber] = slot;
}
// requires: projectedSlotMap which contains a mapping of the fields
// for "this" to integers
// effects: Align the fields of this cell query using the
// projectedSlotMap and generates a new query into newMainQuery
// Based on the re-aligned fields in this, re-aligns the
// corresponding fields in otherQuery as well and modifies
// newOtherQuery to contain it
// Example:
// input: Proj[A,B,"5"] = Proj[F,"7",G]
// Proj[C,B] = Proj[H,I]
// projectedSlotMap: A -> 0, B -> 1, C -> 2
// output: Proj[A,B,null] = Proj[F,"7",null]
// Proj[null,B,C] = Proj[null,I,H]
internal void CreateFieldAlignedCellQueries(CellQuery otherQuery, MemberProjectionIndex projectedSlotMap,
out CellQuery newMainQuery, out CellQuery newOtherQuery)
{
// mainSlots and otherSlots hold the new slots for two queries
int numAlignedSlots = projectedSlotMap.Count;
ProjectedSlot[] mainSlots = new ProjectedSlot[numAlignedSlots];
ProjectedSlot[] otherSlots = new ProjectedSlot[numAlignedSlots];
// Go through the slots for this query and find the new slot for them
for (int i = 0; i < m_projectedSlots.Length; i++)
{
MemberProjectedSlot slot = m_projectedSlots[i] as MemberProjectedSlot;
Debug.Assert(slot != null, "All slots during cell normalization must field slots");
// Get the the ith slot's variable and then get the
// new slot number from the field map
int newSlotNum = projectedSlotMap.IndexOf(slot.MemberPath);
Debug.Assert(newSlotNum >= 0, "Field projected but not in projectedSlotMap");
mainSlots[newSlotNum] = m_projectedSlots[i];
otherSlots[newSlotNum] = otherQuery.m_projectedSlots[i];
// We ignore constants -- note that this is not the
// isHighpriority or discriminator case. An example of this
// is when (say) Address does not have zip but USAddress
// does. Then the constraint looks like Pi_NULL, A, B(E) =
// Pi_x, y, z(S)
// We don't care about this null in the view generation of
// the left side. Note that this could happen in inheritance
// or in cases when say the S side has 20 fields but the C
// side has only 3 - the other 17 are null or default.
// NOTE: We allow such constants only on the C side and not
// ont the S side. Otherwise, we can have a situation Pi_A,
// B, C(E) = Pi_5, y, z(S) Then someone can set A to 7 and we
// will not roundtrip. We check for this in validation
}
// Make the new cell queries with the new slots
newMainQuery = new CellQuery(this, mainSlots);
newOtherQuery = new CellQuery(otherQuery, otherSlots);
}
// requires: All slots in this are null or non-constants
// effects: Returns the non-null slots of this
internal AttributeSet GetNonNullSlots()
{
AttributeSet attributes = new AttributeSet(MemberPath.EqualityComparer);
foreach (ProjectedSlot projectedSlot in m_projectedSlots)
{
// null means 'unused' slot -- we ignore those
if (projectedSlot != null)
{
MemberProjectedSlot projectedVar = projectedSlot as MemberProjectedSlot;
Debug.Assert(projectedVar != null, "Projected slot must not be a constant");
attributes.Add(projectedVar.MemberPath);
}
}
return attributes;
}
// effects: Returns an error record if the keys of the extent/associationSet being mapped are
// present in the projected slots of this query. Returns null
// otherwise. ownerCell indicates the cell that owns this and
// resourceString is a resource used for error messages
internal ErrorLog.Record VerifyKeysPresent(Cell ownerCell, Func<object, object, string> formatEntitySetMessage,
Func<object, object, object, string> formatAssociationSetMessage, ViewGenErrorCode errorCode)
{
List<MemberPath> prefixes = new List<MemberPath>(1);
// Keep track of the key corresponding to each prefix
List<ExtentKey> keys = new List<ExtentKey>(1);
if (Extent is EntitySet)
{
// For entity set just get the full path of the key properties
MemberPath prefix = new MemberPath(Extent);
prefixes.Add(prefix);
EntityType entityType = (EntityType)Extent.ElementType;
List<ExtentKey> entitySetKeys = ExtentKey.GetKeysForEntityType(prefix, entityType);
Debug.Assert(entitySetKeys.Count == 1, "Currently, we only support primary keys");
keys.Add(entitySetKeys[0]);
}
else
{
AssociationSet relationshipSet = (AssociationSet)Extent;
// For association set, get the full path of the key
// properties of each end
foreach (AssociationSetEnd relationEnd in relationshipSet.AssociationSetEnds)
{
AssociationEndMember assocEndMember = relationEnd.CorrespondingAssociationEndMember;
MemberPath prefix = new MemberPath(relationshipSet, assocEndMember);
prefixes.Add(prefix);
List<ExtentKey> endKeys = ExtentKey.GetKeysForEntityType(prefix,
MetadataHelper.GetEntityTypeForEnd(assocEndMember));
Debug.Assert(endKeys.Count == 1, "Currently, we only support primary keys");
keys.Add(endKeys[0]);
}
}
for (int i = 0; i < prefixes.Count; i++)
{
MemberPath prefix = prefixes[i];
// Get all or none key slots that are being projected in this cell query
List<MemberProjectedSlot> keySlots = MemberProjectedSlot.GetKeySlots(GetMemberProjectedSlots(), prefix);
if (keySlots == null)
{
ExtentKey key = keys[i];
string message;
if (Extent is EntitySet)
{
string keyPropertiesString = MemberPath.PropertiesToUserString(key.KeyFields, true);
message = formatEntitySetMessage(keyPropertiesString, Extent.Name);
}
else
{
string endName = prefix.RootEdmMember.Name;
string keyPropertiesString = MemberPath.PropertiesToUserString(key.KeyFields, false);
message = formatAssociationSetMessage(keyPropertiesString, endName, Extent.Name);
}
ErrorLog.Record error = new ErrorLog.Record(true, errorCode, message, ownerCell, String.Empty);
return error;
}
}
return null;
}
internal IEnumerable<MemberPath> GetProjectedMembers()
{
foreach (MemberProjectedSlot slot in this.GetMemberProjectedSlots())
{
yield return slot.MemberPath;
}
}
// effects: Returns the fields in this, i.e., not constants or null slots
private IEnumerable<MemberProjectedSlot> GetMemberProjectedSlots()
{
foreach (ProjectedSlot slot in m_projectedSlots)
{
MemberProjectedSlot memberSlot = slot as MemberProjectedSlot;
if (memberSlot != null)
{
yield return memberSlot;
}
}
}
// effects: Returns the fields that are used in the query (both projected and non-projected)
// Output list is a copy, i.e., can be modified by the caller
internal List<MemberProjectedSlot> GetAllQuerySlots()
{
HashSet<MemberProjectedSlot> slots = new HashSet<MemberProjectedSlot>(GetMemberProjectedSlots());
slots.Add(new MemberProjectedSlot(SourceExtentMemberPath));
foreach (var restriction in Conditions)
{
slots.Add(restriction.RestrictedMemberSlot);
}
return new List<MemberProjectedSlot>(slots);
}
// effects: returns the index at which this slot appears in the projection
// or -1 if it is not projected
internal int GetProjectedPosition(MemberProjectedSlot slot)
{
for (int i = 0; i < m_projectedSlots.Length; i++)
{
if (MemberProjectedSlot.EqualityComparer.Equals(slot, m_projectedSlots[i]))
{
return i;
}
}
return -1;
}
// effects: returns the List of indexes at which this member appears in the projection
// or empty list if it is not projected
internal List<int> GetProjectedPositions(MemberPath member)
{
List<int> pathIndexes = new List<int>();
for (int i = 0; i < m_projectedSlots.Length; i++)
{
MemberProjectedSlot slot = m_projectedSlots[i] as MemberProjectedSlot;
if (slot != null && MemberPath.EqualityComparer.Equals(member, slot.MemberPath))
{
pathIndexes.Add(i);
}
}
return pathIndexes;
}
// effects: Determines the slot numbers for members in cellQuery
// Returns a set of those paths in the same order as paths. If even
// one of the path entries is not projected in the cellquery, returns null
internal List<int> GetProjectedPositions(IEnumerable<MemberPath> paths)
{
List<int> pathIndexes = new List<int>();
foreach (MemberPath member in paths)
{
// Get the index in checkQuery and add to pathIndexes
List<int> slotIndexes = GetProjectedPositions(member);
Debug.Assert(slotIndexes != null);
if (slotIndexes.Count == 0)
{ // member is not projected
return null;
}
Debug.Assert(slotIndexes.Count == 1, "Expecting the path to be projected only once");
pathIndexes.Add(slotIndexes[0]);
}
return pathIndexes;
}
// effects : Return the slot numbers for members in Cell Query that
// represent the association end member passed in.
internal List<int> GetAssociationEndSlots(AssociationEndMember endMember)
{
List<int> slotIndexes = new List<int>();
Debug.Assert(this.Extent is AssociationSet);
for (int i = 0; i < m_projectedSlots.Length; i++)
{
MemberProjectedSlot slot = m_projectedSlots[i] as MemberProjectedSlot;
if (slot != null && slot.MemberPath.RootEdmMember.Equals(endMember))
{
slotIndexes.Add(i);
}
}
return slotIndexes;
}
// effects: Determines the slot numbers for members in cellQuery
// Returns a set of those paths in the same order as paths. If even
// one of the path entries is not projected in the cellquery, returns null
// If a path is projected more than once, than we choose the one from the
// slotsToSearchFrom domain.
internal List<int> GetProjectedPositions(IEnumerable<MemberPath> paths, List<int> slotsToSearchFrom)
{
List<int> pathIndexes = new List<int>();
foreach (MemberPath member in paths)
{
// Get the index in checkQuery and add to pathIndexes
List<int> slotIndexes = GetProjectedPositions(member);
Debug.Assert(slotIndexes != null);
if (slotIndexes.Count == 0)
{ // member is not projected
return null;
}
int slotIndex = -1;
if (slotIndexes.Count > 1)
{
for (int i = 0; i < slotIndexes.Count; i++)
{
if (slotsToSearchFrom.Contains(slotIndexes[i]))
{
Debug.Assert(slotIndex == -1, "Should be projected only once");
slotIndex = slotIndexes[i];
}
}
if (slotIndex == -1)
{
return null;
}
}
else
{
slotIndex = slotIndexes[0];
}
pathIndexes.Add(slotIndex);
}
return pathIndexes;
}
// requires: The CellConstantDomains in the OneOfConsts of the where
// clause are partially done
// effects: Given the domains of different variables in domainMap,
// fixes the whereClause of this such that all the
// CellConstantDomains in OneOfConsts are complete
internal void UpdateWhereClause(MemberDomainMap domainMap)
{
List<BoolExpression> atoms = new List<BoolExpression>();
foreach (BoolExpression atom in WhereClause.Atoms)
{
BoolLiteral literal = atom.AsLiteral;
MemberRestriction restriction = literal as MemberRestriction;
Debug.Assert(restriction != null, "All bool literals must be OneOfConst at this point");
// The oneOfConst needs to be fixed with the new possible values from the domainMap.
IEnumerable<Constant> possibleValues = domainMap.GetDomain(restriction.RestrictedMemberSlot.MemberPath);
MemberRestriction newOneOf = restriction.CreateCompleteMemberRestriction(possibleValues);
// Prevent optimization of single constraint e.g: "300 in (300)"
// But we want to optimize type constants e.g: "category in (Category)"
// To prevent optimization of bool expressions we add a Sentinel OneOF
ScalarRestriction scalarConst = restriction as ScalarRestriction;
bool addSentinel =
scalarConst != null &&
!scalarConst.Domain.Contains(Constant.Null) &&
!scalarConst.Domain.Contains(Constant.NotNull) &&
!scalarConst.Domain.Contains(Constant.Undefined);
if (addSentinel)
{
domainMap.AddSentinel(newOneOf.RestrictedMemberSlot.MemberPath);
}
atoms.Add(BoolExpression.CreateLiteral(newOneOf, domainMap));
if (addSentinel)
{
domainMap.RemoveSentinel(newOneOf.RestrictedMemberSlot.MemberPath);
}
}
// We create a new whereClause that has the memberDomainMap set
if (atoms.Count > 0)
{
m_whereClause = BoolExpression.CreateAnd(atoms.ToArray());
}
}
#endregion
#region BooleanExprs related Methods
// effects: Returns a boolean expression corresponding to the
// "varNum" boolean in this.
internal BoolExpression GetBoolVar(int varNum)
{
return m_boolExprs[varNum];
}
// effects: Initalizes the booleans of this cell query to be
// true. Creates numBoolVars booleans and sets the cellNum boolean to true
internal void InitializeBoolExpressions(int numBoolVars, int cellNum)
{
//Debug.Assert(m_boolExprs.Count == 0, "Overwriting existing booleans");
m_boolExprs = new List<BoolExpression>(numBoolVars);
for (int i = 0; i < numBoolVars; i++)
{
m_boolExprs.Add(null);
}
Debug.Assert(cellNum < numBoolVars, "Trying to set boolean with too high an index");
m_boolExprs[cellNum] = BoolExpression.True;
}
#endregion
#region WhereClause related methods
// requires: The current whereClause corresponds to "True", "OneOfConst" or "
// "OneOfConst AND ... AND OneOfConst"
// effects: Yields all the conjuncts (OneOfConsts) in this (i.e., if the whereClause is
// just True, yields nothing
internal IEnumerable<MemberRestriction> GetConjunctsFromWhereClause()
{
return GetConjunctsFromWhereClause(m_whereClause);
}
internal IEnumerable<MemberRestriction> GetConjunctsFromOriginalWhereClause()
{
return GetConjunctsFromWhereClause(m_originalWhereClause);
}
private IEnumerable<MemberRestriction> GetConjunctsFromWhereClause(BoolExpression whereClause)
{
foreach (BoolExpression boolExpr in whereClause.Atoms)
{
if (boolExpr.IsTrue)
{
continue;
}
MemberRestriction result = boolExpr.AsLiteral as MemberRestriction;
Debug.Assert(result != null, "Atom must be restriction");
yield return result;
}
}
// requires: whereClause is of the form specified in GetConjunctsFromWhereClause
// effects: Converts the whereclause to a user-readable string
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal void WhereClauseToUserString(StringBuilder builder, MetadataWorkspace workspace)
{
bool isFirst = true;
foreach (MemberRestriction restriction in GetConjunctsFromWhereClause())
{
if (isFirst == false)
{
builder.Append(System.Data.Entity.Strings.ViewGen_AND);
}
restriction.ToUserString(false, builder, workspace);
}
}
#endregion
#region Full CellQuery methods
// effects: Determines all the identifiers used in this and adds them to identifiers
internal void GetIdentifiers(CqlIdentifiers identifiers)
{
foreach (ProjectedSlot projectedSlot in m_projectedSlots)
{
MemberProjectedSlot slot = projectedSlot as MemberProjectedSlot;
if (slot != null)
{
slot.MemberPath.GetIdentifiers(identifiers);
}
}
m_extentMemberPath.GetIdentifiers(identifiers);
}
internal void CreateBasicCellRelation(ViewCellRelation viewCellRelation)
{
List<MemberProjectedSlot> slots = GetAllQuerySlots();
// Create a base cell relation that has all the scalar slots of this
m_basicCellRelation = new BasicCellRelation(this, viewCellRelation, slots);
}
#endregion
#region String Methods
// effects: Modifies stringBuilder to contain a string representation
// of the cell query in terms of the original cells that are being used
internal override void ToCompactString(StringBuilder stringBuilder)
{
// This could be a simplified view where a number of cells
// got merged or it could be one of the original booleans. So
// determine their numbers using the booleans in m_cellWrapper
List<BoolExpression> boolExprs = m_boolExprs;
int i = 0;
bool first = true;
foreach (BoolExpression boolExpr in boolExprs)
{
if (boolExpr != null)
{
if (false == first)
{
stringBuilder.Append(",");
}
else
{
stringBuilder.Append("[");
}
StringUtil.FormatStringBuilder(stringBuilder, "C{0}", i);
first = false;
}
i++;
}
if (true == first)
{
// No booleans, i.e., no compact representation. Use full string to avoid empty output
ToFullString(stringBuilder);
}
else
{
stringBuilder.Append("]");
}
}
internal override void ToFullString(StringBuilder builder)
{
builder.Append("SELECT ");
if (m_selectDistinct == SelectDistinct.Yes)
{
builder.Append("DISTINCT ");
}
StringUtil.ToSeparatedString(builder, m_projectedSlots, ", ", "_");
if (m_boolExprs.Count > 0)
{
builder.Append(", Bool[");
StringUtil.ToSeparatedString(builder, m_boolExprs, ", ", "_");
builder.Append("]");
}
builder.Append(" FROM ");
m_extentMemberPath.ToFullString(builder);
if (false == m_whereClause.IsTrue)
{
builder.Append(" WHERE ");
m_whereClause.ToFullString(builder);
}
}
public override string ToString()
{
return ToFullString();
}
// eSQL representation of cell query
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal string ToESqlString()
{
StringBuilder builder = new StringBuilder();
builder.Append("\n\tSELECT ");
if (m_selectDistinct == SelectDistinct.Yes)
{
builder.Append("DISTINCT ");
}
foreach (ProjectedSlot ps in m_projectedSlots)
{
MemberProjectedSlot jtn = ps as MemberProjectedSlot;
StructuralType st = jtn.MemberPath.LeafEdmMember.DeclaringType;
StringBuilder sb = new StringBuilder();
jtn.MemberPath.AsEsql(sb, "e");
builder.AppendFormat("{0}, ", sb.ToString());
}
//remove the extra-comma after the last slot
builder.Remove(builder.Length - 2, 2);
builder.Append("\n\tFROM ");
EntitySetBase extent = m_extentMemberPath.Extent;
CqlWriter.AppendEscapedQualifiedName(builder, extent.EntityContainer.Name, extent.Name);
builder.Append(" AS e");
if (m_whereClause.IsTrue == false)
{
builder.Append("\n\tWHERE ");
StringBuilder qbuilder = new StringBuilder();
m_whereClause.AsEsql(qbuilder, "e");
builder.Append(qbuilder.ToString());
}
builder.Append("\n ");
return builder.ToString();
}
#endregion
}
}
| |
//
// Copyright (C) 2012-2014 DataStax Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
using NUnit.Framework;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
#if !NO_MOCKS
using Moq;
#endif
namespace Cassandra.Tests
{
[TestFixture]
public class RowSetUnitTests
{
[Test]
public void RowIteratesThroughValues()
{
var rs = CreateStringsRowset(4, 1);
var row = rs.First();
//Use Linq's IEnumerable ToList: it iterates and maps to a list
var cellValues = row.ToList();
Assert.AreEqual("row_0_col_0", cellValues[0]);
Assert.AreEqual("row_0_col_1", cellValues[1]);
Assert.AreEqual("row_0_col_2", cellValues[2]);
Assert.AreEqual("row_0_col_3", cellValues[3]);
}
/// <summary>
/// Test that all possible ways to get the value from the row gets the same value
/// </summary>
[Test]
public void RowGetTheSameValues()
{
var row = CreateStringsRowset(3, 1).First();
var value00 = row[0];
var value01 = row.GetValue<object>(0);
var value02 = row.GetValue(typeof(object), 0);
Assert.True(value00.Equals(value01) && value01.Equals(value02), "Row values do not match");
var value10 = (string)row[1];
var value11 = row.GetValue<string>(1);
var value12 = (string)row.GetValue(typeof(string), 1);
Assert.True(value10.Equals(value11) && value11.Equals(value12), "Row values do not match");
var value20 = (string)row["col_2"];
var value21 = row.GetValue<string>("col_2");
var value22 = (string)row.GetValue(typeof(string), "col_2");
Assert.True(value20.Equals(value21) && value21.Equals(value22), "Row values do not match");
}
[Test]
public void RowSetIteratesTest()
{
var rs = CreateStringsRowset(2, 3);
//Use Linq's IEnumerable ToList to iterate and map it to a list
var rowList = rs.ToList();
Assert.AreEqual(3, rowList.Count);
Assert.AreEqual("row_0_col_0", rowList[0].GetValue<string>("col_0"));
Assert.AreEqual("row_1_col_1", rowList[1].GetValue<string>("col_1"));
Assert.AreEqual("row_2_col_0", rowList[2].GetValue<string>("col_0"));
}
[Test]
public void RowSetCallsFetchNextTest()
{
//Create a rowset with 1 row
var rs = CreateStringsRowset(1, 1, "a_");
Assert.True(rs.AutoPage);
//It has paging state, stating that there are more pages
rs.PagingState = new byte[] { 0 };
//Add a handler to fetch next
rs.FetchNextPage = (pagingState) =>
{
return CreateStringsRowset(1, 1, "b_");
};
//use linq to iterate and map it to a list
var rowList = rs.ToList();
Assert.AreEqual(2, rowList.Count);
Assert.AreEqual("a_row_0_col_0", rowList[0].GetValue<string>("col_0"));
Assert.AreEqual("b_row_0_col_0", rowList[1].GetValue<string>("col_0"));
}
[Test]
public void RowSetDoesNotCallFetchNextWhenAutoPageFalseTest()
{
//Create a rowset with 1 row
var rs = CreateStringsRowset(1, 1, "a_");
//Set to not to automatically page
rs.AutoPage = false;
//It has paging state, stating that there are more pages
rs.PagingState = new byte[] { 0 };
//Add a handler to fetch next
var called = false;
rs.FetchNextPage = (pagingState) =>
{
called = true;
return CreateStringsRowset(1, 1, "b_");
};
//use linq to iterate and map it to a list
var rowList = rs.ToList();
Assert.False(called);
Assert.AreEqual(1, rowList.Count);
}
/// <summary>
/// Ensures that in case there is an exception while retrieving the next page, it propagates.
/// </summary>
[Test]
public void RowSetFetchNextPropagatesExceptionTest()
{
var rs = CreateStringsRowset(1, 1);
//It has paging state, stating that there are more pages.
rs.PagingState = new byte[] { 0 };
//Throw a test exception when fetching the next page.
rs.FetchNextPage = (pagingState) =>
{
throw new TestException();
};
//use linq to iterate and map it to a list
//The row set should throw an exception when getting the next page.
Assert.Throws<TestException>(() => { rs.ToList(); });
}
/// <summary>
/// Tests that once iterated, it can not be iterated any more.
/// </summary>
[Test]
public void RowSetMustDequeue()
{
var rowLength = 10;
var rs = CreateStringsRowset(2, rowLength);
rs.FetchNextPage = (pagingState) =>
{
Assert.Fail("Event to get next page must not be called as there is no paging state.");
return null;
};
//Use Linq to iterate
var rowsFirstIteration = rs.ToList();
Assert.AreEqual(rowLength, rowsFirstIteration.Count);
//Following iterations must yield 0 rows
var rowsSecondIteration = rs.ToList();
var rowsThridIteration = rs.ToList();
Assert.AreEqual(0, rowsSecondIteration.Count);
Assert.AreEqual(0, rowsThridIteration.Count);
Assert.IsTrue(rs.IsExhausted());
Assert.IsTrue(rs.IsFullyFetched);
}
/// <summary>
/// Tests that when multi threading, all enumerators of the same rowset wait for the fetching.
/// </summary>
[Test]
public void RowSetFetchNextAllEnumeratorsWait()
{
var pageSize = 10;
var rs = CreateStringsRowset(10, pageSize);
rs.PagingState = new byte[0];
var fetchCounter = 0;
rs.FetchNextPage = (pagingState) =>
{
fetchCounter++;
//fake a fetch
Thread.Sleep(1000);
return CreateStringsRowset(10, pageSize);
};
var counterList = new ConcurrentBag<int>();
Action iteration = () =>
{
var counter = 0;
foreach (var row in rs)
{
counter++;
//Try to synchronize, all the threads will try to fetch at the almost same time.
Thread.Sleep(300);
}
counterList.Add(counter);
};
//Invoke it in parallel more than 10 times
Parallel.Invoke(iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration, iteration);
//Assert that the fetch was called just 1 time
Assert.AreEqual(1, fetchCounter);
//Sum all rows dequeued from the different threads
var totalRows = counterList.Sum();
//Check that the total amount of rows dequeued are the same as pageSize * number of pages.
Assert.AreEqual(pageSize * 2, totalRows);
}
[Test]
public void RowSetFetchNext3Pages()
{
var rowLength = 10;
var rs = CreateStringsRowset(10, rowLength, "page_0_");
rs.PagingState = new byte[0];
var fetchCounter = 0;
rs.FetchNextPage = (pagingState) =>
{
fetchCounter++;
var pageRowSet = CreateStringsRowset(10, rowLength, "page_" + fetchCounter + "_");
if (fetchCounter < 3)
{
//when retrieving the pages, state that there are more results
pageRowSet.PagingState = new byte[0];
}
else
{
//On the 3rd page, state that there aren't any more pages.
pageRowSet.PagingState = null;
}
return pageRowSet;
};
//Use Linq to iterate
var rows = rs.ToList();
Assert.AreEqual(3, fetchCounter, "Fetch must have been called 3 times");
Assert.AreEqual(rows.Count, rowLength * 4, "RowSet must contain 4 pages in total");
//Check the values are in the correct order
Assert.AreEqual(rows[0].GetValue<string>(0), "page_0_row_0_col_0");
Assert.AreEqual(rows[rowLength].GetValue<string>(0), "page_1_row_0_col_0");
Assert.AreEqual(rows[rowLength * 2].GetValue<string>(0), "page_2_row_0_col_0");
Assert.AreEqual(rows[rowLength * 3].GetValue<string>(0), "page_3_row_0_col_0");
}
[Test]
public void RowSetFetchNext3PagesExplicitFetch()
{
var rowLength = 10;
var rs = CreateStringsRowset(10, rowLength, "page_0_");
rs.PagingState = new byte[0];
var fetchCounter = 0;
rs.FetchNextPage = (pagingState) =>
{
fetchCounter++;
var pageRowSet = CreateStringsRowset(10, rowLength, "page_" + fetchCounter + "_");
if (fetchCounter < 3)
{
//when retrieving the pages, state that there are more results
pageRowSet.PagingState = new byte[0];
}
else if (fetchCounter == 3)
{
//On the 3rd page, state that there aren't any more pages.
pageRowSet.PagingState = null;
}
else
{
throw new Exception("It should not be called more than 3 times.");
}
return pageRowSet;
};
Assert.AreEqual(rowLength * 1, rs.InnerQueueCount);
rs.FetchMoreResults();
Assert.AreEqual(rowLength * 2, rs.InnerQueueCount);
rs.FetchMoreResults();
Assert.AreEqual(rowLength * 3, rs.InnerQueueCount);
rs.FetchMoreResults();
Assert.AreEqual(rowLength * 4, rs.InnerQueueCount);
//Use Linq to iterate:
var rows = rs.ToList();
Assert.AreEqual(rows.Count, rowLength * 4, "RowSet must contain 4 pages in total");
//Check the values are in the correct order
Assert.AreEqual(rows[0].GetValue<string>(0), "page_0_row_0_col_0");
Assert.AreEqual(rows[rowLength].GetValue<string>(0), "page_1_row_0_col_0");
Assert.AreEqual(rows[rowLength * 2].GetValue<string>(0), "page_2_row_0_col_0");
Assert.AreEqual(rows[rowLength * 3].GetValue<string>(0), "page_3_row_0_col_0");
}
[Test]
public void NotExistentColumnThrows()
{
var row = CreateSampleRowSet().First();
var ex = Assert.Throws<ArgumentException>(() => row.GetValue<string>("not_existent_col"));
StringAssert.Contains("Column", ex.Message);
StringAssert.Contains("not found", ex.Message);
}
[Test]
public void NullValuesWithStructTypeColumnThrows()
{
//Row with all null values
var row = CreateSampleRowSet().Last();
Assert.IsNull(row.GetValue<string>("text_sample"));
Assert.Throws<NullReferenceException>(() => row.GetValue<int>("int_sample"));
Assert.DoesNotThrow(() => row.GetValue<int?>("int_sample"));
}
#if !NO_MOCKS
[Test]
public void RowsetIsMockable()
{
var rowMock = new Mock<Row>();
rowMock.Setup(r => r.GetValue<int>(It.Is<string>(n => n == "int_value"))).Returns(100);
var rows = new Row[]
{
rowMock.Object
};
var mock = new Mock<RowSet>();
mock
.Setup(r => r.GetEnumerator()).Returns(() => ((IEnumerable<Row>)rows).GetEnumerator());
var rs = mock.Object;
var rowArray = rs.ToArray();
Assert.AreEqual(rowArray.Length, 1);
Assert.AreEqual(rowArray[0].GetValue<int>("int_value"), 100);
}
#endif
/// <summary>
/// Creates a rowset.
/// The columns are named: col_0, ..., col_n
/// The rows values are: row_0_col_0, ..., row_m_col_n
/// </summary>
private static RowSet CreateStringsRowset(int columnLength, int rowLength, string valueModifier = null)
{
var columns = new List<CqlColumn>();
var columnIndexes = new Dictionary<string, int>();
for (var i = 0; i < columnLength; i++)
{
var c = new CqlColumn()
{
Index = i,
Name = "col_" + i,
TypeCode = ColumnTypeCode.Text,
Type = typeof(string)
};
columns.Add(c);
columnIndexes.Add(c.Name, c.Index);
}
var rs = new RowSet();
for (var j = 0; j < rowLength; j++)
{
rs.AddRow(new Row(columns.Select(c => valueModifier + "row_" + j + "_col_" + c.Index).Cast<object>().ToArray(), columns.ToArray(), columnIndexes));
}
return rs;
}
/// <summary>
/// Creates a RowSet with few rows with int, text columns (null values in the last row)
/// </summary>
private static RowSet CreateSampleRowSet()
{
var columns = new List<CqlColumn>
{
new CqlColumn()
{
Index = 0,
Name = "text_sample",
TypeCode = ColumnTypeCode.Text,
Type = typeof (string)
},
new CqlColumn()
{
Index = 1,
Name = "int_sample",
TypeCode = ColumnTypeCode.Int,
Type = typeof(int)
}
};
var columnIndexes = columns.ToDictionary(c => c.Name, c => c.Index);
var rs = new RowSet();
var rowValues = new object[]
{
"text value",
100
};
rs.AddRow(new Row(rowValues, columns.ToArray(), columnIndexes));
rs.AddRow(new Row(new object[] { null, null}, columns.ToArray(), columnIndexes));
return rs;
}
[Test]
public void RowSet_Empty_Returns_Iterable_Instace()
{
var rs = RowSet.Empty();
Assert.AreEqual(0, rs.Columns.Length);
Assert.True(rs.IsExhausted());
Assert.True(rs.IsFullyFetched);
Assert.AreEqual(0, rs.Count());
//iterate a second time
Assert.AreEqual(0, rs.Count());
//Different instances
Assert.AreNotSame(RowSet.Empty(), rs);
Assert.DoesNotThrow(() => rs.FetchMoreResults());
Assert.AreEqual(0, rs.GetAvailableWithoutFetching());
}
public void RowSet_Empty_Call_AddRow_Throws()
{
var rs = RowSet.Empty();
Assert.Throws<InvalidOperationException>(() => rs.AddRow(new Row()));
}
[Test]
public void Row_TryConvertToType_Should_Convert_Timestamps()
{
var timestampTypeInfo = new CqlColumn {TypeCode = ColumnTypeCode.Timestamp};
var values = new[]
{
//column desc, value, type and expected type
new object[] {DateTimeOffset.Now, timestampTypeInfo, typeof(DateTime)},
new object[] {DateTimeOffset.Now, timestampTypeInfo, typeof(DateTimeOffset)},
new object[] {DateTimeOffset.Now, timestampTypeInfo, typeof(object), typeof(DateTimeOffset)},
new object[] {DateTimeOffset.Now, timestampTypeInfo, typeof(IConvertible), typeof(DateTime)}
};
foreach (var item in values)
{
var value = Row.TryConvertToType(item[0], (CqlColumn)item[1], (Type)item[2]);
Assert.AreEqual(item.Length > 3 ? item[3] : item[2], value.GetType());
}
}
[Test]
public void Row_TryConvertToType_Should_Convert_Lists()
{
var listIntTypeInfo = new CqlColumn
{
TypeCode = ColumnTypeCode.List,
TypeInfo = new ListColumnInfo { ValueTypeCode = ColumnTypeCode.Int },
Type = typeof(IEnumerable<int>)
};
var values = new[]
{
new object[] {new [] {1, 2, 3}, listIntTypeInfo, typeof(int[])},
new object[] {new [] {1, 2, 3}, listIntTypeInfo, typeof(object), typeof(int[])},
new object[] {new [] {1, 2, 3}, listIntTypeInfo, typeof(IEnumerable<int>), typeof(int[])},
new object[] {new [] {1, 2, 3}, listIntTypeInfo, typeof(List<int>)},
new object[] {new [] {1, 2, 3}, listIntTypeInfo, typeof(IList<int>), typeof(List<int>)}
};
foreach (var item in values)
{
var value = Row.TryConvertToType(item[0], (CqlColumn)item[1], (Type)item[2]);
Assert.AreEqual(item.Length > 3 ? item[3] : item[2], value.GetType());
CollectionAssert.AreEqual((int[])item[0], (IEnumerable<int>)value);
}
}
[Test]
public void Row_TryConvertToType_Should_Convert_Sets()
{
var setIntTypeInfo = new CqlColumn
{
TypeCode = ColumnTypeCode.Set,
TypeInfo = new SetColumnInfo { KeyTypeCode = ColumnTypeCode.Int },
Type = typeof(IEnumerable<int>)
};
var values = new[]
{
new object[] {new [] {1, 2, 3}, setIntTypeInfo, typeof(int[])},
new object[] {new [] {1, 2, 3}, setIntTypeInfo, typeof(object), typeof(int[])},
new object[] {new [] {1, 2, 3}, setIntTypeInfo, typeof(IEnumerable<int>), typeof(int[])},
new object[] {new [] {1, 2, 3}, setIntTypeInfo, typeof(HashSet<int>)},
new object[] {new [] {1, 2, 3}, setIntTypeInfo, typeof(SortedSet<int>)},
new object[] {new [] {1, 2, 3}, setIntTypeInfo, typeof(ISet<int>), typeof(SortedSet<int>)}
};
foreach (var item in values)
{
var value = Row.TryConvertToType(item[0], (CqlColumn)item[1], (Type)item[2]);
Assert.AreEqual(item.Length > 3 ? item[3] : item[2], value.GetType());
CollectionAssert.AreEqual((int[]) item[0], (IEnumerable<int>) value);
}
}
[Test]
public void Row_TryConvertToType_Should_Convert_Uuid_Collections()
{
var setTypeInfo = new CqlColumn
{
TypeCode = ColumnTypeCode.Set,
TypeInfo = new SetColumnInfo { KeyTypeCode = ColumnTypeCode.Timeuuid }
};
var listTypeInfo = new CqlColumn
{
TypeCode = ColumnTypeCode.List,
TypeInfo = new ListColumnInfo { ValueTypeCode = ColumnTypeCode.Timeuuid }
};
var values = new[]
{
Tuple.Create(new Guid[] { TimeUuid.NewId() }, setTypeInfo, typeof(TimeUuid[])),
Tuple.Create(new Guid[] { TimeUuid.NewId() }, setTypeInfo, typeof(SortedSet<TimeUuid>)),
Tuple.Create(new Guid[] { TimeUuid.NewId() }, listTypeInfo, typeof(List<TimeUuid>)),
Tuple.Create(new Guid[] { TimeUuid.NewId() }, setTypeInfo, typeof(HashSet<TimeUuid>)),
Tuple.Create(new Guid[] { TimeUuid.NewId() }, setTypeInfo, typeof(ISet<TimeUuid>)),
Tuple.Create(new Guid[] { Guid.NewGuid() }, setTypeInfo, typeof(HashSet<Guid>)),
Tuple.Create(new Guid[] { Guid.NewGuid() }, setTypeInfo, typeof(SortedSet<Guid>)),
Tuple.Create(new Guid[] { Guid.NewGuid() }, listTypeInfo, typeof(List<Guid>)),
Tuple.Create(new Guid[] { Guid.NewGuid() }, listTypeInfo, typeof(Guid[])),
Tuple.Create(new Guid[] { Guid.NewGuid() }, listTypeInfo, typeof(IList<Guid>))
};
foreach (var item in values)
{
var value = Row.TryConvertToType(item.Item1, item.Item2, item.Item3);
Assert.True(item.Item3.GetTypeInfo().IsInstanceOfType(value), "{0} is not assignable from {1}",
item.Item3, value.GetType());
Assert.AreEqual(item.Item1.First().ToString(),
(from object v in (IEnumerable)value select v.ToString()).FirstOrDefault());
}
}
[Test]
public void Row_TryConvertToType_Should_Convert_Nested_Collections()
{
var setTypeInfo = new CqlColumn
{
TypeCode = ColumnTypeCode.Set,
TypeInfo = new SetColumnInfo
{
KeyTypeCode = ColumnTypeCode.Set,
KeyTypeInfo = new SetColumnInfo { KeyTypeCode = ColumnTypeCode.Int }
}
};
var listTypeInfo = new CqlColumn
{
TypeCode = ColumnTypeCode.List,
TypeInfo = new ListColumnInfo
{
ValueTypeCode = ColumnTypeCode.Set,
ValueTypeInfo = new SetColumnInfo { KeyTypeCode = ColumnTypeCode.Timeuuid }
}
};
var values = new[]
{
Tuple.Create((IEnumerable)new [] { new Guid[] { TimeUuid.NewId() } }, listTypeInfo, typeof(TimeUuid[][])),
Tuple.Create((IEnumerable)new [] { new [] { Guid.NewGuid() } }, listTypeInfo, typeof(Guid[][])),
Tuple.Create((IEnumerable)new [] { new Guid[] { TimeUuid.NewId() } }, listTypeInfo, typeof(SortedSet<TimeUuid>[])),
Tuple.Create((IEnumerable)new [] { new [] { Guid.NewGuid() } }, listTypeInfo, typeof(HashSet<Guid>[])),
Tuple.Create((IEnumerable)new [] { new [] { 314 } }, setTypeInfo, typeof(HashSet<int>[])),
Tuple.Create((IEnumerable)new [] { new [] { 213 } }, setTypeInfo, typeof(int[][])),
Tuple.Create((IEnumerable)new [] { new [] { 111 } }, setTypeInfo, typeof(SortedSet<SortedSet<int>>))
};
foreach (var item in values)
{
var value = Row.TryConvertToType(item.Item1, item.Item2, item.Item3);
Assert.True(item.Item3.GetTypeInfo().IsInstanceOfType(value), "{0} is not assignable from {1}",
item.Item3, value.GetType());
Assert.AreEqual(TestHelper.FirstString(item.Item1), TestHelper.FirstString((IEnumerable) value));
}
}
[Test]
public void Row_TryConvertToType_Should_Convert_Dictionaries()
{
var mapTypeInfo1 = new CqlColumn
{
TypeCode = ColumnTypeCode.Map,
TypeInfo = new MapColumnInfo
{
KeyTypeCode = ColumnTypeCode.Timeuuid,
ValueTypeCode = ColumnTypeCode.Set,
ValueTypeInfo = new SetColumnInfo { KeyTypeCode = ColumnTypeCode.Int }
}
};
var values = new[]
{
Tuple.Create(
(IDictionary) new SortedDictionary<Guid, IEnumerable<int>>
{
{ Guid.NewGuid(), new[] { 1, 2, 3}}
},
mapTypeInfo1, typeof(SortedDictionary<Guid, IEnumerable<int>>)),
Tuple.Create(
(IDictionary) new SortedDictionary<Guid, IEnumerable<int>>
{
{ TimeUuid.NewId(), new[] { 1, 2, 3}}
},
mapTypeInfo1, typeof(IDictionary<TimeUuid, int[]>))
};
foreach (var item in values)
{
var value = Row.TryConvertToType(item.Item1, item.Item2, item.Item3);
Assert.True(item.Item3.GetTypeInfo().IsInstanceOfType(value), "{0} is not assignable from {1}",
item.Item3, value.GetType());
Assert.AreEqual(TestHelper.FirstString(item.Item1), TestHelper.FirstString((IEnumerable)value));
}
}
// From DB!
//System.Collections.Generic.SortedDictionary`2[System.String,System.Collections.Generic.IEnumerable`1[System.String]]
[Test]
public void Row_TryConvertToType_Should_Convert_Timestamp_Collections()
{
var setTypeInfo = new CqlColumn
{
TypeCode = ColumnTypeCode.Set,
TypeInfo = new SetColumnInfo { KeyTypeCode = ColumnTypeCode.Timestamp },
Type = typeof(IEnumerable<DateTimeOffset>)
};
var listTypeInfo = new CqlColumn
{
TypeCode = ColumnTypeCode.List,
TypeInfo = new ListColumnInfo { ValueTypeCode = ColumnTypeCode.Timestamp }
};
var values = new[]
{
Tuple.Create(new [] { DateTimeOffset.UtcNow }, setTypeInfo, typeof(DateTime[])),
Tuple.Create(new [] { DateTimeOffset.UtcNow }, setTypeInfo, typeof(SortedSet<DateTime>)),
Tuple.Create(new [] { DateTimeOffset.UtcNow }, listTypeInfo, typeof(List<DateTime>)),
Tuple.Create(new [] { DateTimeOffset.UtcNow }, setTypeInfo, typeof(HashSet<DateTime>)),
Tuple.Create(new [] { DateTimeOffset.UtcNow }, setTypeInfo, typeof(HashSet<DateTimeOffset>)),
Tuple.Create(new [] { DateTimeOffset.UtcNow }, setTypeInfo, typeof(SortedSet<DateTimeOffset>)),
Tuple.Create(new [] { DateTimeOffset.UtcNow }, listTypeInfo, typeof(List<DateTimeOffset>)),
Tuple.Create(new [] { DateTimeOffset.UtcNow }, listTypeInfo, typeof(DateTimeOffset[]))
};
foreach (var item in values)
{
var value = Row.TryConvertToType(item.Item1, item.Item2, item.Item3);
Assert.True(item.Item3.GetTypeInfo().IsInstanceOfType(value), "{0} is not assignable from {1}",
item.Item3, value.GetType());
Assert.AreEqual(item.Item1.First().Ticks,
(from object v in (IEnumerable)value select (v is DateTime ? ((DateTime)v).Ticks : ((DateTimeOffset)v).Ticks)).FirstOrDefault());
}
}
private class TestException : Exception { }
}
}
| |
//
// GalleryRemote.cs
//
// Author:
// Larry Ewing <lewing@novell.com>
// Stephane Delcroix <sdelcroix*novell.com>
// Stephen Shaw <sshaw@decriptor.com>
//
// Copyright (C) 2004-2008 Novell, Inc.
// Copyright (C) 2004-2007 Larry Ewing
// Copyright (C) 2006-2008 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.IO;
using System.Collections.Generic;
using FSpot.Core;
using Hyena;
/* These classes are based off the documentation at
*
* http://codex.gallery2.org/index.php/Gallery_Remote:Protocol
*/
namespace FSpot.Exporters.Gallery
{
public enum AlbumPermission : byte
{
None = 0,
Add = 1,
Write = 2,
Delete = 4,
DeleteAlbum = 8,
CreateSubAlbum = 16
}
public class Album : IComparable
{
public int RefNum;
public string Name = String.Empty;
public string Title = String.Empty;
public string Summary = String.Empty;
public int ParentRefNum;
public int ResizeSize;
public int ThumbSize;
public List<Image> Images;
public string BaseURL = String.Empty;
public AlbumPermission Perms = AlbumPermission.None;
public Album Parent {
get {
if (ParentRefNum != 0)
return Gallery.LookupAlbum (ParentRefNum);
else
return null;
}
}
protected List<int> parents = null;
public List<int> Parents {
get {
if (parents != null)
return parents;
if (Parent == null) {
parents = new List<int> ();
} else {
parents = Parent.Parents;
parents.Add (Parent.RefNum);
}
return parents;
}
}
public Gallery Gallery { get; private set; }
public Album (Gallery gallery, string name, int ref_num)
{
Name = name;
Gallery = gallery;
this.RefNum = ref_num;
Images = new List<Image> ();
}
public void Rename (string name)
{
Gallery.MoveAlbum (this, name);
}
public void Add (IPhoto item)
{
Add (item, item.DefaultVersion.Uri.LocalPath);
}
public int Add (IPhoto item, string path)
{
if (item == null)
Log.Warning ("NO PHOTO");
return Gallery.AddItem (this,
path,
Path.GetFileName (item.DefaultVersion.Uri.LocalPath),
item.Name,
item.Description,
true);
}
public string GetUrl ()
{
return Gallery.GetAlbumUrl(this);
}
public int CompareTo (Object obj)
{
Album other = obj as Album;
int numThis = this.Parents.Count;
int numOther = other.Parents.Count;
int thisVal = -1, otherVal = -1;
//find where they first differ
int maxIters = Math.Min (numThis, numOther);
int i = 0;
while (i < maxIters) {
thisVal = (int)this.Parents[i];
otherVal = (int)other.Parents[i];
if (thisVal != otherVal) {
break;
}
i++;
}
int retVal;
if (i < numThis && i < numOther) {
//Parentage differed
retVal = thisVal.CompareTo (otherVal);
} else if (i < numThis) {
//other shorter
thisVal = (int)this.Parents[i];
retVal = thisVal.CompareTo (other.RefNum);
//if equal, we want to make the shorter one come first
if (retVal == 0)
retVal = 1;
} else if (i < numOther) {
//this shorter
otherVal = (int)other.Parents[i];
retVal = this.RefNum.CompareTo (otherVal);
//if equal, we want to make the shorter one come first
if (retVal == 0)
retVal = -1;
} else {
//children of the same parent
retVal = this.RefNum.CompareTo (other.RefNum);
}
return retVal;
}
}
public class Image
{
public string Name;
public int RawWidth;
public int RawHeight;
public string ResizedName;
public int ResizedWidth;
public int ResizedHeight;
public string ThumbName;
public int ThumbWidth;
public int ThumbHeight;
public int RawFilesize;
public string Caption;
public string Description;
public int Clicks;
public Album Owner;
public string Url;
public Image (Album album, string name) {
Name = name;
Owner = album;
}
}
public enum ResultCode {
Success = 0,
MajorVersionInvalid = 101,
MajorMinorVersionInvalid = 102,
VersionFormatInvalid = 103,
VersionMissing = 104,
PasswordWrong = 201,
LoginMissing = 202,
UnknownComand = 301,
NoAddPermission = 401,
NoFilename = 402,
UploadPhotoFailed = 403,
NoWritePermission = 404,
NoCreateAlbumPermission = 501,
CreateAlbumFailed = 502,
// This result is specific to this implementation
UnknownResponse = 1000
}
public enum GalleryVersion : byte
{
VersionUnknown = 0,
Version1 = 1,
Version2 = 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.
using System.Buffers;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
public partial class FileStream : Stream
{
// This is an internal object extending TaskCompletionSource with fields
// for all of the relevant data necessary to complete the IO operation.
// This is used by IOCallback and all of the async methods.
private unsafe class FileStreamCompletionSource : TaskCompletionSource<int>
{
private const long NoResult = 0;
private const long ResultSuccess = (long)1 << 32;
private const long ResultError = (long)2 << 32;
private const long RegisteringCancellation = (long)4 << 32;
private const long CompletedCallback = (long)8 << 32;
private const ulong ResultMask = ((ulong)uint.MaxValue) << 32;
private static Action<object?>? s_cancelCallback;
private readonly FileStream _stream;
private readonly int _numBufferedBytes;
private CancellationTokenRegistration _cancellationRegistration;
#if DEBUG
private bool _cancellationHasBeenRegistered;
#endif
private NativeOverlapped* _overlapped; // Overlapped class responsible for operations in progress when an appdomain unload occurs
private long _result; // Using long since this needs to be used in Interlocked APIs
// Using RunContinuationsAsynchronously for compat reasons (old API used Task.Factory.StartNew for continuations)
protected FileStreamCompletionSource(FileStream stream, int numBufferedBytes, byte[]? bytes)
: base(TaskCreationOptions.RunContinuationsAsynchronously)
{
_numBufferedBytes = numBufferedBytes;
_stream = stream;
_result = NoResult;
// Create the native overlapped. We try to use the preallocated overlapped if possible: it's possible if the byte
// buffer is null (there's nothing to pin) or the same one that's associated with the preallocated overlapped (and
// thus is already pinned) and if no one else is currently using the preallocated overlapped. This is the fast-path
// for cases where the user-provided buffer is smaller than the FileStream's buffer (such that the FileStream's
// buffer is used) and where operations on the FileStream are not being performed concurrently.
Debug.Assert(bytes == null || ReferenceEquals(bytes, _stream._buffer));
// The _preallocatedOverlapped is null if the internal buffer was never created, so we check for
// a non-null bytes before using the stream's _preallocatedOverlapped
_overlapped = bytes != null && _stream.CompareExchangeCurrentOverlappedOwner(this, null) == null ?
_stream._fileHandle.ThreadPoolBinding!.AllocateNativeOverlapped(_stream._preallocatedOverlapped!) : // allocated when buffer was created, and buffer is non-null
_stream._fileHandle.ThreadPoolBinding!.AllocateNativeOverlapped(s_ioCallback, this, bytes);
Debug.Assert(_overlapped != null, "AllocateNativeOverlapped returned null");
}
internal NativeOverlapped* Overlapped => _overlapped;
public void SetCompletedSynchronously(int numBytes)
{
ReleaseNativeResource();
TrySetResult(numBytes + _numBufferedBytes);
}
public void RegisterForCancellation(CancellationToken cancellationToken)
{
#if DEBUG
Debug.Assert(cancellationToken.CanBeCanceled);
Debug.Assert(!_cancellationHasBeenRegistered, "Cannot register for cancellation twice");
_cancellationHasBeenRegistered = true;
#endif
// Quick check to make sure the IO hasn't completed
if (_overlapped != null)
{
Action<object?>? cancelCallback = s_cancelCallback ??= Cancel;
// Register the cancellation only if the IO hasn't completed
long packedResult = Interlocked.CompareExchange(ref _result, RegisteringCancellation, NoResult);
if (packedResult == NoResult)
{
_cancellationRegistration = cancellationToken.UnsafeRegister(cancelCallback, this);
// Switch the result, just in case IO completed while we were setting the registration
packedResult = Interlocked.Exchange(ref _result, NoResult);
}
else if (packedResult != CompletedCallback)
{
// Failed to set the result, IO is in the process of completing
// Attempt to take the packed result
packedResult = Interlocked.Exchange(ref _result, NoResult);
}
// If we have a callback that needs to be completed
if ((packedResult != NoResult) && (packedResult != CompletedCallback) && (packedResult != RegisteringCancellation))
{
CompleteCallback((ulong)packedResult);
}
}
}
internal virtual void ReleaseNativeResource()
{
// Ensure that cancellation has been completed and cleaned up.
_cancellationRegistration.Dispose();
// Free the overlapped.
// NOTE: The cancellation must *NOT* be running at this point, or it may observe freed memory
// (this is why we disposed the registration above).
if (_overlapped != null)
{
_stream._fileHandle.ThreadPoolBinding!.FreeNativeOverlapped(_overlapped);
_overlapped = null;
}
// Ensure we're no longer set as the current completion source (we may not have been to begin with).
// Only one operation at a time is eligible to use the preallocated overlapped,
_stream.CompareExchangeCurrentOverlappedOwner(null, this);
}
// When doing IO asynchronously (i.e. _isAsync==true), this callback is
// called by a free thread in the threadpool when the IO operation
// completes.
internal static void IOCallback(uint errorCode, uint numBytes, NativeOverlapped* pOverlapped)
{
// Extract the completion source from the overlapped. The state in the overlapped
// will either be a FileStream (in the case where the preallocated overlapped was used),
// in which case the operation being completed is its _currentOverlappedOwner, or it'll
// be directly the FileStreamCompletionSource that's completing (in the case where the preallocated
// overlapped was already in use by another operation).
object? state = ThreadPoolBoundHandle.GetNativeOverlappedState(pOverlapped);
Debug.Assert(state is FileStream || state is FileStreamCompletionSource);
FileStreamCompletionSource completionSource = state is FileStream fs ?
fs._currentOverlappedOwner! : // must be owned
(FileStreamCompletionSource)state!;
Debug.Assert(completionSource != null);
Debug.Assert(completionSource._overlapped == pOverlapped, "Overlaps don't match");
// Handle reading from & writing to closed pipes. While I'm not sure
// this is entirely necessary anymore, maybe it's possible for
// an async read on a pipe to be issued and then the pipe is closed,
// returning this error. This may very well be necessary.
ulong packedResult;
if (errorCode != 0 && errorCode != ERROR_BROKEN_PIPE && errorCode != ERROR_NO_DATA)
{
packedResult = ((ulong)ResultError | errorCode);
}
else
{
packedResult = ((ulong)ResultSuccess | numBytes);
}
// Stow the result so that other threads can observe it
// And, if no other thread is registering cancellation, continue
if (NoResult == Interlocked.Exchange(ref completionSource._result, (long)packedResult))
{
// Successfully set the state, attempt to take back the callback
if (Interlocked.Exchange(ref completionSource._result, CompletedCallback) != NoResult)
{
// Successfully got the callback, finish the callback
completionSource.CompleteCallback(packedResult);
}
// else: Some other thread stole the result, so now it is responsible to finish the callback
}
// else: Some other thread is registering a cancellation, so it *must* finish the callback
}
private void CompleteCallback(ulong packedResult)
{
// Free up the native resource and cancellation registration
CancellationToken cancellationToken = _cancellationRegistration.Token; // access before disposing registration
ReleaseNativeResource();
// Unpack the result and send it to the user
long result = (long)(packedResult & ResultMask);
if (result == ResultError)
{
int errorCode = unchecked((int)(packedResult & uint.MaxValue));
if (errorCode == Interop.Errors.ERROR_OPERATION_ABORTED)
{
TrySetCanceled(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true));
}
else
{
Exception e = Win32Marshal.GetExceptionForWin32Error(errorCode);
e.SetCurrentStackTrace();
TrySetException(e);
}
}
else
{
Debug.Assert(result == ResultSuccess, "Unknown result");
TrySetResult((int)(packedResult & uint.MaxValue) + _numBufferedBytes);
}
}
private static void Cancel(object? state)
{
// WARNING: This may potentially be called under a lock (during cancellation registration)
Debug.Assert(state is FileStreamCompletionSource, "Unknown state passed to cancellation");
FileStreamCompletionSource completionSource = (FileStreamCompletionSource)state;
Debug.Assert(completionSource._overlapped != null && !completionSource.Task.IsCompleted, "IO should not have completed yet");
// If the handle is still valid, attempt to cancel the IO
if (!completionSource._stream._fileHandle.IsInvalid &&
!Interop.Kernel32.CancelIoEx(completionSource._stream._fileHandle, completionSource._overlapped))
{
int errorCode = Marshal.GetLastWin32Error();
// ERROR_NOT_FOUND is returned if CancelIoEx cannot find the request to cancel.
// This probably means that the IO operation has completed.
if (errorCode != Interop.Errors.ERROR_NOT_FOUND)
{
throw Win32Marshal.GetExceptionForWin32Error(errorCode);
}
}
}
public static FileStreamCompletionSource Create(FileStream stream, int numBufferedBytesRead, ReadOnlyMemory<byte> memory)
{
// If the memory passed in is the stream's internal buffer, we can use the base FileStreamCompletionSource,
// which has a PreAllocatedOverlapped with the memory already pinned. Otherwise, we use the derived
// MemoryFileStreamCompletionSource, which Retains the memory, which will result in less pinning in the case
// where the underlying memory is backed by pre-pinned buffers.
return MemoryMarshal.TryGetArray(memory, out ArraySegment<byte> buffer) && ReferenceEquals(buffer.Array, stream._buffer) ?
new FileStreamCompletionSource(stream, numBufferedBytesRead, buffer.Array) :
new MemoryFileStreamCompletionSource(stream, numBufferedBytesRead, memory);
}
}
/// <summary>
/// Extends <see cref="FileStreamCompletionSource"/> with to support disposing of a
/// <see cref="MemoryHandle"/> when the operation has completed. This should only be used
/// when memory doesn't wrap a byte[].
/// </summary>
private sealed class MemoryFileStreamCompletionSource : FileStreamCompletionSource
{
private MemoryHandle _handle; // mutable struct; do not make this readonly
internal MemoryFileStreamCompletionSource(FileStream stream, int numBufferedBytes, ReadOnlyMemory<byte> memory) :
base(stream, numBufferedBytes, bytes: null) // this type handles the pinning, so null is passed for bytes
{
_handle = memory.Pin();
}
internal override void ReleaseNativeResource()
{
_handle.Dispose();
base.ReleaseNativeResource();
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using Edustructures.Metadata.DataElements;
using Edustructures.SifWorks;
namespace Edustructures.Metadata
{
/// <summary> Encapsulates a DataObject (<object>) or Infrastructure Message (<infra>) definition
/// *
/// *
/// </summary>
public class ObjectDef : AbstractDef
{
public const int FLAG_TOPICOBJECT = 0x00100000;
public const int FLAG_EMPTYOBJECT = 0x00200000;
public const int FLAG_INFRAOBJECT = 0x00400000;
internal Dictionary<String, FieldDef> fFields = new Dictionary<String, FieldDef>();
private int fFieldSeq = 1;
private string mPackage;
private string mSuperClass;
private string mExtrasFile;
private string mRenderAs;
/**
* If this object accepts a text value, holds the datatype of that value.
*/
private FieldType fValueType;
/// <summary> Gets the local package name where this object's class should be generated.
/// The local package name excludes the "com.edustructures.sifworks." prefix
/// </summary>
public virtual string LocalPackage
{
get { return mPackage; }
set { mPackage = value; }
}
/// <summary> Gets the name used to represent this object in the DTD class. A static
/// String is defined with this name, having a value equal to the string
/// returned by getName.
/// </summary>
public virtual string DTDSymbol
{
get { return Name.ToUpper(); }
}
/// <summary> Gets the element tag name
/// </summary>
public override string Name
{
get { return fName; }
}
public virtual string ExtrasFile
{
get { return mExtrasFile; }
set { mExtrasFile = value; }
}
public virtual string Superclass
{
get { return mSuperClass; }
set { mSuperClass = value; }
}
public virtual string RenderAs
{
get { return mRenderAs; }
set { mRenderAs = value; }
}
public virtual string fTag
{
get
{
if ( mRenderAs == null ) {
return fName;
}
return mRenderAs;
}
}
public virtual bool Empty
{
get { return (fFlags & FLAG_EMPTYOBJECT) != 0; }
}
/// <summary> Is this object a top-level SIF object such as StudentPersonal?
/// </summary>
/// <summary> Sets the topic flag
/// </summary>
public virtual bool Topic
{
get { return (fFlags & FLAG_TOPICOBJECT) != 0; }
set
{
if ( value ) {
fFlags |= FLAG_TOPICOBJECT;
}
else {
fFlags &= ~ FLAG_TOPICOBJECT;
}
}
}
/// <summary> Is this an <infra> object describing a SIF Infrastructure message?
/// </summary>
public virtual bool Infra
{
get { return (fFlags & FLAG_INFRAOBJECT) != 0; }
}
/// <summary> Does this object serve as the superclass for one or more subclasses?
/// </summary>
public virtual bool Shared
{
get { return fShared; }
set { fShared = value; }
}
public virtual FieldDef[] Fields
{
get
{
FieldDef[] arr = new FieldDef[fFields.Count];
fFields.Values.CopyTo( arr, 0 );
// Sort by sequence # first
Array.Sort( arr );
return arr;
}
}
public IDictionary GetAllFields()
{
return fFields;
}
public virtual FieldDef[] Attributes
{
get { return GetFields( FieldDef.FLAG_ATTRIBUTE ); }
}
public virtual FieldDef[] Elements
{
get { return GetFields( FieldDef.FLAG_ELEMENT ); }
}
/// <summary> Get all attributes and elements that are marked mandatory (M) or
/// required (R)
/// </summary>
public virtual FieldDef[] MandatoryFields
{
get { return GetFields( FLAG_MANDATORY | FLAG_REQUIRED ); }
}
/// <summary> For complex fields, returns the names of the fields that serve as the
/// object's key. By default this method returns all attributes marked with
/// an "R" flag (and if no attributes exist or none are marked with an "R"
/// flag, returns all elements marked with an "R" flag).
/// </summary>
public virtual FieldDef[] Key
{
get
{
ArrayList v = new ArrayList();
FieldDef[] attrs = Attributes;
int loop = 0;
while ( attrs != null ) {
for ( int i = 0; i < attrs.Length; i++ ) {
int f = attrs[i].Flags;
if ( ((f & FLAG_REQUIRED) != 0 || (f & FLAG_MANDATORY) != 0) &&
((f & FieldDef.FLAG_NOT_A_KEY) == 0) ) {
v.Add( attrs[i] );
}
}
// There are a few inconsistencies in the SIF schema such that some
// objects' keys are described by elements, not attributes. So, if we
// get here and have no keys, loop again processing element fields
// instead of attribute fields.
//
if ( v.Count == 0 && loop == 0 ) {
attrs = Elements;
}
else {
attrs = null;
}
loop++;
}
FieldDef[] arr = new FieldDef[v.Count];
v.CopyTo( arr );
Array.Sort( arr );
return arr;
}
}
/// <summary> The shared flag indicates this object serves as the superclass for
/// one or more sub-classes. For example, "CountryOfResidency" uses "Country"
/// as its superclass, so the "Country" object is marked as shared in the
/// definition file.
/// </summary>
private bool fShared;
/// <summary> Constructor
/// </summary>
/// <param name="id">Sequence number of this object
/// </param>
/// <param name="name">Element name (e.g. "StudentPersonal", "OtherId", etc.)
/// </param>
/// <param name="localPackage">Package name (e.g. "common", "student", "food", etc.)
/// </param>
/// <param name="version">Version of SIF this object is being defined for
///
/// </param>
public ObjectDef( int id,
string name,
string srcLocation,
string localPackage,
SifVersion version )
: base( name )
{
this.SourceLocation = srcLocation;
this.LocalPackage = localPackage;
//this.LatestVersion =
}
/// <summary> Indicates this is an <infra> object describing a SIF Infrastructure message
/// </summary>
public virtual void setInfra()
{
fFlags |= FLAG_INFRAOBJECT;
}
public virtual FieldDef DefineAttr( string name,
string classType )
{
return DefineAttrOrElement( name, classType, FieldDef.FLAG_ATTRIBUTE );
}
public virtual FieldDef DefineElement( string name,
string classType )
{
return DefineAttrOrElement( name, classType, FieldDef.FLAG_ELEMENT );
}
private FieldDef DefineAttrOrElement( string name,
string classType,
int type )
{
FieldDef def = null;
if ( fFields.ContainsKey( name ) ) {
def = fFields[name];
}
else {
def = new FieldDef( this, name, classType, fFieldSeq++, type );
fFields[name] = def;
}
return def;
}
public virtual FieldDef GetField( string name )
{
if ( fFields.ContainsKey( name ) ) {
return (FieldDef) fFields[name];
}
return null;
}
public String PackageQualifiedDTDSymbol
{
get { return PackageDTDName + "." + DTDSymbol; }
}
public String PackageDTDName
{
get { return mPackage.Substring( 0, 1 ).ToUpper() + mPackage.Substring( 1 ) + "DTD"; }
}
public void SetEnumType( string enumType )
{
fValueType = FieldType.ToEnumType( FieldType.GetFieldType( "String" ), enumType );
}
private FieldDef[] GetFields( int flags )
{
ArrayList v = new ArrayList();
foreach ( FieldDef f in fFields.Values ) {
if ( (f.Flags & flags) != 0 ) {
v.Add( f );
}
}
if ( (flags & FLAG_MANDATORY) != 0 ) {
FieldDef valueDef = GetValueDef();
if ( valueDef != null ) {
v.Add( valueDef );
}
}
FieldDef[] arr = new FieldDef[v.Count];
v.CopyTo( arr );
Array.Sort( arr );
return arr;
}
public FieldDef GetValueDef()
{
FieldDef returnValue = null;
FieldType valueType = GetValueType();
if ( valueType != null ) {
try {
returnValue =
new FieldDef
( this, "Value", valueType, 999,
FieldDef.FLAG_TEXT_VALUE | FLAG_MANDATORY );
}
catch ( ParseException parseEx ) {
Console.WriteLine( parseEx );
throw parseEx;
}
returnValue.Desc = "Gets or sets the content value of the <" + this.fName +
"> element";
returnValue.EarliestVersion = this.EarliestVersion;
returnValue.LatestVersion = this.LatestVersion;
// returnValue.ElementDefConst = this.PackageQualifiedDTDSymbol;
}
return returnValue;
}
/**
* Does this element have a text value?
* @return true if this element has no elements or attributes, or it has
* no elements but at least one attribute and the FLAG_EMPTYOBJECT flag
*
* is not set
*/
public FieldType GetValueType()
{
if ( fValueType == null ) {
if ( (fFlags & FLAG_EMPTYOBJECT) == 0 ) {
if ( fFields == null || fFields.Count == 0 || GetElements().Length == 0 ) {
fValueType = FieldType.GetFieldType( "String" );
}
}
}
return fValueType;
}
/// <summary>
/// If this this object accepts an element value the datatype of that
/// value is set in the metadata using a "datatype" element/// </summary>
/// <param name="dataType"></param>
public void SetDataType( String dataType )
{
fValueType = FieldType.GetFieldType( dataType );
}
/// <summary>
/// Does this element have a text value?
/// </summary>
/// <returns>true if this element has no elements or attributes, or it has
/// no elements but at least one attribute and the FLAG_EMPTYOBJECT flag
/// is not set</returns>
public FieldType ValueType
{
get
{
if ( fValueType == null ) {
if ( (fFlags & FLAG_EMPTYOBJECT) == 0 ) {
if ( fFields == null || fFields.Count == 0 || GetElements().Length == 0 ) {
fValueType = FieldType.GetFieldType( "String" );
}
}
}
return fValueType;
}
}
public FieldDef[] GetElements()
{
return GetFields( FieldDef.FLAG_ELEMENT );
}
}
}
| |
//
// TypeDefinitionCollection.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// Generated by /CodeGen/cecil-gen.rb do not edit
// Fri Mar 30 18:43:56 +0200 2007
//
// (C) 2005 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
namespace Mono.Cecil {
using System;
using System.Collections;
using System.Collections.Specialized;
using Mono.Cecil.Cil;
using Hcp = Mono.Cecil.HashCodeProvider;
using Cmp = System.Collections.Comparer;
public sealed class TypeDefinitionCollection : NameObjectCollectionBase, IList, IReflectionVisitable {
ModuleDefinition m_container;
public TypeDefinition this [int index] {
get { return this.BaseGet (index) as TypeDefinition; }
set { this.BaseSet (index, value); }
}
public TypeDefinition this [string fullName] {
get { return this.BaseGet (fullName) as TypeDefinition; }
set { this.BaseSet (fullName, value); }
}
public ModuleDefinition Container {
get { return m_container; }
}
public bool IsSynchronized {
get { return false; }
}
public object SyncRoot {
get { return this; }
}
bool IList.IsReadOnly {
get { return false; }
}
bool IList.IsFixedSize {
get { return false; }
}
object IList.this [int index] {
get { return BaseGet (index); }
set {
Check (value);
BaseSet (index, value);
}
}
public TypeDefinitionCollection (ModuleDefinition container) :
base (Hcp.Instance, Cmp.Default)
{
m_container = container;
}
public void Add (TypeDefinition value)
{
if (value == null)
throw new ArgumentNullException ("value");
Attach (value);
this.BaseAdd (value.FullName, value);
}
public void Clear ()
{
foreach (TypeDefinition item in this)
Detach (item);
this.BaseClear ();
}
public bool Contains (TypeDefinition value)
{
return Contains (value.FullName);
}
public bool Contains (string fullName)
{
return this.BaseGet (fullName) != null;
}
public int IndexOf (TypeDefinition value)
{
string [] keys = this.BaseGetAllKeys ();
return Array.IndexOf (keys, value.FullName, 0, keys.Length);
}
public void Remove (TypeDefinition value)
{
this.BaseRemove (value.FullName);
Detach (value);
}
public void RemoveAt (int index)
{
TypeDefinition item = this [index];
Remove (item);
Detach (item);
}
public void CopyTo (Array ary, int index)
{
this.BaseGetAllValues ().CopyTo (ary, index);
}
public new IEnumerator GetEnumerator ()
{
return this.BaseGetAllValues ().GetEnumerator ();
}
public void Accept (IReflectionVisitor visitor)
{
visitor.VisitTypeDefinitionCollection (this);
}
#if CF_1_0 || CF_2_0
internal object [] BaseGetAllValues ()
{
object [] values = new object [this.Count];
for (int i=0; i < values.Length; ++i) {
values [i] = this.BaseGet (i);
}
return values;
}
#endif
void Check (object value)
{
if (!(value is TypeDefinition))
throw new ArgumentException ();
}
int IList.Add (object value)
{
Check (value);
Add (value as TypeDefinition);
return 0;
}
bool IList.Contains (object value)
{
Check (value);
return Contains (value as TypeDefinition);
}
int IList.IndexOf (object value)
{
throw new NotSupportedException ();
}
void IList.Insert (int index, object value)
{
throw new NotSupportedException ();
}
void IList.Remove (object value)
{
Check (value);
Remove (value as TypeDefinition);
}
void Detach (TypeReference type)
{
type.Module = null;
}
void Attach (TypeReference type)
{
if (type.Module != null)
throw new ReflectionException ("Type is already attached, clone it instead");
type.Module = m_container;
type.AttachToScope (m_container);
}
}
}
| |
using System;
using System.IO;
using System.Text;
using Raksha.Asn1;
using Raksha.Asn1.X509;
using Raksha.Crypto;
using Raksha.Utilities;
using Raksha.X509;
namespace Raksha.Pkix
{
/// <summary>
/// A trust anchor or most-trusted Certification Authority (CA).
///
/// This class represents a "most-trusted CA", which is used as a trust anchor
/// for validating X.509 certification paths. A most-trusted CA includes the
/// public key of the CA, the CA's name, and any constraints upon the set of
/// paths which may be validated using this key. These parameters can be
/// specified in the form of a trusted X509Certificate or as individual
/// parameters.
/// </summary>
public class TrustAnchor
{
private readonly AsymmetricKeyParameter pubKey;
private readonly string caName;
private readonly X509Name caPrincipal;
private readonly X509Certificate trustedCert;
private byte[] ncBytes;
private NameConstraints nc;
/// <summary>
/// Creates an instance of TrustAnchor with the specified X509Certificate and
/// optional name constraints, which are intended to be used as additional
/// constraints when validating an X.509 certification path.
/// The name constraints are specified as a byte array. This byte array
/// should contain the DER encoded form of the name constraints, as they
/// would appear in the NameConstraints structure defined in RFC 2459 and
/// X.509. The ASN.1 definition of this structure appears below.
///
/// <pre>
/// NameConstraints ::= SEQUENCE {
/// permittedSubtrees [0] GeneralSubtrees OPTIONAL,
/// excludedSubtrees [1] GeneralSubtrees OPTIONAL }
///
/// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
///
/// GeneralSubtree ::= SEQUENCE {
/// base GeneralName,
/// minimum [0] BaseDistance DEFAULT 0,
/// maximum [1] BaseDistance OPTIONAL }
///
/// BaseDistance ::= INTEGER (0..MAX)
///
/// GeneralName ::= CHOICE {
/// otherName [0] OtherName,
/// rfc822Name [1] IA5String,
/// dNSName [2] IA5String,
/// x400Address [3] ORAddress,
/// directoryName [4] Name,
/// ediPartyName [5] EDIPartyName,
/// uniformResourceIdentifier [6] IA5String,
/// iPAddress [7] OCTET STRING,
/// registeredID [8] OBJECT IDENTIFIER}
/// </pre>
///
/// Note that the name constraints byte array supplied is cloned to protect
/// against subsequent modifications.
/// </summary>
/// <param name="trustedCert">a trusted X509Certificate</param>
/// <param name="nameConstraints">a byte array containing the ASN.1 DER encoding of a
/// NameConstraints extension to be used for checking name
/// constraints. Only the value of the extension is included, not
/// the OID or criticality flag. Specify null to omit the
/// parameter.</param>
/// <exception cref="ArgumentNullException">if the specified X509Certificate is null</exception>
public TrustAnchor(
X509Certificate trustedCert,
byte[] nameConstraints)
{
if (trustedCert == null)
throw new ArgumentNullException("trustedCert");
this.trustedCert = trustedCert;
this.pubKey = null;
this.caName = null;
this.caPrincipal = null;
setNameConstraints(nameConstraints);
}
/// <summary>
/// Creates an instance of <c>TrustAnchor</c> where the
/// most-trusted CA is specified as an X500Principal and public key.
/// </summary>
/// <remarks>
/// <p>
/// Name constraints are an optional parameter, and are intended to be used
/// as additional constraints when validating an X.509 certification path.
/// </p><p>
/// The name constraints are specified as a byte array. This byte array
/// contains the DER encoded form of the name constraints, as they
/// would appear in the NameConstraints structure defined in RFC 2459
/// and X.509. The ASN.1 notation for this structure is supplied in the
/// documentation for the other constructors.
/// </p><p>
/// Note that the name constraints byte array supplied here is cloned to
/// protect against subsequent modifications.
/// </p>
/// </remarks>
/// <param name="caPrincipal">the name of the most-trusted CA as X509Name</param>
/// <param name="pubKey">the public key of the most-trusted CA</param>
/// <param name="nameConstraints">
/// a byte array containing the ASN.1 DER encoding of a NameConstraints extension to
/// be used for checking name constraints. Only the value of the extension is included,
/// not the OID or criticality flag. Specify <c>null</c> to omit the parameter.
/// </param>
/// <exception cref="ArgumentNullException">
/// if <c>caPrincipal</c> or <c>pubKey</c> is null
/// </exception>
public TrustAnchor(
X509Name caPrincipal,
AsymmetricKeyParameter pubKey,
byte[] nameConstraints)
{
if (caPrincipal == null)
throw new ArgumentNullException("caPrincipal");
if (pubKey == null)
throw new ArgumentNullException("pubKey");
this.trustedCert = null;
this.caPrincipal = caPrincipal;
this.caName = caPrincipal.ToString();
this.pubKey = pubKey;
setNameConstraints(nameConstraints);
}
/// <summary>
/// Creates an instance of <code>TrustAnchor</code> where the most-trusted
/// CA is specified as a distinguished name and public key. Name constraints
/// are an optional parameter, and are intended to be used as additional
/// constraints when validating an X.509 certification path.
/// <br/>
/// The name constraints are specified as a byte array. This byte array
/// contains the DER encoded form of the name constraints, as they would
/// appear in the NameConstraints structure defined in RFC 2459 and X.509.
/// </summary>
/// <param name="caName">the X.500 distinguished name of the most-trusted CA in RFC
/// 2253 string format</param>
/// <param name="pubKey">the public key of the most-trusted CA</param>
/// <param name="nameConstraints">a byte array containing the ASN.1 DER encoding of a
/// NameConstraints extension to be used for checking name
/// constraints. Only the value of the extension is included, not
/// the OID or criticality flag. Specify null to omit the
/// parameter.</param>
/// throws NullPointerException, IllegalArgumentException
public TrustAnchor(
string caName,
AsymmetricKeyParameter pubKey,
byte[] nameConstraints)
{
if (caName == null)
throw new ArgumentNullException("caName");
if (pubKey == null)
throw new ArgumentNullException("pubKey");
if (caName.Length == 0)
throw new ArgumentException("caName can not be an empty string");
this.caPrincipal = new X509Name(caName);
this.pubKey = pubKey;
this.caName = caName;
this.trustedCert = null;
setNameConstraints(nameConstraints);
}
/// <summary>
/// Returns the most-trusted CA certificate.
/// </summary>
public X509Certificate TrustedCert
{
get { return this.trustedCert; }
}
/// <summary>
/// Returns the name of the most-trusted CA as an X509Name.
/// </summary>
public X509Name CA
{
get { return this.caPrincipal; }
}
/// <summary>
/// Returns the name of the most-trusted CA in RFC 2253 string format.
/// </summary>
public string CAName
{
get { return this.caName; }
}
/// <summary>
/// Returns the public key of the most-trusted CA.
/// </summary>
public AsymmetricKeyParameter CAPublicKey
{
get { return this.pubKey; }
}
/// <summary>
/// Decode the name constraints and clone them if not null.
/// </summary>
private void setNameConstraints(
byte[] bytes)
{
if (bytes == null)
{
ncBytes = null;
nc = null;
}
else
{
ncBytes = (byte[]) bytes.Clone();
// validate DER encoding
//nc = new NameConstraintsExtension(Boolean.FALSE, bytes);
nc = NameConstraints.GetInstance(Asn1Object.FromByteArray(bytes));
}
}
public byte[] GetNameConstraints
{
get { return Arrays.Clone(ncBytes); }
}
/// <summary>
/// Returns a formatted string describing the <code>TrustAnchor</code>.
/// </summary>
/// <returns>a formatted string describing the <code>TrustAnchor</code></returns>
public override string ToString()
{
// TODO Some of the sub-objects might not implement ToString() properly
string nl = Platform.NewLine;
StringBuilder sb = new StringBuilder();
sb.Append("[");
sb.Append(nl);
if (this.pubKey != null)
{
sb.Append(" Trusted CA Public Key: ").Append(this.pubKey).Append(nl);
sb.Append(" Trusted CA Issuer Name: ").Append(this.caName).Append(nl);
}
else
{
sb.Append(" Trusted CA cert: ").Append(this.TrustedCert).Append(nl);
}
if (nc != null)
{
sb.Append(" Name Constraints: ").Append(nc).Append(nl);
}
return sb.ToString();
}
}
}
| |
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Apis.Oauth2.v2
{
/// <summary>The Oauth2 Service.</summary>
public class Oauth2Service : Google.Apis.Services.BaseClientService
{
/// <summary>The API version.</summary>
public const string Version = "v2";
/// <summary>The discovery version used to generate this service.</summary>
public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0;
/// <summary>Constructs a new service.</summary>
public Oauth2Service() : this(new Google.Apis.Services.BaseClientService.Initializer())
{
}
/// <summary>Constructs a new service.</summary>
/// <param name="initializer">The service initializer.</param>
public Oauth2Service(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer)
{
Userinfo = new UserinfoResource(this);
}
/// <summary>Gets the service supported features.</summary>
public override System.Collections.Generic.IList<string> Features => new string[0];
/// <summary>Gets the service name.</summary>
public override string Name => "oauth2";
/// <summary>Gets the service base URI.</summary>
public override string BaseUri =>
#if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45
BaseUriOverride ?? "https://www.googleapis.com/";
#else
"https://www.googleapis.com/";
#endif
/// <summary>Gets the service base path.</summary>
public override string BasePath => "";
#if !NET40
/// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary>
public override string BatchUri => "https://www.googleapis.com/batch/oauth2/v2";
/// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary>
public override string BatchPath => "batch/oauth2/v2";
#endif
/// <summary>Available OAuth 2.0 scopes for use with the Google OAuth2 API.</summary>
public class Scope
{
/// <summary>View your email address</summary>
public static string UserinfoEmail = "https://www.googleapis.com/auth/userinfo.email";
/// <summary>See your personal info, including any personal info you've made publicly available</summary>
public static string UserinfoProfile = "https://www.googleapis.com/auth/userinfo.profile";
/// <summary>Associate you with your personal info on Google</summary>
public static string Openid = "openid";
}
/// <summary>Available OAuth 2.0 scope constants for use with the Google OAuth2 API.</summary>
public static class ScopeConstants
{
/// <summary>View your email address</summary>
public const string UserinfoEmail = "https://www.googleapis.com/auth/userinfo.email";
/// <summary>See your personal info, including any personal info you've made publicly available</summary>
public const string UserinfoProfile = "https://www.googleapis.com/auth/userinfo.profile";
/// <summary>Associate you with your personal info on Google</summary>
public const string Openid = "openid";
}
public virtual TokeninfoRequest Tokeninfo()
{
return new TokeninfoRequest(this);
}
public class TokeninfoRequest : Oauth2BaseServiceRequest<Google.Apis.Oauth2.v2.Data.Tokeninfo>
{
/// <summary>Constructs a new Tokeninfo request.</summary>
public TokeninfoRequest(Google.Apis.Services.IClientService service) : base(service)
{
InitParameters();
}
[Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string AccessToken { get; set; }
[Google.Apis.Util.RequestParameterAttribute("id_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string IdToken { get; set; }
/// <summary>Gets the method name.</summary>
public override string MethodName => "tokeninfo";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "POST";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "oauth2/v2/tokeninfo";
/// <summary>Initializes Tokeninfo parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter
{
Name = "access_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("id_token", new Google.Apis.Discovery.Parameter
{
Name = "id_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>Gets the Userinfo resource.</summary>
public virtual UserinfoResource Userinfo { get; }
}
/// <summary>A base abstract class for Oauth2 requests.</summary>
public abstract class Oauth2BaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse>
{
/// <summary>Constructs a new Oauth2BaseServiceRequest instance.</summary>
protected Oauth2BaseServiceRequest(Google.Apis.Services.IClientService service) : base(service)
{
}
/// <summary>Data format for the response.</summary>
[Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<AltEnum> Alt { get; set; }
/// <summary>Data format for the response.</summary>
public enum AltEnum
{
/// <summary>Responses with Content-Type of application/json</summary>
[Google.Apis.Util.StringValueAttribute("json")]
Json = 0,
}
/// <summary>Selector specifying which fields to include in a partial response.</summary>
[Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Fields { get; set; }
/// <summary>
/// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required
/// unless you provide an OAuth 2.0 token.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)]
public virtual string Key { get; set; }
/// <summary>OAuth 2.0 token for the current user.</summary>
[Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)]
public virtual string OauthToken { get; set; }
/// <summary>Returns response with indentations and line breaks.</summary>
[Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)]
public virtual System.Nullable<bool> PrettyPrint { get; set; }
/// <summary>
/// An opaque string that represents a user for quota purposes. Must not exceed 40 characters.
/// </summary>
[Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)]
public virtual string QuotaUser { get; set; }
/// <summary>Deprecated. Please use quotaUser instead.</summary>
[Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)]
public virtual string UserIp { get; set; }
/// <summary>Initializes Oauth2 parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter
{
Name = "alt",
IsRequired = false,
ParameterType = "query",
DefaultValue = "json",
Pattern = null,
});
RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter
{
Name = "fields",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("key", new Google.Apis.Discovery.Parameter
{
Name = "key",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter
{
Name = "oauth_token",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter
{
Name = "prettyPrint",
IsRequired = false,
ParameterType = "query",
DefaultValue = "true",
Pattern = null,
});
RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter
{
Name = "quotaUser",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
RequestParameters.Add("userIp", new Google.Apis.Discovery.Parameter
{
Name = "userIp",
IsRequired = false,
ParameterType = "query",
DefaultValue = null,
Pattern = null,
});
}
}
/// <summary>The "userinfo" collection of methods.</summary>
public class UserinfoResource
{
private const string Resource = "userinfo";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public UserinfoResource(Google.Apis.Services.IClientService service)
{
this.service = service;
V2 = new V2Resource(service);
}
/// <summary>Gets the V2 resource.</summary>
public virtual V2Resource V2 { get; }
/// <summary>The "v2" collection of methods.</summary>
public class V2Resource
{
private const string Resource = "v2";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public V2Resource(Google.Apis.Services.IClientService service)
{
this.service = service;
Me = new MeResource(service);
}
/// <summary>Gets the Me resource.</summary>
public virtual MeResource Me { get; }
/// <summary>The "me" collection of methods.</summary>
public class MeResource
{
private const string Resource = "me";
/// <summary>The service which this resource belongs to.</summary>
private readonly Google.Apis.Services.IClientService service;
/// <summary>Constructs a new resource.</summary>
public MeResource(Google.Apis.Services.IClientService service)
{
this.service = service;
}
public virtual GetRequest Get()
{
return new GetRequest(service);
}
public class GetRequest : Oauth2BaseServiceRequest<Google.Apis.Oauth2.v2.Data.Userinfo>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service) : base(service)
{
InitParameters();
}
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "userinfo/v2/me";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
}
public virtual GetRequest Get()
{
return new GetRequest(service);
}
public class GetRequest : Oauth2BaseServiceRequest<Google.Apis.Oauth2.v2.Data.Userinfo>
{
/// <summary>Constructs a new Get request.</summary>
public GetRequest(Google.Apis.Services.IClientService service) : base(service)
{
InitParameters();
}
/// <summary>Gets the method name.</summary>
public override string MethodName => "get";
/// <summary>Gets the HTTP method.</summary>
public override string HttpMethod => "GET";
/// <summary>Gets the REST path.</summary>
public override string RestPath => "oauth2/v2/userinfo";
/// <summary>Initializes Get parameter list.</summary>
protected override void InitParameters()
{
base.InitParameters();
}
}
}
}
namespace Google.Apis.Oauth2.v2.Data
{
public class Tokeninfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>Who is the intended audience for this token. In general the same as issued_to.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("audience")]
public virtual string Audience { get; set; }
/// <summary>The email address of the user. Present only if the email scope is present in the request.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("email")]
public virtual string Email { get; set; }
/// <summary>The expiry time of the token, as number of seconds left until expiry.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("expires_in")]
public virtual System.Nullable<int> ExpiresIn { get; set; }
/// <summary>To whom was the token issued to. In general the same as audience.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("issued_to")]
public virtual string IssuedTo { get; set; }
/// <summary>The space separated list of scopes granted to this token.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("scope")]
public virtual string Scope { get; set; }
/// <summary>The obfuscated user id.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("user_id")]
public virtual string UserId { get; set; }
/// <summary>
/// Boolean flag which is true if the email address is verified. Present only if the email scope is present in
/// the request.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("verified_email")]
public virtual System.Nullable<bool> VerifiedEmail { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
public class Userinfo : Google.Apis.Requests.IDirectResponseSchema
{
/// <summary>The user's email address.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("email")]
public virtual string Email { get; set; }
/// <summary>The user's last name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("family_name")]
public virtual string FamilyName { get; set; }
/// <summary>The user's gender.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("gender")]
public virtual string Gender { get; set; }
/// <summary>The user's first name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("given_name")]
public virtual string GivenName { get; set; }
/// <summary>The hosted domain e.g. example.com if the user is Google apps user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("hd")]
public virtual string Hd { get; set; }
/// <summary>The obfuscated ID of the user.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("id")]
public virtual string Id { get; set; }
/// <summary>URL of the profile page.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("link")]
public virtual string Link { get; set; }
/// <summary>The user's preferred locale.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("locale")]
public virtual string Locale { get; set; }
/// <summary>The user's full name.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("name")]
public virtual string Name { get; set; }
/// <summary>URL of the user's picture image.</summary>
[Newtonsoft.Json.JsonPropertyAttribute("picture")]
public virtual string Picture { get; set; }
/// <summary>
/// Boolean flag which is true if the email address is verified. Always verified because we only return the
/// user's primary email address.
/// </summary>
[Newtonsoft.Json.JsonPropertyAttribute("verified_email")]
public virtual System.Nullable<bool> VerifiedEmail { get; set; }
/// <summary>The ETag of the item.</summary>
public virtual string ETag { get; set; }
}
}
| |
#region License
// Copyright 2008-2009 Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
#region Nothing to see here...backwards compatibility hackery to follow
namespace FluentValidation.Validators {
using System;
using System.Collections.Generic;
using System.Linq;
using Attributes;
using Internal;
using Results;
[Obsolete("Generic versions of IPropertyValidator have been deprecated. Custom validators should inherit from the abstract base class FluentValidation.Validators.PropertyValidator")]
// ReSharper disable UnusedTypeParameter
public interface IPropertyValidator<T> {
// ReSharper restore UnusedTypeParameter
}
[Obsolete("Generic versions of IPropertyValidator have been deprecated. Custom validators should inherit from the abstract base class FluentValidation.Validators.PropertyValidator")]
public interface IPropertyValidator<TInstance, TProperty> : IPropertyValidator<TInstance> {
PropertyValidatorResult Validate(PropertyValidatorContext<TInstance, TProperty> context);
}
[Obsolete("The generic version of PropertyValidatorContext has been deprecated. Please use PropertyValidatorContext instead.")]
public class PropertyValidatorContext<T, TProperty> {
readonly Func<T, TProperty> propertyValueFunc;
bool propertyValueSet;
TProperty propertyValue;
readonly IEnumerable<Func<T, object>> customFormatArgs;
public TProperty PropertyValue {
get {
if (!propertyValueSet) {
propertyValue = propertyValueFunc(Instance);
propertyValueSet = true;
}
return propertyValue;
}
}
public string PropertyDescription { get; private set; }
public T Instance { get; private set; }
public string CustomError { get; private set; }
public PropertyValidatorContext(string propertyDescription, T instance, Func<T, TProperty> propertyValueFunc)
: this(propertyDescription, instance, propertyValueFunc, null, null) {
}
public PropertyValidatorContext(string propertyDescription, T instance, Func<T, TProperty> propertyValueFunc, string customError, IEnumerable<Func<T, object>> customFormatArgs) {
propertyValueFunc.Guard("propertyValueFunc cannot be null");
CustomError = customError;
PropertyDescription = propertyDescription;
Instance = instance;
this.customFormatArgs = customFormatArgs;
this.propertyValueFunc = propertyValueFunc;
}
public string GetFormattedErrorMessage(Type type, MessageFormatter formatter) {
string error = CustomError ?? ValidationMessageAttribute.GetMessage(type);
if (customFormatArgs != null) {
formatter.AppendAdditionalArguments(
customFormatArgs.Select(func => func(Instance)).ToArray()
);
}
return formatter.BuildMessage(error);
}
}
[Obsolete]
internal class BackwardsCompatibilityValidatorAdaptor<T, TProperty> : PropertyValidator {
readonly IPropertyValidator<T, TProperty> obsoleteValidator;
public BackwardsCompatibilityValidatorAdaptor(IPropertyValidator<T, TProperty> obsoleteValidator)
: base(null as string) {
this.obsoleteValidator = obsoleteValidator;
}
public override IEnumerable<ValidationFailure> Validate(PropertyValidatorContext context) {
Func<T, TProperty> propertyValueFunc = x => (TProperty)context.PropertyValueFunc(x);
IEnumerable<Func<T, object>> customMessageFormatArgs = ConvertNewFormatArgsToOldFormatArgs();
var obsoleteContext = new PropertyValidatorContext<T, TProperty>(context.PropertyDescription, (T)context.Instance, propertyValueFunc, ErrorMessageSource.BuildErrorMessage(), customMessageFormatArgs);
var oldResult = obsoleteValidator.Validate(obsoleteContext);
var results = new List<ValidationFailure>();
if (! oldResult.IsValid) {
var newResult = new ValidationFailure(context.PropertyName, oldResult.Error, context.PropertyValue);
results.Add(newResult);
}
return results;
}
IEnumerable<Func<T, object>> ConvertNewFormatArgsToOldFormatArgs() {
return CustomMessageFormatArguments.Select(func => new Func<T, object>(x => func(x))).ToList();
}
protected override bool IsValid(PropertyValidatorContext context) {
throw new NotImplementedException();
}
}
}
namespace FluentValidation {
using System;
using Internal;
using Results;
using Validators;
public static class ObsoleteExtensions {
[Obsolete("This method has a typo in its name. Please use AppendPropertyName instead.")]
public static MessageFormatter AppendProperyName(this MessageFormatter formatter, string name) {
return formatter.AppendPropertyName(name);
}
[Obsolete("The generic IPropertyValidator interface has been deprecated. Please modify your custom validators to inherit from the abstract base class FluentValidation.Validators.PropertyValidator.")]
public static IRuleBuilderOptions<T, TProperty> SetValidator<T,TProperty>(this IRuleBuilder<T, TProperty> rule, IPropertyValidator<T,TProperty> validator) {
return rule.SetValidator(new BackwardsCompatibilityValidatorAdaptor<T, TProperty>(validator));
}
public static ValidationResult Validate<T>(this IValidator<T> validator, T instance, IValidatorSelector selector) {
var context = new ValidationContext<T>(instance, new PropertyChain(), selector);
return validator.Validate(context);
}
}
}
namespace FluentValidation.Attributes {
using System;
using Internal;
using Resources;
[Obsolete("The ValidationMessage attribute has been deprecated. Your validators should now inherit from the abstract base class FluentValidation.Validators.PropertyValidator and specify the error message in the constructor.")]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class ValidationMessageAttribute : Attribute {
public string Key { get; set; }
public string Message { get; set; }
public static string GetMessage(Type type) {
var attribute = (ValidationMessageAttribute)GetCustomAttribute(type, typeof(ValidationMessageAttribute), false);
if (attribute == null) {
throw new InvalidOperationException(string.Format("Type '{0}' does does not declare a ValidationMessageAttribute.", type.Name));
}
if (string.IsNullOrEmpty(attribute.Key) && string.IsNullOrEmpty(attribute.Message)) {
throw new InvalidOperationException(string.Format("Type '{0}' declares a ValidationMessageAttribute but neither the Key nor Message are set.", type.Name));
}
if (!string.IsNullOrEmpty(attribute.Message)) {
return attribute.Message;
}
var accessor = ResourceHelper.BuildResourceAccessor(attribute.Key, ValidatorOptions.ResourceProviderType ?? typeof(Messages));
var message = accessor.Accessor();
if (message == null) {
throw new InvalidOperationException(string.Format("Could not find a resource key with the name '{0}'.", attribute.Key));
}
return message;
}
}
}
namespace FluentValidation.Results {
using System;
[Obsolete("PropertyValidatorResult is obsolete - custom validators should now inherit from FluentValidation.Validators.PropertyValidator")]
public class PropertyValidatorResult {
public PropertyValidatorResult(string error) {
Error = error;
}
public string Error { get; private set; }
public bool IsValid {
get { return Error == null; }
}
public static PropertyValidatorResult Success() {
return new PropertyValidatorResult(null);
}
public static PropertyValidatorResult Failure(string error) {
return new PropertyValidatorResult(error);
}
}
}
#endregion
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Umbraco.Core;
using Umbraco.Core.Models;
using Umbraco.Core.Models.EntityBase;
using Umbraco.Core.Models.Membership;
using Umbraco.Core.Models.Rdbms;
using Umbraco.Core.Persistence.Caching;
using Umbraco.Core.Persistence.Factories;
using Umbraco.Core.Persistence.Mappers;
using Umbraco.Core.Persistence.Querying;
using Umbraco.Core.Persistence.Relators;
using Umbraco.Core.Persistence.SqlSyntax;
using Umbraco.Core.Persistence.UnitOfWork;
namespace Umbraco.Core.Persistence.Repositories
{
/// <summary>
/// Represents the UserRepository for doing CRUD operations for <see cref="IUser"/>
/// </summary>
internal class UserRepository : PetaPocoRepositoryBase<int, IUser>, IUserRepository
{
private readonly IUserTypeRepository _userTypeRepository;
private readonly CacheHelper _cacheHelper;
public UserRepository(IDatabaseUnitOfWork work, IUserTypeRepository userTypeRepository, CacheHelper cacheHelper)
: base(work)
{
_userTypeRepository = userTypeRepository;
_cacheHelper = cacheHelper;
}
public UserRepository(IDatabaseUnitOfWork work, IRepositoryCacheProvider cache, IUserTypeRepository userTypeRepository, CacheHelper cacheHelper)
: base(work, cache)
{
_userTypeRepository = userTypeRepository;
_cacheHelper = cacheHelper;
}
#region Overrides of RepositoryBase<int,IUser>
protected override IUser PerformGet(int id)
{
var sql = GetBaseQuery(false);
sql.Where(GetBaseWhereClause(), new { Id = id });
var dto = Database.Fetch<UserDto, User2AppDto, UserDto>(new UserSectionRelator().Map, sql).FirstOrDefault();
if (dto == null)
return null;
var userType = _userTypeRepository.Get(dto.Type);
var userFactory = new UserFactory(userType);
var user = userFactory.BuildEntity(dto);
return user;
}
protected override IEnumerable<IUser> PerformGetAll(params int[] ids)
{
if (ids.Any())
{
return PerformGetAllOnIds(ids);
}
var sql = GetBaseQuery(false);
return ConvertFromDtos(Database.Fetch<UserDto, User2AppDto, UserDto>(new UserSectionRelator().Map, sql))
.ToArray(); // important so we don't iterate twice, if we don't do thsi we can end up with null vals in cache if we were caching.
}
private IEnumerable<IUser> PerformGetAllOnIds(params int[] ids)
{
if (ids.Any() == false) yield break;
foreach (var id in ids)
{
yield return Get(id);
}
}
protected override IEnumerable<IUser> PerformGetByQuery(IQuery<IUser> query)
{
var sqlClause = GetBaseQuery(false);
var translator = new SqlTranslator<IUser>(sqlClause, query);
var sql = translator.Translate();
var dtos = Database.Fetch<UserDto, User2AppDto, UserDto>(new UserSectionRelator().Map, sql);
foreach (var dto in dtos.DistinctBy(x => x.Id))
{
yield return Get(dto.Id);
}
}
#endregion
#region Overrides of PetaPocoRepositoryBase<int,IUser>
protected override Sql GetBaseQuery(bool isCount)
{
var sql = new Sql();
if (isCount)
{
sql.Select("COUNT(*)").From<UserDto>();
}
else
{
return GetBaseQuery("*");
}
return sql;
}
private static Sql GetBaseQuery(string columns)
{
var sql = new Sql();
sql.Select(columns)
.From<UserDto>()
.LeftJoin<User2AppDto>()
.On<UserDto, User2AppDto>(left => left.Id, right => right.UserId);
return sql;
}
protected override string GetBaseWhereClause()
{
return "umbracoUser.id = @Id";
}
protected override IEnumerable<string> GetDeleteClauses()
{
var list = new List<string>
{
"DELETE FROM cmsTask WHERE userId = @Id",
"DELETE FROM cmsTask WHERE parentUserId = @Id",
"DELETE FROM umbracoUser2NodePermission WHERE userId = @Id",
"DELETE FROM umbracoUser2NodeNotify WHERE userId = @Id",
"DELETE FROM umbracoUserLogins WHERE userID = @Id",
"DELETE FROM umbracoUser2app WHERE " + SqlSyntaxContext.SqlSyntaxProvider.GetQuotedColumnName("user") + "=@Id",
"DELETE FROM umbracoUser WHERE id = @Id"
};
return list;
}
protected override Guid NodeObjectTypeId
{
get { throw new NotImplementedException(); }
}
protected override void PersistNewItem(IUser entity)
{
var userFactory = new UserFactory(entity.UserType);
var userDto = userFactory.BuildDto(entity);
var id = Convert.ToInt32(Database.Insert(userDto));
entity.Id = id;
foreach (var sectionDto in userDto.User2AppDtos)
{
//need to set the id explicitly here
sectionDto.UserId = id;
Database.Insert(sectionDto);
}
((ICanBeDirty)entity).ResetDirtyProperties();
}
protected override void PersistUpdatedItem(IUser entity)
{
var userFactory = new UserFactory(entity.UserType);
var userDto = userFactory.BuildDto(entity);
var dirtyEntity = (ICanBeDirty)entity;
//build list of columns to check for saving - we don't want to save the password if it hasn't changed!
//List the columns to save, NOTE: would be nice to not have hard coded strings here but no real good way around that
var colsToSave = new Dictionary<string, string>()
{
{"userDisabled", "IsApproved"},
{"userNoConsole", "IsLockedOut"},
{"userType", "UserType"},
{"startStructureID", "StartContentId"},
{"startMediaID", "StartMediaId"},
{"userName", "Name"},
{"userLogin", "Username"},
{"userEmail", "Email"},
{"userLanguage", "Language"}
};
//create list of properties that have changed
var changedCols = colsToSave
.Where(col => dirtyEntity.IsPropertyDirty(col.Value))
.Select(col => col.Key)
.ToList();
// DO NOT update the password if it has not changed or if it is null or empty
if (dirtyEntity.IsPropertyDirty("RawPasswordValue") && entity.RawPasswordValue.IsNullOrWhiteSpace() == false)
{
changedCols.Add("userPassword");
}
//only update the changed cols
if (changedCols.Count > 0)
{
Database.Update(userDto, changedCols);
}
//update the sections if they've changed
var user = (User)entity;
if (user.IsPropertyDirty("AllowedSections"))
{
//now we need to delete any applications that have been removed
foreach (var section in user.RemovedSections)
{
//we need to manually delete thsi record because it has a composite key
Database.Delete<User2AppDto>("WHERE app=@Section AND " + SqlSyntaxContext.SqlSyntaxProvider.GetQuotedColumnName("user") + "=@UserId",
new { Section = section, UserId = (int)user.Id });
}
//for any that exist on the object, we need to determine if we need to update or insert
//NOTE: the User2AppDtos collection wil always be equal to the User.AllowedSections
foreach (var sectionDto in userDto.User2AppDtos)
{
//if something has been added then insert it
if (user.AddedSections.Contains(sectionDto.AppAlias))
{
//we need to insert since this was added
Database.Insert(sectionDto);
}
else
{
//we need to manually update this record because it has a composite key
Database.Update<User2AppDto>("SET app=@Section WHERE app=@Section AND " + SqlSyntaxContext.SqlSyntaxProvider.GetQuotedColumnName("user") + "=@UserId",
new { Section = sectionDto.AppAlias, UserId = sectionDto.UserId });
}
}
}
((ICanBeDirty)entity).ResetDirtyProperties();
}
#endregion
#region Implementation of IUserRepository
public int GetCountByQuery(IQuery<IUser> query)
{
var sqlClause = GetBaseQuery("umbracoUser.id");
var translator = new SqlTranslator<IUser>(sqlClause, query);
var subquery = translator.Translate();
//get the COUNT base query
var sql = GetBaseQuery(true)
.Append(new Sql("WHERE umbracoUser.id IN (" + subquery.SQL + ")", subquery.Arguments));
return Database.ExecuteScalar<int>(sql);
}
public bool Exists(string username)
{
var sql = new Sql();
var escapedUserName = PetaPocoExtensions.EscapeAtSymbols(username);
sql.Select("COUNT(*)")
.From<UserDto>()
.Where<UserDto>(x => x.UserName == escapedUserName);
return Database.ExecuteScalar<int>(sql) > 0;
}
public IEnumerable<IUser> GetUsersAssignedToSection(string sectionAlias)
{
//Here we're building up a query that looks like this, a sub query is required because the resulting structure
// needs to still contain all of the section rows per user.
//SELECT *
//FROM [umbracoUser]
//LEFT JOIN [umbracoUser2app]
//ON [umbracoUser].[id] = [umbracoUser2app].[user]
//WHERE umbracoUser.id IN (SELECT umbracoUser.id
// FROM [umbracoUser]
// LEFT JOIN [umbracoUser2app]
// ON [umbracoUser].[id] = [umbracoUser2app].[user]
// WHERE umbracoUser2app.app = 'content')
var sql = GetBaseQuery(false);
var innerSql = GetBaseQuery("umbracoUser.id");
innerSql.Where("umbracoUser2app.app = " + SqlSyntaxContext.SqlSyntaxProvider.GetQuotedValue(sectionAlias));
sql.Where(string.Format("umbracoUser.id IN ({0})", innerSql.SQL));
return ConvertFromDtos(Database.Fetch<UserDto, User2AppDto, UserDto>(new UserSectionRelator().Map, sql));
}
/// <summary>
/// Gets paged user results
/// </summary>
/// <param name="query">
/// The where clause, if this is null all records are queried
/// </param>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="totalRecords"></param>
/// <param name="orderBy"></param>
/// <returns></returns>
/// <remarks>
/// The query supplied will ONLY work with data specifically on the umbracoUser table because we are using PetaPoco paging (SQL paging)
/// </remarks>
public IEnumerable<IUser> GetPagedResultsByQuery(IQuery<IUser> query, int pageIndex, int pageSize, out int totalRecords, Expression<Func<IUser, string>> orderBy)
{
if (orderBy == null) throw new ArgumentNullException("orderBy");
var sql = new Sql();
sql.Select("*").From<UserDto>();
Sql resultQuery;
if (query != null)
{
var translator = new SqlTranslator<IUser>(sql, query);
resultQuery = translator.Translate();
}
else
{
resultQuery = sql;
}
//get the referenced column name
var expressionMember = ExpressionHelper.GetMemberInfo(orderBy);
//now find the mapped column name
var mapper = MappingResolver.Current.ResolveMapperByType(typeof(IUser));
var mappedField = mapper.Map(expressionMember.Name);
if (mappedField.IsNullOrWhiteSpace())
{
throw new ArgumentException("Could not find a mapping for the column specified in the orderBy clause");
}
//need to ensure the order by is in brackets, see: https://github.com/toptensoftware/PetaPoco/issues/177
resultQuery.OrderBy(string.Format("({0})", mappedField));
var pagedResult = Database.Page<UserDto>(pageIndex + 1, pageSize, resultQuery);
totalRecords = Convert.ToInt32(pagedResult.TotalItems);
//now that we have the user dto's we need to construct true members from the list.
if (totalRecords == 0)
{
return Enumerable.Empty<IUser>();
}
var result = GetAll(pagedResult.Items.Select(x => x.Id).ToArray());
//now we need to ensure this result is also ordered by the same order by clause
return result.OrderBy(orderBy.Compile());
}
/// <summary>
/// Returns permissions for a given user for any number of nodes
/// </summary>
/// <param name="userId"></param>
/// <param name="entityIds"></param>
/// <returns></returns>
public IEnumerable<EntityPermission> GetUserPermissionsForEntities(int userId, params int[] entityIds)
{
var repo = new PermissionRepository<IContent>(UnitOfWork, _cacheHelper);
return repo.GetUserPermissionsForEntities(userId, entityIds);
}
/// <summary>
/// Replaces the same permission set for a single user to any number of entities
/// </summary>
/// <param name="userId"></param>
/// <param name="permissions"></param>
/// <param name="entityIds"></param>
public void ReplaceUserPermissions(int userId, IEnumerable<char> permissions, params int[] entityIds)
{
var repo = new PermissionRepository<IContent>(UnitOfWork, _cacheHelper);
repo.ReplaceUserPermissions(userId, permissions, entityIds);
}
#endregion
private IEnumerable<IUser> ConvertFromDtos(IEnumerable<UserDto> dtos)
{
var foundUserTypes = new Dictionary<short, IUserType>();
return dtos.Select(dto =>
{
//first we need to get the user type
IUserType userType;
if (foundUserTypes.ContainsKey(dto.Type))
{
userType = foundUserTypes[dto.Type];
}
else
{
userType = _userTypeRepository.Get(dto.Type);
//put it in the local cache
foundUserTypes.Add(dto.Type, userType);
}
var userFactory = new UserFactory(userType);
return userFactory.BuildEntity(dto);
});
}
}
}
| |
// 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: Debugging Macros for use in the Base Class Libraries
**
**
============================================================*/
namespace System
{
using System.IO;
using System.Text;
using System.Diagnostics;
using Microsoft.Win32;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
internal enum LogLevel
{
Trace = 0,
Status = 20,
Warning = 40,
Error = 50,
Panic = 100,
}
internal struct SwitchStructure
{
internal String name;
internal int value;
internal SwitchStructure(String n, int v)
{
name = n;
value = v;
}
}
// Only statics, does not need to be marked with the serializable attribute
internal static class BCLDebug
{
internal static volatile bool m_registryChecked = false;
internal static volatile bool m_loggingNotEnabled = false;
private static readonly SwitchStructure[] switches = {
new SwitchStructure("NLS", 0x00000001),
new SwitchStructure("SER", 0x00000002),
new SwitchStructure("DYNIL",0x00000004),
new SwitchStructure("REMOTE",0x00000008),
new SwitchStructure("BINARY",0x00000010), //Binary Formatter
new SwitchStructure("SOAP",0x00000020), // Soap Formatter
new SwitchStructure("REMOTINGCHANNELS",0x00000040),
new SwitchStructure("CACHE",0x00000080),
new SwitchStructure("RESMGRFILEFORMAT", 0x00000100), // .resources files
new SwitchStructure("PERF", 0x00000200),
new SwitchStructure("CORRECTNESS", 0x00000400),
new SwitchStructure("MEMORYFAILPOINT", 0x00000800),
new SwitchStructure("DATETIME", 0x00001000), // System.DateTime managed tracing
new SwitchStructure("INTEROP", 0x00002000), // Interop tracing
};
private static readonly LogLevel[] levelConversions = {
LogLevel.Panic,
LogLevel.Error,
LogLevel.Error,
LogLevel.Warning,
LogLevel.Warning,
LogLevel.Status,
LogLevel.Status,
LogLevel.Trace,
LogLevel.Trace,
LogLevel.Trace,
LogLevel.Trace
};
[Conditional("_LOGGING")]
static public void Log(String message)
{
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
if (!m_registryChecked)
{
CheckRegistry();
}
System.Diagnostics.Log.Trace(message);
System.Diagnostics.Log.Trace(Environment.NewLine);
}
[Conditional("_LOGGING")]
static public void Log(String switchName, String message)
{
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
if (!m_registryChecked)
{
CheckRegistry();
}
try
{
LogSwitch ls;
ls = LogSwitch.GetSwitch(switchName);
if (ls != null)
{
System.Diagnostics.Log.Trace(ls, message);
System.Diagnostics.Log.Trace(ls, Environment.NewLine);
}
}
catch
{
System.Diagnostics.Log.Trace("Exception thrown in logging." + Environment.NewLine);
System.Diagnostics.Log.Trace("Switch was: " + ((switchName == null) ? "<null>" : switchName) + Environment.NewLine);
System.Diagnostics.Log.Trace("Message was: " + ((message == null) ? "<null>" : message) + Environment.NewLine);
}
}
//
// This code gets called during security startup, so we can't go through Marshal to get the values. This is
// just a small helper in native code instead of that.
//
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private extern static int GetRegistryLoggingValues(out bool loggingEnabled, out bool logToConsole, out int logLevel);
private static void CheckRegistry()
{
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
if (m_registryChecked)
{
return;
}
m_registryChecked = true;
bool loggingEnabled;
bool logToConsole;
int logLevel;
int facilityValue;
facilityValue = GetRegistryLoggingValues(out loggingEnabled, out logToConsole, out logLevel);
// Note we can get into some recursive situations where we call
// ourseves recursively through the .cctor. That's why we have the
// check for levelConversions == null.
if (!loggingEnabled)
{
m_loggingNotEnabled = true;
}
if (loggingEnabled && levelConversions != null)
{
try
{
//The values returned for the logging levels in the registry don't map nicely onto the
//values which we support internally (which are an approximation of the ones that
//the System.Diagnostics namespace uses) so we have a quick map.
Debug.Assert(logLevel >= 0 && logLevel <= 10, "logLevel>=0 && logLevel<=10");
logLevel = (int)levelConversions[logLevel];
if (facilityValue > 0)
{
for (int i = 0; i < switches.Length; i++)
{
if ((switches[i].value & facilityValue) != 0)
{
LogSwitch L = new LogSwitch(switches[i].name, switches[i].name, System.Diagnostics.Log.GlobalSwitch);
L.MinimumLevel = (LoggingLevels)logLevel;
}
}
System.Diagnostics.Log.GlobalSwitch.MinimumLevel = (LoggingLevels)logLevel;
System.Diagnostics.Log.IsConsoleEnabled = logToConsole;
}
}
catch
{
//Silently eat any exceptions.
}
}
}
internal static bool CheckEnabled(String switchName)
{
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return false;
if (!m_registryChecked)
CheckRegistry();
LogSwitch logSwitch = LogSwitch.GetSwitch(switchName);
if (logSwitch == null)
{
return false;
}
return ((int)logSwitch.MinimumLevel <= (int)LogLevel.Trace);
}
private static bool CheckEnabled(String switchName, LogLevel level, out LogSwitch logSwitch)
{
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
{
logSwitch = null;
return false;
}
logSwitch = LogSwitch.GetSwitch(switchName);
if (logSwitch == null)
{
return false;
}
return ((int)logSwitch.MinimumLevel <= (int)level);
}
[Conditional("_LOGGING")]
public static void Log(String switchName, LogLevel level, params Object[] messages)
{
if (AppDomain.CurrentDomain.IsUnloadingForcedFinalize())
return;
//Add code to check if logging is enabled in the registry.
LogSwitch logSwitch;
if (!m_registryChecked)
{
CheckRegistry();
}
if (!CheckEnabled(switchName, level, out logSwitch))
{
return;
}
StringBuilder sb = StringBuilderCache.Acquire();
for (int i = 0; i < messages.Length; i++)
{
String s;
try
{
if (messages[i] == null)
{
s = "<null>";
}
else
{
s = messages[i].ToString();
}
}
catch
{
s = "<unable to convert>";
}
sb.Append(s);
}
System.Diagnostics.Log.LogMessage((LoggingLevels)((int)level), logSwitch, StringBuilderCache.GetStringAndRelease(sb));
}
[Conditional("_LOGGING")]
public static void Trace(String switchName, String format, params Object[] messages)
{
if (m_loggingNotEnabled)
{
return;
}
LogSwitch logSwitch;
if (!CheckEnabled(switchName, LogLevel.Trace, out logSwitch))
{
return;
}
StringBuilder sb = StringBuilderCache.Acquire();
sb.AppendFormat(format, messages);
sb.Append(Environment.NewLine);
System.Diagnostics.Log.LogMessage(LoggingLevels.TraceLevel0, logSwitch, StringBuilderCache.GetStringAndRelease(sb));
}
}
}
| |
//
// (C) Copyright 2003-2011 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
//
using System;
using System.IO;
using System.Collections.Generic;
using Autodesk.Revit;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using Autodesk.Revit.ApplicationServices;
namespace Revit.SDK.Samples.WindowWizard.CS
{
/// <summary>
/// Inherited from WindowCreation class
/// </summary>
class DoubleHungWinCreation : WindowCreation
{
#region Class Memeber Variables
/// <summary>
/// store the Application
/// </summary>
private UIApplication m_application;
/// <summary>
/// store the document
/// </summary>
private Document m_document;
/// <summary>
/// store the FamilyManager
/// </summary>
private FamilyManager m_familyManager;
/// <summary>
/// store the CreateDimension instance
/// </summary>
CreateDimension m_dimensionCreator ;
/// <summary>
/// store the CreateExtrusion instance
/// </summary>
CreateExtrusion m_extrusionCreator ;
/// <summary>
/// store the sash referenceplane
/// </summary>
ReferencePlane m_sashPlane;
/// <summary>
/// store the center referenceplane
/// </summary>
ReferencePlane m_centerPlane;
/// <summary>
/// store the exterior referenceplane
/// </summary>
ReferencePlane m_exteriorPlane;
/// <summary>
/// store the top referenceplane
/// </summary>
ReferencePlane m_topPlane;
/// <summary>
/// store the sill referenceplane
/// </summary>
ReferencePlane m_sillPlane;
/// <summary>
/// store the right view of the document
/// </summary>
Autodesk.Revit.DB.View m_rightView;
/// <summary>
/// store the frame category
/// </summary>
Category m_frameCat;
/// <summary>
/// store the glass category
/// </summary>
Category m_glassCat;
/// <summary>
/// store the thickness parameter of wall
/// </summary>
double m_wallThickness;
/// <summary>
/// store the height parameter of wall
/// </summary>
double m_height;
/// <summary>
/// store the width parameter of wall
/// </summary>
double m_width;
/// <summary>
/// store the sillheight parameter of wall
/// </summary>
double m_sillHeight;
/// <summary>
/// store the windowInset parameter of wall
/// </summary>
double m_windowInset;
/// <summary>
/// Store the height value of wall
/// </summary>
double m_wallHeight;
/// <summary>
/// Store the width value of wall
/// </summary>
double m_wallWidth;
/// <summary>
/// store the glass material ID
/// </summary>
int m_glassMatID;
/// <summary>
/// store the sash material ID
/// </summary>
int m_sashMatID;
#endregion
/// <summary>
/// constructor of DoubleHungWinCreation
/// </summary>
/// <param name="para">WizardParameter</param>
/// <param name="commandData">ExternalCommandData</param>
public DoubleHungWinCreation(WizardParameter para, ExternalCommandData commandData) : base(para)
{
m_application = commandData.Application;
m_document = commandData.Application.ActiveUIDocument.Document;
m_familyManager = m_document.FamilyManager;
CollectTemplateInfo();
para.Validator = new ValidateWindowParameter(m_wallHeight, m_wallWidth);
switch (m_document.DisplayUnitSystem)
{
case Autodesk.Revit.DB.DisplayUnit.METRIC:
para.Validator.IsMetric = true;
break;
case Autodesk.Revit.DB.DisplayUnit.IMPERIAL:
para.Validator.IsMetric = false;
break;
}
para.PathName = Path.GetDirectoryName(para.PathName) + "Double Hung.rfa";
CreateCommon();
}
#region Class Implementation
/// <summary>
/// The implementation of CreateFrame()
/// </summary>
public override void CreateFrame()
{
SubTransaction subTransaction = new SubTransaction(m_document);
subTransaction.Start();
//get the wall in the document and retrieve the exterior face
List<Wall> walls = Utility.GetElements<Wall>(m_application, m_document);
Face exteriorWallFace = GeoHelper.GetWallFace(walls[0], m_rightView, true);
//create sash referenceplane and exterior referenceplane
CreateRefPlane refPlaneCreator = new CreateRefPlane();
if(m_sashPlane==null)
m_sashPlane = refPlaneCreator.Create(m_document, m_centerPlane, m_rightView, new Autodesk.Revit.DB.XYZ (0, m_wallThickness / 2 - m_windowInset, 0), new Autodesk.Revit.DB.XYZ (0, 0, 1), "Sash");
if (m_exteriorPlane==null)
m_exteriorPlane = refPlaneCreator.Create(m_document, m_centerPlane, m_rightView, new Autodesk.Revit.DB.XYZ (0, m_wallThickness / 2, 0), new Autodesk.Revit.DB.XYZ (0, 0, 1), "MyExterior");
m_document.Regenerate();
//add dimension between sash reference plane and wall face,and add parameter "Window Inset",label the dimension with window-inset parameter
Dimension windowInsetDimension = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, exteriorWallFace);
FamilyParameter windowInsetPara = m_familyManager.AddParameter("Window Inset", BuiltInParameterGroup.INVALID, ParameterType.Length, false);
m_familyManager.Set(windowInsetPara, m_windowInset);
windowInsetDimension.Label = windowInsetPara;
//create the exterior frame
double frameCurveOffset1 = 0.075;
CurveArray curveArr1 = m_extrusionCreator.CreateRectangle(m_width / 2, -m_width / 2, m_sillHeight + m_height, m_sillHeight, 0);
CurveArray curveArr2 = m_extrusionCreator.CreateCurveArrayByOffset(curveArr1, frameCurveOffset1);
CurveArrArray curveArrArray1 = new CurveArrArray();
curveArrArray1.Append(curveArr1);
curveArrArray1.Append(curveArr2);
Extrusion extFrame = m_extrusionCreator.NewExtrusion(curveArrArray1, m_sashPlane, m_wallThickness / 2 + m_wallThickness/12, -m_windowInset);
extFrame.SetVisibility( CreateVisibility());
m_document.Regenerate();
//add alignment between wall face and exterior frame face
Face exteriorExtrusionFace1=GeoHelper.GetExtrusionFace(extFrame,m_rightView,true);
Face interiorExtrusionFace1 = GeoHelper.GetExtrusionFace(extFrame,m_rightView,false);
CreateAlignment alignmentCreator = new CreateAlignment(m_document);
alignmentCreator.AddAlignment(m_rightView,exteriorWallFace,exteriorExtrusionFace1);
//add dimension between sash referenceplane and exterior frame face and lock the dimension
Dimension extFrameWithSashPlane = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, interiorExtrusionFace1);
extFrameWithSashPlane.IsLocked = true;
m_document.Regenerate();
//create the interior frame
double frameCurveOffset2 = 0.125;
CurveArray curveArr3 = m_extrusionCreator.CreateRectangle(m_width / 2, -m_width / 2, m_sillHeight + m_height, m_sillHeight, 0);
CurveArray curveArr4 = m_extrusionCreator.CreateCurveArrayByOffset(curveArr3, frameCurveOffset2);
m_document.Regenerate();
CurveArrArray curveArrArray2 = new CurveArrArray();
curveArrArray2.Append(curveArr3);
curveArrArray2.Append(curveArr4);
Extrusion intFrame = m_extrusionCreator.NewExtrusion(curveArrArray2, m_sashPlane, m_wallThickness - m_windowInset, m_wallThickness / 2 + m_wallThickness / 12);
intFrame.SetVisibility( CreateVisibility());
m_document.Regenerate();
//add alignment between interior face of wall and interior frame face
Face interiorWallFace = GeoHelper.GetWallFace(walls[0], m_rightView, false);
Face interiorExtrusionFace2 = GeoHelper.GetExtrusionFace(intFrame, m_rightView, false);
Face exteriorExtrusionFace2 = GeoHelper.GetExtrusionFace(intFrame, m_rightView, true);
alignmentCreator.AddAlignment(m_rightView, interiorWallFace, interiorExtrusionFace2);
//add dimension between sash referenceplane and interior frame face and lock the dimension
Dimension intFrameWithSashPlane = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, exteriorExtrusionFace2);
intFrameWithSashPlane.IsLocked = true;
//create the sill frame
CurveArray sillCurs = m_extrusionCreator.CreateRectangle(m_width / 2, -m_width / 2, m_sillHeight + frameCurveOffset1, m_sillHeight, 0);
CurveArrArray sillCurveArray = new CurveArrArray();
sillCurveArray.Append(sillCurs);
Extrusion sillFrame= m_extrusionCreator.NewExtrusion(sillCurveArray, m_sashPlane, -m_windowInset, -m_windowInset - 0.1);
m_document.Regenerate();
//add alignment between wall face and sill frame face
Face sillExtFace = GeoHelper.GetExtrusionFace(sillFrame, m_rightView, false);
alignmentCreator.AddAlignment(m_rightView, sillExtFace, exteriorWallFace);
m_document.Regenerate();
//set subcategories of the frames
if (m_frameCat != null)
{
extFrame.Subcategory = m_frameCat;
intFrame.Subcategory = m_frameCat;
sillFrame.Subcategory = m_frameCat;
}
subTransaction.Commit();
}
/// <summary>
/// The implementation of CreateSash(),and creating the Window Sash Solid Geometry
/// </summary>
public override void CreateSash()
{
double frameCurveOffset1 = 0.075;
double frameDepth = 7*m_wallThickness/12+m_windowInset;
double sashCurveOffset = 0.075;
double sashDepth = (frameDepth - m_windowInset) / 2;
//get the exterior view and sash referenceplane which are used in this process
Autodesk.Revit.DB.View exteriorView = Utility.GetViewByName("Exterior", m_application, m_document);
SubTransaction subTransaction = new SubTransaction(m_document);
subTransaction.Start();
//add a middle reference plane between the top referenceplane and sill referenceplane
CreateRefPlane refPlaneCreator = new CreateRefPlane();
ReferencePlane middlePlane=refPlaneCreator.Create(m_document, m_topPlane, exteriorView, new Autodesk.Revit.DB.XYZ (0, 0, -m_height / 2), new Autodesk.Revit.DB.XYZ (0, -1, 0), "tempmiddle");
m_document.Regenerate();
//add dimension between top, sill, and middle reference plane, make the dimension segment equal
Dimension dim = m_dimensionCreator.AddDimension(exteriorView, m_topPlane, m_sillPlane, middlePlane);
dim.AreSegmentsEqual = true;
//create first sash
CurveArray curveArr5 = m_extrusionCreator.CreateRectangle(m_width / 2 - frameCurveOffset1, -m_width / 2 + frameCurveOffset1, m_sillHeight + m_height / 2 + sashCurveOffset / 2, m_sillHeight + frameCurveOffset1, 0);
CurveArray curveArr6 = m_extrusionCreator.CreateCurveArrayByOffset(curveArr5, sashCurveOffset);
m_document.Regenerate();
CurveArrArray curveArrArray3 = new CurveArrArray();
curveArrArray3.Append(curveArr5);
curveArrArray3.Append(curveArr6);
Extrusion sash1 = m_extrusionCreator.NewExtrusion(curveArrArray3, m_sashPlane, 2 * sashDepth, sashDepth);
m_document.Regenerate();
Face esashFace1=GeoHelper.GetExtrusionFace(sash1,m_rightView,true);
Face isashFace1=GeoHelper.GetExtrusionFace(sash1,m_rightView,false);
Dimension sashDim1=m_dimensionCreator.AddDimension(m_rightView,esashFace1,isashFace1);
sashDim1.IsLocked = true;
Dimension sashWithPlane1 = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, isashFace1);
sashWithPlane1.IsLocked = true;
sash1.SetVisibility(CreateVisibility());
//create second sash
CurveArray curveArr7 = m_extrusionCreator.CreateRectangle(m_width / 2 - frameCurveOffset1, -m_width / 2 + frameCurveOffset1, m_sillHeight + m_height - frameCurveOffset1, m_sillHeight + m_height / 2 - sashCurveOffset / 2, 0);
CurveArray curveArr8 = m_extrusionCreator.CreateCurveArrayByOffset(curveArr7, sashCurveOffset);
m_document.Regenerate();
CurveArrArray curveArrArray4 = new CurveArrArray();
curveArrArray4.Append(curveArr7);
curveArrArray4.Append(curveArr8);
Extrusion sash2 = m_extrusionCreator.NewExtrusion(curveArrArray4, m_sashPlane, sashDepth, 0);
sash2.SetVisibility(CreateVisibility());
m_document.Regenerate();
Face esashFace2 = GeoHelper.GetExtrusionFace(sash2, m_rightView, true);
Face isashFace2 = GeoHelper.GetExtrusionFace(sash2, m_rightView, false);
Dimension sashDim2 = m_dimensionCreator.AddDimension(m_rightView, esashFace2, isashFace2);
sashDim2.IsLocked = true;
Dimension sashWithPlane2 = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, isashFace2);
m_document.Regenerate();
sashWithPlane2.IsLocked = true;
//set category of the sash extrusions
if (m_frameCat != null)
{
sash1.Subcategory = m_frameCat;
sash2.Subcategory = m_frameCat;
}
Autodesk.Revit.DB.ElementId id = new ElementId(m_sashMatID);
sash1.ParametersMap.get_Item("Material").Set(id);
sash2.ParametersMap.get_Item("Material").Set(id);
subTransaction.Commit();
}
/// <summary>
/// The implementation of CreateGlass(), creating the Window Glass Solid Geometry
/// </summary>
public override void CreateGlass()
{
double frameCurveOffset1 = 0.075;
double frameDepth = m_wallThickness - 0.15;
double sashCurveOffset = 0.075;
double sashDepth = (frameDepth - m_windowInset) / 2;
double glassDepth = 0.05;
double glassOffsetSash = 0.05; //from the exterior of the sash
//create first glass
SubTransaction subTransaction = new SubTransaction(m_document);
subTransaction.Start();
CurveArray curveArr9 = m_extrusionCreator.CreateRectangle(m_width / 2 - frameCurveOffset1 - sashCurveOffset, -m_width / 2 + frameCurveOffset1 + sashCurveOffset, m_sillHeight + m_height / 2 - sashCurveOffset / 2, m_sillHeight + frameCurveOffset1 + sashCurveOffset, 0);
m_document.Regenerate();
CurveArrArray curveArrArray5 = new CurveArrArray();
curveArrArray5.Append(curveArr9);
Extrusion glass1 = m_extrusionCreator.NewExtrusion(curveArrArray5, m_sashPlane, sashDepth + glassOffsetSash + glassDepth, sashDepth + glassOffsetSash);
m_document.Regenerate();
glass1.SetVisibility(CreateVisibility());
m_document.Regenerate();
Face eglassFace1 = GeoHelper.GetExtrusionFace(glass1, m_rightView, true);
Face iglassFace1 = GeoHelper.GetExtrusionFace(glass1, m_rightView, false);
Dimension glassDim1 = m_dimensionCreator.AddDimension(m_rightView, eglassFace1, iglassFace1);
glassDim1.IsLocked = true;
Dimension glass1WithSashPlane = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, eglassFace1);
glass1WithSashPlane.IsLocked = true;
//create the second glass
CurveArray curveArr10 = m_extrusionCreator.CreateRectangle(m_width / 2 - frameCurveOffset1 - sashCurveOffset, -m_width / 2 + frameCurveOffset1 + sashCurveOffset, m_sillHeight + m_height - frameCurveOffset1 - sashCurveOffset, m_sillHeight + m_height / 2 + sashCurveOffset / 2, 0);
CurveArrArray curveArrArray6 = new CurveArrArray();
curveArrArray6.Append(curveArr10);
Extrusion glass2 = m_extrusionCreator.NewExtrusion(curveArrArray6, m_sashPlane, glassOffsetSash + glassDepth, glassOffsetSash);
m_document.Regenerate();
glass2.SetVisibility(CreateVisibility());
m_document.Regenerate();
Face eglassFace2 = GeoHelper.GetExtrusionFace(glass2, m_rightView, true);
Face iglassFace2 = GeoHelper.GetExtrusionFace(glass2, m_rightView, false);
Dimension glassDim2 = m_dimensionCreator.AddDimension(m_rightView, eglassFace2, iglassFace2);
glassDim2.IsLocked = true;
Dimension glass2WithSashPlane = m_dimensionCreator.AddDimension(m_rightView, m_sashPlane, eglassFace2);
glass2WithSashPlane.IsLocked = true;
//set category
if (null != m_glassCat)
{
glass1.Subcategory = m_glassCat;
glass2.Subcategory = m_glassCat;
}
Autodesk.Revit.DB.ElementId id = new ElementId(m_glassMatID);
glass1.ParametersMap.get_Item("Material").Set(id);
glass2.ParametersMap.get_Item("Material").Set(id);
subTransaction.Commit();
}
/// <summary>
/// The implementation of CreateMaterial()
/// </summary>
public override void CreateMaterial()
{
SubTransaction subTransaction = new SubTransaction(m_document);
subTransaction.Start();
FilteredElementCollector elementCollector = new FilteredElementCollector(m_document);
elementCollector.WherePasses(new ElementClassFilter(typeof(Material)));
IList<Element> materials = elementCollector.ToElements();
foreach (Element materialElement in materials)
{
Material material = materialElement as Material;
if (0 == material.Name.CompareTo(m_para.SashMat))
{
m_sashMatID = material.Id.IntegerValue;
}
if (0 == material.Name.CompareTo(m_para.GlassMat))
{
m_glassMatID = material.Id.IntegerValue;
}
}
subTransaction.Commit();
}
/// <summary>
/// The implementation of CombineAndBuild() ,defining New Window Types
/// </summary>
public override void CombineAndBuild()
{
SubTransaction subTransaction = new SubTransaction(m_document);
subTransaction.Start();
foreach (String type in m_para.WinParaTab.Keys)
{
WindowParameter para = m_para.WinParaTab[type] as WindowParameter;
newFamilyType(para);
}
subTransaction.Commit();
try
{
m_document.SaveAs(m_para.PathName);
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine("Write to " + m_para.PathName + " Failed");
System.Diagnostics.Debug.WriteLine(e.Message);
}
}
/// <summary>
/// The method is used to collect template information, specifying the New Window Parameters
/// </summary>
private void CollectTemplateInfo()
{
List<Wall> walls = Utility.GetElements<Wall>(m_application, m_document);
m_wallThickness = walls[0].Width;
ParameterMap paraMap = walls[0].ParametersMap;
Parameter wallheightPara = paraMap.get_Item("Unconnected Height");
if (wallheightPara != null)
{
m_wallHeight = wallheightPara.AsDouble();
}
Parameter wallwidthPara = paraMap.get_Item("Length");
if (wallwidthPara != null)
{
m_wallWidth = wallwidthPara.AsDouble();
}
m_windowInset = m_wallThickness/10;
FamilyType type = m_familyManager.CurrentType;
FamilyParameter heightPara = m_familyManager.get_Parameter(BuiltInParameter.WINDOW_HEIGHT);
FamilyParameter widthPara = m_familyManager.get_Parameter(BuiltInParameter.WINDOW_WIDTH);
FamilyParameter sillHeightPara = m_familyManager.get_Parameter("Default Sill Height");
if(type.HasValue(heightPara))
{
switch(heightPara.StorageType)
{
case StorageType.Double:
m_height=type.AsDouble(heightPara).Value;
break;
case StorageType.Integer:
m_height = type.AsInteger(heightPara).Value;
break;
}
}
if (type.HasValue(widthPara))
{
switch (widthPara.StorageType)
{
case StorageType.Double:
m_width = type.AsDouble(widthPara).Value;
break;
case StorageType.Integer:
m_width = type.AsDouble(widthPara).Value;
break;
}
}
if (type.HasValue(sillHeightPara))
{
switch (sillHeightPara.StorageType)
{
case StorageType.Double:
m_sillHeight = type.AsDouble(sillHeightPara).Value;
break;
case StorageType.Integer:
m_sillHeight = type.AsDouble(sillHeightPara).Value;
break;
}
}
//set the height,width and sillheight parameter of the opening
m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_HEIGHT),
m_height);
m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_WIDTH),
m_width);
m_familyManager.Set(m_familyManager.get_Parameter("Default Sill Height"),m_sillHeight);
//get materials
FilteredElementCollector elementCollector = new FilteredElementCollector(m_document);
elementCollector.WherePasses(new ElementClassFilter(typeof(Material)));
IList<Element> materials= elementCollector.ToElements();
foreach (Element materialElement in materials)
{
Material material = materialElement as Material;
m_para.GlassMaterials.Add(material.Name);
m_para.FrameMaterials.Add(material.Name);
}
//get categories
Categories categories = m_document.Settings.Categories;
Category category = categories.get_Item(BuiltInCategory.OST_Windows);
CategoryNameMap cnm = category.SubCategories;
if (cnm.Contains("Frame/Mullion"))
{
m_frameCat = cnm.get_Item("Frame/Mullion");
}
if (cnm.Contains("Glass"))
{
m_glassCat = cnm.get_Item("Glass");
}
//get referenceplanes
List<ReferencePlane> planes = Utility.GetElements<ReferencePlane>(m_application,m_document);
foreach(ReferencePlane p in planes)
{
if (p.Name.Equals("Sash"))
m_sashPlane = p;
if (p.Name.Equals("Exterior"))
m_exteriorPlane = p;
if (p.Name.Equals("Center (Front/Back)"))
m_centerPlane = p;
if (p.Name.Equals("Top") || p.Name.Equals("Head"))
m_topPlane = p;
if (p.Name.Equals("Sill") || p.Name.Equals("Bottom"))
m_sillPlane = p;
}
}
/// <summary>
/// the method is used to create new family type
/// </summary>
/// <param name="para">WindowParameter</param>
/// <returns>indicate whether the NewType is successful</returns>
private bool newFamilyType(WindowParameter para)//string typeName, double height, double width, double sillHeight)
{
DoubleHungWinPara dbhungPara = para as DoubleHungWinPara;
string typeName = dbhungPara.Type;
double height = dbhungPara.Height;
double width = dbhungPara.Width;
double sillHeight = dbhungPara.SillHeight;
double windowInset = dbhungPara.Inset;
switch (m_document.DisplayUnitSystem)
{
case Autodesk.Revit.DB.DisplayUnit.METRIC:
height = Utility.MetricToImperial(height);
width = Utility.MetricToImperial(width);
sillHeight = Utility.MetricToImperial(sillHeight);
windowInset = Utility.MetricToImperial(windowInset);
break;
}
try
{
FamilyType type = m_familyManager.NewType(typeName);
m_familyManager.CurrentType = type;
m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_HEIGHT),height);
m_familyManager.Set(m_familyManager.get_Parameter(BuiltInParameter.WINDOW_WIDTH),width);
m_familyManager.Set(m_familyManager.get_Parameter("Default Sill Height"),sillHeight);
m_familyManager.Set(m_familyManager.get_Parameter("Window Inset"), windowInset);
return true;
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine(e.Message);
return false;
}
}
/// <summary>
/// The method is used to create a FamilyElementVisibility instance
/// </summary>
/// <returns>FamilyElementVisibility instance</returns>
private FamilyElementVisibility CreateVisibility()
{
FamilyElementVisibility familyElemVisibility = new FamilyElementVisibility(FamilyElementVisibilityType.Model);
familyElemVisibility.IsShownInCoarse = true;
familyElemVisibility.IsShownInFine = true;
familyElemVisibility.IsShownInMedium = true;
familyElemVisibility.IsShownInFrontBack = true;
familyElemVisibility.IsShownInLeftRight = true;
familyElemVisibility.IsShownInPlanRCPCut = false;
return familyElemVisibility;
}
/// <summary>
/// The method is used to create common class variables in this class
/// </summary>
private void CreateCommon()
{
//create common
m_dimensionCreator = new CreateDimension(m_application.Application, m_document);
m_extrusionCreator = new CreateExtrusion(m_application.Application, m_document);
m_rightView = Utility.GetViewByName("Right", m_application, m_document);
}
#endregion
}
}
| |
/*
* UltraCart Rest API V2
*
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: support@ultracart.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 = com.ultracart.admin.v2.Client.SwaggerDateConverter;
namespace com.ultracart.admin.v2.Model
{
/// <summary>
/// CartItemMultimedia
/// </summary>
[DataContract]
public partial class CartItemMultimedia : IEquatable<CartItemMultimedia>, IValidatableObject
{
/// <summary>
/// Type of multimedia
/// </summary>
/// <value>Type of multimedia</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum TypeEnum
{
/// <summary>
/// Enum Image for value: Image
/// </summary>
[EnumMember(Value = "Image")]
Image = 1,
/// <summary>
/// Enum PDF for value: PDF
/// </summary>
[EnumMember(Value = "PDF")]
PDF = 2,
/// <summary>
/// Enum Text for value: Text
/// </summary>
[EnumMember(Value = "Text")]
Text = 3,
/// <summary>
/// Enum Unknown for value: Unknown
/// </summary>
[EnumMember(Value = "Unknown")]
Unknown = 4,
/// <summary>
/// Enum Video for value: Video
/// </summary>
[EnumMember(Value = "Video")]
Video = 5
}
/// <summary>
/// Type of multimedia
/// </summary>
/// <value>Type of multimedia</value>
[DataMember(Name="type", EmitDefaultValue=false)]
public TypeEnum? Type { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="CartItemMultimedia" /> class.
/// </summary>
/// <param name="code">Code assigned to the multimedia.</param>
/// <param name="description">Description.</param>
/// <param name="excludeFromGallery">True if the image should be excluded from galleries.</param>
/// <param name="imageHeight">Image height.</param>
/// <param name="imageWidth">Image width.</param>
/// <param name="isDefault">True if the multimedia is the default for this type.</param>
/// <param name="thumbnails">Thumbnails of the images.</param>
/// <param name="type">Type of multimedia.</param>
/// <param name="url">URL to view multimedia at.</param>
public CartItemMultimedia(string code = default(string), string description = default(string), bool? excludeFromGallery = default(bool?), int? imageHeight = default(int?), int? imageWidth = default(int?), bool? isDefault = default(bool?), List<CartItemMultimediaThumbnail> thumbnails = default(List<CartItemMultimediaThumbnail>), TypeEnum? type = default(TypeEnum?), string url = default(string))
{
this.Code = code;
this.Description = description;
this.ExcludeFromGallery = excludeFromGallery;
this.ImageHeight = imageHeight;
this.ImageWidth = imageWidth;
this.IsDefault = isDefault;
this.Thumbnails = thumbnails;
this.Type = type;
this.Url = url;
}
/// <summary>
/// Code assigned to the multimedia
/// </summary>
/// <value>Code assigned to the multimedia</value>
[DataMember(Name="code", EmitDefaultValue=false)]
public string Code { get; set; }
/// <summary>
/// Description
/// </summary>
/// <value>Description</value>
[DataMember(Name="description", EmitDefaultValue=false)]
public string Description { get; set; }
/// <summary>
/// True if the image should be excluded from galleries
/// </summary>
/// <value>True if the image should be excluded from galleries</value>
[DataMember(Name="exclude_from_gallery", EmitDefaultValue=false)]
public bool? ExcludeFromGallery { get; set; }
/// <summary>
/// Image height
/// </summary>
/// <value>Image height</value>
[DataMember(Name="image_height", EmitDefaultValue=false)]
public int? ImageHeight { get; set; }
/// <summary>
/// Image width
/// </summary>
/// <value>Image width</value>
[DataMember(Name="image_width", EmitDefaultValue=false)]
public int? ImageWidth { get; set; }
/// <summary>
/// True if the multimedia is the default for this type
/// </summary>
/// <value>True if the multimedia is the default for this type</value>
[DataMember(Name="is_default", EmitDefaultValue=false)]
public bool? IsDefault { get; set; }
/// <summary>
/// Thumbnails of the images
/// </summary>
/// <value>Thumbnails of the images</value>
[DataMember(Name="thumbnails", EmitDefaultValue=false)]
public List<CartItemMultimediaThumbnail> Thumbnails { get; set; }
/// <summary>
/// URL to view multimedia at
/// </summary>
/// <value>URL to view multimedia at</value>
[DataMember(Name="url", EmitDefaultValue=false)]
public string Url { 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 CartItemMultimedia {\n");
sb.Append(" Code: ").Append(Code).Append("\n");
sb.Append(" Description: ").Append(Description).Append("\n");
sb.Append(" ExcludeFromGallery: ").Append(ExcludeFromGallery).Append("\n");
sb.Append(" ImageHeight: ").Append(ImageHeight).Append("\n");
sb.Append(" ImageWidth: ").Append(ImageWidth).Append("\n");
sb.Append(" IsDefault: ").Append(IsDefault).Append("\n");
sb.Append(" Thumbnails: ").Append(Thumbnails).Append("\n");
sb.Append(" Type: ").Append(Type).Append("\n");
sb.Append(" Url: ").Append(Url).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public virtual string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as CartItemMultimedia);
}
/// <summary>
/// Returns true if CartItemMultimedia instances are equal
/// </summary>
/// <param name="input">Instance of CartItemMultimedia to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CartItemMultimedia input)
{
if (input == null)
return false;
return
(
this.Code == input.Code ||
(this.Code != null &&
this.Code.Equals(input.Code))
) &&
(
this.Description == input.Description ||
(this.Description != null &&
this.Description.Equals(input.Description))
) &&
(
this.ExcludeFromGallery == input.ExcludeFromGallery ||
(this.ExcludeFromGallery != null &&
this.ExcludeFromGallery.Equals(input.ExcludeFromGallery))
) &&
(
this.ImageHeight == input.ImageHeight ||
(this.ImageHeight != null &&
this.ImageHeight.Equals(input.ImageHeight))
) &&
(
this.ImageWidth == input.ImageWidth ||
(this.ImageWidth != null &&
this.ImageWidth.Equals(input.ImageWidth))
) &&
(
this.IsDefault == input.IsDefault ||
(this.IsDefault != null &&
this.IsDefault.Equals(input.IsDefault))
) &&
(
this.Thumbnails == input.Thumbnails ||
this.Thumbnails != null &&
this.Thumbnails.SequenceEqual(input.Thumbnails)
) &&
(
this.Type == input.Type ||
(this.Type != null &&
this.Type.Equals(input.Type))
) &&
(
this.Url == input.Url ||
(this.Url != null &&
this.Url.Equals(input.Url))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Code != null)
hashCode = hashCode * 59 + this.Code.GetHashCode();
if (this.Description != null)
hashCode = hashCode * 59 + this.Description.GetHashCode();
if (this.ExcludeFromGallery != null)
hashCode = hashCode * 59 + this.ExcludeFromGallery.GetHashCode();
if (this.ImageHeight != null)
hashCode = hashCode * 59 + this.ImageHeight.GetHashCode();
if (this.ImageWidth != null)
hashCode = hashCode * 59 + this.ImageWidth.GetHashCode();
if (this.IsDefault != null)
hashCode = hashCode * 59 + this.IsDefault.GetHashCode();
if (this.Thumbnails != null)
hashCode = hashCode * 59 + this.Thumbnails.GetHashCode();
if (this.Type != null)
hashCode = hashCode * 59 + this.Type.GetHashCode();
if (this.Url != null)
hashCode = hashCode * 59 + this.Url.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
//
// HIToolbox.cs
//
// Author:
// Michael Hutchinson <mhutchinson@novell.com>
// Miguel de Icaza
//
// Copyright (c) 2009 Novell, Inc. (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Runtime.InteropServices;
#pragma warning disable 0169
namespace OsxIntegration.Framework
{
internal static class HIToolbox
{
const string hiToolboxLib = "/System/Library/Frameworks/Carbon.framework/Versions/A/Frameworks/HIToolbox.framework/Versions/A/HIToolbox";
[DllImport (hiToolboxLib)]
static extern CarbonMenuStatus CreateNewMenu (ushort menuId, MenuAttributes attributes, out IntPtr menuRef);
public static IntPtr CreateMenu (ushort id, string title, MenuAttributes attributes)
{
IntPtr menuRef;
CheckResult (CreateNewMenu (id, attributes, out menuRef));
SetMenuTitle (menuRef, title);
return menuRef;
}
[DllImport (hiToolboxLib)]
internal static extern CarbonMenuStatus SetRootMenu (IntPtr menuRef);
[DllImport (hiToolboxLib)]
internal static extern void DeleteMenu (IntPtr menuRef);
[DllImport (hiToolboxLib)]
internal static extern void ClearMenuBar ();
[DllImport (hiToolboxLib)]
internal static extern ushort CountMenuItems (IntPtr menuRef);
[DllImport (hiToolboxLib)]
internal static extern void DeleteMenuItem (IntPtr menuRef, ushort index);
[DllImport (hiToolboxLib)]
internal static extern void InsertMenu (IntPtr menuRef, ushort before_id);
[DllImport (hiToolboxLib)]
static extern CarbonMenuStatus AppendMenuItemTextWithCFString (IntPtr menuRef, IntPtr cfString, MenuItemAttributes attributes, uint commandId, out ushort index);
public static ushort AppendMenuItem (IntPtr parentRef, string title, MenuItemAttributes attributes, uint commandId)
{
ushort index;
IntPtr str = CoreFoundation.CreateString (title);
CarbonMenuStatus result = AppendMenuItemTextWithCFString (parentRef, str, attributes, commandId, out index);
CoreFoundation.Release (str);
CheckResult (result);
return index;
}
public static ushort AppendMenuSeparator (IntPtr parentRef)
{
ushort index;
CarbonMenuStatus result = AppendMenuItemTextWithCFString (parentRef, IntPtr.Zero, MenuItemAttributes.Separator, 0, out index);
CheckResult (result);
return index;
}
[DllImport (hiToolboxLib)]
static extern CarbonMenuStatus InsertMenuItemTextWithCFString (IntPtr menuRef, IntPtr cfString, ushort afterItemIndex,
MenuItemAttributes attributes, uint commandID, out ushort index);
public static ushort InsertMenuItem (IntPtr parentRef, string title, ushort afterItemIndex, MenuItemAttributes attributes, uint commandId)
{
ushort index;
IntPtr str = CoreFoundation.CreateString (title);
CarbonMenuStatus result = InsertMenuItemTextWithCFString (parentRef, str, afterItemIndex, attributes, commandId, out index);
CoreFoundation.Release (str);
CheckResult (result);
return index;
}
public static ushort InsertMenuSeparator (IntPtr parentRef, ushort afterItemIndex)
{
ushort index;
CarbonMenuStatus result = InsertMenuItemTextWithCFString (parentRef, IntPtr.Zero, afterItemIndex, MenuItemAttributes.Separator, 0, out index);
CheckResult (result);
return index;
}
[DllImport (hiToolboxLib)]
static extern CarbonMenuStatus EnableMenuItem (IntPtr menuRef, ushort index);
public static void EnableMenuItem (HIMenuItem item)
{
CheckResult (EnableMenuItem (item.MenuRef, item.Index));
}
[DllImport (hiToolboxLib)]
static extern CarbonMenuStatus DisableMenuItem (IntPtr menuRef, ushort index);
public static void DisableMenuItem (HIMenuItem item)
{
CheckResult (DisableMenuItem (item.MenuRef, item.Index));
}
[DllImport (hiToolboxLib)]
static extern CarbonMenuStatus ChangeMenuItemAttributes (IntPtr menu, ushort item, MenuItemAttributes setTheseAttributes,
MenuItemAttributes clearTheseAttributes);
public static void ChangeMenuItemAttributes (HIMenuItem item, MenuItemAttributes toSet, MenuItemAttributes toClear)
{
CheckResult (ChangeMenuItemAttributes (item.MenuRef, item.Index, toSet, toClear));
}
[DllImport (hiToolboxLib)]
internal static extern CarbonMenuStatus SetMenuItemHierarchicalMenu (IntPtr parentMenu, ushort parent_index, IntPtr submenu);
[DllImport (hiToolboxLib)]
static extern CarbonMenuStatus SetMenuTitleWithCFString (IntPtr menuRef, IntPtr cfstring);
public static void SetMenuTitle (IntPtr menuRef, string title)
{
IntPtr str = CoreFoundation.CreateString (title);
CarbonMenuStatus result = SetMenuTitleWithCFString (menuRef, str);
CoreFoundation.Release (str);
CheckResult (result);
}
[DllImport (hiToolboxLib)]
static extern CarbonMenuStatus SetMenuItemTextWithCFString (IntPtr menuRef, ushort index, IntPtr cfstring);
public static void SetMenuItemText (IntPtr menuRef, ushort index, string title)
{
IntPtr str = CoreFoundation.CreateString (title);
CarbonMenuStatus result = SetMenuItemTextWithCFString (menuRef, index, str);
CoreFoundation.Release (str);
CheckResult (result);
}
[DllImport (hiToolboxLib)]
internal static extern CarbonMenuStatus SetMenuItemKeyGlyph (IntPtr menuRef, ushort index, short glyph);
[DllImport (hiToolboxLib)]
internal static extern CarbonMenuStatus SetMenuItemCommandKey (IntPtr menuRef, ushort index, bool isVirtualKey, ushort key);
[DllImport (hiToolboxLib)]
internal static extern CarbonMenuStatus SetMenuItemModifiers (IntPtr menuRef, ushort index, MenuAccelModifier modifiers);
[DllImport (hiToolboxLib)]
static extern CarbonMenuStatus GetMenuItemCommandID (IntPtr menuRef, ushort index, out uint commandId);
public static uint GetMenuItemCommandID (HIMenuItem item)
{
uint id;
CheckResult (GetMenuItemCommandID (item.MenuRef, item.Index, out id));
return id;
}
[DllImport (hiToolboxLib)]
static extern CarbonMenuStatus GetIndMenuItemWithCommandID (IntPtr startAtMenuRef, uint commandID, uint commandItemIndex,
out IntPtr itemMenuRef, out ushort itemIndex);
public static HIMenuItem GetMenuItem (uint commandId)
{
IntPtr itemMenuRef;
ushort itemIndex;
CheckResult (GetIndMenuItemWithCommandID (IntPtr.Zero, commandId, 1, out itemMenuRef, out itemIndex));
return new HIMenuItem (itemMenuRef, itemIndex);
}
[DllImport (hiToolboxLib)]
public static extern CarbonMenuStatus CancelMenuTracking (IntPtr rootMenu, bool inImmediate, MenuDismissalReason reason);
[DllImport (hiToolboxLib)]
public static extern CarbonMenuStatus SetMenuItemData (IntPtr menu, uint indexOrCommandID, bool isCommandID, ref MenuItemData data);
[DllImport (hiToolboxLib)]
static extern CarbonMenuStatus SetMenuItemRefCon (IntPtr menuRef, ushort index, uint inRefCon);
public static void SetMenuItemReferenceConstant (HIMenuItem item, uint value)
{
CheckResult (SetMenuItemRefCon (item.MenuRef, item.Index, value));
}
[DllImport (hiToolboxLib)]
static extern CarbonMenuStatus GetMenuItemRefCon (IntPtr menuRef, ushort index, out uint inRefCon);
public static uint GetMenuItemReferenceConstant (HIMenuItem item)
{
uint val;
CheckResult (GetMenuItemRefCon (item.MenuRef, item.Index, out val));
return val;
}
internal static void CheckResult (CarbonMenuStatus result)
{
if (result != CarbonMenuStatus.Ok)
throw new CarbonMenuException (result);
}
}
class CarbonMenuException : Exception
{
public CarbonMenuException (CarbonMenuStatus result)
{
this.Result = result;
}
public CarbonMenuStatus Result { get; private set; }
public override string ToString ()
{
return string.Format("CarbonMenuException: Result={0}\n{1}", Result, StackTrace);
}
}
internal enum CarbonMenuStatus // this is an OSStatus
{
Ok = 0,
PropertyInvalid = -5603,
PropertyNotFound = -5604,
NotFound = -5620,
UsesSystemDef = -5621,
ItemNotFound = -5622,
Invalid = -5623
}
[Flags]
internal enum MenuAttributes {
ExcludesMarkColumn = 1,
AutoDisable = 1 << 2,
UsePencilGlyph = 1 << 3,
Hidden = 1 << 4,
CondenseSeparators = 1 << 5,
DoNotCacheImage = 1 << 6,
DoNotUseUserCommandKeys = 1 << 7
}
internal enum MenuAccelModifier : byte
{
CommandModifier = 0,
ShiftModifier = 1 << 0,
OptionModifier = 1 << 1,
ControlModifier = 1 << 2,
None = 1 << 3
}
[Flags]
internal enum MenuItemAttributes : uint
{
Disabled = 1 << 0,
IconDisabled = 1 << 1,
SubmenuParentChoosable = 1 << 2,
Dynamic = 1 << 3,
NotPreviousAlternate = 1 << 4,
Hidden = 1 << 5,
Separator = 1 << 6,
SectionHeader = 1 << 7,
IgnoreMeta = 1 << 8,
AutoRepeat = 1 << 9,
UseVirtualKey = 1 << 10,
CustomDraw = 1 << 11,
IncludeInCmdKeyMatching = 1 << 12,
AutoDisable = 1 << 13,
UpdateSingleItem = 1 << 14
}
internal enum MenuDismissalReason : uint
{
DismissedBySelection = 1,
DismissedByUserCancel = 2,
DismissedByMouseDown = 3,
DismissedByMouseUp = 4,
DismissedByKeyEvent = 5,
DismissedByAppSwitch = 6,
DismissedByTimeout = 7,
DismissedByCancelMenuTracking = 8,
DismissedByActivationChange = 9,
DismissedByFocusChange = 10,
}
[StructLayout(LayoutKind.Sequential, Pack = 2)]
internal struct MenuItemData
{
MenuItemDataFlags whichData; //8
IntPtr text; //Str255 //12
[MarshalAs (UnmanagedType.U2)] //14
char mark;
[MarshalAs (UnmanagedType.U2)] //16
char cmdKey;
uint cmdKeyGlyph; //20
uint cmdKeyModifiers; //24
byte style; //25
[MarshalAs (UnmanagedType.U1)] //26
bool enabled;
[MarshalAs (UnmanagedType.U1)] //27
bool iconEnabled;
byte filler1; //28
int iconID; //32
uint iconType; //36
IntPtr iconHandle; //40
uint cmdID; //44
CarbonTextEncoding encoding; //48
ushort submenuID; //50
IntPtr submenuHandle; //54
int fontID; //58
uint refcon; //62
// LAMESPEC: this field is documented as OptionBits
MenuItemAttributes attr; //66
IntPtr cfText; //70
// Collection
IntPtr properties; //74
uint indent; //78
ushort cmdVirtualKey; //80
//these aren't documented
IntPtr attributedText; //84
IntPtr font; //88
#region Properties
public IntPtr Text {
get { return text; }
set {
whichData |= MenuItemDataFlags.Text;
text = value;
}
}
public char Mark {
get { return mark; }
set {
whichData |= MenuItemDataFlags.Mark;
mark = value;
}
}
public char CommandKey {
get { return cmdKey; }
set {
whichData |= MenuItemDataFlags.CmdKey;
cmdKey = value;
}
}
public uint CommandKeyGlyph {
get { return cmdKeyGlyph; }
set {
whichData |= MenuItemDataFlags.CmdKeyGlyph;
cmdKeyGlyph = value;
}
}
public MenuAccelModifier CommandKeyModifiers {
get { return (MenuAccelModifier) cmdKeyModifiers; }
set {
whichData |= MenuItemDataFlags.CmdKeyModifiers;
cmdKeyModifiers = (uint) value;
}
}
public byte Style {
get { return style; }
set {
whichData |= MenuItemDataFlags.Style;
style = value;
}
}
public bool Enabled {
get { return enabled; }
set {
whichData |= MenuItemDataFlags.Enabled;
enabled = value;
}
}
public bool IconEnabled {
get { return iconEnabled; }
set {
whichData |= MenuItemDataFlags.IconEnabled;
iconEnabled = value;
}
}
public int IconID {
get { return iconID; }
set {
whichData |= MenuItemDataFlags.IconID;
iconID = value;
}
}
public HIIconHandle IconHandle {
get { return new HIIconHandle (iconHandle, iconType); }
set {
whichData |= MenuItemDataFlags.IconHandle;
iconHandle = value.Ref;
iconType = value.Type;
}
}
public uint CommandID {
get { return cmdID; }
set {
whichData |= MenuItemDataFlags.CommandID;
cmdID = value;
}
}
public CarbonTextEncoding Encoding {
get { return encoding; }
set {
whichData |= MenuItemDataFlags.TextEncoding;
encoding = value;
}
}
public ushort SubmenuID {
get { return submenuID; }
set {
whichData |= MenuItemDataFlags.SubmenuID;
submenuID = value;
}
}
public IntPtr SubmenuHandle {
get { return submenuHandle; }
set {
whichData |= MenuItemDataFlags.SubmenuHandle;
submenuHandle = value;
}
}
public int FontID {
get { return fontID; }
set {
whichData |= MenuItemDataFlags.FontID;
fontID = value;
}
}
public uint ReferenceConstant {
get { return refcon; }
set {
whichData |= MenuItemDataFlags.Refcon;
refcon = value;
}
}
public MenuItemAttributes Attributes {
get { return attr; }
set {
whichData |= MenuItemDataFlags.Attributes;
attr = value;
}
}
public IntPtr CFText {
get { return cfText; }
set {
whichData |= MenuItemDataFlags.CFString;
cfText = value;
}
}
public IntPtr Properties {
get { return properties; }
set {
whichData |= MenuItemDataFlags.Properties;
properties = value;
}
}
public uint Indent {
get { return indent; }
set {
whichData |= MenuItemDataFlags.Indent;
indent = value;
}
}
public ushort CommandVirtualKey {
get { return cmdVirtualKey; }
set {
whichData |= MenuItemDataFlags.CmdVirtualKey;
cmdVirtualKey = value;
}
}
#endregion
#region 'Has' properties
public bool HasText {
get { return (whichData & MenuItemDataFlags.Text) != 0; }
}
public bool HasMark {
get { return (whichData & MenuItemDataFlags.Mark) != 0; }
}
public bool HasCommandKey {
get { return (whichData & MenuItemDataFlags.CmdKey) != 0; }
}
public bool HasCommandKeyGlyph {
get { return (whichData & MenuItemDataFlags.CmdKeyGlyph) != 0; }
}
public bool HasCommandKeyModifiers {
get { return (whichData & MenuItemDataFlags.CmdKeyModifiers) != 0; }
}
public bool HasStyle {
get { return (whichData & MenuItemDataFlags.Style) != 0; }
}
public bool HasEnabled {
get { return (whichData & MenuItemDataFlags.Enabled) != 0; }
}
public bool HasIconEnabled {
get { return (whichData & MenuItemDataFlags.IconEnabled) != 0; }
}
public bool HasIconID {
get { return (whichData & MenuItemDataFlags.IconID) != 0; }
}
public bool HasIconHandle {
get { return (whichData & MenuItemDataFlags.IconHandle) != 0; }
}
public bool HasCommandID {
get { return (whichData & MenuItemDataFlags.CommandID) != 0; }
}
public bool HasEncoding {
get { return (whichData & MenuItemDataFlags.TextEncoding) != 0; }
}
public bool HasSubmenuID {
get { return (whichData & MenuItemDataFlags.SubmenuID) != 0; }
}
public bool HasSubmenuHandle {
get { return (whichData & MenuItemDataFlags.SubmenuHandle) != 0; }
}
public bool HasFontID {
get { return (whichData & MenuItemDataFlags.FontID) != 0; }
}
public bool HasRefcon {
get { return (whichData & MenuItemDataFlags.Refcon) != 0; }
}
public bool HasAttributes {
get { return (whichData & MenuItemDataFlags.Attributes) != 0; }
}
public bool HasCFText {
get { return (whichData & MenuItemDataFlags.CFString) != 0; }
}
public bool HasProperties {
get { return (whichData & MenuItemDataFlags.Properties) != 0; }
}
public bool HasIndent {
get { return (whichData & MenuItemDataFlags.Indent) != 0; }
}
public bool HasCommandVirtualKey {
get { return (whichData & MenuItemDataFlags.CmdVirtualKey) != 0; }
}
#endregion
}
struct HIIconHandle
{
IntPtr _ref;
uint type;
public HIIconHandle (IntPtr @ref, uint type)
{
this._ref = @ref;
this.type = type;
}
public IntPtr Ref { get { return _ref; } }
public uint Type { get { return type; } }
}
enum CarbonTextEncoding : uint
{
}
enum MenuItemDataFlags : ulong
{
Text = (1 << 0),
Mark = (1 << 1),
CmdKey = (1 << 2),
CmdKeyGlyph = (1 << 3),
CmdKeyModifiers = (1 << 4),
Style = (1 << 5),
Enabled = (1 << 6),
IconEnabled = (1 << 7),
IconID = (1 << 8),
IconHandle = (1 << 9),
CommandID = (1 << 10),
TextEncoding = (1 << 11),
SubmenuID = (1 << 12),
SubmenuHandle = (1 << 13),
FontID = (1 << 14),
Refcon = (1 << 15),
Attributes = (1 << 16),
CFString = (1 << 17),
Properties = (1 << 18),
Indent = (1 << 19),
CmdVirtualKey = (1 << 20),
AllDataVersionOne = 0x000FFFFF,
AllDataVersionTwo = AllDataVersionOne | CmdVirtualKey,
}
enum MenuGlyphs : byte //char
{
None = 0x00,
TabRight = 0x02,
TabLeft = 0x03,
Enter = 0x04,
Shift = 0x05,
Control = 0x06,
Option = 0x07,
Space = 0x09,
DeleteRight = 0x0A,
Return = 0x0B,
ReturnR2L = 0x0C,
NonmarkingReturn = 0x0D,
Pencil = 0x0F,
DownwardArrowDashed = 0x10,
Command = 0x11,
Checkmark = 0x12,
Diamond = 0x13,
AppleLogoFilled = 0x14,
ParagraphKorean = 0x15,
DeleteLeft = 0x17,
LeftArrowDashed = 0x18,
UpArrowDashed = 0x19,
RightArrowDashed = 0x1A,
Escape = 0x1B,
Clear = 0x1C,
LeftDoubleQuotesJapanese = 0x1D,
RightDoubleQuotesJapanese = 0x1E,
TrademarkJapanese = 0x1F,
Blank = 0x61,
PageUp = 0x62,
CapsLock = 0x63,
LeftArrow = 0x64,
RightArrow = 0x65,
NorthwestArrow = 0x66,
Help = 0x67,
UpArrow = 0x68,
SoutheastArrow = 0x69,
DownArrow = 0x6A,
PageDown = 0x6B,
AppleLogoOutline = 0x6C,
ContextualMenu = 0x6D,
Power = 0x6E,
F1 = 0x6F,
F2 = 0x70,
F3 = 0x71,
F4 = 0x72,
F5 = 0x73,
F6 = 0x74,
F7 = 0x75,
F8 = 0x76,
F9 = 0x77,
F10 = 0x78,
F11 = 0x79,
F12 = 0x7A,
F13 = 0x87,
F14 = 0x88,
F15 = 0x89,
ControlISO = 0x8A,
Eject = 0x8C
};
}
| |
/*
* 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.Reflection;
using System.Threading;
using System.Timers;
using log4net;
using Nwc.XmlRpc;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Grid.Framework;
using Timer = System.Timers.Timer;
namespace OpenSim.Grid.MessagingServer.Modules
{
public class MessageRegionModule : IMessageRegionLookup
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private MessageServerConfig m_cfg;
private IInterServiceUserService m_userServerModule;
private IGridServiceCore m_messageCore;
// a dictionary of all current regions this server knows about
private Dictionary<ulong, RegionProfileData> m_regionInfoCache = new Dictionary<ulong, RegionProfileData>();
public MessageRegionModule(MessageServerConfig config, IGridServiceCore messageCore)
{
m_cfg = config;
m_messageCore = messageCore;
}
public void Initialize()
{
m_messageCore.RegisterInterface<IMessageRegionLookup>(this);
}
public void PostInitialize()
{
IInterServiceUserService messageUserServer;
if (m_messageCore.TryGet<IInterServiceUserService>(out messageUserServer))
{
m_userServerModule = messageUserServer;
}
}
public void RegisterHandlers()
{
//have these in separate method as some servers restart the http server and reregister all the handlers.
}
/// <summary>
/// Gets and caches a RegionInfo object from the gridserver based on regionhandle
/// if the regionhandle is already cached, use the cached values
/// Gets called by lots of threads!!!!!
/// </summary>
/// <param name="regionhandle">handle to the XY of the region we're looking for</param>
/// <returns>A RegionInfo object to stick in the presence info</returns>
public RegionProfileData GetRegionInfo(ulong regionhandle)
{
RegionProfileData regionInfo = null;
lock (m_regionInfoCache)
{
m_regionInfoCache.TryGetValue(regionhandle, out regionInfo);
}
if (regionInfo == null) // not found in cache
{
regionInfo = RequestRegionInfo(regionhandle);
if (regionInfo != null) // lookup was successful
{
lock (m_regionInfoCache)
{
m_regionInfoCache[regionhandle] = regionInfo;
}
}
}
return regionInfo;
}
public int ClearRegionCache()
{
int cachecount = 0;
lock (m_regionInfoCache)
{
cachecount = m_regionInfoCache.Count;
m_regionInfoCache.Clear();
}
return cachecount;
}
/// <summary>
/// Get RegionProfileData from the GridServer.
/// We'll cache this information in GetRegionInfo and use it for presence updates
/// </summary>
/// <param name="regionHandle"></param>
/// <returns></returns>
public RegionProfileData RequestRegionInfo(ulong regionHandle)
{
RegionProfileData regionProfile = null;
try
{
Hashtable requestData = new Hashtable();
requestData["region_handle"] = regionHandle.ToString();
requestData["authkey"] = m_cfg.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(m_cfg.GridServerURL, methodName), 3000);
Hashtable responseData = (Hashtable)GridResp.Value;
if (responseData.ContainsKey("error"))
{
m_log.Error("[GRID]: error received from grid server" + responseData["error"]);
return null;
}
uint regX = Convert.ToUInt32((string)responseData["region_locx"]);
uint regY = Convert.ToUInt32((string)responseData["region_locy"]);
regionProfile = new RegionProfileData();
regionProfile.serverHostName = (string)responseData["sim_ip"];
regionProfile.serverPort = Convert.ToUInt16((string)responseData["sim_port"]);
regionProfile.httpPort = (uint)Convert.ToInt32((string)responseData["http_port"]);
regionProfile.regionHandle = Utils.UIntsToLong((regX * Constants.RegionSize), (regY * Constants.RegionSize));
regionProfile.regionLocX = regX;
regionProfile.regionLocY = regY;
regionProfile.remotingPort = Convert.ToUInt32((string)responseData["remoting_port"]);
regionProfile.UUID = new UUID((string)responseData["region_UUID"]);
regionProfile.regionName = (string)responseData["region_name"];
if (requestData.ContainsKey("product"))
regionProfile.product = (ProductRulesUse)Convert.ToInt32(requestData["product"]);
else
regionProfile.product = ProductRulesUse.UnknownUse;
if (requestData.ContainsKey("outside_ip"))
regionProfile.OutsideIP = (string)responseData["outside_ip"];
}
catch (WebException e)
{
m_log.ErrorFormat("[GRID]: Region lookup failed for {0}: {1} ", regionHandle.ToString(), e.Message);
}
return regionProfile;
}
public XmlRpcResponse RegionStartup(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
result["success"] = "FALSE";
if (m_userServerModule.SendToUserServer(requestData, "region_startup"))
result["success"] = "TRUE";
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
public XmlRpcResponse RegionShutdown(XmlRpcRequest request, IPEndPoint remoteClient)
{
Hashtable requestData = (Hashtable)request.Params[0];
Hashtable result = new Hashtable();
result["success"] = "FALSE";
if (m_userServerModule.SendToUserServer(requestData, "region_shutdown"))
result["success"] = "TRUE";
XmlRpcResponse response = new XmlRpcResponse();
response.Value = result;
return response;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.