context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Tracing; using System.Globalization; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Splunk.Logging { public class TestHttpEventCollector { private readonly Uri uri = new Uri("http://localhost:8089"); // a dummy uri private const string token = "TOKEN-GUID"; #region Trace listener interceptor that replaces a real Splunk server for testing. private class Response { public HttpStatusCode Code; public string Context; public Response(HttpStatusCode code = HttpStatusCode.OK, string context = "{\"text\":\"Success\",\"code\":0}") { Code = code; Context = context; } } private delegate Response RequestHandler(string token, List<HttpEventCollectorEventInfo> events); // we inject this method into HTTP event collector middleware chain to mimic a Splunk // server private HttpEventCollectorSender.HttpEventCollectorMiddleware MiddlewareInterceptor( RequestHandler handler, HttpEventCollectorSender.HttpEventCollectorMiddleware middleware) { HttpEventCollectorSender.HttpEventCollectorMiddleware interceptor = (string token, List<HttpEventCollectorEventInfo> events, HttpEventCollectorSender.HttpEventCollectorHandler next) => { Response response = handler(token, events); HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); httpResponseMessage.StatusCode = response.Code; byte[] buf = Encoding.UTF8.GetBytes(response.Context); httpResponseMessage.Content = new StringContent(response.Context); var task = new Task<HttpResponseMessage>(() => { return httpResponseMessage; }); task.RunSynchronously(); return task; }; if (middleware != null) { // chain middleware to interceptor var temp = interceptor; interceptor = (token, events, next) => { return middleware(token, events, (t, e) => { return temp(t, e, next); }); }; } return interceptor; } // Input trace listener private TraceSource Trace( RequestHandler handler, HttpEventCollectorEventInfo.Metadata metadata = null, int batchInterval = 0, int batchSizeBytes = 0, int batchSizeCount = 0, HttpEventCollectorSender.SendMode sendMode = HttpEventCollectorSender.SendMode.Parallel, HttpEventCollectorSender.HttpEventCollectorMiddleware middleware = null) { var trace = new TraceSource("HttpEventCollectorLogger"); trace.Switch.Level = SourceLevels.All; trace.Listeners.Add( new HttpEventCollectorTraceListener( uri: uri, token: token, metadata: metadata, sendMode: sendMode, batchInterval: batchInterval, batchSizeBytes: batchSizeBytes, batchSizeCount: batchSizeCount, middleware: MiddlewareInterceptor(handler, middleware)) ); return trace; } private TraceSource TraceDefault(RequestHandler handler) { var trace = new TraceSource("HttpEventCollectorLogger"); trace.Switch.Level = SourceLevels.All; trace.Listeners.Add( new HttpEventCollectorTraceListener( uri: uri, token: token, middleware: MiddlewareInterceptor(handler, null)) ); return trace; } private TraceSource TraceCustomFormatter( RequestHandler handler, HttpEventCollectorSender.HttpEventCollectorFormatter formatter, HttpEventCollectorSender.HttpEventCollectorMiddleware middleware) { var trace = new TraceSource("HttpEventCollectorLogger"); trace.Switch.Level = SourceLevels.All; trace.Listeners.Add( new HttpEventCollectorTraceListener( uri: uri, token: token, middleware: middleware, formatter: formatter, sendMode: HttpEventCollectorSender.SendMode.Parallel) ); return trace; } // Event sink private struct SinkTrace : IDisposable { public TestEventSource Source { set; get; } public HttpEventCollectorSink Sink { set; get; } public ObservableEventListener Listener { get; set; } public void Dispose() { Sink.OnCompleted(); Listener.Dispose(); } } private SinkTrace TraceSource( RequestHandler handler, HttpEventCollectorEventInfo.Metadata metadata = null, HttpEventCollectorSender.SendMode sendMode = HttpEventCollectorSender.SendMode.Parallel, int batchInterval = 0, int batchSizeBytes = 0, int batchSizeCount = 0, HttpEventCollectorSender.HttpEventCollectorMiddleware middleware = null) { var listener = new ObservableEventListener(); var sink = new HttpEventCollectorSink( uri: uri, token: token, formatter: new TestEventFormatter(), metadata: metadata, sendMode: sendMode, batchInterval: batchInterval, batchSizeBytes: batchSizeBytes, batchSizeCount: batchSizeCount, middleware: MiddlewareInterceptor(handler, middleware)); listener.Subscribe(sink); var eventSource = TestEventSource.GetInstance(); listener.EnableEvents(eventSource, EventLevel.LogAlways, Keywords.All); return new SinkTrace() { Source = eventSource, Sink = sink, Listener = listener }; } #endregion [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorCoreTest")] [Fact] public void HttpEventCollectorCoreTest() { // authorization var trace = Trace((token, input) => { Assert.True(token == "TOKEN-GUID", "authentication"); return new Response(); }); trace.TraceInformation("info"); trace.Close(); // metadata double now = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; var metadata = new HttpEventCollectorEventInfo.Metadata( index: "main", source: "localhost", sourceType: "log", host: "demohost" ); trace = Trace( metadata: metadata, handler: (token, events) => { Assert.True(events[0].Index == "main"); Assert.True(events[0].Source == "localhost"); Assert.True(events[0].SourceType == "log"); Assert.True(events[0].Host == "demohost"); // check that timestamp is correct double time = double.Parse(events[0].Timestamp); Assert.True(time - now < 10.0); // it cannot be more than 10s after sending event return new Response(); } ); trace.TraceInformation("info"); trace.Close(); // test various tracing commands trace = Trace((token, events) => { Assert.True(events[0].Event.Message == "info"); return new Response(); }); trace.TraceInformation("info"); trace.Close(); trace = Trace((token, events) => { Assert.True(events[0].Event.Severity == "Information"); Assert.True(events[0].Event.Id == "1"); Assert.True(((string[])(events[0].Event.Data))[0] == "one"); Assert.True(((string[])(events[0].Event.Data))[1] == "two"); return new Response(); }); trace.TraceData(TraceEventType.Information, 1, new string[] { "one", "two" }); trace.Close(); trace = Trace((token, events) => { Assert.True(events[0].Event.Severity == "Critical"); Assert.True(events[0].Event.Id == "2"); return new Response(); }); trace.TraceEvent(TraceEventType.Critical, 2); trace.Close(); trace = Trace((token, events) => { Assert.True(events[0].Event.Severity == "Error"); Assert.True(events[0].Event.Id == "3"); Assert.True(events[0].Event.Message == "hello"); return new Response(); }); trace.TraceEvent(TraceEventType.Error, 3, "hello"); trace.Close(); trace = Trace((token, events) => { Assert.True(events[0].Event.Severity == "Resume"); Assert.True(events[0].Event.Id == "4"); Assert.True(events[0].Event.Message == "hello world"); return new Response(); }); trace.TraceEvent(TraceEventType.Resume, 4, "hello {0}", "world"); trace.Close(); Guid guid = new Guid("11111111-2222-3333-4444-555555555555"); trace = Trace((token, events) => { Assert.True(events[0].Event.Id == "5"); Assert.True(((Guid)(events[0].Event.Data)).CompareTo(guid) == 0); return new Response(); }); trace.TraceTransfer(5, "transfer", guid); trace.Close(); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorSerializationTest")] [Fact] public void HttpEventCollectorSerializationTest() { Func<String, List<HttpEventCollectorEventInfo>, Response> noopHandler = (token, events) => { return new Response(); }; int numFormattedEvents = 0; var middlewareEvents = new List<HttpEventCollectorEventInfo>(); var trace = TraceCustomFormatter( handler: (token, events) => { Assert.Equal(events.Count, 2); Assert.Equal(events[0].Event.Mesage, "hello"); return new Response(); }, formatter: (eventInfo) => { numFormattedEvents++; var ev = eventInfo.Event; switch (numFormattedEvents) { case 1: ev = ev.Message; break; case 2: ev = new { newProperty = "hello world!", Id = eventInfo.Event.Id, Message = eventInfo.Event.Message, Data = eventInfo.Event.Data, Severity = eventInfo.Event.Severity }; break; case 3: string[] fieldArray = { "that", "I", "want" }; ev = new { i = "can", use = "any", fields = fieldArray, seriously = true, num = 99.9 }; break; } return ev; }, middleware: new HttpEventCollectorSender.HttpEventCollectorMiddleware((token, events, next) => { middlewareEvents = events; Response response = noopHandler(token, events); HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); httpResponseMessage.StatusCode = response.Code; byte[] buf = Encoding.UTF8.GetBytes(response.Context); httpResponseMessage.Content = new StringContent(response.Context); var task = new Task<HttpResponseMessage>(() => { return httpResponseMessage; }); task.RunSynchronously(); return task; }) ); trace.TraceInformation("hello"); trace.TraceInformation("hello2"); trace.TraceInformation("hello3"); (trace.Listeners[trace.Listeners.Count - 1] as HttpEventCollectorTraceListener).FlushAsync().RunSynchronously(); trace.Close(); Assert.Equal(numFormattedEvents, 3); Assert.Equal(middlewareEvents.Count, 3); Assert.Equal(middlewareEvents[0].Event, "hello"); Assert.Equal(middlewareEvents[1].Event.Message, "hello2"); Assert.Equal(middlewareEvents[1].Event.Severity, "Information"); Assert.Equal(middlewareEvents[1].Event.Id, "0"); // Defaults to "0" Assert.Equal(middlewareEvents[1].Event.newProperty, "hello world!"); Assert.Equal(middlewareEvents[2].Event.i, "can"); Assert.Equal(middlewareEvents[2].Event.use, "any"); Assert.Equal(middlewareEvents[2].Event.fields.Length, 3); string[] expectedFields = { "that", "I", "want" }; Assert.Equal(middlewareEvents[2].Event.fields, expectedFields); Assert.Equal(middlewareEvents[2].Event.seriously, true); Assert.Equal(middlewareEvents[2].Event.num, 99.9); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorBatchingCountTest")] [Fact] public void HttpEventCollectorBatchingCountTest() { var trace = Trace( handler: (token, events) => { Assert.True(events.Count == 3); Assert.True(events[0].Event.Message == "info 1"); Assert.True(events[1].Event.Message == "info 2"); Assert.True(events[2].Event.Message == "info 3"); return new Response(); }, batchSizeCount: 3 ); trace.TraceInformation("info 1"); trace.TraceInformation("info 2"); trace.TraceInformation("info 3"); trace.TraceInformation("info 1"); trace.TraceInformation("info 2"); trace.TraceInformation("info 3"); trace.Close(); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorBatchingSizeTest")] [Fact] public void HttpEventCollectorBatchingSizeTest() { // estimate serialized event size HttpEventCollectorEventInfo ei = new HttpEventCollectorEventInfo(null, TraceEventType.Information.ToString(), "info ?", null, null); int size = HttpEventCollectorSender.SerializeEventInfo(ei).Length; var trace = Trace( handler: (token, events) => { Assert.True(events.Count == 4); Assert.True(events[0].Event.Message == "info 1"); Assert.True(events[1].Event.Message == "info 2"); Assert.True(events[2].Event.Message == "info 3"); Assert.True(events[3].Event.Message == "info 4"); return new Response(); }, batchSizeBytes: 4 * size - size / 2 // 4 events trigger post ); trace.TraceInformation("info 1"); trace.TraceInformation("info 2"); trace.TraceInformation("info 3"); trace.TraceInformation("info 4"); trace.TraceInformation("info 1"); trace.TraceInformation("info 2"); trace.TraceInformation("info 3"); trace.TraceInformation("info 4"); trace.Close(); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorBatchingIntervalTest")] [Fact] public void HttpEventCollectorBatchingIntervalTest() { var trace = Trace( handler: (token, events) => { Assert.True(events.Count == 4); Assert.True(events[0].Event.Message == "info 1"); Assert.True(events[1].Event.Message == "info 2"); Assert.True(events[2].Event.Message == "info 3"); Assert.True(events[3].Event.Message == "info 4"); return new Response(); }, batchInterval: 1000 ); trace.TraceInformation("info 1"); trace.TraceInformation("info 2"); trace.TraceInformation("info 3"); trace.TraceInformation("info 4"); trace.Close(); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorResendTest")] [Fact] public void HttpEventCollectorResendTest() { int resendCount = 0; HttpEventCollectorResendMiddleware resend = new HttpEventCollectorResendMiddleware(3); var trace = Trace( handler: (auth, input) => { resendCount++; // mimic server error, this problem is considered as "fixable" // by resend middleware return new Response(HttpStatusCode.InternalServerError, "{\"text\":\"Error\"}"); }, middleware: (new HttpEventCollectorResendMiddleware(3)).Plugin // repeat 3 times ); (trace.Listeners[trace.Listeners.Count-1] as HttpEventCollectorTraceListener).AddLoggingFailureHandler( (exception) => { // error handler should be called after a single "normal post" and 3 "retries" Assert.True(resendCount == 4); // check exception events Assert.True(exception.Events.Count == 1); Assert.True(exception.Events[0].Event.Message == "info"); }); trace.TraceInformation("info"); trace.Close(); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorSinkCoreTest")] [Fact] public void HttpEventCollectorSinkCoreTest() { // authorization var trace = TraceSource((token, events) => { Assert.True(token == "TOKEN-GUID", "authentication"); return new Response(); }); trace.Source.Message("", ""); trace.Dispose(); // metadata var metadata = new HttpEventCollectorEventInfo.Metadata( index: "main", source: "localhost", sourceType: "log", host: "demohost" ); trace = TraceSource( metadata: metadata, handler: (token, events) => { Assert.True(events[0].Event.Message == "EventId=1 EventName=MessageInfo Level=Error \"FormattedMessage=world - hello\" \"message=hello\" \"caller=world\"\r\n"); Assert.True(events[0].Index == "main"); Assert.True(events[0].Source == "localhost"); Assert.True(events[0].SourceType == "log"); Assert.True(events[0].Host == "demohost"); return new Response(); } ); trace.Source.Message("hello", "world"); trace.Dispose(); // timestamp // metadata double now = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds; trace = TraceSource( handler: (token, events) => { // check that timestamp is correct double time = double.Parse(events[0].Timestamp); Assert.True(time - now < 10.0); // it cannot be more than 10s after sending event return new Response(); } ); trace.Source.Message("", ""); trace.Dispose(); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorSinkBatchingTest")] [Fact] public void HttpEventCollectorSinkBatchingTest() { var trace = TraceSource((token, events) => { Assert.True(events.Count == 3); Assert.True(events[0].Event.Message == "EventId=1 EventName=MessageInfo Level=Error \"FormattedMessage=one - 1\" \"message=1\" \"caller=one\"\r\n"); Assert.True(events[1].Event.Message == "EventId=1 EventName=MessageInfo Level=Error \"FormattedMessage=two - 2\" \"message=2\" \"caller=two\"\r\n"); Assert.True(events[2].Event.Message == "EventId=1 EventName=MessageInfo Level=Error \"FormattedMessage=three - 3\" \"message=3\" \"caller=three\"\r\n"); return new Response(); }, batchSizeCount: 3); trace.Source.Message("1", "one"); trace.Source.Message("2", "two"); trace.Source.Message("3", "three"); trace.Source.Message("1", "one"); trace.Source.Message("2", "two"); trace.Source.Message("3", "three"); trace.Dispose(); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorAsyncFlushTest")] [Fact] public void HttpEventCollectorAsyncFlushTest() { var trace = Trace( handler: (token, events) => { Assert.True(events.Count == 4); Assert.True(events[0].Event.Message == "info 1"); Assert.True(events[1].Event.Message == "info 2"); Assert.True(events[2].Event.Message == "info 3"); Assert.True(events[3].Event.Message == "info 4"); return new Response(); }, batchInterval: 10000 ); trace.TraceInformation("info 1"); trace.TraceInformation("info 2"); trace.TraceInformation("info 3"); trace.TraceInformation("info 4"); HttpEventCollectorTraceListener listener = trace.Listeners[1] as HttpEventCollectorTraceListener; listener.FlushAsync().RunSynchronously(); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorSeqModeTest")] [Fact] public void HttpEventCollectorSeqModeTest() { int expected = 0; var trace = Trace( handler: (token, events) => { Assert.True(events.Count == 1); Assert.True(int.Parse(events[0].Event.Message) == expected); expected++; return new Response(); }, sendMode: HttpEventCollectorSender.SendMode.Sequential ); for (int n = 0; n < 100; n++) trace.TraceInformation(n.ToString()); trace.Close(); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorSeqModeWithBatchTest")] [Fact] public void HttpEventCollectorSeqModeWithBatchTest() { int expected = 0; var trace = Trace( handler: (token, events) => { Assert.True(events.Count == 2); Assert.True(int.Parse(events[0].Event.Message) == expected); Assert.True(int.Parse(events[1].Event.Message) == expected + 1); expected += 2; return new Response(); }, sendMode: HttpEventCollectorSender.SendMode.Sequential, batchSizeCount: 2 ); for (int n = 0; n < 100; n++) trace.TraceInformation(n.ToString()); trace.Close(); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorDefaultSettingsCountTest")] [Fact] public void HttpEventCollectorDefaultSettingsCountTest() { var trace = TraceDefault( handler: (token, events) => { Assert.True(events.Count == HttpEventCollectorSender.DefaultBatchCount); return new Response(); } ); for (int n = 0; n < HttpEventCollectorSender.DefaultBatchCount * 10; n++) trace.TraceInformation(n.ToString()); trace.Close(); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorDefaultSettingsSizeTest")] [Fact] public void HttpEventCollectorDefaultSettingsSizeTest() { var trace = TraceDefault( handler: (token, events) => { Assert.True(events.Count == 1); return new Response(); } ); for (int n = 0; n < 10; n++) { trace.TraceInformation(new String('*', HttpEventCollectorSender.DefaultBatchSize)); } trace.Close(); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorDefaultSettingsIntervalTest")] [Fact] public void HttpEventCollectorDefaultSettingsIntervalTest() { bool eventReceived = false; var trace = TraceDefault( handler: (token, events) => { eventReceived = true; return new Response(); } ); trace.TraceInformation("=|:-)"); Thread.Sleep(HttpEventCollectorSender.DefaultBatchInterval / 2); Assert.False(eventReceived); Thread.Sleep(HttpEventCollectorSender.DefaultBatchInterval); Assert.True(eventReceived); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorEventInfoTimestampsTest")] [Fact] public void HttpEventCollectorEventInfoTimestampsTest() { // test setting timestamp DateTime utcNow = DateTime.UtcNow; double nowEpoch = (utcNow - new DateTime(1970, 1, 1)).TotalSeconds; HttpEventCollectorEventInfo ei = new HttpEventCollectorEventInfo(utcNow.AddHours(-1), null, null, null, null, null); double epochTimestamp = double.Parse(ei.Timestamp); double diff = Math.Ceiling(nowEpoch - epochTimestamp); Assert.True(diff >= 3600.0); // test default timestamp ei = new HttpEventCollectorEventInfo(null, null, null, null, null); utcNow = DateTime.UtcNow; nowEpoch = (utcNow - new DateTime(1970, 1, 1)).TotalSeconds; epochTimestamp = double.Parse(ei.Timestamp); diff = Math.Ceiling(nowEpoch - epochTimestamp); Assert.True(diff< 10.0); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorEventInfoTimestampsInvariantTest")] [Fact] public void HttpEventCollectorEventInfoTimestampsInvariantTest() { // Change Culture temporarily for this test var backupCulture = Thread.CurrentThread.CurrentCulture; Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE"); // test setting timestamp DateTime utcNow = DateTime.UtcNow; double nowEpoch = (utcNow - new DateTime(1970, 1, 1)).TotalSeconds; HttpEventCollectorEventInfo ei = new HttpEventCollectorEventInfo(utcNow.AddHours(-1), null, null, null, null, null); // Reset the culture before any assertions Thread.CurrentThread.CurrentCulture = backupCulture; // Ensure we have a comma when using a non-US culture Assert.True(ei.Timestamp.Contains(",")); } [Trait("integration-tests", "Splunk.Logging.HttpEventCollectorSenderMetadataOverrideTest")] [Fact] public void HttpEventCollectorSenderMetadataOverrideTest() { Func<String, List<HttpEventCollectorEventInfo>, Response> noopHandler = (token, events) => { return new Response(); }; HttpEventCollectorEventInfo.Metadata defaultmetadata = new HttpEventCollectorEventInfo.Metadata(index: "defaulttestindex", source: "defaulttestsource", sourceType: "defaulttestsourcetype", host: "defaulttesthost"); HttpEventCollectorEventInfo.Metadata overridemetadata = new HttpEventCollectorEventInfo.Metadata(index: "overridetestindex", source: "overridetestsource", sourceType: "overridetestsourcetype", host: "overridetesthost"); HttpEventCollectorSender httpEventCollectorSender = new HttpEventCollectorSender(uri, "TOKEN-GUID", defaultmetadata, HttpEventCollectorSender.SendMode.Sequential, 100000, 100000, 3, new HttpEventCollectorSender.HttpEventCollectorMiddleware((token, events, next) => { Assert.True(events.Count == 3); // Id = id1 should have the default meta data values. Assert.True(events[0].Event.Id == "id1"); Assert.True(events[0].Index == defaultmetadata.Index); Assert.True(events[0].Source == defaultmetadata.Source); Assert.True(events[0].SourceType == defaultmetadata.SourceType); Assert.True(events[0].Host == defaultmetadata.Host); // Id = id2 should have the metadataOverride values. Assert.True(events[1].Event.Id == "id2"); Assert.True(events[1].Index == overridemetadata.Index); Assert.True(events[1].Source == overridemetadata.Source); Assert.True(events[1].SourceType == overridemetadata.SourceType); Assert.True(events[1].Host == overridemetadata.Host); // Id = id3 should have the default meta data values. Assert.True(events[2].Event.Id == "id3"); Assert.True(events[2].Index == defaultmetadata.Index); Assert.True(events[2].Source == defaultmetadata.Source); Assert.True(events[2].SourceType == defaultmetadata.SourceType); Assert.True(events[2].Host == defaultmetadata.Host); Response response = noopHandler(token, events); HttpResponseMessage httpResponseMessage = new HttpResponseMessage(); httpResponseMessage.StatusCode = response.Code; byte[] buf = Encoding.UTF8.GetBytes(response.Context); httpResponseMessage.Content = new StringContent(response.Context); var task = new Task<HttpResponseMessage>(() => { return httpResponseMessage; }); task.RunSynchronously(); return task; }) ); httpEventCollectorSender.Send(id: "id1"); httpEventCollectorSender.Send(id: "id2", metadataOverride: overridemetadata); httpEventCollectorSender.Send(id: "id3"); httpEventCollectorSender.FlushSync(); httpEventCollectorSender.Dispose(); } } }
using System; using System.Diagnostics; using i64 = System.Int64; namespace System.Data.SQLite { public 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. ** ************************************************************************* ** This file contains the sqlite3_get_table() and //sqlite3_free_table() ** interface routines. These are just wrappers around the main ** interface routine of sqlite3_exec(). ** ** These routines are in a separate files so that they will not be linked ** if they are not used. ************************************************************************* ** 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" //#include <stdlib.h> //#include <string.h> #if !SQLITE_OMIT_GET_TABLE /* ** This structure is used to pass data from sqlite3_get_table() through ** to the callback function is uses to build the result. */ class TabResult { public string[] azResult; public string zErrMsg; public int nResult; public int nAlloc; public int nRow; public int nColumn; public int nData; public int rc; }; /* ** This routine is called once for each row in the result table. Its job ** is to fill in the TabResult structure appropriately, allocating new ** memory as necessary. */ static public int sqlite3_get_table_cb( object pArg, i64 nCol, object Oargv, object Ocolv ) { string[] argv = (string[])Oargv; string[]colv = (string[])Ocolv; TabResult p = (TabResult)pArg; int need; int i; string z; /* Make sure there is enough space in p.azResult to hold everything ** we need to remember from this invocation of the callback. */ if( p.nRow==0 && argv!=null ){ need = (int)nCol*2; }else{ need = (int)nCol; } if( p.nData + need >= p.nAlloc ){ string[] azNew; p.nAlloc = p.nAlloc*2 + need + 1; azNew = new string[p.nAlloc];//sqlite3_realloc( p.azResult, sizeof(char*)*p.nAlloc ); if( azNew==null ) goto malloc_failed; p.azResult = azNew; } /* If this is the first row, then generate an extra row containing ** the names of all columns. */ if( p.nRow==0 ){ p.nColumn = (int)nCol; for(i=0; i<nCol; i++){ z = sqlite3_mprintf("%s", colv[i]); if( z==null ) goto malloc_failed; p.azResult[p.nData++ -1] = z; } }else if( p.nColumn!=nCol ){ //sqlite3_free(ref p.zErrMsg); p.zErrMsg = sqlite3_mprintf( "sqlite3_get_table() called with two or more incompatible queries" ); p.rc = SQLITE_ERROR; return 1; } /* Copy over the row data */ if( argv!=null ){ for(i=0; i<nCol; i++){ if( argv[i]==null ){ z = null; }else{ int n = sqlite3Strlen30(argv[i])+1; //z = sqlite3_malloc( n ); //if( z==0 ) goto malloc_failed; z= argv[i];//memcpy(z, argv[i], n); } p.azResult[p.nData++ -1] = z; } p.nRow++; } return 0; malloc_failed: p.rc = SQLITE_NOMEM; return 1; } /* ** Query the database. But instead of invoking a callback for each row, ** malloc() for space to hold the result and return the entire results ** at the conclusion of the call. ** ** The result that is written to ***pazResult is held in memory obtained ** from malloc(). But the caller cannot free this memory directly. ** Instead, the entire table should be passed to //sqlite3_free_table() when ** the calling procedure is finished using it. */ static public int sqlite3_get_table( sqlite3 db, /* The database on which the SQL executes */ string zSql, /* The SQL to be executed */ ref string[] pazResult, /* Write the result table here */ ref int pnRow, /* Write the number of rows in the result here */ ref int pnColumn, /* Write the number of columns of result here */ ref string pzErrMsg /* Write error messages here */ ){ int rc; TabResult res = new TabResult(); pazResult = null; pnColumn = 0; pnRow = 0; pzErrMsg = ""; res.zErrMsg = ""; res.nResult = 0; res.nRow = 0; res.nColumn = 0; res.nData = 1; res.nAlloc = 20; res.rc = SQLITE_OK; res.azResult = new string[res.nAlloc];// sqlite3_malloc( sizeof( char* ) * res.nAlloc ); if( res.azResult==null ){ db.errCode = SQLITE_NOMEM; return SQLITE_NOMEM; } res.azResult[0] = null; rc = sqlite3_exec(db, zSql, (dxCallback) sqlite3_get_table_cb, res, ref pzErrMsg); //Debug.Assert( sizeof(res.azResult[0])>= sizeof(res.nData) ); //res.azResult = SQLITE_INT_TO_PTR( res.nData ); if( (rc&0xff)==SQLITE_ABORT ){ //sqlite3_free_table(ref res.azResult[1] ); if( res.zErrMsg !=""){ if( pzErrMsg !=null ){ //sqlite3_free(ref pzErrMsg); pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg); } //sqlite3_free(ref res.zErrMsg); } db.errCode = res.rc; /* Assume 32-bit assignment is atomic */ return res.rc; } //sqlite3_free(ref res.zErrMsg); if( rc!=SQLITE_OK ){ //sqlite3_free_table(ref res.azResult[1]); return rc; } if( res.nAlloc>res.nData ){ string[] azNew; Array.Resize(ref res.azResult, res.nData-1);//sqlite3_realloc( res.azResult, sizeof(char*)*(res.nData+1) ); //if( azNew==null ){ // //sqlite3_free_table(ref res.azResult[1]); // db.errCode = SQLITE_NOMEM; // return SQLITE_NOMEM; //} res.nAlloc = res.nData+1; //res.azResult = azNew; } pazResult = res.azResult; pnColumn = res.nColumn; pnRow = res.nRow; return rc; } /* ** This routine frees the space the sqlite3_get_table() malloced. */ static void //sqlite3_free_table( ref string azResult /* Result returned from from sqlite3_get_table() */ ){ if( azResult !=null){ int i, n; //azResult--; //Debug.Assert( azResult!=0 ); //n = SQLITE_PTR_TO_INT(azResult[0]); //for(i=1; i<n; i++){ if( azResult[i] ) //sqlite3_free(azResult[i]); } //sqlite3_free(ref azResult); } } #endif //* SQLITE_OMIT_GET_TABLE */ } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * * Contains some contributions under the Thrift Software License. * Please see doc/old-thrift-license.txt in the Thrift distribution for * details. */ using System; using System.Net.Sockets; namespace FluentCassandra.Thrift.Transport { public class TSocket : TStreamTransport { private TcpClient client = null; private string host = null; private int port = 0; private int timeout = 0; public TSocket(TcpClient client) { this.client = client; if (IsOpen) { inputStream = client.GetStream(); outputStream = client.GetStream(); } } public TSocket(string host, int port) : this(host, port, 0) { } public TSocket(string host, int port, int timeout) { this.host = host; this.port = port; this.timeout = timeout; InitSocket(); } private void InitSocket() { client = new TcpClient(); client.ReceiveTimeout = client.SendTimeout = timeout; client.Client.NoDelay = true; } public int Timeout { set { client.ReceiveTimeout = client.SendTimeout = timeout = value; } } public TcpClient TcpClient { get { return client; } } public string Host { get { return host; } } public int Port { get { return port; } } public override bool IsOpen { get { if (client == null) { return false; } return client.Connected; } } public override void Open() { if (IsOpen) { throw new TTransportException(TTransportException.ExceptionType.AlreadyOpen, "Socket already connected"); } if (String.IsNullOrEmpty(host)) { throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open null host"); } if (port <= 0) { throw new TTransportException(TTransportException.ExceptionType.NotOpen, "Cannot open without port"); } if (client == null) { InitSocket(); } if( timeout == 0) // no timeout -> infinite { client.Connect(host, port); } else // we have a timeout -> use it { ConnectHelper hlp = new ConnectHelper(client); IAsyncResult asyncres = client.BeginConnect(host, port, new AsyncCallback(ConnectCallback), hlp); bool bConnected = asyncres.AsyncWaitHandle.WaitOne(timeout) && client.Connected; if (!bConnected) { lock (hlp.Mutex) { if( hlp.CallbackDone) { asyncres.AsyncWaitHandle.Close(); client.Close(); } else { hlp.DoCleanup = true; client = null; } } throw new TTransportException(TTransportException.ExceptionType.TimedOut, "Connect timed out"); } } inputStream = client.GetStream(); outputStream = client.GetStream(); } static void ConnectCallback(IAsyncResult asyncres) { ConnectHelper hlp = asyncres.AsyncState as ConnectHelper; lock (hlp.Mutex) { hlp.CallbackDone = true; try { if( hlp.Client.Client != null) hlp.Client.EndConnect(asyncres); } catch (SocketException) { // catch that away } if (hlp.DoCleanup) { asyncres.AsyncWaitHandle.Close(); if (hlp.Client is IDisposable) ((IDisposable)hlp.Client).Dispose(); hlp.Client = null; } } } private class ConnectHelper { public object Mutex = new object(); public bool DoCleanup = false; public bool CallbackDone = false; public TcpClient Client; public ConnectHelper(TcpClient client) { Client = client; } } public override void Close() { base.Close(); if (client != null) { client.Close(); client = null; } } #region " IDisposable Support " private bool _IsDisposed; // IDisposable protected override void Dispose(bool disposing) { if (!_IsDisposed) { if (disposing) { if (client != null) ((IDisposable)client).Dispose(); base.Dispose(disposing); } } _IsDisposed = true; } #endregion } }
using System; using NUnit.Framework; namespace DotSpatial.Projections.Tests.Geographic { /// <summary> /// This class contains all the tests for the Europe category of Geographic coordinate systems /// </summary> [TestFixture] public class Europe { [Test] public void Belge1972_EPSG31370() { // see https://dotspatial.codeplex.com/discussions/548133 var source = ProjectionInfo.FromEpsgCode(31370); var dest = KnownCoordinateSystems.Geographic.World.WGS1984; double[] vertices = { 156117.21, 133860.06 }; Reproject.ReprojectPoints(vertices, null, source, dest, 0, 1); Assert.IsTrue(Math.Abs(vertices[0] - 4.455) < 1e-7); Assert.IsTrue(Math.Abs(vertices[1] - 50.515485) < 1e-7); } [Test] public void Albanian1987() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Albanian1987; Tester.TestProjection(pStart); } [Test] public void ATFParis() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.ATFParis; Tester.TestProjection(pStart); } [Test] public void Belge1950Brussels() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Belge1950Brussels; Tester.TestProjection(pStart); } [Test] public void Belge1972() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Belge1972; Tester.TestProjection(pStart); } [Test] public void Bern1898() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Bern1898; Tester.TestProjection(pStart); } [Test] public void Bern1898Bern() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Bern1898Bern; Tester.TestProjection(pStart); } [Test] public void Bern1938() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Bern1938; Tester.TestProjection(pStart); } [Test] public void CH1903() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.CH1903; Tester.TestProjection(pStart); } [Test] public void Datum73() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Datum73; Tester.TestProjection(pStart); } [Test] public void DatumLisboaBessel() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.DatumLisboaBessel; Tester.TestProjection(pStart); } [Test] public void DatumLisboaHayford() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.DatumLisboaHayford; Tester.TestProjection(pStart); } [Test] public void DealulPiscului1933Romania() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.DealulPiscului1933Romania; Tester.TestProjection(pStart); } [Test] public void DealulPiscului1970Romania() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.DealulPiscului1970Romania; Tester.TestProjection(pStart); } [Test] public void DeutscheHauptdreiecksnetz() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.DeutscheHauptdreiecksnetz; Tester.TestProjection(pStart); } [Test, Ignore("")] // to be removed eventually, replaced with Amersfoort, DutchRD is to be found in ProjectedCategories.Nationalgrids as it is a Projected coordinate system public void DutchRD() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.DutchRD; Tester.TestProjection(pStart); } [Test] public void Amersfoort() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Amersfoort; Tester.TestProjection(pStart); } [Test] public void Estonia1937() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Estonia1937; Tester.TestProjection(pStart); } [Test] public void Estonia1992() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Estonia1992; Tester.TestProjection(pStart); } [Test] public void Estonia1997() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Estonia1997; Tester.TestProjection(pStart); } [Test] public void ETRF1989() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.ETRF1989; Tester.TestProjection(pStart); } [Test] public void ETRS1989() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.ETRS1989; Tester.TestProjection(pStart); } [Test] public void EUREFFIN() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.EUREFFIN; Tester.TestProjection(pStart); } [Test] public void European1979() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.European1979; Tester.TestProjection(pStart); } [Test] public void EuropeanDatum1950() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.EuropeanDatum1950; Tester.TestProjection(pStart); } [Test] public void EuropeanDatum1987() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.EuropeanDatum1987; Tester.TestProjection(pStart); } [Test] [Ignore("Verify this test")] public void Greek() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Greek; Tester.TestProjection(pStart); } [Test] [Ignore("Verify this test")] public void GreekAthens() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.GreekAthens; Tester.TestProjection(pStart); } [Test] public void GreekGeodeticRefSystem1987() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.GreekGeodeticRefSystem1987; Tester.TestProjection(pStart); } [Test] public void Hermannskogel() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Hermannskogel; Tester.TestProjection(pStart); } [Test] public void Hjorsey1955() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Hjorsey1955; Tester.TestProjection(pStart); } [Test] public void HungarianDatum1972() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.HungarianDatum1972; Tester.TestProjection(pStart); } [Test] public void IRENET95() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.IRENET95; Tester.TestProjection(pStart); } [Test] public void ISN1993() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.ISN1993; Tester.TestProjection(pStart); } [Test] public void Kartastokoordinaattijarjestelma() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Kartastokoordinaattijarjestelma; Tester.TestProjection(pStart); } [Test] public void Lisbon() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Lisbon; Tester.TestProjection(pStart); } [Test] public void LisbonLisbon() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.LisbonLisbon; Tester.TestProjection(pStart); } [Test] public void Lisbon1890() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Lisbon1890; Tester.TestProjection(pStart); } [Test] public void Lisbon1890Lisbon() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Lisbon1890Lisbon; Tester.TestProjection(pStart); } [Test] public void LKS1992() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.LKS1992; Tester.TestProjection(pStart); } [Test] public void LKS1994() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.LKS1994; Tester.TestProjection(pStart); } [Test] public void Luxembourg1930() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Luxembourg1930; Tester.TestProjection(pStart); } [Test] public void Madrid1870Madrid() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Madrid1870Madrid; Tester.TestProjection(pStart); } [Test] public void MGIFerro() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.MGIFerro; Tester.TestProjection(pStart); } [Test] public void MilitarGeographischeInstitut() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.MilitarGeographischeInstitut; Tester.TestProjection(pStart); } [Test] public void MonteMario() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.MonteMario; Tester.TestProjection(pStart); } [Test] public void MonteMarioRome() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.MonteMarioRome; Tester.TestProjection(pStart); } [Test] public void NGO1948() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.NGO1948; Tester.TestProjection(pStart); } [Test] public void NGO1948Oslo() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.NGO1948Oslo; Tester.TestProjection(pStart); } [Test] public void NorddeGuerreParis() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.NorddeGuerreParis; Tester.TestProjection(pStart); } [Test] public void NouvelleTriangulationFrancaise() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.NouvelleTriangulationFrancaise; Tester.TestProjection(pStart); } [Test] public void NTFParis() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.NTFParis; Tester.TestProjection(pStart); } [Test] public void OSSN1980() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.OSSN1980; Tester.TestProjection(pStart); } [Test] public void OSGB1936() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.OSGB1936; Tester.TestProjection(pStart); } [Test] public void OSGB1970SN() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.OSGB1970SN; Tester.TestProjection(pStart); } [Test] public void OSNI1952() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.OSNI1952; Tester.TestProjection(pStart); } [Test] public void Pulkovo1942() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Pulkovo1942; Tester.TestProjection(pStart); } [Test] public void Pulkovo1942Adj1958() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Pulkovo1942Adj1958; Tester.TestProjection(pStart); } [Test] public void Pulkovo1942Adj1983() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Pulkovo1942Adj1983; Tester.TestProjection(pStart); } [Test] public void Pulkovo1995() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Pulkovo1995; Tester.TestProjection(pStart); } [Test] public void Qornoq() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Qornoq; Tester.TestProjection(pStart); } [Test] public void ReseauNationalBelge1950() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.ReseauNationalBelge1950; Tester.TestProjection(pStart); } [Test] public void ReseauNationalBelge1972() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.ReseauNationalBelge1972; Tester.TestProjection(pStart); } [Test] public void Reykjavik1900() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Reykjavik1900; Tester.TestProjection(pStart); } [Test] public void RGF1993() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.RGF1993; Tester.TestProjection(pStart); } [Test] public void Roma1940() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.Roma1940; Tester.TestProjection(pStart); } [Test] public void RT1990() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.RT1990; Tester.TestProjection(pStart); } [Test] public void RT38() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.RT38; Tester.TestProjection(pStart); } [Test] public void RT38Stockholm() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.RT38Stockholm; Tester.TestProjection(pStart); } [Test] public void S42Hungary() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.S42Hungary; Tester.TestProjection(pStart); } [Test] public void SJTSK() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.SJTSK; Tester.TestProjection(pStart); } [Test] public void SWEREF99() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.SWEREF99; Tester.TestProjection(pStart); } [Test] public void SwissTRF1995() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.SwissTRF1995; Tester.TestProjection(pStart); } [Test] public void TM65() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.TM65; Tester.TestProjection(pStart); } [Test] public void TM75() { ProjectionInfo pStart = KnownCoordinateSystems.Geographic.Europe.TM75; Tester.TestProjection(pStart); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================= ** ** ** ** ** ** Purpose: The BitArray class manages a compact array of bit values. ** ** =============================================================================*/ namespace System.Collections { using System; using System.Security.Permissions; using System.Diagnostics.Contracts; // A vector of bits. Use this to store bits efficiently, without having to do bit // shifting yourself. [System.Runtime.InteropServices.ComVisible(true)] [Serializable()] public sealed class BitArray : ICollection, ICloneable { private BitArray() { } /*========================================================================= ** 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), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); 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)); } Contract.EndContractBlock(); // 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 > Int32.MaxValue / BitsPerByte) { throw new ArgumentException(Environment.GetResourceString("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; } Contract.Assert(bytes.Length - j >= 0, "BitArray byteLength problem"); Contract.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)); } Contract.EndContractBlock(); 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)); } Contract.EndContractBlock(); // this value is chosen to prevent overflow when computing m_length if (values.Length > Int32.MaxValue / BitsPerInt32) { throw new ArgumentException(Environment.GetResourceString("Argument_ArrayTooLarge", BitsPerInt32), nameof(values)); } m_array = new int[values.Length]; m_length = values.Length * BitsPerInt32; Array.Copy(values, m_array, values.Length); _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)); } Contract.EndContractBlock(); int arrayLength = GetArrayLength(bits.m_length, BitsPerInt32); m_array = new int[arrayLength]; m_length = bits.m_length; Array.Copy(bits.m_array, m_array, arrayLength); _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), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); 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), Environment.GetResourceString("ArgumentOutOfRange_Index")); } Contract.EndContractBlock(); 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(Environment.GetResourceString("Arg_ArrayLengthsDiffer")); Contract.EndContractBlock(); 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(Environment.GetResourceString("Arg_ArrayLengthsDiffer")); Contract.EndContractBlock(); 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(Environment.GetResourceString("Arg_ArrayLengthsDiffer")); Contract.EndContractBlock(); 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; } public int Length { get { Contract.Ensures(Contract.Result<int>() >= 0); return m_length; } set { if (value < 0) { throw new ArgumentOutOfRangeException(nameof(value), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); } Contract.EndContractBlock(); int newints = GetArrayLength(value, BitsPerInt32); if (newints > m_array.Length || newints + _ShrinkThreshold < m_array.Length) { // grow or shrink (if wasting more than _ShrinkThreshold ints) int[] newarray = new int[newints]; Array.Copy(m_array, newarray, newints > m_array.Length ? m_array.Length : newints); m_array = newarray; } 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++; } } // ICollection implementation public void CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(nameof(array)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (array.Rank != 1) throw new ArgumentException(Environment.GetResourceString("Arg_RankMultiDimNotSupported"), nameof(array)); Contract.EndContractBlock(); if (array is int[]) { Array.Copy(m_array, 0, array, index, GetArrayLength(m_length, BitsPerInt32)); } else if (array is byte[]) { int arrayLength = GetArrayLength(m_length, BitsPerByte); if ((array.Length - index) < arrayLength) throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen")); byte [] b = (byte[])array; 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 } else if (array is bool[]) { if (array.Length - index < m_length) throw new ArgumentException(Environment.GetResourceString("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(Environment.GetResourceString("Arg_BitArrayTypeUnsupported"), nameof(array)); } public int Count { get { Contract.Ensures(Contract.Result<int>() >= 0); return m_length; } } public Object Clone() { Contract.Ensures(Contract.Result<Object>() != null); Contract.Ensures(((BitArray)Contract.Result<Object>()).Length == this.Length); return new BitArray(this); } public Object SyncRoot { get { if( _syncRoot == null) { System.Threading.Interlocked.CompareExchange<Object>(ref _syncRoot, new Object(), null); } return _syncRoot; } } public bool IsReadOnly { get { return false; } } public bool IsSynchronized { get { return false; } } 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) { Contract.Assert(div > 0, "GetArrayLength: div arg must be greater than 0"); return n > 0 ? (((n - 1) / div) + 1) : 0; } [Serializable] 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() { if (version != bitarray._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion)); if (index < (bitarray.Count-1)) { index++; currentElement = bitarray.Get(index); return true; } else index = bitarray.Count; return false; } public virtual Object Current { get { if (index == -1) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted)); if (index >= bitarray.Count) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded)); return currentElement; } } public void Reset() { if (version != bitarray._version) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumFailedVersion)); index = -1; } } private int[] m_array; private int m_length; private int _version; [NonSerialized] private Object _syncRoot; private const int _ShrinkThreshold = 256; } }
/** \file Projectile.cs \author Samuel J. Crawford, Brooks MacLachlan, and W. Spencer Smith \brief Contains the entire Projectile program */ using System; using System.IO; public class Projectile { /** \brief Controls the flow of the program \param args List of command-line arguments */ public static void Main(string[] args) { StreamWriter outfile; string filename = args[0]; outfile = new StreamWriter("log.txt", true); outfile.Write("var 'filename' assigned to "); outfile.Write(filename); outfile.WriteLine(" in module Projectile"); outfile.Close(); InputParameters inParams = new InputParameters(filename); double t_flight = func_t_flight(inParams); outfile = new StreamWriter("log.txt", true); outfile.Write("var 't_flight' assigned to "); outfile.Write(t_flight); outfile.WriteLine(" in module Projectile"); outfile.Close(); double p_land = func_p_land(inParams); outfile = new StreamWriter("log.txt", true); outfile.Write("var 'p_land' assigned to "); outfile.Write(p_land); outfile.WriteLine(" in module Projectile"); outfile.Close(); double d_offset = func_d_offset(inParams, p_land); outfile = new StreamWriter("log.txt", true); outfile.Write("var 'd_offset' assigned to "); outfile.Write(d_offset); outfile.WriteLine(" in module Projectile"); outfile.Close(); string s = func_s(inParams, d_offset); outfile = new StreamWriter("log.txt", true); outfile.Write("var 's' assigned to "); outfile.Write(s); outfile.WriteLine(" in module Projectile"); outfile.Close(); write_output(s, d_offset); } /** \brief Calculates flight duration: the time when the projectile lands (s) \param inParams structure holding the input values \return flight duration: the time when the projectile lands (s) */ public static double func_t_flight(InputParameters inParams) { StreamWriter outfile; outfile = new StreamWriter("log.txt", true); outfile.WriteLine("function func_t_flight called with inputs: {"); outfile.Write(" inParams = "); outfile.WriteLine("Instance of InputParameters object"); outfile.WriteLine(" }"); outfile.Close(); return 2 * inParams.v_launch * Math.Sin(inParams.theta) / Constants.g_vect; } /** \brief Calculates landing position: the distance from the launcher to the final position of the projectile (m) \param inParams structure holding the input values \return landing position: the distance from the launcher to the final position of the projectile (m) */ public static double func_p_land(InputParameters inParams) { StreamWriter outfile; outfile = new StreamWriter("log.txt", true); outfile.WriteLine("function func_p_land called with inputs: {"); outfile.Write(" inParams = "); outfile.WriteLine("Instance of InputParameters object"); outfile.WriteLine(" }"); outfile.Close(); return 2 * Math.Pow(inParams.v_launch, 2) * Math.Sin(inParams.theta) * Math.Cos(inParams.theta) / Constants.g_vect; } /** \brief Calculates distance between the target position and the landing position: the offset between the target position and the landing position (m) \param inParams structure holding the input values \param p_land landing position: the distance from the launcher to the final position of the projectile (m) \return distance between the target position and the landing position: the offset between the target position and the landing position (m) */ public static double func_d_offset(InputParameters inParams, double p_land) { StreamWriter outfile; outfile = new StreamWriter("log.txt", true); outfile.WriteLine("function func_d_offset called with inputs: {"); outfile.Write(" inParams = "); outfile.Write("Instance of InputParameters object"); outfile.WriteLine(", "); outfile.Write(" p_land = "); outfile.WriteLine(p_land); outfile.WriteLine(" }"); outfile.Close(); return p_land - inParams.p_target; } /** \brief Calculates output message as a string \param inParams structure holding the input values \param d_offset distance between the target position and the landing position: the offset between the target position and the landing position (m) \return output message as a string */ public static string func_s(InputParameters inParams, double d_offset) { StreamWriter outfile; outfile = new StreamWriter("log.txt", true); outfile.WriteLine("function func_s called with inputs: {"); outfile.Write(" inParams = "); outfile.Write("Instance of InputParameters object"); outfile.WriteLine(", "); outfile.Write(" d_offset = "); outfile.WriteLine(d_offset); outfile.WriteLine(" }"); outfile.Close(); if (Math.Abs(d_offset / inParams.p_target) < Constants.epsilon) { return "The target was hit."; } else if (d_offset < 0) { return "The projectile fell short."; } else { return "The projectile went long."; } } /** \brief Writes the output values to output.txt \param s output message as a string \param d_offset distance between the target position and the landing position: the offset between the target position and the landing position (m) */ public static void write_output(string s, double d_offset) { StreamWriter outfile; outfile = new StreamWriter("log.txt", true); outfile.WriteLine("function write_output called with inputs: {"); outfile.Write(" s = "); outfile.Write(s); outfile.WriteLine(", "); outfile.Write(" d_offset = "); outfile.WriteLine(d_offset); outfile.WriteLine(" }"); outfile.Close(); StreamWriter outputfile; outputfile = new StreamWriter("output.txt", false); outputfile.Write("s = "); outputfile.WriteLine(s); outputfile.Write("d_offset = "); outputfile.WriteLine(d_offset); outputfile.Close(); } } /** \brief Structure for holding the input values */ public class InputParameters { public double v_launch; public double theta; public double p_target; /** \brief Initializes input object by reading inputs and checking physical constraints and software constraints on the input \param filename name of the input file */ public InputParameters(string filename) { StreamWriter outfile; outfile = new StreamWriter("log.txt", true); outfile.WriteLine("function InputParameters called with inputs: {"); outfile.Write(" filename = "); outfile.WriteLine(filename); outfile.WriteLine(" }"); outfile.Close(); this.get_input(filename); this.input_constraints(); } /** \brief Reads input from a file with the given file name \param filename name of the input file */ private void get_input(string filename) { StreamWriter outfile; outfile = new StreamWriter("log.txt", true); outfile.WriteLine("function get_input called with inputs: {"); outfile.Write(" filename = "); outfile.WriteLine(filename); outfile.WriteLine(" }"); outfile.Close(); StreamReader infile; infile = new StreamReader(filename); infile.ReadLine(); this.v_launch = Double.Parse(infile.ReadLine()); outfile = new StreamWriter("log.txt", true); outfile.Write("var 'this.v_launch' assigned to "); outfile.Write(this.v_launch); outfile.WriteLine(" in module Projectile"); outfile.Close(); infile.ReadLine(); this.theta = Double.Parse(infile.ReadLine()); outfile = new StreamWriter("log.txt", true); outfile.Write("var 'this.theta' assigned to "); outfile.Write(this.theta); outfile.WriteLine(" in module Projectile"); outfile.Close(); infile.ReadLine(); this.p_target = Double.Parse(infile.ReadLine()); outfile = new StreamWriter("log.txt", true); outfile.Write("var 'this.p_target' assigned to "); outfile.Write(this.p_target); outfile.WriteLine(" in module Projectile"); outfile.Close(); infile.Close(); } /** \brief Verifies that input values satisfy the physical constraints and software constraints */ private void input_constraints() { StreamWriter outfile; outfile = new StreamWriter("log.txt", true); outfile.WriteLine("function input_constraints called with inputs: {"); outfile.WriteLine(" }"); outfile.Close(); if (!(this.v_launch > 0)) { Console.Write("Warning: "); Console.Write("v_launch has value "); Console.Write(this.v_launch); Console.Write(" but suggested to be "); Console.Write("above "); Console.Write(0); Console.WriteLine("."); } if (!(0 < this.theta && this.theta < Math.PI / 2)) { Console.Write("Warning: "); Console.Write("theta has value "); Console.Write(this.theta); Console.Write(" but suggested to be "); Console.Write("between "); Console.Write(0); Console.Write(" and "); Console.Write(Math.PI / 2); Console.Write(" ((pi)/(2))"); Console.WriteLine("."); } if (!(this.p_target > 0)) { Console.Write("Warning: "); Console.Write("p_target has value "); Console.Write(this.p_target); Console.Write(" but suggested to be "); Console.Write("above "); Console.Write(0); Console.WriteLine("."); } } } /** \brief Structure for holding the constant values */ public class Constants { public const double g_vect = 9.8; public const double epsilon = 2.0e-2; }
using System; using Android.Widget; using Android.Content; using Android.Util; namespace ManneDoForms.Droid.Common.PhotoViewDroid { public class PhotoViewDroid:ImageView,IPhotoViewDroid { private PhotoViewDroidAttacher mAttacher; private ScaleType mPendingScaleType; public PhotoViewDroid(Context context):base(context, null, 0) { base.SetScaleType(ScaleType.Matrix); mAttacher = new PhotoViewDroidAttacher(this); if (null != mPendingScaleType) { SetScaleType(mPendingScaleType); mPendingScaleType = null; } } public PhotoViewDroid(Context context, IAttributeSet attr) :base(context, attr, 0){ base.SetScaleType(ScaleType.Matrix); mAttacher = new PhotoViewDroidAttacher(this); if (null != mPendingScaleType) { SetScaleType(mPendingScaleType); mPendingScaleType = null; } } public PhotoViewDroid(Context context, IAttributeSet attr, int defStyle):base(context, attr, defStyle) { base.SetScaleType(ScaleType.Matrix); mAttacher = new PhotoViewDroidAttacher(this); if (null != mPendingScaleType) { SetScaleType(mPendingScaleType); mPendingScaleType = null; } } public PhotoViewDroidAttacher GetPhotoViewDroidAttacher() { return mAttacher; } #region IPhotoView imp public bool CanZoom () { return mAttacher.CanZoom(); } public Android.Graphics.RectF GetDisplayRect () { return mAttacher.GetDisplayRect(); } public bool SetDisplayMatrix (Android.Graphics.Matrix finalMatrix) { return mAttacher.SetDisplayMatrix(finalMatrix); } public Android.Graphics.Matrix GetDisplayMatrix () { return mAttacher.GetDrawMatrix(); } public float GetMinScale () { return GetMinimumScale(); } public float GetMinimumScale () { return mAttacher.GetMinimumScale(); } public float GetMidScale () { return GetMediumScale(); } public float GetMediumScale () { return mAttacher.GetMediumScale(); } public float GetMaxScale () { return GetMaximumScale(); } public float GetMaximumScale () { return mAttacher.GetMaximumScale(); } public float GetScale () { return mAttacher.GetScale(); } public override ImageView.ScaleType GetScaleType() { return mAttacher.GetScaleType(); } public void SetAllowParentInterceptOnEdge (bool allow) { mAttacher.SetAllowParentInterceptOnEdge(allow); } public void SetMinScale (float minScale) { SetMinimumScale(minScale); } public void SetMinimumScale (float minimumScale) { mAttacher.SetMinimumScale(minimumScale); } public void SetMidScale (float midScale) { SetMediumScale(midScale); } public void SetMediumScale (float mediumScale) { mAttacher.SetMediumScale(mediumScale); } public void SetMaxScale (float maxScale) { SetMaximumScale(maxScale); } public void SetMaximumScale (float maximumScale) { mAttacher.SetMaximumScale(maximumScale); } public void SetOnMatrixChangeListener (PhotoViewDroidAttacher.IOnMatrixChangedListener listener) { mAttacher.SetOnMatrixChangeListener(listener); } public override void SetOnLongClickListener(Android.Views.View.IOnLongClickListener listener) { mAttacher.SetOnLongClickListener(listener); } public void SetOnPhotoTapListener (PhotoViewDroidAttacher.IOnPhotoTapListener listener) { mAttacher.SetOnPhotoTapListener(listener); } public PhotoViewDroidAttacher.IOnPhotoTapListener GetOnPhotoTapListener () { return mAttacher.GetOnPhotoTapListener(); } public void SetOnViewTapListener (PhotoViewDroidAttacher.IOnViewTapListener listener) { mAttacher.SetOnViewTapListener(listener); } public void SetRotationTo (float rotationDegree) { mAttacher.SetRotationTo(rotationDegree); } public void SetRotationBy (float rotationDegree) { mAttacher.SetRotationBy(rotationDegree); } public PhotoViewDroidAttacher.IOnViewTapListener GetOnViewTapListener () { return mAttacher.GetOnViewTapListener(); } public void SetScale (float scale) { mAttacher.SetScale(scale); } public void SetScale (float scale, bool animate) { mAttacher.SetScale(scale, animate); } public void SetScale (float scale, float focalX, float focalY, bool animate) { mAttacher.SetScale(scale, focalX, focalY, animate); } public override void SetScaleType (ScaleType scaleType) { if (null != mAttacher) { mAttacher.SetScaleType(scaleType); } else { mPendingScaleType = scaleType; } } public void SetZoomable (bool zoomable) { mAttacher.SetZoomable(zoomable); } public void SetPhotoViewRotation (float rotationDegree) { mAttacher.SetRotationTo(rotationDegree); } public Android.Graphics.Bitmap GetVisibleRectangleBitmap () { return mAttacher.GetVisibleRectangleBitmap(); } public void SetZoomTransitionDuration (int milliseconds) { mAttacher.SetZoomTransitionDuration(milliseconds); } public IPhotoViewDroid GetIPhotoViewImplementation () { return mAttacher; } public void SetOnDoubleTapListener (Android.Views.GestureDetector.IOnDoubleTapListener newOnDoubleTapListener) { mAttacher.SetOnDoubleTapListener(newOnDoubleTapListener); } #endregion #region ImageView public override void SetImageDrawable (Android.Graphics.Drawables.Drawable drawable) { base.SetImageDrawable (drawable); if (null != mAttacher) { mAttacher.Update(); } } public override void SetImageResource (int resId) { base.SetImageResource (resId); if (null != mAttacher) { mAttacher.Update(); } } public override void SetImageURI (Android.Net.Uri uri) { base.SetImageURI (uri); if (null != mAttacher) { mAttacher.Update(); } } protected override void OnDetachedFromWindow () { mAttacher.Cleanup(); base.OnDetachedFromWindow (); } #endregion } }
#if !NOT_UNITY3D using System; using System.Collections.Generic; using System.Linq; using ModestTree; using UnityEngine; using UnityEngine.Serialization; using Zenject.Internal; #if UNITY_EDITOR using UnityEditor; #endif namespace Zenject { public abstract class Context : MonoBehaviour { [FormerlySerializedAs("Installers")] [SerializeField] List<MonoInstaller> _installers = new List<MonoInstaller>(); [SerializeField] List<MonoInstaller> _installerPrefabs = new List<MonoInstaller>(); [SerializeField] List<ScriptableObjectInstaller> _scriptableObjectInstallers = new List<ScriptableObjectInstaller>(); List<InstallerBase> _normalInstallers = new List<InstallerBase>(); public IEnumerable<MonoInstaller> Installers { get { return _installers; } set { _installers.Clear(); _installers.AddRange(value); } } public IEnumerable<MonoInstaller> InstallerPrefabs { get { return _installerPrefabs; } set { _installerPrefabs.Clear(); _installerPrefabs.AddRange(value); } } public IEnumerable<ScriptableObjectInstaller> ScriptableObjectInstallers { get { return _scriptableObjectInstallers; } set { _scriptableObjectInstallers.Clear(); _scriptableObjectInstallers.AddRange(value); } } // Unlike other installer types this has to be set through code public IEnumerable<InstallerBase> NormalInstallers { get { return _normalInstallers; } set { _normalInstallers.Clear(); _normalInstallers.AddRange(value); } } public abstract DiContainer Container { get; } public void AddNormalInstaller(InstallerBase installer) { _normalInstallers.Add(installer); } public abstract IEnumerable<GameObject> GetRootGameObjects(); void CheckInstallerPrefabTypes() { foreach (var installer in _installers) { Assert.IsNotNull(installer, "Found null installer in Context '{0}'", this.name); #if UNITY_EDITOR Assert.That(PrefabUtility.GetPrefabType(installer.gameObject) != PrefabType.Prefab, "Found prefab with name '{0}' in the Installer property of Context '{1}'. You should use the property 'InstallerPrefabs' for this instead.", installer.name, this.name); #endif } foreach (var installerPrefab in _installerPrefabs) { Assert.IsNotNull(installerPrefab, "Found null prefab in Context"); #if UNITY_EDITOR Assert.That(PrefabUtility.GetPrefabType(installerPrefab.gameObject) == PrefabType.Prefab, "Found non-prefab with name '{0}' in the InstallerPrefabs property of Context '{1}'. You should use the property 'Installer' for this instead", installerPrefab.name, this.name); #endif Assert.That(installerPrefab.GetComponent<MonoInstaller>() != null, "Expected to find component with type 'MonoInstaller' on given installer prefab '{0}'", installerPrefab.name); } } protected void InstallInstallers() { CheckInstallerPrefabTypes(); // Ideally we would just have one flat list of all the installers // since that way the user has complete control over the order, but // that's not possible since Unity does not allow serializing lists of interfaces // (and it has to be an inteface since the scriptable object installers only share // the interface) // // So the best we can do is have a hard-coded order in terms of the installer type // // The order is: // - Normal installers given directly via code // - ScriptableObject installers // - MonoInstallers in the scene // - Prefab Installers // // We put ScriptableObject installers before the MonoInstallers because // ScriptableObjectInstallers are often used for settings (including settings // that are injected into other installers like MonoInstallers) var allInstallers = _normalInstallers.Cast<IInstaller>() .Concat(_scriptableObjectInstallers.Cast<IInstaller>()).Concat(_installers.Cast<IInstaller>()).ToList(); foreach (var installerPrefab in _installerPrefabs) { Assert.IsNotNull(installerPrefab, "Found null installer prefab in '{0}'", this.GetType()); var installerGameObject = GameObject.Instantiate(installerPrefab.gameObject); installerGameObject.transform.SetParent(this.transform, false); var installer = installerGameObject.GetComponent<MonoInstaller>(); Assert.IsNotNull(installer, "Could not find installer component on prefab '{0}'", installerPrefab.name); allInstallers.Add(installer); } foreach (var installer in allInstallers) { Assert.IsNotNull(installer, "Found null installer in '{0}'", this.GetType()); Container.Inject(installer); installer.InstallBindings(); } } protected void InstallSceneBindings() { foreach (var binding in GetInjectableMonoBehaviours().OfType<ZenjectBinding>()) { if (binding == null) { continue; } if (binding.Context == null) { InstallZenjectBinding(binding); } } // We'd prefer to use GameObject.FindObjectsOfType<ZenjectBinding>() here // instead but that doesn't find inactive gameobjects foreach (var binding in Resources.FindObjectsOfTypeAll<ZenjectBinding>()) { if (binding == null) { continue; } if (binding.Context == this) { InstallZenjectBinding(binding); } } } void InstallZenjectBinding(ZenjectBinding binding) { if (!binding.enabled) { return; } if (binding.Components == null || binding.Components.IsEmpty()) { Log.Warn("Found empty list of components on ZenjectBinding on object '{0}'", binding.name); return; } string identifier = null; if (binding.Identifier.Trim().Length > 0) { identifier = binding.Identifier; } foreach (var component in binding.Components) { var bindType = binding.BindType; if (component == null) { Log.Warn("Found null component in ZenjectBinding on object '{0}'", binding.name); continue; } var componentType = component.GetType(); switch (bindType) { case ZenjectBinding.BindTypes.Self: { Container.Bind(componentType).WithId(identifier).FromInstance(component, true); break; } case ZenjectBinding.BindTypes.BaseType: { Container.Bind(componentType.BaseType()).WithId(identifier).FromInstance(component, true); break; } case ZenjectBinding.BindTypes.AllInterfaces: { Container.Bind(componentType.Interfaces().ToArray()).WithId(identifier).FromInstance(component, true); break; } case ZenjectBinding.BindTypes.AllInterfacesAndSelf: { Container.Bind(componentType.Interfaces().Append(componentType).ToArray()).WithId(identifier).FromInstance(component, true); break; } default: { throw Assert.CreateException(); } } } } protected abstract IEnumerable<MonoBehaviour> GetInjectableMonoBehaviours(); } } #endif
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Threading; namespace Sakuno.Collections { public class Deque<T> : IEnumerable<T>, ICollection, IReadOnlyCollection<T> { T[] _array; int _count; public int Count => _count; int _head, _tail; int _version; public T this[int index] { get { if (index < 0 || index >= _count) throw new ArgumentOutOfRangeException(); return GetElement(index); } set { if (index < 0 || index >= _count) throw new ArgumentOutOfRangeException(); _array[GetOffset(index)] = value; _version++; } } bool ICollection.IsSynchronized => false; object? _threadSyncLock; object ICollection.SyncRoot => _threadSyncLock ?? Interlocked.CompareExchange(ref _threadSyncLock, new object(), null); public Deque() =>_array = Array.Empty<T>(); public Deque(int capacity) { if (capacity < 0) throw new ArgumentOutOfRangeException(nameof(capacity)); _array = new T[capacity]; } public Deque(IEnumerable<T> collection) { if (collection == null) throw new ArgumentNullException(nameof(collection)); _array = new T[4]; foreach (var item in collection) Enqueue(item); } public void Enqueue(T item) { GrowCapacityIfNecessary(); _array[_tail] = item; _tail = (_tail + 1) % _array.Length; _count++; _version++; } public void EnqueueFront(T item) { GrowCapacityIfNecessary(); _head = (_head + _array.Length - 1) % _array.Length; _array[_head] = item; _count++; _version++; } public void Enqueue(T item, QueueSide side) { switch (side) { case QueueSide.Back: Enqueue(item); break; case QueueSide.Front: EnqueueFront(item); break; default: throw new ArgumentException(nameof(side)); } } public T Dequeue() { if (_count == 0) throw new InvalidOperationException(); var result = _array[_head]; _array[_head] = default!; _head = (_head + 1) % _array.Length; _count--; _version++; return result; } public T DequeueBack() { if (_count == 0) throw new InvalidOperationException(); _tail = (_tail + _array.Length - 1) % _array.Length; var result = _array[_tail]; _array[_tail] = default!; _count--; _version++; return result; } public T Dequeue(QueueSide side) => side switch { QueueSide.Back => DequeueBack(), QueueSide.Front => Dequeue(), _ => throw new ArgumentException(nameof(side)), }; public T Peek() { if (_count == 0) throw new InvalidOperationException(); return _array[_head]; } public T PeekBack() { if (_count == 0) throw new InvalidOperationException(); var tail = (_tail + _array.Length - 1) % _array.Length; return _array[tail]; } public T Peek(QueueSide side) => side switch { QueueSide.Back => PeekBack(), QueueSide.Front => Peek(), _ => throw new ArgumentException(nameof(side)), }; public void Clear() { if (_head < _tail) Array.Clear(_array, _head, _count); else { Array.Clear(_array, _head, _array.Length - _head); Array.Clear(_array, 0, _tail); } _head = _tail = 0; _count = 0; _version++; } public bool Contains(T item) { var index = _head; var count = _count; while (count-- > 0) { if (item == null && _array[index] == null) return true; else if (_array[index] != null && EqualityComparer<T>.Default.Equals(_array[index], item)) return true; index = (index + 1) % _array.Length; } return false; } [MethodImpl(MethodImplOptions.AggressiveInlining)] int GetOffset(int index) => (_head + index) % _array.Length; [MethodImpl(MethodImplOptions.AggressiveInlining)] internal T GetElement(int index) => _array[GetOffset(index)]; void GrowCapacityIfNecessary() { if (_count != _array.Length) return; var capacity = Math.Max(_array.Length * 2, _array.Length + 4); var array = new T[capacity]; if (_count > 0) { if (_head < _tail) Array.Copy(_array, _head, array, 0, _count); else { Array.Copy(_array, _head, array, 0, _array.Length - _head); Array.Copy(_array, 0, array, _array.Length - _head, _tail); } } _array = array; _head = 0; _tail = _count != capacity ? _count : 0; _version++; } public Enumerator GetEnumerator() => new Enumerator(this); public ReverseEnumerator GetReverseEnumerator() => new ReverseEnumerator(this); public IEnumerator<T> GetEnumerator(QueueSide side) => side switch { QueueSide.Back => GetReverseEnumerator(), QueueSide.Front => GetEnumerator(), _ => throw new ArgumentException(nameof(side)), }; IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); IEnumerator<T> IEnumerable<T>.GetEnumerator() => GetEnumerator(); void ICollection.CopyTo(Array array, int index) { if (array == null) throw new ArgumentNullException(); if (array.Rank != 1 || array.GetLowerBound(0)!=0) throw new RankException(); var length = array.Length; if (index < 0 || index > length) throw new ArgumentOutOfRangeException(); if (length - index < _count) throw new ArgumentException(); var totalCount = _count; if (totalCount == 0) return; var count = Math.Min(_array.Length - _head, totalCount); Array.Copy(_array, _head, array, index, count); totalCount -= count; if (totalCount > 0) Array.Copy(_array, 0, array, index + _array.Length - _head, totalCount); } public struct Enumerator : IEnumerator<T> { Deque<T> _owner; int _version; int _index; [AllowNull] [MaybeNull] T _current; public T Current { get { if (_index < 0) throw new InvalidOperationException(); return _current; } } object? IEnumerator.Current => Current; public Enumerator(Deque<T> owner) { _owner = owner; _version = _owner._version; _index = -1; _current = default; } public bool MoveNext() { if (_version != _owner._version) throw new InvalidOperationException(); if (_index == -2) return false; _index++; if (_index == _owner._count) { Dispose(); return false; } _current = _owner.GetElement(_index); return true; } public void Dispose() { _index = -2; _current = default; } void IEnumerator.Reset() { if (_version != _owner._version) throw new InvalidOperationException(); _index = -1; _current = default; } } public struct ReverseEnumerator : IEnumerator<T> { Deque<T> _owner; int _version; int _index; [AllowNull] [MaybeNull] T _current; public T Current { get { if (_index < 0) throw new InvalidOperationException(); return _current; } } object? IEnumerator.Current => Current; public ReverseEnumerator(Deque<T> owner) { _owner = owner; _version = _owner._version; _index = _owner._count; _current = default; } public bool MoveNext() { if (_version != _owner._version) throw new InvalidOperationException(); if (_index == -2) return false; _index--; if (_index == -1) { Dispose(); return false; } _current = _owner.GetElement(_index); return true; } public void Dispose() { _index = -2; _current = default; } void IEnumerator.Reset() { if (_version != _owner._version) throw new InvalidOperationException(); _index = -1; _current = default; } } } }
//------------------------------------------------------------------------------ // <copyright file="HttpCookie.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * HttpCookie - collection + name + path * * Copyright (c) 1998 Microsoft Corporation */ namespace System.Web { using System.Text; using System.Collections; using System.Collections.Specialized; using System.Globalization; using System.Security.Permissions; using System.Web.Configuration; using System.Web.Management; /// <devdoc> /// <para> /// Provides a type-safe way /// to access multiple HTTP cookies. /// </para> /// </devdoc> public sealed class HttpCookie { private String _name; private String _path = "/"; private bool _secure; private bool _httpOnly; private String _domain; private bool _expirationSet; private DateTime _expires; private String _stringValue; private HttpValueCollection _multiValue; private bool _changed; private bool _added; internal HttpCookie() { _changed = true; } /* * Constructor - empty cookie with name */ /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Web.HttpCookie'/> /// class. /// </para> /// </devdoc> public HttpCookie(String name) { _name = name; SetDefaultsFromConfig(); _changed = true; } /* * Constructor - cookie with name and value */ /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Web.HttpCookie'/> /// class. /// </para> /// </devdoc> public HttpCookie(String name, String value) { _name = name; _stringValue = value; SetDefaultsFromConfig(); _changed = true; } private void SetDefaultsFromConfig() { HttpCookiesSection config = RuntimeConfig.GetConfig().HttpCookies; _secure = config.RequireSSL; _httpOnly = config.HttpOnlyCookies; if (config.Domain != null && config.Domain.Length > 0) _domain = config.Domain; } /* * Whether the cookie contents have changed */ internal bool Changed { get { return _changed; } set { _changed = value; } } /* * Whether the cookie has been added */ internal bool Added { get { return _added; } set { _added = value; } } // DevID 251951 Cookie is getting duplicated by ASP.NET when they are added via a native module // This flag is used to remember that this cookie came from an IIS Set-Header flag, // so we don't duplicate it and send it back to IIS internal bool FromHeader { get; set; } /* * Cookie name */ /// <devdoc> /// <para> /// Gets /// or sets the name of cookie. /// </para> /// </devdoc> public String Name { get { return _name;} set { _name = value; _changed = true; } } /* * Cookie path */ /// <devdoc> /// <para> /// Gets or sets the URL prefix to transmit with the /// current cookie. /// </para> /// </devdoc> public String Path { get { return _path;} set { _path = value; _changed = true; } } /* * 'Secure' flag */ /// <devdoc> /// <para> /// Indicates whether the cookie should be transmitted only over HTTPS. /// </para> /// </devdoc> public bool Secure { get { return _secure;} set { _secure = value; _changed = true; } } /// <summary> /// Determines whether this cookie is allowed to participate in output caching. /// </summary> /// <remarks> /// If a given HttpResponse contains one or more outbound cookies with Shareable = false (the default value), /// output caching will be suppressed for that response. This prevents cookies that contain potentially /// sensitive information, e.g. FormsAuth cookies, from being cached in the response and sent to multiple /// clients. If a developer wants to allow a response containing cookies to be cached, he should configure /// caching as normal for the response, e.g. via the OutputCache directive, MVC's [OutputCache] attribute, /// etc., and he should make sure that all outbound cookies are marked Shareable = true. /// </remarks> public bool Shareable { get; set; // don't need to set _changed flag since Set-Cookie header isn't affected by value of Shareable } /// <devdoc> /// <para> /// Indicates whether the cookie should have HttpOnly attribute /// </para> /// </devdoc> public bool HttpOnly { get { return _httpOnly;} set { _httpOnly = value; _changed = true; } } /* * Cookie domain */ /// <devdoc> /// <para> /// Restricts domain cookie is to be used with. /// </para> /// </devdoc> public String Domain { get { return _domain;} set { _domain = value; _changed = true; } } /* * Cookie expiration */ /// <devdoc> /// <para> /// Expiration time for cookie (in minutes). /// </para> /// </devdoc> public DateTime Expires { get { return(_expirationSet ? _expires : DateTime.MinValue); } set { _expires = value; _expirationSet = true; _changed = true; } } /* * Cookie value as string */ /// <devdoc> /// <para> /// Gets /// or /// sets an individual cookie value. /// </para> /// </devdoc> public String Value { get { if (_multiValue != null) return _multiValue.ToString(false); else return _stringValue; } set { if (_multiValue != null) { // reset multivalue collection to contain // single keyless value _multiValue.Reset(); _multiValue.Add(null, value); } else { // remember as string _stringValue = value; } _changed = true; } } /* * Checks is cookie has sub-keys */ /// <devdoc> /// <para>Gets a /// value indicating whether the cookie has sub-keys.</para> /// </devdoc> public bool HasKeys { get { return Values.HasKeys();} } private bool SupportsHttpOnly(HttpContext context) { if (context != null && context.Request != null) { HttpBrowserCapabilities browser = context.Request.Browser; return (browser != null && (browser.Type != "IE5" || browser.Platform != "MacPPC")); } return false; } /* * Cookie values as multivalue collection */ /// <devdoc> /// <para>Gets individual key:value pairs within a single cookie object.</para> /// </devdoc> public NameValueCollection Values { get { if (_multiValue == null) { // create collection on demand _multiValue = new HttpValueCollection(); // convert existing string value into multivalue if (_stringValue != null) { if (_stringValue.IndexOf('&') >= 0 || _stringValue.IndexOf('=') >= 0) _multiValue.FillFromString(_stringValue); else _multiValue.Add(null, _stringValue); _stringValue = null; } } _changed = true; return _multiValue; } } /* * Default indexed property -- lookup the multivalue collection */ /// <devdoc> /// <para> /// Shortcut for HttpCookie$Values[key]. Required for ASP compatibility. /// </para> /// </devdoc> public String this[String key] { get { return Values[key]; } set { Values[key] = value; _changed = true; } } /* * Construct set-cookie header */ internal HttpResponseHeader GetSetCookieHeader(HttpContext context) { StringBuilder s = new StringBuilder(); // cookiename= if (!String.IsNullOrEmpty(_name)) { s.Append(_name); s.Append('='); } // key=value&... if (_multiValue != null) s.Append(_multiValue.ToString(false)); else if (_stringValue != null) s.Append(_stringValue); // domain if (!String.IsNullOrEmpty(_domain)) { s.Append("; domain="); s.Append(_domain); } // expiration if (_expirationSet && _expires != DateTime.MinValue) { s.Append("; expires="); s.Append(HttpUtility.FormatHttpCookieDateTime(_expires)); } // path if (!String.IsNullOrEmpty(_path)) { s.Append("; path="); s.Append(_path); } // secure if (_secure) s.Append("; secure"); // httponly, Note: IE5 on the Mac doesn't support this if (_httpOnly && SupportsHttpOnly(context)) { s.Append("; HttpOnly"); } // return as HttpResponseHeader return new HttpResponseHeader(HttpWorkerRequest.HeaderSetCookie, s.ToString()); } } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////// public enum HttpCookieMode { UseUri, // cookieless=true UseCookies, // cookieless=false AutoDetect, // cookieless=AutoDetect; Probe if device is cookied UseDeviceProfile // cookieless=UseDeviceProfile; Base decision on caps } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the autoscaling-2011-01-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.AutoScaling.Model { /// <summary> /// Container for the parameters to the CreateLaunchConfiguration operation. /// Creates a launch configuration. /// /// /// <para> /// If you exceed your maximum limit of launch configurations, which by default is 100 /// per region, the call fails. For information about viewing and updating this limit, /// see <a>DescribeAccountLimits</a>. /// </para> /// /// <para> /// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/LaunchConfiguration.html">Launch /// Configurations</a> in the <i>Auto Scaling Developer Guide</i>. /// </para> /// </summary> public partial class CreateLaunchConfigurationRequest : AmazonAutoScalingRequest { private bool? _associatePublicIpAddress; private List<BlockDeviceMapping> _blockDeviceMappings = new List<BlockDeviceMapping>(); private string _classicLinkVPCId; private List<string> _classicLinkVPCSecurityGroups = new List<string>(); private bool? _ebsOptimized; private string _iamInstanceProfile; private string _imageId; private string _instanceId; private InstanceMonitoring _instanceMonitoring; private string _instanceType; private string _kernelId; private string _keyName; private string _launchConfigurationName; private string _placementTenancy; private string _ramdiskId; private List<string> _securityGroups = new List<string>(); private string _spotPrice; private string _userData; /// <summary> /// Gets and sets the property AssociatePublicIpAddress. /// <para> /// Used for groups that launch instances into a virtual private cloud (VPC). Specifies /// whether to assign a public IP address to each instance. For more information, see /// <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/autoscalingsubnets.html">Auto /// Scaling and Amazon Virtual Private Cloud</a> in the <i>Auto Scaling Developer Guide</i>. /// </para> /// /// <para> /// If you specify a value for this parameter, be sure to specify at least one subnet /// using the <i>VPCZoneIdentifier</i> parameter when you create your group. /// </para> /// /// <para> /// Default: If the instance is launched into a default subnet, the default is <code>true</code>. /// If the instance is launched into a nondefault subnet, the default is <code>false</code>. /// For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-supported-platforms.html">Supported /// Platforms</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// </summary> public bool AssociatePublicIpAddress { get { return this._associatePublicIpAddress.GetValueOrDefault(); } set { this._associatePublicIpAddress = value; } } // Check to see if AssociatePublicIpAddress property is set internal bool IsSetAssociatePublicIpAddress() { return this._associatePublicIpAddress.HasValue; } /// <summary> /// Gets and sets the property BlockDeviceMappings. /// <para> /// One or more mappings that specify how block devices are exposed to the instance. For /// more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/block-device-mapping-concepts.html">Block /// Device Mapping</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// </summary> public List<BlockDeviceMapping> BlockDeviceMappings { get { return this._blockDeviceMappings; } set { this._blockDeviceMappings = value; } } // Check to see if BlockDeviceMappings property is set internal bool IsSetBlockDeviceMappings() { return this._blockDeviceMappings != null && this._blockDeviceMappings.Count > 0; } /// <summary> /// Gets and sets the property ClassicLinkVPCId. /// <para> /// The ID of a ClassicLink-enabled VPC to link your EC2-Classic instances to. This parameter /// is supported only if you are launching EC2-Classic instances. For more information, /// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> /// in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// </summary> public string ClassicLinkVPCId { get { return this._classicLinkVPCId; } set { this._classicLinkVPCId = value; } } // Check to see if ClassicLinkVPCId property is set internal bool IsSetClassicLinkVPCId() { return this._classicLinkVPCId != null; } /// <summary> /// Gets and sets the property ClassicLinkVPCSecurityGroups. /// <para> /// The IDs of one or more security groups for the VPC specified in <code>ClassicLinkVPCId</code>. /// This parameter is required if <code>ClassicLinkVPCId</code> is specified, and is not /// supported otherwise. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/vpc-classiclink.html">ClassicLink</a> /// in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// </summary> public List<string> ClassicLinkVPCSecurityGroups { get { return this._classicLinkVPCSecurityGroups; } set { this._classicLinkVPCSecurityGroups = value; } } // Check to see if ClassicLinkVPCSecurityGroups property is set internal bool IsSetClassicLinkVPCSecurityGroups() { return this._classicLinkVPCSecurityGroups != null && this._classicLinkVPCSecurityGroups.Count > 0; } /// <summary> /// Gets and sets the property EbsOptimized. /// <para> /// Indicates whether the instance is optimized for Amazon EBS I/O. By default, the instance /// is not optimized for EBS I/O. The optimization provides dedicated throughput to Amazon /// EBS and an optimized configuration stack to provide optimal I/O performance. This /// optimization is not available with all instance types. Additional usage charges apply. /// For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EBSOptimized.html">Amazon /// EBS-Optimized Instances</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// </summary> public bool EbsOptimized { get { return this._ebsOptimized.GetValueOrDefault(); } set { this._ebsOptimized = value; } } // Check to see if EbsOptimized property is set internal bool IsSetEbsOptimized() { return this._ebsOptimized.HasValue; } /// <summary> /// Gets and sets the property IamInstanceProfile. /// <para> /// The name or the Amazon Resource Name (ARN) of the instance profile associated with /// the IAM role for the instance. /// </para> /// /// <para> /// EC2 instances launched with an IAM role will automatically have AWS security credentials /// available. You can use IAM roles with Auto Scaling to automatically enable applications /// running on your EC2 instances to securely access other AWS resources. For more information, /// see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/us-iam-role.html">Launch /// Auto Scaling Instances with an IAM Role</a> in the <i>Auto Scaling Developer Guide</i>. /// </para> /// </summary> public string IamInstanceProfile { get { return this._iamInstanceProfile; } set { this._iamInstanceProfile = value; } } // Check to see if IamInstanceProfile property is set internal bool IsSetIamInstanceProfile() { return this._iamInstanceProfile != null; } /// <summary> /// Gets and sets the property ImageId. /// <para> /// The ID of the Amazon Machine Image (AMI) to use to launch your EC2 instances. For /// more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/finding-an-ami.html">Finding /// an AMI</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// </summary> public string ImageId { get { return this._imageId; } set { this._imageId = value; } } // Check to see if ImageId property is set internal bool IsSetImageId() { return this._imageId != null; } /// <summary> /// Gets and sets the property InstanceId. /// <para> /// The ID of the EC2 instance to use to create the launch configuration. /// </para> /// /// <para> /// The new launch configuration derives attributes from the instance, with the exception /// of the block device mapping. /// </para> /// /// <para> /// To create a launch configuration with a block device mapping or override any other /// instance attributes, specify them as part of the same request. /// </para> /// /// <para> /// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/create-lc-with-instanceID.html">Create /// a Launch Configuration Using an EC2 Instance</a> in the <i>Auto Scaling Developer /// Guide</i>. /// </para> /// </summary> public string InstanceId { get { return this._instanceId; } set { this._instanceId = value; } } // Check to see if InstanceId property is set internal bool IsSetInstanceId() { return this._instanceId != null; } /// <summary> /// Gets and sets the property InstanceMonitoring. /// <para> /// Enables detailed monitoring if it is disabled. Detailed monitoring is enabled by default. /// </para> /// /// <para> /// When detailed monitoring is enabled, Amazon CloudWatch generates metrics every minute /// and your account is charged a fee. When you disable detailed monitoring, by specifying /// <code>False</code>, CloudWatch generates metrics every 5 minutes. For more information, /// see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/as-instance-monitoring.html">Monitor /// Your Auto Scaling Instances</a> in the <i>Auto Scaling Developer Guide</i>. /// </para> /// </summary> public InstanceMonitoring InstanceMonitoring { get { return this._instanceMonitoring; } set { this._instanceMonitoring = value; } } // Check to see if InstanceMonitoring property is set internal bool IsSetInstanceMonitoring() { return this._instanceMonitoring != null; } /// <summary> /// Gets and sets the property InstanceType. /// <para> /// The instance type of the EC2 instance. For information about available instance types, /// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html#AvailableInstanceTypes"> /// Available Instance Types</a> in the <i>Amazon Elastic Cloud Compute User Guide.</i> /// /// </para> /// </summary> public string InstanceType { get { return this._instanceType; } set { this._instanceType = value; } } // Check to see if InstanceType property is set internal bool IsSetInstanceType() { return this._instanceType != null; } /// <summary> /// Gets and sets the property KernelId. /// <para> /// The ID of the kernel associated with the AMI. /// </para> /// </summary> public string KernelId { get { return this._kernelId; } set { this._kernelId = value; } } // Check to see if KernelId property is set internal bool IsSetKernelId() { return this._kernelId != null; } /// <summary> /// Gets and sets the property KeyName. /// <para> /// The name of the key pair. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html">Amazon /// EC2 Key Pairs</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// </summary> public string KeyName { get { return this._keyName; } set { this._keyName = value; } } // Check to see if KeyName property is set internal bool IsSetKeyName() { return this._keyName != null; } /// <summary> /// Gets and sets the property LaunchConfigurationName. /// <para> /// The name of the launch configuration. This name must be unique within the scope of /// your AWS account. /// </para> /// </summary> public string LaunchConfigurationName { get { return this._launchConfigurationName; } set { this._launchConfigurationName = value; } } // Check to see if LaunchConfigurationName property is set internal bool IsSetLaunchConfigurationName() { return this._launchConfigurationName != null; } /// <summary> /// Gets and sets the property PlacementTenancy. /// <para> /// The tenancy of the instance. An instance with a tenancy of <code>dedicated</code> /// runs on single-tenant hardware and can only be launched into a VPC. /// </para> /// /// <para> /// You must set the value of this parameter to <code>dedicated</code> if want to launch /// Dedicated Instances into a shared tenancy VPC (VPC with instance placement tenancy /// attribute set to <code>default</code>). /// </para> /// /// <para> /// If you specify a value for this parameter, be sure to specify at least one subnet /// using the <i>VPCZoneIdentifier</i> parameter when you create your group. /// </para> /// /// <para> /// For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/autoscalingsubnets.html">Auto /// Scaling and Amazon Virtual Private Cloud</a> in the <i>Auto Scaling Developer Guide</i>. /// /// </para> /// /// <para> /// Valid values: <code>default</code> | <code>dedicated</code> /// </para> /// </summary> public string PlacementTenancy { get { return this._placementTenancy; } set { this._placementTenancy = value; } } // Check to see if PlacementTenancy property is set internal bool IsSetPlacementTenancy() { return this._placementTenancy != null; } /// <summary> /// Gets and sets the property RamdiskId. /// <para> /// The ID of the RAM disk associated with the AMI. /// </para> /// </summary> public string RamdiskId { get { return this._ramdiskId; } set { this._ramdiskId = value; } } // Check to see if RamdiskId property is set internal bool IsSetRamdiskId() { return this._ramdiskId != null; } /// <summary> /// Gets and sets the property SecurityGroups. /// <para> /// One or more security groups with which to associate the instances. /// </para> /// /// <para> /// If your instances are launched in EC2-Classic, you can either specify security group /// names or the security group IDs. For more information about security groups for EC2-Classic, /// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-network-security.html">Amazon /// EC2 Security Groups</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// /// <para> /// If your instances are launched into a VPC, specify security group IDs. For more information, /// see <a href="http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_SecurityGroups.html">Security /// Groups for Your VPC</a> in the <i>Amazon Virtual Private Cloud User Guide</i>. /// </para> /// </summary> public List<string> SecurityGroups { get { return this._securityGroups; } set { this._securityGroups = value; } } // Check to see if SecurityGroups property is set internal bool IsSetSecurityGroups() { return this._securityGroups != null && this._securityGroups.Count > 0; } /// <summary> /// Gets and sets the property SpotPrice. /// <para> /// The maximum hourly price to be paid for any Spot Instance launched to fulfill the /// request. Spot Instances are launched when the price you specify exceeds the current /// Spot market price. For more information, see <a href="http://docs.aws.amazon.com/AutoScaling/latest/DeveloperGuide/US-SpotInstances.html">Launch /// Spot Instances in Your Auto Scaling Group</a> in the <i>Auto Scaling Developer Guide</i>. /// </para> /// </summary> public string SpotPrice { get { return this._spotPrice; } set { this._spotPrice = value; } } // Check to see if SpotPrice property is set internal bool IsSetSpotPrice() { return this._spotPrice != null; } /// <summary> /// Gets and sets the property UserData. /// <para> /// The user data to make available to the launched EC2 instances. For more information, /// see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html">Instance /// Metadata and User Data</a> in the <i>Amazon Elastic Compute Cloud User Guide</i>. /// </para> /// /// <para> /// At this time, launch configurations don't support compressed (zipped) user data files. /// </para> /// </summary> public string UserData { get { return this._userData; } set { this._userData = value; } } // Check to see if UserData property is set internal bool IsSetUserData() { return this._userData != null; } } }
using System; using System.Threading.Tasks; using LanguageExt.Effects.Traits; using LanguageExt.TypeClasses; using static LanguageExt.Prelude; namespace LanguageExt { public static partial class Prelude { /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, Console.writeLine<RT>("x should be 100!")) /// select x; /// /// </example> public static Aff<RT, Unit> unless<RT>(bool flag, Aff<RT, Unit> alternative) where RT : struct, HasCancel<RT> => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, Console.writeLine<RT>("x should be 100!")) /// select x; /// /// </example> public static Eff<RT, Unit> unless<RT>(bool flag, Eff<RT, Unit> alternative) where RT : struct, HasCancel<RT> => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, Console.writeLine<RT>("x should be 100!")) /// select x; /// /// </example> public static Aff<Unit> unless(bool flag, Aff<Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, Console.writeLine<RT>("x should be 100!")) /// select x; /// /// </example> public static Eff<Unit> unless(bool flag, Eff<Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, Try(() => WriteLineAsync<RT>("x should be 100!"))) /// select x; /// /// </example> public static Try<Unit> unless(bool flag, Try<Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, TryAsync(() => WriteLineAsync<RT>("x should be 100!"))) /// select x; /// /// </example> public static TryAsync<Unit> unless(bool flag, TryAsync<Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, TryOption(() => WriteLineAsync<RT>("x should be 100!"))) /// select x; /// /// </example> public static TryOption<Unit> unless(bool flag, TryOption<Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, TryOptionAsync(() => WriteLineAsync<RT>("x should be 100!"))) /// select x; /// /// </example> public static TryOptionAsync<Unit> unless(bool flag, TryOptionAsync<Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, None) /// select x; /// /// </example> public static Option<Unit> unless(bool flag, Option<Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, None) /// select x; /// /// </example> public static OptionUnsafe<Unit> unless(bool flag, OptionUnsafe<Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, None) /// select x; /// /// </example> public static OptionAsync<Unit> unless(bool flag, OptionAsync<Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, Left<string, int>("100 is the only value accepted")) /// select x; /// /// </example> public static Either<L, Unit> unless<L>(bool flag, Either<L, Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, LeftUnsafe<string, int>("100 is the only value accepted")) /// select x; /// /// </example> public static EitherUnsafe<L, Unit> unless<L>(bool flag, EitherUnsafe<L, Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, LeftAsync<string, int>("100 is the only value accepted")) /// select x; /// /// </example> public static EitherAsync<L, Unit> unless<L>(bool flag, EitherAsync<L, Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, FinFail(Error.New("100 is the only value accepted")) /// select x; /// /// </example> public static Fin<Unit> unless(bool flag, Fin<Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, async () => await LaunchMissiles()) /// select x; /// /// </example> public static Task<Unit> unless(bool flag, Task<Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, async () => await LaunchMissiles()) /// select x; /// /// </example> public static ValueTask<Unit> unless(bool flag, ValueTask<Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, Fail<string, Unit>("100 is the only value accepted")) /// select x; /// /// </example> public static Validation<L, Unit> unless<L>(bool flag, Validation<L, Unit> alternative) => when(!flag, alternative); /// <summary> /// Run the `alternative` when the `flag` is `false`, return `Pure Unit` when `true` /// </summary> /// <param name="flag">If `false` the `alternative` is run</param> /// <param name="alternative">Computation to run if the flag is `false`</param> /// <returns>Either the result of the `alternative` computation if the `flag` is `false` or `Unit`</returns> /// <example> /// /// from x in ma /// from _ in unless(x == 100, Fail<MString, string, Unit>("100 is the only value accepted")) /// select x; /// /// </example> public static Validation<MonoidL, L, Unit> unless<MonoidL, L>(bool flag, Validation<MonoidL, L, Unit> alternative) where MonoidL : struct, Monoid<L>, Eq<L> => when(!flag, alternative); } }
using System; using static OneOf.Functions; namespace OneOf { public struct OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> : IOneOf { readonly T0 _value0; readonly T1 _value1; readonly T2 _value2; readonly T3 _value3; readonly T4 _value4; readonly T5 _value5; readonly T6 _value6; readonly T7 _value7; readonly T8 _value8; readonly T9 _value9; readonly T10 _value10; readonly T11 _value11; readonly T12 _value12; readonly int _index; OneOf(int index, T0 value0 = default, T1 value1 = default, T2 value2 = default, T3 value3 = default, T4 value4 = default, T5 value5 = default, T6 value6 = default, T7 value7 = default, T8 value8 = default, T9 value9 = default, T10 value10 = default, T11 value11 = default, T12 value12 = default) { _index = index; _value0 = value0; _value1 = value1; _value2 = value2; _value3 = value3; _value4 = value4; _value5 = value5; _value6 = value6; _value7 = value7; _value8 = value8; _value9 = value9; _value10 = value10; _value11 = value11; _value12 = value12; } public object Value => _index switch { 0 => _value0, 1 => _value1, 2 => _value2, 3 => _value3, 4 => _value4, 5 => _value5, 6 => _value6, 7 => _value7, 8 => _value8, 9 => _value9, 10 => _value10, 11 => _value11, 12 => _value12, _ => throw new InvalidOperationException() }; public int Index => _index; public bool IsT0 => _index == 0; public bool IsT1 => _index == 1; public bool IsT2 => _index == 2; public bool IsT3 => _index == 3; public bool IsT4 => _index == 4; public bool IsT5 => _index == 5; public bool IsT6 => _index == 6; public bool IsT7 => _index == 7; public bool IsT8 => _index == 8; public bool IsT9 => _index == 9; public bool IsT10 => _index == 10; public bool IsT11 => _index == 11; public bool IsT12 => _index == 12; public T0 AsT0 => _index == 0 ? _value0 : throw new InvalidOperationException($"Cannot return as T0 as result is T{_index}"); public T1 AsT1 => _index == 1 ? _value1 : throw new InvalidOperationException($"Cannot return as T1 as result is T{_index}"); public T2 AsT2 => _index == 2 ? _value2 : throw new InvalidOperationException($"Cannot return as T2 as result is T{_index}"); public T3 AsT3 => _index == 3 ? _value3 : throw new InvalidOperationException($"Cannot return as T3 as result is T{_index}"); public T4 AsT4 => _index == 4 ? _value4 : throw new InvalidOperationException($"Cannot return as T4 as result is T{_index}"); public T5 AsT5 => _index == 5 ? _value5 : throw new InvalidOperationException($"Cannot return as T5 as result is T{_index}"); public T6 AsT6 => _index == 6 ? _value6 : throw new InvalidOperationException($"Cannot return as T6 as result is T{_index}"); public T7 AsT7 => _index == 7 ? _value7 : throw new InvalidOperationException($"Cannot return as T7 as result is T{_index}"); public T8 AsT8 => _index == 8 ? _value8 : throw new InvalidOperationException($"Cannot return as T8 as result is T{_index}"); public T9 AsT9 => _index == 9 ? _value9 : throw new InvalidOperationException($"Cannot return as T9 as result is T{_index}"); public T10 AsT10 => _index == 10 ? _value10 : throw new InvalidOperationException($"Cannot return as T10 as result is T{_index}"); public T11 AsT11 => _index == 11 ? _value11 : throw new InvalidOperationException($"Cannot return as T11 as result is T{_index}"); public T12 AsT12 => _index == 12 ? _value12 : throw new InvalidOperationException($"Cannot return as T12 as result is T{_index}"); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T0 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(0, value0: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T1 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(1, value1: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T2 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(2, value2: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T3 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(3, value3: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T4 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(4, value4: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T5 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(5, value5: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T6 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(6, value6: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T7 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(7, value7: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T8 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(8, value8: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T9 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(9, value9: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T10 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(10, value10: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T11 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(11, value11: t); public static implicit operator OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(T12 t) => new OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(12, value12: t); public void Switch(Action<T0> f0, Action<T1> f1, Action<T2> f2, Action<T3> f3, Action<T4> f4, Action<T5> f5, Action<T6> f6, Action<T7> f7, Action<T8> f8, Action<T9> f9, Action<T10> f10, Action<T11> f11, Action<T12> f12) { if (_index == 0 && f0 != null) { f0(_value0); return; } if (_index == 1 && f1 != null) { f1(_value1); return; } if (_index == 2 && f2 != null) { f2(_value2); return; } if (_index == 3 && f3 != null) { f3(_value3); return; } if (_index == 4 && f4 != null) { f4(_value4); return; } if (_index == 5 && f5 != null) { f5(_value5); return; } if (_index == 6 && f6 != null) { f6(_value6); return; } if (_index == 7 && f7 != null) { f7(_value7); return; } if (_index == 8 && f8 != null) { f8(_value8); return; } if (_index == 9 && f9 != null) { f9(_value9); return; } if (_index == 10 && f10 != null) { f10(_value10); return; } if (_index == 11 && f11 != null) { f11(_value11); return; } if (_index == 12 && f12 != null) { f12(_value12); return; } throw new InvalidOperationException(); } public TResult Match<TResult>(Func<T0, TResult> f0, Func<T1, TResult> f1, Func<T2, TResult> f2, Func<T3, TResult> f3, Func<T4, TResult> f4, Func<T5, TResult> f5, Func<T6, TResult> f6, Func<T7, TResult> f7, Func<T8, TResult> f8, Func<T9, TResult> f9, Func<T10, TResult> f10, Func<T11, TResult> f11, Func<T12, TResult> f12) { if (_index == 0 && f0 != null) { return f0(_value0); } if (_index == 1 && f1 != null) { return f1(_value1); } if (_index == 2 && f2 != null) { return f2(_value2); } if (_index == 3 && f3 != null) { return f3(_value3); } if (_index == 4 && f4 != null) { return f4(_value4); } if (_index == 5 && f5 != null) { return f5(_value5); } if (_index == 6 && f6 != null) { return f6(_value6); } if (_index == 7 && f7 != null) { return f7(_value7); } if (_index == 8 && f8 != null) { return f8(_value8); } if (_index == 9 && f9 != null) { return f9(_value9); } if (_index == 10 && f10 != null) { return f10(_value10); } if (_index == 11 && f11 != null) { return f11(_value11); } if (_index == 12 && f12 != null) { return f12(_value12); } throw new InvalidOperationException(); } public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> FromT0(T0 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> FromT1(T1 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> FromT2(T2 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> FromT3(T3 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> FromT4(T4 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> FromT5(T5 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> FromT6(T6 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> FromT7(T7 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> FromT8(T8 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> FromT9(T9 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> FromT10(T10 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> FromT11(T11 input) => input; public static OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> FromT12(T12 input) => input; public OneOf<TResult, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> MapT0<TResult>(Func<T0, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => mapFunc(AsT0), 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; } public OneOf<T0, TResult, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> MapT1<TResult>(Func<T1, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => mapFunc(AsT1), 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, TResult, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> MapT2<TResult>(Func<T2, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => mapFunc(AsT2), 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, TResult, T4, T5, T6, T7, T8, T9, T10, T11, T12> MapT3<TResult>(Func<T3, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => mapFunc(AsT3), 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, TResult, T5, T6, T7, T8, T9, T10, T11, T12> MapT4<TResult>(Func<T4, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => mapFunc(AsT4), 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, TResult, T6, T7, T8, T9, T10, T11, T12> MapT5<TResult>(Func<T5, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => mapFunc(AsT5), 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, TResult, T7, T8, T9, T10, T11, T12> MapT6<TResult>(Func<T6, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => mapFunc(AsT6), 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, T6, TResult, T8, T9, T10, T11, T12> MapT7<TResult>(Func<T7, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => mapFunc(AsT7), 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, TResult, T9, T10, T11, T12> MapT8<TResult>(Func<T8, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => mapFunc(AsT8), 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, TResult, T10, T11, T12> MapT9<TResult>(Func<T9, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => mapFunc(AsT9), 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, TResult, T11, T12> MapT10<TResult>(Func<T10, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => mapFunc(AsT10), 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, TResult, T12> MapT11<TResult>(Func<T11, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => mapFunc(AsT11), 12 => AsT12, _ => throw new InvalidOperationException() }; } public OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult> MapT12<TResult>(Func<T12, TResult> mapFunc) { if (mapFunc == null) { throw new ArgumentNullException(nameof(mapFunc)); } return _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => mapFunc(AsT12), _ => throw new InvalidOperationException() }; } public bool TryPickT0(out T0 value, out OneOf<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> remainder) { value = IsT0 ? AsT0 : default; remainder = _index switch { 0 => default, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; return this.IsT0; } public bool TryPickT1(out T1 value, out OneOf<T0, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> remainder) { value = IsT1 ? AsT1 : default; remainder = _index switch { 0 => AsT0, 1 => default, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; return this.IsT1; } public bool TryPickT2(out T2 value, out OneOf<T0, T1, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> remainder) { value = IsT2 ? AsT2 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => default, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; return this.IsT2; } public bool TryPickT3(out T3 value, out OneOf<T0, T1, T2, T4, T5, T6, T7, T8, T9, T10, T11, T12> remainder) { value = IsT3 ? AsT3 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => default, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; return this.IsT3; } public bool TryPickT4(out T4 value, out OneOf<T0, T1, T2, T3, T5, T6, T7, T8, T9, T10, T11, T12> remainder) { value = IsT4 ? AsT4 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => default, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; return this.IsT4; } public bool TryPickT5(out T5 value, out OneOf<T0, T1, T2, T3, T4, T6, T7, T8, T9, T10, T11, T12> remainder) { value = IsT5 ? AsT5 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => default, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; return this.IsT5; } public bool TryPickT6(out T6 value, out OneOf<T0, T1, T2, T3, T4, T5, T7, T8, T9, T10, T11, T12> remainder) { value = IsT6 ? AsT6 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => default, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; return this.IsT6; } public bool TryPickT7(out T7 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T8, T9, T10, T11, T12> remainder) { value = IsT7 ? AsT7 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => default, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; return this.IsT7; } public bool TryPickT8(out T8 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T9, T10, T11, T12> remainder) { value = IsT8 ? AsT8 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => default, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; return this.IsT8; } public bool TryPickT9(out T9 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T10, T11, T12> remainder) { value = IsT9 ? AsT9 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => default, 10 => AsT10, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; return this.IsT9; } public bool TryPickT10(out T10 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T11, T12> remainder) { value = IsT10 ? AsT10 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => default, 11 => AsT11, 12 => AsT12, _ => throw new InvalidOperationException() }; return this.IsT10; } public bool TryPickT11(out T11 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T12> remainder) { value = IsT11 ? AsT11 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => default, 12 => AsT12, _ => throw new InvalidOperationException() }; return this.IsT11; } public bool TryPickT12(out T12 value, out OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> remainder) { value = IsT12 ? AsT12 : default; remainder = _index switch { 0 => AsT0, 1 => AsT1, 2 => AsT2, 3 => AsT3, 4 => AsT4, 5 => AsT5, 6 => AsT6, 7 => AsT7, 8 => AsT8, 9 => AsT9, 10 => AsT10, 11 => AsT11, 12 => default, _ => throw new InvalidOperationException() }; return this.IsT12; } bool Equals(OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> other) => _index == other._index && _index switch { 0 => Equals(_value0, other._value0), 1 => Equals(_value1, other._value1), 2 => Equals(_value2, other._value2), 3 => Equals(_value3, other._value3), 4 => Equals(_value4, other._value4), 5 => Equals(_value5, other._value5), 6 => Equals(_value6, other._value6), 7 => Equals(_value7, other._value7), 8 => Equals(_value8, other._value8), 9 => Equals(_value9, other._value9), 10 => Equals(_value10, other._value10), 11 => Equals(_value11, other._value11), 12 => Equals(_value12, other._value12), _ => false }; public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } return obj is OneOf<T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> o && Equals(o); } public override string ToString() => _index switch { 0 => FormatValue(_value0), 1 => FormatValue(_value1), 2 => FormatValue(_value2), 3 => FormatValue(_value3), 4 => FormatValue(_value4), 5 => FormatValue(_value5), 6 => FormatValue(_value6), 7 => FormatValue(_value7), 8 => FormatValue(_value8), 9 => FormatValue(_value9), 10 => FormatValue(_value10), 11 => FormatValue(_value11), 12 => FormatValue(_value12), _ => throw new InvalidOperationException("Unexpected index, which indicates a problem in the OneOf codegen.") }; public override int GetHashCode() { unchecked { int hashCode = _index switch { 0 => _value0?.GetHashCode(), 1 => _value1?.GetHashCode(), 2 => _value2?.GetHashCode(), 3 => _value3?.GetHashCode(), 4 => _value4?.GetHashCode(), 5 => _value5?.GetHashCode(), 6 => _value6?.GetHashCode(), 7 => _value7?.GetHashCode(), 8 => _value8?.GetHashCode(), 9 => _value9?.GetHashCode(), 10 => _value10?.GetHashCode(), 11 => _value11?.GetHashCode(), 12 => _value12?.GetHashCode(), _ => 0 } ?? 0; return (hashCode*397) ^ _index; } } } }
namespace GraphQLCore.Tests.Type { using GraphQLCore; using GraphQLCore.Type; using GraphQLCore.Type.Complex; using NUnit.Framework; using System; using System.Linq; using System.Collections; using System.Reflection; using System.Collections.Generic; [TestFixture] public class GraphQLUnionTypeTests { public class TestUnionType : GraphQLUnionType { public TestUnionType() : base("TestUnion", "Some union description") { this.AddPossibleType(typeof(CatSchemaType)); this.AddPossibleType(typeof(DogSchemaType)); } public override Type ResolveType(object data) { if (data is Cat) return typeof(Cat); else if (data is Dog) return typeof(Dog); return null; } } public class Cat { public int Id {get; set;} public string Name {get; set;} public string WhatDoesTheCatSay {get; set;} } public class Dog { public int Id { get; set; } public string Name { get; set; } public string WhatDoesTheDogSay { get; set; } } public class Chicken { public int Id { get; set; } public string Name { get; set; } public string WhatDoesTheChickenSay { get; set; } } public class CatSchemaType : GraphQLObjectType<Cat> { public CatSchemaType() : base("Cat", string.Empty) { this.Field("id", e => e.Id); this.Field("name", e => e.Name); this.Field("whatDoesTheCatSay", e => e.WhatDoesTheCatSay); } } public class DogSchemaType : GraphQLObjectType<Dog> { public DogSchemaType() : base("Dog", string.Empty) { this.Field("id", e => e.Id); this.Field("name", e => e.Name); this.Field("whatDoesTheDogSay", e => e.WhatDoesTheDogSay); } } public class ChickenSchemaType : GraphQLObjectType<Chicken> { public ChickenSchemaType() : base("Chicken", string.Empty) { this.Field("id", e => e.Id); this.Field("name", e => e.Name); this.Field("whatDoesTheChickenSay", e => e.WhatDoesTheChickenSay); } } public class TestRootType : GraphQLObjectType { public TestRootType() : base("Query", string.Empty) { this.Field("animal", () => new Cat() { Id = 1, Name = "Mourek", WhatDoesTheCatSay = "Meow" }).ResolveWithUnion<TestUnionType>(); this.Field("unionReturningInvalidType", () => new Chicken() { }).ResolveWithUnion<TestUnionType>(); ; } } public class TestSchema : GraphQLSchema { public TestSchema() { var query = new TestRootType(); this.AddKnownType(new ChickenSchemaType()); this.AddKnownType(new DogSchemaType()); this.AddKnownType(new CatSchemaType()); this.AddKnownType(new TestUnionType()); this.AddKnownType(query); this.Query(query); } } [Test] public void CanReturnDataFromResolver() { var schema = new TestSchema(); var result = schema.Execute(@" { animal { __typename ... on Cat { id name whatDoesTheCatSay } } } "); Assert.AreEqual("Cat", result.data.animal.__typename); Assert.AreEqual(1, result.data.animal.id); Assert.AreEqual("Mourek", result.data.animal.name); Assert.AreEqual("Meow", result.data.animal.whatDoesTheCatSay); } [Test] public void ResolvesCatModelForTwoFragments() { var schema = new TestSchema(); var result = schema.Execute(@" { animal { __typename ... on Cat { id name whatDoesTheCatSay } ... on Dog { id name whatDoesTheDogSay } } } "); Assert.AreEqual("Cat", result.data.animal.__typename); Assert.AreEqual(1, result.data.animal.id); Assert.AreEqual("Mourek", result.data.animal.name); Assert.AreEqual("Meow", result.data.animal.whatDoesTheCatSay); } [Test] public void ResolvesUnknownTypeToNull() { var schema = new TestSchema(); var result = schema.Execute(@" { unionReturningInvalidType { __typename ... on Cat { id name whatDoesTheCatSay } ... on Dog { id name whatDoesTheDogSay } } } "); Assert.AreEqual(null, result.data.unionReturningInvalidType); } [Test] public void CorrectlyIntrospectsUnionType() { /* kind must return __TypeKind.UNION. name must return a String. description may return a String or null. possibleTypes returns the list of types that can be represented within this union. They must be object types. All other fields must return null. */ var schema = new TestSchema(); var result = schema.Execute(@" { __type(name: " + "\"TestUnion\"" + @") { name description kind possibleTypes { name } interfaces { name } fields { name } inputFields { name } ofType { name } } } "); Assert.AreEqual("TestUnion", result.data.__type.name); Assert.AreEqual("Some union description", result.data.__type.description); Assert.AreEqual("UNION", result.data.__type.kind); Assert.AreEqual("Dog", ((IEnumerable<dynamic>)result.data.__type.possibleTypes).ElementAt(0).name); Assert.AreEqual("Cat", ((IEnumerable<dynamic>)result.data.__type.possibleTypes).ElementAt(1).name); Assert.IsNull(result.data.__type.interfaces); Assert.IsNull(result.data.__type.fields); Assert.IsNull(result.data.__type.inputFields); Assert.IsNull(result.data.__type.ofType); } } }
/** * Copyright 2015-2016 GetSocial B.V. * * 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 GetSocialSdk.Core { /// <summary> /// List of properties that influence the behavior and UI of the SDK. /// Learn more about SDK customizations from the <a href="http://docs.getsocial.im/#customizing-the-appearance">documentation</a>. /// </summary> public static class Property { /// <summary> /// The width of the window. /// </summary> public const string WindowWidth = "window.width"; // dimension /// <summary> /// The height of the window. /// </summary> public const string WindowHeight = "window.height"; // dimension /// <summary> /// The color of the window background. /// </summary> public const string WindowBgColor = "window.bg-color"; // color /// <summary> /// The window background image. /// </summary> public const string WindowBgImage = "window.bg-image"; // drawable /// <summary> /// The window overlay image. /// </summary> public const string WindowOverlayImage = "window.overlay-image"; // drawable /// <summary> /// The color of the window tint. /// </summary> public const string WindowTintColor = "window.tint-color"; // color /// <summary> /// The window animation style. /// </summary> public const string WindowAnimationStyle = "window.animation-style"; // animation style /// <summary> /// The height of the header. /// </summary> public const string HeaderHeight = "header.height"; // dimension /// <summary> /// The color of the header background. /// </summary> public const string HeaderBgColor = "header.bg-color"; // color /// <summary> /// The top padding of the header. /// </summary> public const string HeaderPaddingTop = "header.padding-top"; // dimension /// <summary> /// The bottom padding of the header. /// </summary> public const string HeaderPaddingBottom = "header.padding-bottom"; // dimension /// <summary> /// The title text style. /// </summary> public const string TitleTextStyle = "title.text-style"; // text style /// <summary> /// The title margin top. /// </summary> [System.Obsolete("Use HeaderPaddingTop instead")] public const string TitleMarginTop = "title.margin-top"; // dimension /// <summary> /// The width of the back button. /// </summary> public const string BackButtonWidth = "back-button.width"; // dimension /// <summary> /// The height of the back button. /// </summary> public const string BackButtonHeight = "back-button.height"; // dimension /// <summary> /// The back button margin left. /// </summary> public const string BackButtonMarginLeft = "back-button.margin-left"; // dimension /// <summary> /// The back button margin top. /// </summary> public const string BackButtonMarginTop = "back-button.margin-top"; // dimension /// <summary> /// The back button background image normal. /// </summary> public const string BackButtonBgImageNormal = "back-button.bg-image-normal"; // drawable /// <summary> /// The back button background image pressed. /// </summary> public const string BackButtonBgImagePressed = "back-button.bg-image-pressed"; // drawable /// <summary> /// The width of the close button. /// </summary> public const string CloseButtonWidth = "close-button.width"; // dimension /// <summary> /// The height of the close button. /// </summary> public const string CloseButtonHeight = "close-button.height"; // dimension /// <summary> /// The close button margin right. /// </summary> public const string CloseButtonMarginRight = "close-button.margin-right"; // dimension /// <summary> /// The close button margin top. /// </summary> public const string CloseButtonMarginTop = "close-button.margin-top"; // dimension /// <summary> /// The close button background image normal. /// </summary> public const string CloseButtonBgImageNormal = "close-button.bg-image-normal"; // drawable /// <summary> /// The close button background image pressed. /// </summary> public const string CloseButtonBgImagePressed = "close-button.bg-image-pressed"; // drawable /// <summary> /// The content margin top. /// </summary> public const string ContentMarginTop = "content.margin-top"; // dimension /// <summary> /// The content margin left. /// </summary> public const string ContentMarginLeft = "content.margin-left"; // dimension /// <summary> /// The content margin right. /// </summary> public const string ContentMarginRight = "content.margin-right"; // dimension /// <summary> /// The content margin bottom. /// </summary> public const string ContentMarginBottom = "content.margin-bottom"; // dimension /// <summary> /// The content text style. /// </summary> public const string ContentTextStyle = "content.text-style"; // text style /// <summary> /// The entity name text style. /// </summary> public const string EntityNameTextStyle = "entity-name.text-style"; // text style /// <summary> /// The timestamp text style. /// </summary> public const string TimestampTextStyle = "timestamp.text-style"; // text style /// <summary> /// The badge text style. /// </summary> public const string BadgeTextStyle = "badge.text-style"; // text style /// <summary> /// The badge background image. /// </summary> public const string BadgeBgImage = "badge.bg-image"; // drawable /// <summary> /// The badge background image insets. /// </summary> public const string BadgeBgImageInsets = "badge.bg-image-insets"; // insets /// <summary> /// The badge text insets. /// </summary> public const string BadgeTextInsets = "badge.text-insets"; //insets /// <summary> /// The link text style. /// </summary> public const string LinkTextStyle = "link.text-style"; // text style /// <summary> /// The verified account background image. /// </summary> public const string VerifiedAccountBgImage = "verified-account-badge.bg-image"; // drawable /// <summary> /// The invite friends button text style. /// </summary> public const string InviteFriendsButtonTextStyle = "invite-friends-button.text-style"; // text style /// <summary> /// The invite friends button text Y offset normal. /// </summary> public const string InviteFriendsButtonTextYOffsetNormal = "invite-friends-button.text-y-offset-normal"; // dimension /// <summary> /// The invite friends button text Y offset pressed. /// </summary> public const string InviteFriendsButtonTextYOffsetPressed = "invite-friends-button.text-y-offset-pressed"; // dimension /// <summary> /// The color of the invite friends button bar. /// </summary> public const string InviteFriendsButtonBarColor = "invite-friends-button.bar-color"; // color /// <summary> /// The invite friends button background image normal. /// </summary> public const string InviteFriendsButtonBgImageNormal = "invite-friends-button.bg-image-normal"; // drawable /// <summary> /// The invite friends button background image pressed. /// </summary> public const string InviteFriendsButtonBgImagePressed = "invite-friends-button.bg-image-pressed"; // drawable /// <summary> /// The invite friends button background image pressed insets. /// </summary> public const string InviteFriendsButtonBgImagePressedInsets = "invite-friends-button.bg-image-pressed-insets"; // insets /// <summary> /// The invite friends button background image normal insets. /// </summary> public const string InviteFriendsButtonBgImageNormalInsets = "invite-friends-button.bg-image-normal-insets"; // insets /// <summary> /// The activity action button text style. /// </summary> public const string ActivityActionButtonTextStyle = "activity-action-button.text-style"; // text style /// <summary> /// The activity action button text Y offset normal. /// </summary> public const string ActivityActionButtonTextYOffsetNormal = "activity-action-button.text-y-offset-normal"; // dimension /// <summary> /// The activity action button text Y offset pressed. /// </summary> public const string ActivityActionButtonTextYOffsetPressed = "activity-action-button.text-y-offset-pressed"; // dimension /// <summary> /// The activity action button background image normal. /// </summary> public const string ActivityActionButtonBgImageNormal = "activity-action-button.bg-image-normal"; // drawable /// <summary> /// The activity action button background image pressed. /// </summary> public const string ActivityActionButtonBgImagePressed = "activity-action-button.bg-image-pressed"; // drawable /// <summary> /// The activity action button background image normal insets. /// </summary> public const string ActivityActionButtonBgImageNormalInsets = "activity-action-button.bg-image-normal-insets"; // insets /// <summary> /// The activity action button background image pressed insets. /// </summary> public const string ActivityActionButtonBgImagePressedInsets = "activity-action-button.bg-image-pressed-insets"; // insets /// <summary> /// The activity image aspect ratio. /// </summary> public const string ActivityImageAspectRatio = "activity-image.aspect-ratio"; // aspect ratio /// <summary> /// The activity image radius. /// </summary> public const string ActivityImageRadius = "activity-image.radius"; // dimension /// <summary> /// The activity image default image. /// </summary> public const string ActivityImageDefaultImage = "activity-image.default-image"; //drawable /// <summary> /// The overscroll text style. /// </summary> public const string OverscrollTextStyle = "overscroll.text-style"; // text style /// <summary> /// The placeholder title text style. /// </summary> public const string PlaceholderTitleTextStyle = "placeholder-title.text-style"; // text style /// <summary> /// The placeholder content text style. /// </summary> public const string PlaceholderContentTextStyle = "placeholder-content.text-style"; // text style /// <summary> /// The input field text style. /// </summary> public const string InputFieldTextStyle = "input-field.text-style"; // text style /// <summary> /// The color of the input field background. /// </summary> public const string InputFieldBgColor = "input-field.bg-color"; // color /// <summary> /// The color of the input field hint. /// </summary> public const string InputFieldHintColor = "input-field.hint-color"; // color /// <summary> /// The size of the input field border. /// </summary> public const string InputFieldBorderSize = "input-field.border-size"; // dimension /// <summary> /// The color of the input field border. /// </summary> public const string InputFieldBorderColor = "input-field.border-color"; // color /// <summary> /// The input field radius. /// </summary> public const string InputFieldRadius = "input-field.radius"; // dimension /// <summary> /// The color of the activity input bar background. /// </summary> public const string ActivityInputBarBgColor = "activity-input-bar.bg-color"; // color /// <summary> /// The color of the comment input bar background. /// </summary> public const string CommentInputBarBgColor = "comment-input-bar.bg-color"; // color /// <summary> /// The size of the avatar border. /// </summary> public const string AvatarBorderSize = "avatar.border-size"; // dimension /// <summary> /// The color of the avatar border. /// </summary> public const string AvatarBorderColor = "avatar.border-color"; // color /// <summary> /// The avatar radius. /// </summary> public const string AvatarRadius = "avatar.radius"; // dimension /// <summary> /// The avatar default image. /// </summary> public const string AvatarDefaultImage = "avatar.default-image"; // drawable /// <summary> /// The like button background image normal. /// </summary> public const string LikeButtonBgImageNormal = "like-button.bg-image-normal"; // drawable /// <summary> /// The like button background image selected. /// </summary> public const string LikeButtonBgImageSelected = "like-button.bg-image-selected"; // drawable /// <summary> /// The color of the divider background. /// </summary> public const string DividerBgColor = "divider.bg-color"; // color /// <summary> /// The height of the divider. /// </summary> public const string DividerHeight = "divider.height"; // dimension /// <summary> /// The load more button text style. /// </summary> public const string LoadMoreButtonTextStyle = "load-more-button.text-style"; // text style /// <summary> /// The load more button text Y offset normal. /// </summary> public const string LoadMoreButtonTextYOffsetNormal = "load-more-button.text-y-offset-normal"; // dimension /// <summary> /// The load more button text Y offset pressed. /// </summary> public const string LoadMoreButtonTextYOffsetPressed = "load-more-button.text-y-offset-pressed"; // dimension /// <summary> /// The load more button background image normal. /// </summary> public const string LoadMoreButtonBgImageNormal = "load-more-button.bg-image-normal"; // drawable /// <summary> /// The load more button background image pressed. /// </summary> public const string LoadMoreButtonBgImagePressed = "load-more-button.bg-image-pressed"; // drawable /// <summary> /// The load more button background image normal insets. /// </summary> public const string LoadMoreButtonBgImageNormalInsets = "load-more-button.bg-image-normal-insets"; // insets /// <summary> /// The load more button background image pressed insets. /// </summary> public const string LoadMoreButtonBgImagePressedInsets = "load-more-button.bg-image-pressed-insets"; // insets /// <summary> /// The post button background image normal. /// </summary> public const string PostButtonBgImageNormal = "post-button.bg-image-normal"; // drawable /// <summary> /// The post button background image pressed. /// </summary> public const string PostButtonBgImagePressed = "post-button.bg-image-pressed"; // drawable /// <summary> /// The segment bar text style normal. /// </summary> public const string SegmentBarTextStyleNormal = "segment-bar.text-style-normal"; // text style /// <summary> /// The segment bar text style selected. /// </summary> public const string SegmentBarTextStyleSelected = "segment-bar.text-style-selected"; // text style /// <summary> /// The color of the segment bar border. /// </summary> public const string SegmentBarBorderColor = "segment-bar.border-color"; // color /// <summary> /// The size of the segment bar border. /// </summary> public const string SegmentBarBorderSize = "segment-bar.border-size"; // dimension /// <summary> /// The segment bar border radius. /// </summary> public const string SegmentBarBorderRadius = "segment-bar.border-radius"; // dimension /// <summary> /// The segment bar background color normal. /// </summary> public const string SegmentBarBgColorNormal = "segment-bar.bg-color-normal"; // color /// <summary> /// The segment bar background color selected. /// </summary> public const string SegmentBarBgColorSelected = "segment-bar.bg-color-selected"; // color /// <summary> /// The segment bar background image normal. /// </summary> public const string SegmentBarBgImageNormal = "segment-bar.bg-image-normal"; // drawable /// <summary> /// /*The segment bar background image pressed.*/ /// </summary> public const string SegmentBarBgImagePressed = "segment-bar.bg-image-pressed"; // drawable /// <summary> /// The loading indicator background image. /// </summary> public const string LoadingIndicatorBgImage = "loading-indicator.bg-image"; // drawable /// <summary> /// The notification icon comment background image. /// </summary> public const string NotificationIconCommentBgImage = "notification-icon-comment.bg-image"; // drawable /// <summary> /// The notification icon like background image. /// </summary> public const string NotificationIconLikeBgImage = "notification-icon-like.bg-image"; // drawable /// <summary> /// The no network placeholder background image. /// </summary> public const string NoNetworkPlaceholderBgImage = "no-network-placeholder.bg-image"; // drawable /// <summary> /// The no activity placeholder background image. /// </summary> public const string NoActivityPlaceholderBgImage = "no-activity-placeholder.bg-image"; // drawable /// <summary> /// The invite provider placeholder background image. /// </summary> public const string InviteProviderPlaceholderBgImage = "invite-provider-placeholder.bg-image"; // drawable /// <summary> /// The list item background color odd. /// </summary> public const string ListItemBgColorOdd = "list-item.bg-color-odd"; // color /// <summary> /// The list item background color even. /// </summary> public const string ListItemBgColorEven = "list-item.bg-color-even"; // color /// <summary> /// The notification list item background color read. /// </summary> public const string NotificationListItemBgColorRead = "notification-list-item.bg-color-read"; // color /// <summary> /// The notification list item background color unread. /// </summary> public const string NotificationListItemBgColorUnread = "notification-list-item.bg-color-unread"; // color } }
// This file was created automatically, do not modify the contents of this file. // ReSharper disable InvalidXmlDocComment // ReSharper disable InconsistentNaming // ReSharper disable CheckNamespace // ReSharper disable MemberCanBePrivate.Global using System; using System.Runtime.InteropServices; // Source file C:\Program Files\Epic Games\UE_4.22\Engine\Source\Runtime\Core\Public\Math\Vector.h:29 namespace UnrealEngine { public partial class FVector : NativeStructWrapper { public FVector(IntPtr NativePointer, bool IsRef = false) : base(NativePointer, IsRef) { } /// <summary> /// Default constructor (no initialization). /// </summary> public FVector() : base(E_CreateStruct_FVector(), false) { } /// <summary> /// Constructor initializing all components to a single float value. /// </summary> /// <param name="inF">Value to set all components to.</param> public FVector(float inF) : base(E_CreateStruct_FVector_float(inF), false) { } /// <summary> /// Constructor using initial values for each component. /// </summary> /// <param name="inX">X Coordinate.</param> /// <param name="inY">Y Coordinate.</param> /// <param name="inZ">Z Coordinate.</param> public FVector(float inX, float inY, float inZ) : base(E_CreateStruct_FVector_float_float_float(inX, inY, inZ), false) { } /// <summary> /// Constructs a vector from an FVector2D and Z value. /// </summary> /// <param name="v">Vector to copy from.</param> /// <param name="inZ">Z Coordinate.</param> public FVector(FVector2D v, float inZ) : base(E_CreateStruct_FVector_FVector2D_float(v, inZ), false) { } /// <summary> /// Constructor using the XYZ components from a 4D vector. /// </summary> /// <param name="v">4D Vector to copy from.</param> public FVector(FVector4 v) : base(E_CreateStruct_FVector_FVector4(v), false) { } /// <summary> /// Constructs a vector from an FLinearColor. /// </summary> /// <param name="inColor">Color to copy from.</param> public FVector(FLinearColor inColor) : base(E_CreateStruct_FVector_FLinearColor(inColor), false) { } /// <summary> /// Constructs a vector from an FIntVector. /// </summary> /// <param name="inVector">FIntVector to copy from.</param> public FVector(FIntVector inVector) : base(E_CreateStruct_FVector_FIntVector(inVector), false) { } /// <summary> /// Constructs a vector from an FIntPoint. /// </summary> /// <param name="a">Int Point used to set X and Y coordinates, Z is set to zero.</param> public FVector(FIntPoint a) : base(E_CreateStruct_FVector_FIntPoint(a), false) { } [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_FVector_BackwardVector_GET(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_FVector_DownVector_GET(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_FVector_ForwardVector_GET(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_FVector_LeftVector_GET(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_FVector_OneVector_GET(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_FVector_RightVector_GET(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_FVector_UpVector_GET(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FVector_X_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FVector_X_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FVector_Y_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FVector_Y_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_PROP_FVector_Z_GET(IntPtr Ptr); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_PROP_FVector_Z_SET(IntPtr Ptr, float Value); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_PROP_FVector_ZeroVector_GET(); #region DLLInmport [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FVector(); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FVector_float(float inF); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FVector_float_float_float(float inX, float inY, float inZ); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FVector_FVector2D_float(IntPtr v, float inZ); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FVector_FVector4(IntPtr v); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FVector_FLinearColor(IntPtr inColor); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FVector_FIntVector(IntPtr inVector); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_CreateStruct_FVector_FIntPoint(IntPtr a); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FVector_AddBounded(IntPtr self, IntPtr v, float radius); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_AllComponentsEqual(IntPtr self, float tolerance); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_BoundToBox(IntPtr self, IntPtr min, IntPtr max); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_BoundToCube(IntPtr self, float radius); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_BoxPushOut(IntPtr self, IntPtr normal, IntPtr size); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_Coincident(IntPtr self, IntPtr normal1, IntPtr normal2, float parallelCosineThreshold); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_Component(IntPtr self, int index); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_ComponentMax(IntPtr self, IntPtr other); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_ComponentMin(IntPtr self, IntPtr other); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_ContainsNaN(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_Coplanar(IntPtr self, IntPtr base1, IntPtr normal1, IntPtr base2, IntPtr normal2, float parallelCosineThreshold); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_CosineAngle2D(IntPtr self, IntPtr b); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FVector_CreateOrthonormalBasis(IntPtr self, IntPtr xAxis, IntPtr yAxis, IntPtr zAxis); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_CrossProduct(IntPtr self, IntPtr a, IntPtr b); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_DegreesToRadians(IntPtr self, IntPtr degVector); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FVector_DiagnosticCheckNaN(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_Dist(IntPtr self, IntPtr v1, IntPtr v2); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_Dist2D(IntPtr self, IntPtr v1, IntPtr v2); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_Distance(IntPtr self, IntPtr v1, IntPtr v2); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_DistSquared(IntPtr self, IntPtr v1, IntPtr v2); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_DistSquared2D(IntPtr self, IntPtr v1, IntPtr v2); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_DistSquaredXY(IntPtr self, IntPtr v1, IntPtr v2); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_DistXY(IntPtr self, IntPtr v1, IntPtr v2); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_DotProduct(IntPtr self, IntPtr a, IntPtr b); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_Equals(IntPtr self, IntPtr v, float tolerance); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FVector_FindBestAxisVectors(IntPtr self, IntPtr axis1, IntPtr axis2); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_GetAbs(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_GetAbsMax(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_GetAbsMin(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_GetClampedToMaxSize(IntPtr self, float maxSize); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_GetClampedToMaxSize2D(IntPtr self, float maxSize); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_GetClampedToSize(IntPtr self, float min, float max); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_GetClampedToSize2D(IntPtr self, float min, float max); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_GetMax(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_GetMin(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_GetSafeNormal(IntPtr self, float tolerance); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_GetSafeNormal2D(IntPtr self, float tolerance); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_GetSignVector(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_GetUnsafeNormal(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_GetUnsafeNormal2D(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_GridSnap(IntPtr self, float gridSz); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_HeadingAngle(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_InitFromString(IntPtr self, string inSourceString); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_IsNearlyZero(IntPtr self, float tolerance); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_IsNormalized(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_IsUniform(IntPtr self, float tolerance); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_IsUnit(IntPtr self, float lengthSquaredTolerance); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_IsZero(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_MirrorByPlane(IntPtr self, IntPtr plane); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_MirrorByVector(IntPtr self, IntPtr mirrorNormal); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_Normalize(IntPtr self, float tolerance); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_Orthogonal(IntPtr self, IntPtr normal1, IntPtr normal2, float orthogonalCosineThreshold); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_Parallel(IntPtr self, IntPtr normal1, IntPtr normal2, float parallelCosineThreshold); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_PointPlaneDist(IntPtr self, IntPtr point, IntPtr planeBase, IntPtr planeNormal); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_PointPlaneProject(IntPtr self, IntPtr point, IntPtr plane); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_PointPlaneProject_o1(IntPtr self, IntPtr point, IntPtr a, IntPtr b, IntPtr c); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_PointPlaneProject_o2(IntPtr self, IntPtr point, IntPtr planeBase, IntPtr planeNormal); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_PointsAreNear(IntPtr self, IntPtr point1, IntPtr point2, float dist); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern bool E_FVector_PointsAreSame(IntPtr self, IntPtr p, IntPtr q); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_Projection(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_ProjectOnTo(IntPtr self, IntPtr a); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_ProjectOnToNormal(IntPtr self, IntPtr normal); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_RadiansToDegrees(IntPtr self, IntPtr radVector); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_Reciprocal(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_RotateAngleAxis(IntPtr self, float angleDeg, IntPtr axis); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_Rotation(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FVector_Set(IntPtr self, float inX, float inY, float inZ); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_Size(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_Size2D(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_SizeSquared(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_SizeSquared2D(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_FVector_ToCompactString(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_FVector_ToCompactText(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FVector_ToDirectionAndLength(IntPtr self, IntPtr outDir, float outLength); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_ToOrientationQuat(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_ToOrientationRotator(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_FVector_ToString(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern StringWrapper E_FVector_ToText(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern float E_FVector_Triple(IntPtr self, IntPtr x, IntPtr y, IntPtr z); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_UnitCartesianToSpherical(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern void E_FVector_UnwindEuler(IntPtr self); [DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)] private static extern IntPtr E_FVector_VectorPlaneProject(IntPtr self, IntPtr v, IntPtr planeNormal); #endregion #region Property /// <summary> /// Unreal backward vector (-1,0,0) /// </summary> public static FVector BackwardVector { get => E_PROP_FVector_BackwardVector_GET(); } /// <summary> /// Unreal down vector (0,0,-1) /// </summary> public static FVector DownVector { get => E_PROP_FVector_DownVector_GET(); } /// <summary> /// Unreal forward vector (1,0,0) /// </summary> public static FVector ForwardVector { get => E_PROP_FVector_ForwardVector_GET(); } /// <summary> /// Unreal left vector (0,-1,0) /// </summary> public static FVector LeftVector { get => E_PROP_FVector_LeftVector_GET(); } /// <summary> /// One vector (1,1,1) /// </summary> public static FVector OneVector { get => E_PROP_FVector_OneVector_GET(); } /// <summary> /// Unreal right vector (0,1,0) /// </summary> public static FVector RightVector { get => E_PROP_FVector_RightVector_GET(); } /// <summary> /// Unreal up vector (0,0,1) /// </summary> public static FVector UpVector { get => E_PROP_FVector_UpVector_GET(); } /// <summary> /// Vector's X component. /// </summary> public float X { get => E_PROP_FVector_X_GET(NativePointer); set => E_PROP_FVector_X_SET(NativePointer, value); } /// <summary> /// Vector's Y component. /// </summary> public float Y { get => E_PROP_FVector_Y_GET(NativePointer); set => E_PROP_FVector_Y_SET(NativePointer, value); } /// <summary> /// Vector's Z component. /// </summary> public float Z { get => E_PROP_FVector_Z_GET(NativePointer); set => E_PROP_FVector_Z_SET(NativePointer, value); } /// <summary> /// A zero vector (0,0,0) /// </summary> public static FVector ZeroVector { get => E_PROP_FVector_ZeroVector_GET(); } #endregion #region ExternMethods /// <summary> /// Add a vector to this and clamp the result in a cube. /// </summary> /// <param name="v">Vector to add.</param> /// <param name="radius">Half size of the cube.</param> public void AddBounded(FVector v, float radius) => E_FVector_AddBounded(this, v, radius); /// <summary> /// Checks whether all components of this vector are the same, within a tolerance. /// </summary> /// <param name="tolerance">Error tolerance.</param> /// <return>true</return> public bool AllComponentsEqual(float tolerance) => E_FVector_AllComponentsEqual(this, tolerance); /// <summary> /// Get a copy of this vector, clamped inside of a cube. /// </summary> public FVector BoundToBox(FVector min, FVector max) => E_FVector_BoundToBox(this, min, max); /// <summary> /// Get a copy of this vector, clamped inside of a cube. /// </summary> /// <param name="radius">Half size of the cube.</param> /// <return>A</return> public FVector BoundToCube(float radius) => E_FVector_BoundToCube(this, radius); /// <summary> /// Compute pushout of a box from a plane. /// </summary> /// <param name="normal">The plane normal.</param> /// <param name="size">The size of the box.</param> /// <return>Pushout</return> public float BoxPushOut(FVector normal, FVector size) => E_FVector_BoxPushOut(this, normal, size); /// <summary> /// See if two normal vectors are coincident (nearly parallel and point in the same direction). /// </summary> /// <param name="normal1">First normalized vector.</param> /// <param name="normal2">Second normalized vector.</param> /// <param name="parallelCosineThreshold">Normals are coincident if dot product (cosine of angle between them) is greater than or equal to this. For example: cos(1.0 degrees).</param> /// <return>true</return> public bool Coincident(FVector normal1, FVector normal2, float parallelCosineThreshold) => E_FVector_Coincident(this, normal1, normal2, parallelCosineThreshold); /// <summary> /// Gets a specific component of the vector. /// </summary> /// <param name="index">The index of the component required.</param> /// <return>Reference</return> public float Component(int index) => E_FVector_Component(this, index); /// <summary> /// Gets the component-wise max of two vectors. /// </summary> public FVector ComponentMax(FVector other) => E_FVector_ComponentMax(this, other); /// <summary> /// Gets the component-wise min of two vectors. /// </summary> public FVector ComponentMin(FVector other) => E_FVector_ComponentMin(this, other); /// <summary> /// Utility to check if there are any non-finite values (NaN or Inf) in this vector. /// </summary> /// <return>true</return> public bool ContainsNaN() => E_FVector_ContainsNaN(this); /// <summary> /// See if two planes are coplanar. They are coplanar if the normals are nearly parallel and the planes include the same set of points. /// </summary> /// <param name="base1">The base point in the first plane.</param> /// <param name="normal1">The normal of the first plane.</param> /// <param name="base2">The base point in the second plane.</param> /// <param name="normal2">The normal of the second plane.</param> /// <param name="parallelCosineThreshold">Normals are parallel if absolute value of dot product is greater than or equal to this.</param> /// <return>true</return> public bool Coplanar(FVector base1, FVector normal1, FVector base2, FVector normal2, float parallelCosineThreshold) => E_FVector_Coplanar(this, base1, normal1, base2, normal2, parallelCosineThreshold); /// <summary> /// Returns the cosine of the angle between this vector and another projected onto the XY plane (no Z). /// </summary> /// <param name="b">the other vector to find the 2D cosine of the angle with.</param> /// <return>The</return> public float CosineAngle2D(FVector b) => E_FVector_CosineAngle2D(this, b); /// <summary> /// Create an orthonormal basis from a basis with at least two orthogonal vectors. /// <para>It may change the directions of the X and Y axes to make the basis orthogonal, </para> /// but it won't change the direction of the Z axis. /// <para>All axes will be normalized. </para> /// </summary> /// <param name="xAxis">The input basis' XAxis, and upon return the orthonormal basis' XAxis.</param> /// <param name="yAxis">The input basis' YAxis, and upon return the orthonormal basis' YAxis.</param> /// <param name="zAxis">The input basis' ZAxis, and upon return the orthonormal basis' ZAxis.</param> public void CreateOrthonormalBasis(FVector xAxis, FVector yAxis, FVector zAxis) => E_FVector_CreateOrthonormalBasis(this, xAxis, yAxis, zAxis); /// <summary> /// Calculate the cross product of two vectors. /// </summary> /// <param name="a">The first vector.</param> /// <param name="b">The second vector.</param> /// <return>The</return> public FVector CrossProduct(FVector a, FVector b) => E_FVector_CrossProduct(this, a, b); /// <summary> /// Converts a vector containing degree values to a vector containing radian values. /// </summary> /// <param name="degVector">Vector containing degree values</param> /// <return>Vector</return> public FVector DegreesToRadians(FVector degVector) => E_FVector_DegreesToRadians(this, degVector); public void DiagnosticCheckNaN() => E_FVector_DiagnosticCheckNaN(this); /// <summary> /// Euclidean distance between two points. /// </summary> /// <param name="v1">The first point.</param> /// <param name="v2">The second point.</param> /// <return>The</return> public float Dist(FVector v1, FVector v2) => E_FVector_Dist(this, v1, v2); public float Dist2D(FVector v1, FVector v2) => E_FVector_Dist2D(this, v1, v2); public float Distance(FVector v1, FVector v2) => E_FVector_Distance(this, v1, v2); /// <summary> /// Squared distance between two points. /// </summary> /// <param name="v1">The first point.</param> /// <param name="v2">The second point.</param> /// <return>The</return> public float DistSquared(FVector v1, FVector v2) => E_FVector_DistSquared(this, v1, v2); public float DistSquared2D(FVector v1, FVector v2) => E_FVector_DistSquared2D(this, v1, v2); /// <summary> /// Squared distance between two points in the XY plane only. /// </summary> /// <param name="v1">The first point.</param> /// <param name="v2">The second point.</param> /// <return>The</return> public float DistSquaredXY(FVector v1, FVector v2) => E_FVector_DistSquaredXY(this, v1, v2); /// <summary> /// Euclidean distance between two points in the XY plane (ignoring Z). /// </summary> /// <param name="v1">The first point.</param> /// <param name="v2">The second point.</param> /// <return>The</return> public float DistXY(FVector v1, FVector v2) => E_FVector_DistXY(this, v1, v2); /// <summary> /// Calculate the dot product of two vectors. /// </summary> /// <param name="a">The first vector.</param> /// <param name="b">The second vector.</param> /// <return>The</return> public float DotProduct(FVector a, FVector b) => E_FVector_DotProduct(this, a, b); /// <summary> /// Check against another vector for equality, within specified error limits. /// </summary> /// <param name="v">The vector to check against.</param> /// <param name="tolerance">Error tolerance.</param> /// <return>true</return> public bool Equals(FVector v, float tolerance) => E_FVector_Equals(this, v, tolerance); /// <summary> /// Find good arbitrary axis vectors to represent U and V axes of a plane, /// <para>using this vector as the normal of the plane. </para> /// </summary> /// <param name="axis1">Reference to first axis.</param> /// <param name="axis2">Reference to second axis.</param> public void FindBestAxisVectors(FVector axis1, FVector axis2) => E_FVector_FindBestAxisVectors(this, axis1, axis2); /// <summary> /// Get a copy of this vector with absolute value of each component. /// </summary> /// <return>A</return> public FVector GetAbs() => E_FVector_GetAbs(this); /// <summary> /// Get the maximum absolute value of the vector's components. /// </summary> /// <return>The</return> public float GetAbsMax() => E_FVector_GetAbsMax(this); /// <summary> /// Get the minimum absolute value of the vector's components. /// </summary> /// <return>The</return> public float GetAbsMin() => E_FVector_GetAbsMin(this); /// <summary> /// Create a copy of this vector, with its maximum magnitude clamped to MaxSize. /// </summary> public FVector GetClampedToMaxSize(float maxSize) => E_FVector_GetClampedToMaxSize(this, maxSize); /// <summary> /// Create a copy of this vector, with the maximum 2D magnitude clamped to MaxSize. Z is unchanged. /// </summary> public FVector GetClampedToMaxSize2D(float maxSize) => E_FVector_GetClampedToMaxSize2D(this, maxSize); /// <summary> /// Create a copy of this vector, with its magnitude clamped between Min and Max. /// </summary> public FVector GetClampedToSize(float min, float max) => E_FVector_GetClampedToSize(this, min, max); /// <summary> /// Create a copy of this vector, with the 2D magnitude clamped between Min and Max. Z is unchanged. /// </summary> public FVector GetClampedToSize2D(float min, float max) => E_FVector_GetClampedToSize2D(this, min, max); /// <summary> /// Get the maximum value of the vector's components. /// </summary> /// <return>The</return> public float GetMax() => E_FVector_GetMax(this); /// <summary> /// Get the minimum value of the vector's components. /// </summary> /// <return>The</return> public float GetMin() => E_FVector_GetMin(this); /// <summary> /// Gets a normalized copy of the vector, checking it is safe to do so based on the length. /// <para>Returns zero vector if vector length is too small to safely normalize. </para> /// </summary> /// <param name="tolerance">Minimum squared vector length.</param> /// <return>A</return> public FVector GetSafeNormal(float tolerance) => E_FVector_GetSafeNormal(this, tolerance); /// <summary> /// Gets a normalized copy of the 2D components of the vector, checking it is safe to do so. Z is set to zero. /// <para>Returns zero vector if vector length is too small to normalize. </para> /// </summary> /// <param name="tolerance">Minimum squared vector length.</param> /// <return>Normalized</return> public FVector GetSafeNormal2D(float tolerance) => E_FVector_GetSafeNormal2D(this, tolerance); /// <summary> /// Get a copy of the vector as sign only. /// <para>Each component is set to +1 or -1, with the sign of zero treated as +1. </para> /// </summary> /// <param name="a">copy of the vector with each component set to +1 or -1</param> public FVector GetSignVector() => E_FVector_GetSignVector(this); /// <summary> /// Calculates normalized version of vector without checking for zero length. /// <see cref="GetSafeNormal"/> /// </summary> /// <return>Normalized</return> public FVector GetUnsafeNormal() => E_FVector_GetUnsafeNormal(this); /// <summary> /// Calculates normalized 2D version of vector without checking for zero length. /// <see cref="GetSafeNormal2D"/> /// </summary> /// <return>Normalized</return> public FVector GetUnsafeNormal2D() => E_FVector_GetUnsafeNormal2D(this); /// <summary> /// Gets a copy of this vector snapped to a grid. /// <see cref="FMath"/> /// </summary> /// <param name="gridSz">Grid dimension.</param> /// <return>A</return> public FVector GridSnap(float gridSz) => E_FVector_GridSnap(this, gridSz); /// <summary> /// Convert a direction vector into a 'heading' angle. /// </summary> /// <return>Heading</return> public float HeadingAngle() => E_FVector_HeadingAngle(this); /// <summary> /// Initialize this Vector based on an FString. The String is expected to contain X=, Y=, Z=. /// <para>The FVector will be bogus when InitFromString returns false. </para> /// </summary> /// <param name="inSourceString">FString containing the vector values.</param> /// <return>true</return> public bool InitFromString(string inSourceString) => E_FVector_InitFromString(this, inSourceString); /// <summary> /// Checks whether vector is near to zero within a specified tolerance. /// </summary> /// <param name="tolerance">Error tolerance.</param> /// <return>true</return> public bool IsNearlyZero(float tolerance) => E_FVector_IsNearlyZero(this, tolerance); /// <summary> /// Checks whether vector is normalized. /// </summary> /// <return>true</return> public bool IsNormalized() => E_FVector_IsNormalized(this); /// <summary> /// Check whether X, Y and Z are nearly equal. /// </summary> /// <param name="tolerance">Specified Tolerance.</param> /// <return>true</return> public bool IsUniform(float tolerance) => E_FVector_IsUniform(this, tolerance); /// <summary> /// Check if the vector is of unit length, with specified tolerance. /// </summary> /// <param name="lengthSquaredTolerance">Tolerance against squared length.</param> /// <return>true</return> public bool IsUnit(float lengthSquaredTolerance) => E_FVector_IsUnit(this, lengthSquaredTolerance); /// <summary> /// Checks whether all components of the vector are exactly zero. /// </summary> /// <return>true</return> public bool IsZero() => E_FVector_IsZero(this); /// <summary> /// Mirrors a vector about a plane. /// </summary> /// <param name="plane">Plane to mirror about.</param> /// <return>Mirrored</return> public FVector MirrorByPlane(FPlane plane) => E_FVector_MirrorByPlane(this, plane); /// <summary> /// Mirror a vector about a normal vector. /// </summary> /// <param name="mirrorNormal">Normal vector to mirror about.</param> /// <return>Mirrored</return> public FVector MirrorByVector(FVector mirrorNormal) => E_FVector_MirrorByVector(this, mirrorNormal); /// <summary> /// Normalize this vector in-place if it is larger than a given tolerance. Leaves it unchanged if not. /// </summary> /// <param name="tolerance">Minimum squared length of vector for normalization.</param> /// <return>true</return> public bool Normalize(float tolerance) => E_FVector_Normalize(this, tolerance); /// <summary> /// See if two normal vectors are nearly orthogonal (perpendicular), meaning the angle between them is close to 90 degrees. /// </summary> /// <param name="normal1">First normalized vector.</param> /// <param name="normal2">Second normalized vector.</param> /// <param name="orthogonalCosineThreshold">Normals are orthogonal if absolute value of dot product (cosine of angle between them) is less than or equal to this. For example: cos(89.0 degrees).</param> /// <return>true</return> public bool Orthogonal(FVector normal1, FVector normal2, float orthogonalCosineThreshold) => E_FVector_Orthogonal(this, normal1, normal2, orthogonalCosineThreshold); /// <summary> /// See if two normal vectors are nearly parallel, meaning the angle between them is close to 0 degrees. /// </summary> /// <param name="normal1">First normalized vector.</param> /// <param name="normal1">Second normalized vector.</param> /// <param name="parallelCosineThreshold">Normals are parallel if absolute value of dot product (cosine of angle between them) is greater than or equal to this. For example: cos(1.0 degrees).</param> /// <return>true</return> public bool Parallel(FVector normal1, FVector normal2, float parallelCosineThreshold) => E_FVector_Parallel(this, normal1, normal2, parallelCosineThreshold); /// <summary> /// Calculate the signed distance (in the direction of the normal) between a point and a plane. /// </summary> /// <param name="point">The Point we are checking.</param> /// <param name="planeBase">The Base Point in the plane.</param> /// <param name="planeNormal">The Normal of the plane (assumed to be unit length).</param> /// <return>Signed</return> public float PointPlaneDist(FVector point, FVector planeBase, FVector planeNormal) => E_FVector_PointPlaneDist(this, point, planeBase, planeNormal); /// <summary> /// Calculate the projection of a point on the given plane. /// </summary> /// <param name="point">The point to project onto the plane</param> /// <param name="plane">The plane</param> /// <return>Projection</return> public FVector PointPlaneProject(FVector point, FPlane plane) => E_FVector_PointPlaneProject(this, point, plane); /// <summary> /// Calculate the projection of a point on the plane defined by counter-clockwise (CCW) points A,B,C. /// </summary> /// <param name="point">The point to project onto the plane</param> /// <param name="a">1st of three points in CCW order defining the plane</param> /// <param name="b">2nd of three points in CCW order defining the plane</param> /// <param name="c">3rd of three points in CCW order defining the plane</param> /// <return>Projection</return> public FVector PointPlaneProject(FVector point, FVector a, FVector b, FVector c) => E_FVector_PointPlaneProject_o1(this, point, a, b, c); /// <summary> /// Calculate the projection of a point on the plane defined by PlaneBase and PlaneNormal. /// </summary> /// <param name="point">The point to project onto the plane</param> /// <param name="planeBase">Point on the plane</param> /// <param name="planeNorm">Normal of the plane (assumed to be unit length).</param> /// <return>Projection</return> public FVector PointPlaneProject(FVector point, FVector planeBase, FVector planeNormal) => E_FVector_PointPlaneProject_o2(this, point, planeBase, planeNormal); /// <summary> /// Compare two points and see if they're within specified distance. /// </summary> /// <param name="point1">First vector.</param> /// <param name="point2">Second vector.</param> /// <param name="dist">Specified distance.</param> /// <return>Whether</return> public bool PointsAreNear(FVector point1, FVector point2, float dist) => E_FVector_PointsAreNear(this, point1, point2, dist); /// <summary> /// Compare two points and see if they're the same, using a threshold. /// </summary> /// <param name="p">First vector.</param> /// <param name="q">Second vector.</param> /// <return>Whether</return> public bool PointsAreSame(FVector p, FVector q) => E_FVector_PointsAreSame(this, p, q); /// <summary> /// Projects 2D components of vector based on Z. /// </summary> /// <return>Projected</return> public FVector Projection() => E_FVector_Projection(this); /// <summary> /// Gets a copy of this vector projected onto the input vector. /// </summary> /// <param name="a">Vector to project onto, does not assume it is normalized.</param> /// <return>Projected</return> public FVector ProjectOnTo(FVector a) => E_FVector_ProjectOnTo(this, a); /// <summary> /// Gets a copy of this vector projected onto the input vector, which is assumed to be unit length. /// </summary> /// <param name="normal">Vector to project onto (assumed to be unit length).</param> /// <return>Projected</return> public FVector ProjectOnToNormal(FVector normal) => E_FVector_ProjectOnToNormal(this, normal); /// <summary> /// Converts a vector containing radian values to a vector containing degree values. /// </summary> /// <param name="radVector">Vector containing radian values</param> /// <return>Vector</return> public FVector RadiansToDegrees(FVector radVector) => E_FVector_RadiansToDegrees(this, radVector); /// <summary> /// Gets the reciprocal of this vector, avoiding division by zero. /// <para>Zero components are set to BIG_NUMBER. </para> /// </summary> /// <return>Reciprocal</return> public FVector Reciprocal() => E_FVector_Reciprocal(this); /// <summary> /// Rotates around Axis (assumes Axis.Size() == 1). /// </summary> /// <param name="angle">Angle to rotate (in degrees).</param> /// <param name="axis">Axis to rotate around.</param> /// <return>Rotated</return> public FVector RotateAngleAxis(float angleDeg, FVector axis) => E_FVector_RotateAngleAxis(this, angleDeg, axis); /// <summary> /// Return the FRotator orientation corresponding to the direction in which the vector points. /// <para>Sets Yaw and Pitch to the proper numbers, and sets Roll to zero because the roll can't be determined from a vector. </para> /// @note Identical to 'ToOrientationRotator()' and preserved for legacy reasons. /// <see cref="ToOrientationRotator"/> /// </summary> /// <return>FRotator</return> public FRotator Rotation() => E_FVector_Rotation(this); /// <summary> /// Set the values of the vector directly. /// </summary> /// <param name="inX">New X coordinate.</param> /// <param name="inY">New Y coordinate.</param> /// <param name="inZ">New Z coordinate.</param> public void Set(float inX, float inY, float inZ) => E_FVector_Set(this, inX, inY, inZ); /// <summary> /// Get the length (magnitude) of this vector. /// </summary> /// <return>The</return> public float Size() => E_FVector_Size(this); /// <summary> /// Get the length of the 2D components of this vector. /// </summary> /// <return>The</return> public float Size2D() => E_FVector_Size2D(this); /// <summary> /// Get the squared length of this vector. /// </summary> /// <return>The</return> public float SizeSquared() => E_FVector_SizeSquared(this); /// <summary> /// Get the squared length of the 2D components of this vector. /// </summary> /// <return>The</return> public float SizeSquared2D() => E_FVector_SizeSquared2D(this); /// <summary> /// Get a short textural representation of this vector, for compact readable logging. /// </summary> public string ToCompactString() => E_FVector_ToCompactString(this); /// <summary> /// Get a short locale aware textural representation of this vector, for compact readable logging. /// </summary> public string ToCompactText() => E_FVector_ToCompactText(this); /// <summary> /// Util to convert this vector into a unit direction vector and its original length. /// </summary> /// <param name="outDir">Reference passed in to store unit direction vector.</param> /// <param name="outLength">Reference passed in to store length of the vector.</param> public void ToDirectionAndLength(FVector outDir, float outLength) => E_FVector_ToDirectionAndLength(this, outDir, outLength); /// <summary> /// Return the Quaternion orientation corresponding to the direction in which the vector points. /// <para>Similar to the FRotator version, returns a result without roll such that it preserves the up vector. </para> /// @note If you don't care about preserving the up vector and just want the most direct rotation, you can use the faster /// <para>'FQuat::FindBetweenVectors(FVector::ForwardVector, YourVector)' or 'FQuat::FindBetweenNormals(...)' if you know the vector is of unit length. </para> /// <see cref="ToOrientationRotator"/> /// </summary> /// <return>Quaternion</return> public FQuat ToOrientationQuat() => E_FVector_ToOrientationQuat(this); /// <summary> /// Return the FRotator orientation corresponding to the direction in which the vector points. /// <para>Sets Yaw and Pitch to the proper numbers, and sets Roll to zero because the roll can't be determined from a vector. </para> /// <see cref="ToOrientationQuat"/> /// </summary> /// <return>FRotator</return> public FRotator ToOrientationRotator() => E_FVector_ToOrientationRotator(this); /// <summary> /// Get a textual representation of this vector. /// </summary> /// <return>A</return> public override string ToString() => E_FVector_ToString(this); /// <summary> /// Get a locale aware textual representation of this vector. /// </summary> /// <return>A</return> public string ToText() => E_FVector_ToText(this); /// <summary> /// Triple product of three vectors: X dot (Y cross Z). /// </summary> /// <param name="x">The first vector.</param> /// <param name="y">The second vector.</param> /// <param name="z">The third vector.</param> /// <return>The</return> public float Triple(FVector x, FVector y, FVector z) => E_FVector_Triple(this, x, y, z); /// <summary> /// Converts a Cartesian unit vector into spherical coordinates on the unit sphere. /// </summary> /// <return>Output</return> public FVector2D UnitCartesianToSpherical() => E_FVector_UnitCartesianToSpherical(this); /// <summary> /// When this vector contains Euler angles (degrees), ensure that angles are between +/-180 /// </summary> public void UnwindEuler() => E_FVector_UnwindEuler(this); /// <summary> /// Calculate the projection of a vector on the plane defined by PlaneNormal. /// </summary> /// <param name="v">The vector to project onto the plane.</param> /// <param name="planeNormal">Normal of the plane (assumed to be unit length).</param> /// <return>Projection</return> public FVector VectorPlaneProject(FVector v, FVector planeNormal) => E_FVector_VectorPlaneProject(this, v, planeNormal); #endregion public static implicit operator IntPtr(FVector self) { return self?.NativePointer ?? IntPtr.Zero; } public static implicit operator FVector(IntPtr adress) { return adress == IntPtr.Zero ? null : new FVector(adress, false); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedForwardingRulesClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<ForwardingRules.ForwardingRulesClient> mockGrpcClient = new moq::Mock<ForwardingRules.ForwardingRulesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetForwardingRuleRequest request = new GetForwardingRuleRequest { Region = "regionedb20d96", Project = "projectaa6ff846", ForwardingRule = "forwarding_rule51d5478e", }; ForwardingRule expectedResponse = new ForwardingRule { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", IPAddress = "I_p_addressf1537179", Ports = { "ports9860f047", }, IsMirroringCollector = false, Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", PscConnectionStatus = "psc_connection_status437a3762", Target = "targetaefbae42", PortRange = "port_ranged4420f7d", ServiceDirectoryRegistrations = { new ForwardingRuleServiceDirectoryRegistration(), }, Network = "networkd22ce091", Fingerprint = "fingerprint009e6052", PscConnectionId = 1768355415909345202UL, IpVersion = "ip_versionde91b460", BackendService = "backend_serviceed490d45", Subnetwork = "subnetworkf55bf572", ServiceName = "service_named5df05d5", LoadBalancingScheme = "load_balancing_scheme21346104", ServiceLabel = "service_label5f95d0c0", Description = "description2cf9da67", AllPorts = false, SelfLink = "self_link7e87f12d", MetadataFilters = { new MetadataFilter(), }, IPProtocol = "I_p_protocold854c15f", AllowGlobalAccess = false, Labels = { { "key8a0b6e3c", "value60c16320" }, }, NetworkTier = "network_tiere6fea951", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ForwardingRulesClient client = new ForwardingRulesClientImpl(mockGrpcClient.Object, null); ForwardingRule response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<ForwardingRules.ForwardingRulesClient> mockGrpcClient = new moq::Mock<ForwardingRules.ForwardingRulesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetForwardingRuleRequest request = new GetForwardingRuleRequest { Region = "regionedb20d96", Project = "projectaa6ff846", ForwardingRule = "forwarding_rule51d5478e", }; ForwardingRule expectedResponse = new ForwardingRule { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", IPAddress = "I_p_addressf1537179", Ports = { "ports9860f047", }, IsMirroringCollector = false, Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", PscConnectionStatus = "psc_connection_status437a3762", Target = "targetaefbae42", PortRange = "port_ranged4420f7d", ServiceDirectoryRegistrations = { new ForwardingRuleServiceDirectoryRegistration(), }, Network = "networkd22ce091", Fingerprint = "fingerprint009e6052", PscConnectionId = 1768355415909345202UL, IpVersion = "ip_versionde91b460", BackendService = "backend_serviceed490d45", Subnetwork = "subnetworkf55bf572", ServiceName = "service_named5df05d5", LoadBalancingScheme = "load_balancing_scheme21346104", ServiceLabel = "service_label5f95d0c0", Description = "description2cf9da67", AllPorts = false, SelfLink = "self_link7e87f12d", MetadataFilters = { new MetadataFilter(), }, IPProtocol = "I_p_protocold854c15f", AllowGlobalAccess = false, Labels = { { "key8a0b6e3c", "value60c16320" }, }, NetworkTier = "network_tiere6fea951", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ForwardingRule>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ForwardingRulesClient client = new ForwardingRulesClientImpl(mockGrpcClient.Object, null); ForwardingRule responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ForwardingRule responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<ForwardingRules.ForwardingRulesClient> mockGrpcClient = new moq::Mock<ForwardingRules.ForwardingRulesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetForwardingRuleRequest request = new GetForwardingRuleRequest { Region = "regionedb20d96", Project = "projectaa6ff846", ForwardingRule = "forwarding_rule51d5478e", }; ForwardingRule expectedResponse = new ForwardingRule { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", IPAddress = "I_p_addressf1537179", Ports = { "ports9860f047", }, IsMirroringCollector = false, Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", PscConnectionStatus = "psc_connection_status437a3762", Target = "targetaefbae42", PortRange = "port_ranged4420f7d", ServiceDirectoryRegistrations = { new ForwardingRuleServiceDirectoryRegistration(), }, Network = "networkd22ce091", Fingerprint = "fingerprint009e6052", PscConnectionId = 1768355415909345202UL, IpVersion = "ip_versionde91b460", BackendService = "backend_serviceed490d45", Subnetwork = "subnetworkf55bf572", ServiceName = "service_named5df05d5", LoadBalancingScheme = "load_balancing_scheme21346104", ServiceLabel = "service_label5f95d0c0", Description = "description2cf9da67", AllPorts = false, SelfLink = "self_link7e87f12d", MetadataFilters = { new MetadataFilter(), }, IPProtocol = "I_p_protocold854c15f", AllowGlobalAccess = false, Labels = { { "key8a0b6e3c", "value60c16320" }, }, NetworkTier = "network_tiere6fea951", }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ForwardingRulesClient client = new ForwardingRulesClientImpl(mockGrpcClient.Object, null); ForwardingRule response = client.Get(request.Project, request.Region, request.ForwardingRule); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<ForwardingRules.ForwardingRulesClient> mockGrpcClient = new moq::Mock<ForwardingRules.ForwardingRulesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForRegionOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetForwardingRuleRequest request = new GetForwardingRuleRequest { Region = "regionedb20d96", Project = "projectaa6ff846", ForwardingRule = "forwarding_rule51d5478e", }; ForwardingRule expectedResponse = new ForwardingRule { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", IPAddress = "I_p_addressf1537179", Ports = { "ports9860f047", }, IsMirroringCollector = false, Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", PscConnectionStatus = "psc_connection_status437a3762", Target = "targetaefbae42", PortRange = "port_ranged4420f7d", ServiceDirectoryRegistrations = { new ForwardingRuleServiceDirectoryRegistration(), }, Network = "networkd22ce091", Fingerprint = "fingerprint009e6052", PscConnectionId = 1768355415909345202UL, IpVersion = "ip_versionde91b460", BackendService = "backend_serviceed490d45", Subnetwork = "subnetworkf55bf572", ServiceName = "service_named5df05d5", LoadBalancingScheme = "load_balancing_scheme21346104", ServiceLabel = "service_label5f95d0c0", Description = "description2cf9da67", AllPorts = false, SelfLink = "self_link7e87f12d", MetadataFilters = { new MetadataFilter(), }, IPProtocol = "I_p_protocold854c15f", AllowGlobalAccess = false, Labels = { { "key8a0b6e3c", "value60c16320" }, }, NetworkTier = "network_tiere6fea951", }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ForwardingRule>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ForwardingRulesClient client = new ForwardingRulesClientImpl(mockGrpcClient.Object, null); ForwardingRule responseCallSettings = await client.GetAsync(request.Project, request.Region, request.ForwardingRule, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ForwardingRule responseCancellationToken = await client.GetAsync(request.Project, request.Region, request.ForwardingRule, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/** SpriteStudioPlayer Sprite inspector Copyright(C) Web Technology Corp. */ using UnityEngine; using UnityEditor; using System.Collections.Generic; [CustomEditor(typeof(SsSprite))] public class SsSpriteEditor : Editor { [HideInInspector] static public SsSprite LastSprite; static GameObject databaseGo; SsAssetDatabase _database; string[] _animeNames; int _selectedAnimeIndex; SsSprite _sprite; float _animeFrame; int _startAnimeFrame; int _endAnimeFrame; bool _hFlip; bool _vFlip; bool _drawBoundingBox; bool _changed; List<SsSubAnimeController> _subAnimations = null; void OnEnable() { // SsTimer.StartTimer(); _sprite = target as SsSprite; // add shader keeper if it doesn't exist during show the sprite object substance. PrefabType prefabType = PrefabUtility.GetPrefabType(_sprite); if (_sprite != LastSprite && prefabType != PrefabType.Prefab) { //SsTimer.StartTimer(); SsEditorWindow.AddShaderKeeper(); //SsTimer.EndTimer("checking or add shader keeper"); } _animeFrame = _sprite._animeFrame; _startAnimeFrame = _sprite._startAnimeFrame; _endAnimeFrame = _sprite._endAnimeFrame; _hFlip = _sprite.hFlip; _vFlip = _sprite.vFlip; _drawBoundingBox = _sprite.DrawBoundingBox; _subAnimations = null;//_sprite.subAnimations; // get latest animation list // SsTimer.StartTimer(); if (!databaseGo) databaseGo = SsAssetPostProcessor.GetDatabaseGo(); // SsTimer.EndTimer("load database asset"); if (databaseGo) { //SsTimer.StartTimer(); _database = databaseGo.GetComponent<SsAssetDatabase>(); List<SsAnimation> animeList = _database.animeList; _animeNames = new string[animeList.Count + 1]; for (int i = 0; i < animeList.Count; ++i) _animeNames[i + 1] = animeList[i].name; System.Array.Sort(_animeNames, 1, _animeNames.Length - 1); _animeNames[0] = "<none>"; // get the index of this animation in the list if (_sprite.Animation) { string myAnimeName = _sprite.Animation.name; for (int i = 1; i < _animeNames.Length; ++i) { if (myAnimeName == _animeNames[i]) { _selectedAnimeIndex = i; break; } } } //SsTimer.EndTimer("make anime list"); } else { Debug.LogError("Not found animation list: '" + SsAssetDatabase.filePath + "' needs to reimport animation data"); } LastSprite = _sprite; // SsTimer.EndTimer("SsSpriteEditor.OnEnable()"); } public override void OnInspectorGUI() { if (_animeNames == null) return; // display animation list EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Animation"); int newAnimeIndex = EditorGUILayout.Popup(_selectedAnimeIndex, _animeNames/*, GUILayout.ExpandHeight(true), GUILayout.Height(30)*/); bool pushedGotoAnime = GUILayout.Button("Edit...", GUILayout.Width(40), GUILayout.Height(15)); EditorGUILayout.EndHorizontal(); if (newAnimeIndex != _selectedAnimeIndex) { // change animation _sprite.Animation = (newAnimeIndex == 0 ? null : _database.GetAnime(_animeNames[newAnimeIndex])); _sprite.ResetAnimationStatus(); _changed = true; } if (_sprite.Animation) { if (pushedGotoAnime) { EditorGUIUtility.PingObject(_sprite.Animation); Selection.activeObject = _sprite.Animation; } } // cannot update prefab because SsSprite modifies transform and creates some transoforms as its children. PrefabType prefabType = PrefabUtility.GetPrefabType(_sprite); if (prefabType != PrefabType.Prefab) { if (_sprite.Animation) { // Show default inspector property editor DrawDefaultInspector(); if (_sprite.subAnimations != _subAnimations) { _subAnimations = _sprite.subAnimations; _changed = true; } // clamp values if (_sprite.PlayCount < 0) _sprite.PlayCount = 0; _sprite._startAnimeFrame = Mathf.Clamp(_sprite._startAnimeFrame, 0, _sprite._endAnimeFrame); _sprite._endAnimeFrame = Mathf.Clamp(_sprite._endAnimeFrame, _sprite._startAnimeFrame, _sprite.Animation.EndFrame); if (_sprite._endAnimeFrame < 0) _sprite._endAnimeFrame = 0; _sprite._animeFrame = Mathf.Clamp(_sprite._animeFrame, _sprite._startAnimeFrame, _sprite._endAnimeFrame); // change play direction if (_sprite.PlayDirection != _sprite._prevPlayDirection) { _sprite._prevPlayDirection = _sprite.PlayDirection; // reset animation status _sprite.ResetAnimationStatus(); _changed = true; } if (_sprite._startAnimeFrame != _startAnimeFrame) { _startAnimeFrame = _sprite._startAnimeFrame; _sprite._animeFrame = _startAnimeFrame; // show animation at the selected frame _changed = true; } if (_sprite._endAnimeFrame != _endAnimeFrame) { _endAnimeFrame = _sprite._endAnimeFrame; _sprite._animeFrame = _endAnimeFrame; // show animation at the selected frame _changed = true; } if (!Application.isPlaying && _sprite._animeFrame != _animeFrame) { _animeFrame = _sprite._animeFrame; _changed = true; } if (_sprite.hFlip != _hFlip) { _hFlip = _sprite.hFlip; _changed = true; } if (_sprite.vFlip != _vFlip) { _vFlip = _sprite.vFlip; _changed = true; } if (_sprite.DrawBoundingBox != _drawBoundingBox) { _drawBoundingBox = _sprite.DrawBoundingBox; _changed = true; } } } if (_changed) { if (_sprite._animeFrame < 0) _sprite._animeFrame = 0; _sprite.UpdateVertex(); _sprite.UpdateAlways(); _changed = false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace DotNetNuke.Entities.Urls { using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Web.UI.WebControls; using DotNetNuke.Common; using DotNetNuke.Common.Utilities; using DotNetNuke.Data; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Tabs; using DotNetNuke.Entities.Users; using DotNetNuke.Services.ClientCapability; using DotNetNuke.Services.Exceptions; public class FriendlyUrlController { private const string DisableMobileRedirectCookieName = "disablemobileredirect"; // dnn cookies private const string DisableRedirectPresistCookieName = "disableredirectpresist"; // dnn cookies private const string DisableMobileRedirectQueryStringName = "nomo"; // google uses the same name nomo=1 means do not redirect to mobile // set the web.config AppSettings for the mobile view cookie name private static readonly string MobileViewSiteCookieName = ConfigurationManager.AppSettings[name: "MobileViewSiteCookieName"] ?? "dnn_IsMobile"; private static readonly string DisableMobileViewCookieName = ConfigurationManager.AppSettings[name: "DisableMobileViewSiteCookieName"] ?? "dnn_NoMobile"; // <summary>Gets the Friendly URL Settings for the given portal.</summary> public static FriendlyUrlSettings GetCurrentSettings(int portalId) { return new FriendlyUrlSettings(portalId); } /* /// <summary> /// Determines if the tab is excluded from FriendlyUrl Processing /// </summary> /// <param name="tab"></param> /// <param name="settings"></param> /// <param name="rewriting">If true, we are checking for rewriting purposes, if false, we are checking for friendly Url Generating.</param> /// <returns></returns> private static bool IsExcludedFromFriendlyUrls(TabInfo tab, FriendlyUrlSettings settings, bool rewriting) { //note this is a duplicate of another method in RewriteController.cs bool exclude = false; string tabPath = (tab.TabPath.Replace("//", "/") + ";").ToLower(); if (settings.UseBaseFriendlyUrls != null) { exclude = settings.UseBaseFriendlyUrls.ToLower().Contains(tabPath); } return exclude; } private static void SetExclusionProperties(TabInfo tab, FriendlyUrlSettings settings) { string tabPath = (tab.TabPath.Replace("//", "/") + ";").ToLower(); tab.UseBaseFriendlyUrls = settings.UseBaseFriendlyUrls != null && settings.UseBaseFriendlyUrls.ToLower().Contains(tabPath); } /// <summary> /// Builds up a collection of the Friendly Urls for a tab /// </summary> /// <param name="tab">The TabInfoEx object</param> /// <param name="includeStdUrls">Whether to add in the redirects for the 'standard' DNN urls</param> /// <param name="portalSettings"></param> /// <param name="settings">The current friendly Url settings</param> /// <remarks>Updated to insert where an ascii replacement or spaces-replaced replacement has been made (562)</remarks> private static void BuildFriendlyUrls(TabInfo tab, bool includeStdUrls, PortalSettings portalSettings, FriendlyUrlSettings settings) { //unfriendly Url if (includeStdUrls) { string stdUrl = Globals.glbDefaultPage + "?TabId=" + tab.TabID.ToString(); string stdHttpStatus = "200"; string httpAlias = portalSettings.PortalAlias.HTTPAlias; string defaultCulture = portalSettings.DefaultLanguage; var locales = LocaleController.Instance.GetLocales(portalSettings.PortalId); string baseFriendlyHttpStatus = "200"; int seqNum = -1; //check for custom redirects //bool tabHasCustom200 = false; var culturesWithCustomUrls = new List<string>(); if (tab.TabUrls.Count > 0) { //there are custom redirects for this tab //cycle through all and collect the list of cultures where a //custom redirect has been implemented foreach (TabUrlInfo redirect in tab.TabUrls) { if (redirect.HttpStatus == "200" && !redirect.IsSystem) { //there is a custom redirect for this culture //751 : use the default culture if the redirect doesn't have a valid culture set string redirectCulture = redirect.CultureCode; if (string.IsNullOrEmpty(redirectCulture)) { redirectCulture = portalSettings.DefaultLanguage; } if (!culturesWithCustomUrls.Contains(redirectCulture)) { culturesWithCustomUrls.Add(redirectCulture); } } } } //add friendly urls first (sequence number goes in reverse) if (Host.Host.UseFriendlyUrls) { //determine whether post process or use base by looking at current settings SetExclusionProperties(tab, settings); //friendly Urls are switched on //std = default.aspx?tabId=xx //and page not excluded from redirects bool onlyBaseUrls = tab.UseBaseFriendlyUrls; //use base means only use Base Friendly Urls (searchFriendly) //if not using base urls, and redirect all unfriendly, and not in the list of pages to not redirect if (!onlyBaseUrls & settings.RedirectUnfriendly && !tab.DoNotRedirect) { //all base urls will be 301 baseFriendlyHttpStatus = "301"; stdHttpStatus = "301"; //default url 301'd if friendly Urls on and redirect unfriendly switch 'on' } var localeCodes = new List<string>(); if (!string.IsNullOrEmpty(tab.CultureCode)) { //the tab culture is specified, so skip all locales and only process those for the locale localeCodes.Add(tab.CultureCode); } else { localeCodes.AddRange(from Locale lc in locales.Values select lc.Code); } foreach (string cultureCode in localeCodes) //go through and generate the urls for each language { string langQs = "&language=" + cultureCode; if (cultureCode == defaultCulture) { langQs = ""; } var improvedFriendlyUrls = new Dictionary<string, string>(); //call friendly url provider to get current friendly url (uses all settings) string baseFriendlyUrl = GetFriendlyUrl(tab, stdUrl + langQs, Globals.glbDefaultPage, portalSettings.PortalAlias.HTTPAlias, settings); if (onlyBaseUrls == false) { //get the improved friendly Url for this tab //improved friendly Url = 'human friendly' url generated by Advanced Friendly Url Provider : note call is made to ignore custom redirects //this temp switch is to clear out the useBaseFriendlyUrls setting. The post-process setting means the generated //friendly url will be a base url, and then replaced later when the page is finished. Because we want to pretend we're //looking at the finished product, we clear out the value and restore it after the friendly url generation string improvedFriendlyUrl = GetImprovedFriendlyUrl(tab, stdUrl + langQs, Globals.glbDefaultPage, portalSettings, true, settings); improvedFriendlyUrls.Add("hfurl:" + cultureCode, improvedFriendlyUrl); //get any other values bool autoAsciiConvert = false; bool replaceSpacesWith = false; if (settings.AutoAsciiConvert) { //check to see that the ascii conversion would actually produce a different result string changedTabPath = ReplaceDiacritics(tab.TabPath); if (changedTabPath != tab.TabPath) { autoAsciiConvert = true; } } if (settings.ReplaceSpaceWith != FriendlyUrlSettings.ReplaceSpaceWithNothing) { if (tab.TabName.Contains(" ")) { string tabPath = BuildTabPathWithReplacement(tab, " ", settings.ReplaceSpaceWith); if (tabPath != tab.TabPath) { replaceSpacesWith = true; } } } if (autoAsciiConvert && replaceSpacesWith) { string replaceSpaceWith = settings.ReplaceSpaceWith; settings.ReplaceSpaceWith = "None"; settings.AutoAsciiConvert = false; //get one without auto ascii convert, and replace spaces off string impUrl = GetImprovedFriendlyUrl(tab, stdUrl + langQs, Globals.glbDefaultPage, httpAlias, true, settings); improvedFriendlyUrls.Add("aac:rsw:" + cultureCode, impUrl); settings.AutoAsciiConvert = true; //now get one with ascii convert on, and replace spaces still off //impUrl = GetImprovedFriendlyUrl(tab, stdUrl, Globals.glbDefaultPage, httpAlias, true, settings); //improvedFriendlyUrls.Add("aac", impUrl); settings.ReplaceSpaceWith = replaceSpaceWith; } if (autoAsciiConvert && !replaceSpacesWith) { settings.AutoAsciiConvert = false; //get one with auto ascii convert off string impUrl = GetImprovedFriendlyUrl(tab, stdUrl + langQs, Globals.glbDefaultPage, httpAlias, true, settings); improvedFriendlyUrls.Add("aac:" + cultureCode, impUrl); settings.AutoAsciiConvert = true; } if (!autoAsciiConvert && replaceSpacesWith) { string replaceSpaceWith = settings.ReplaceSpaceWith; settings.ReplaceSpaceWith = "None"; //get one with replace spaces off string impUrl = GetImprovedFriendlyUrl(tab, stdUrl + langQs, Globals.glbDefaultPage, httpAlias, true, settings); improvedFriendlyUrls.Add("rsw:" + cultureCode, impUrl); settings.ReplaceSpaceWith = replaceSpaceWith; } bool tabHasCustom200 = culturesWithCustomUrls.Contains(cultureCode); foreach (string key in improvedFriendlyUrls.Keys) { string friendlyUrl = improvedFriendlyUrls[key]; if (friendlyUrl != baseFriendlyUrl && friendlyUrl != "") { //if the improved friendly Url is different to the base friendly Url, //then we will add it in as a 'fixed' url, except if the improved friendly Url //is actually a redirect in the first place bool found = false; foreach (TabUrlInfo redirect in tab.TabUrls) { //compare each redirect to the improved friendly Url //just in case it is the same if (String.Compare(redirect.Url, friendlyUrl, StringComparison.OrdinalIgnoreCase) == 0) { found = true; } } if (!found) { //ok if hte improved friendly Url isn't a tab redirect record, //then add in the improved friendly Url as a 'fixed' url var predefinedRedirect = new TabUrlInfo { TabId = tab.TabID, CultureCode = cultureCode }; if (key.StartsWith("hfurl") == false) { //this means it's not the actual url, it's either a spaces replace, //auto ascii or both output. It should be a 301 unless redirectunfriendly //is off, or the page is excluded from redirects if (settings.RedirectUnfriendly && !tab.DoNotRedirect) { predefinedRedirect.HttpStatus = "301"; //redirect to custom url } else { predefinedRedirect.HttpStatus = "200"; //allow it to work } } else { //the hfurl key is the base human friendly url if (tabHasCustom200 && (settings.RedirectUnfriendly && !tab.DoNotRedirect)) { predefinedRedirect.HttpStatus = "301"; } else { predefinedRedirect.HttpStatus = "200"; //if no redirects, or not redirecting unfriendly, then 200 is OK } } predefinedRedirect.Url = friendlyUrl; predefinedRedirect.IsSystem = true; predefinedRedirect.SeqNum = seqNum; tab.TabUrls.Insert(0, predefinedRedirect); seqNum--; } } else { //improved Friendly Url same as base Friendly Url, so we 200 this one, regardless of redirection settings if (tabHasCustom200 == false) { baseFriendlyHttpStatus = "200"; } } } } //base friendly url var baseFriendly = new TabUrlInfo { TabId = tab.TabID, HttpStatus = (settings.RedirectUnfriendly == false || IsExcludedFromFriendlyUrls(tab, settings, true)) ? "200" : baseFriendlyHttpStatus, CultureCode = cultureCode, Url = baseFriendlyUrl, IsSystem = true, SeqNum = seqNum }; tab.TabUrls.Insert(0, baseFriendly); seqNum--; } //standard url (/default.aspx?tabid=xx) var std = new TabUrlInfo { TabId = tab.TabID, HttpStatus = stdHttpStatus, CultureCode = (tab.CultureCode == "") ? defaultCulture : tab.CultureCode, Url = stdUrl, IsSystem = true, SeqNum = seqNum, }; tab.TabUrls.Insert(0, std); seqNum--; } } } /// <summary> /// A reflection based call to the Friendly Url provider to get the 'base' (dnn standard) urls /// </summary> /// <param name="tab"></param> /// <param name="path"></param> /// <param name="defaultPage"></param> /// <param name="httpAlias"></param> /// <param name="settings"></param> /// <returns></returns> internal static string GetFriendlyUrl(TabInfo tab, string path, string defaultPage, string httpAlias, FriendlyUrlSettings settings) { List<string> messages; object result = CallFriendlyUrlProviderMethod("BaseFriendlyUrl", out messages, tab, path, defaultPage, httpAlias, settings); if (result == null) { return Globals.NavigateURL(tab.TabID); } return (string) result; } internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, string httpAlias, bool ignoreCustomRedirects) { FriendlyUrlSettings settings = GetCurrentSettings(tab.PortalID); List<string> messages; return GetImprovedFriendlyUrl(tab, path, defaultPage, httpAlias, ignoreCustomRedirects, settings, out messages); } /// <summary> /// A reflection based call to the friendly URl Provider object. Done like this to avoid a circular reference /// </summary> /// <param name="tab"></param> /// <param name="path"></param> /// <param name="defaultPage"></param> /// <param name="httpAlias"></param> /// <param name="ignoreCustomRedirects"></param> /// <param name="settings"></param> /// <returns></returns> internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, string httpAlias, bool ignoreCustomRedirects, FriendlyUrlSettings settings) { List<string> messages; return GetImprovedFriendlyUrl(tab, path, defaultPage, httpAlias, ignoreCustomRedirects, settings, out messages); } internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, string httpAlias, bool ignoreCustomRedirects, FriendlyUrlSettings settings, out List<string> messages) { object result = CallFriendlyUrlProviderMethod("ImprovedFriendlyUrlWithMessages", out messages, tab, path, defaultPage, httpAlias, ignoreCustomRedirects, settings); if (result != null) { return (string) result; } return ""; } internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, PortalSettings portalSettings, bool ignoreCustomRedirects, FriendlyUrlSettings settings) { List<string> messages; object result = CallFriendlyUrlProviderMethod("ImprovedFriendlyUrlWithSettings", out messages, tab, path, defaultPage, portalSettings, ignoreCustomRedirects, settings); if (result != null) { return (string) result; } return ""; } internal static string GetImprovedFriendlyUrl(TabInfo tab, string path, string defaultPage, PortalSettings portalSettings, bool ignoreCustomRedirects, FriendlyUrlSettings settings, out List<string> messages) { object result = CallFriendlyUrlProviderMethod("ImprovedFriendlyUrlWithSettingsAndMessages", out messages, tab, path, defaultPage, portalSettings, ignoreCustomRedirects, settings); if (result != null) { return (string) result; } return ""; } /* /// <summary> /// A reflection based called to the Friendly Url Provider object. Done like this to avoid circular references /// </summary> /// <param name="tab"></param> /// <param name="replaceCharacter"></param> /// <param name="replaceWith"></param> /// <returns></returns> internal static string BuildTabPathWithReplacement(TabInfo tab, string replaceCharacter, string replaceWith) { object result = CallTabPathHelperMethod("BuildTabPathWithReplacement", tab, replaceCharacter, replaceWith); if (result != null) { return (string) result; } return ""; } internal static string ReplaceDiacritics(string tabPath) { object result = CallTabPathHelperMethod("ReplaceDiacritics", tabPath); if (result != null) { return (string) result; } return ""; } public static void RebuildCustomUrlDict(string reason, int portalId) { CallTabDictControllerMethod("InvalidateDictionary", reason, null, portalId); } //internal static void ProcessTestRequest(string httpMethod, Uri requestUri, UrlAction result, NameValueCollection queryString, FriendlyUrlSettings settings, out List<string> messages) //{ // //public void ProcessRequest(HttpContext context, HttpRequest request, HttpServerUtility Server, HttpResponse response, bool useFriendlyUrls, string requestType, Uri requestUri, UrlAction result, NameValueCollection queryStringCol, FriendlyUrlSettings settings) // bool useFriendlyUrls = (DotNetNuke.Entities.Host.HostSettings.GetHostSetting("UseFriendlyUrls") == "Y"); // object retval = CallUrlRewriterMethod("ProcessTestRequest", out messages, useFriendlyUrls, httpMethod, requestUri, result, queryString, settings); //} /// <summary> /// Gets the Reflection MethodInfo object of the FriendlyUrlProvider method, /// as LONG as the iFInity.UrlMaster.FriendlyUrlProvider can be found /// </summary> /// <remarks>This is a heavyweight proc, don't call too much!</remarks> /// <param name="methodName"></param> /// <returns></returns> private static object CallFriendlyUrlProviderMethod(string methodName, out List<string> messages, params object[] parameters) { return CallFriendlyUrlProviderDllMethod(methodName, "iFinity.DNN.Modules.UrlMaster.DNNFriendlyUrlProvider", out messages, parameters); } private static void CallTabDictControllerMethod(string methodName, params object[] parameters) { CallFriendlyUrlProviderDllMethod(methodName, "iFinity.DNN.Modules.UrlMaster.TabDictController", parameters); } private static object CallTabPathHelperMethod(string methodName, params object[] parameters) { return CallFriendlyUrlProviderDllMethod(methodName, "iFinity.DNN.Modules.UrlMaster.TabPathHelper", parameters); } private static object CallFriendlyUrlProviderDllMethod(string methodName, string typeName, params object[] parameters) { List<string> messages; return CallFriendlyUrlProviderDllMethod(methodName, typeName, out messages, parameters); } private static object CallFriendlyUrlProviderDllMethod(string methodName, string typeName, out List<string> messages, params object[] parameters) { object result = null; messages = null; try { object providerObj = null; Assembly urlMasterProvider = Assembly.Load("iFinity.UrlMaster.FriendlyUrlProvider"); Type[] types = urlMasterProvider.GetTypes(); foreach (Type type in types) { if ((type.FullName == typeName) & (type.IsClass)) { Type providerType = type; string providerTypeName = providerType.Name; //570 : check to see if it is an abstract class before trying to instantiate the //calling object if (!providerType.IsAbstract) { // get the provider objects from the stored collection if necessary if (_providerObjects != null) { if (_providerObjects.ContainsKey(providerTypeName)) { providerObj = _providerObjects[providerTypeName]; } } if (providerObj == null) { providerObj = Activator.CreateInstance(providerType); } if (_providerObjects == null) { _providerObjects = new Dictionary<string, object> {{providerTypeName, providerObj}}; } } if (providerObj != null || providerType.IsAbstract) { MethodInfo method = providerType.GetMethod(methodName); if (method != null) { //new collection int messageParmIdx = -1; var parmValues = new List<object>(parameters); ParameterInfo[] methodParms = method.GetParameters(); for (int i = 0; i <= methodParms.GetUpperBound(0); i++) { if (methodParms[i].IsOut && i > parameters.GetUpperBound(0) && methodParms[i].Name.ToLower() == "messages") { //add on another one on the end parmValues.Add(messages); messageParmIdx = i; parameters = parmValues.ToArray(); } if (methodParms[i].Name.ToLower() == "parenttraceid" && i > parameters.GetUpperBound(0)) { parmValues.Add(Guid.Empty); parameters = parmValues.ToArray(); } } result = method.Invoke(providerObj, parameters); //get the out messages value if (messageParmIdx > -1) { messages = (List<string>) parameters[messageParmIdx]; } } break; } } } //} } catch (Exception ex) { //get the standard DNN friendly Url by loading up HttpModules if (messages == null) { messages = new List<string>(); } messages.Add("Error:[" + ex.Message + "]"); if (ex.InnerException != null) { messages.Add("Inner Error:[ " + ex.InnerException.Message + "]"); messages.Add("Stack Trace :[ " + ex.InnerException.StackTrace + "]"); } } return result; } */ public static Dictionary<int, TabInfo> GetTabs(int portalId, bool includeStdUrls) { return GetTabs(portalId, includeStdUrls, GetCurrentSettings(portalId)); } public static Dictionary<int, TabInfo> GetTabs(int portalId, bool includeStdUrls, FriendlyUrlSettings settings) { PortalSettings portalSettings = null; // 716 just ignore portal settings if we don't actually need it if (includeStdUrls) { portalSettings = PortalController.Instance.GetCurrentPortalSettings(); } return GetTabs(portalId, includeStdUrls, portalSettings, settings); } public static Dictionary<int, TabInfo> GetTabs(int portalId, bool includeStdUrls, PortalSettings portalSettings, FriendlyUrlSettings settings) { // 811 : friendly urls for admin/host tabs var tabs = new Dictionary<int, TabInfo>(); var portalTabs = TabController.Instance.GetTabsByPortal(portalId); var hostTabs = TabController.Instance.GetTabsByPortal(-1); foreach (TabInfo tab in portalTabs.Values) { tabs[tab.TabID] = tab; } if (settings.FriendlyAdminHostUrls) { foreach (TabInfo tab in hostTabs.Values) { tabs[tab.TabID] = tab; } } return tabs; } /// <summary> /// Returns a list of http alias values where that alias is associated with a tab as a custom alias. /// </summary> /// <remarks>Aliases returned are all in lower case only.</remarks> /// <returns></returns> public static List<string> GetCustomAliasesForTabs() { var aliases = new List<string>(); IDataReader dr = DataProvider.Instance().GetCustomAliasesForTabs(); try { while (dr.Read()) { aliases.Add(Null.SetNullString(dr["HttpAlias"])); } } catch (Exception exc) { Exceptions.LogException(exc); } finally { CBO.CloseDataReader(dr, true); } return aliases; } public static TabInfo GetTab(int tabId, bool addStdUrls) { PortalSettings portalSettings = PortalController.Instance.GetCurrentPortalSettings(); return GetTab(tabId, addStdUrls, portalSettings, GetCurrentSettings(portalSettings.PortalId)); } public static TabInfo GetTab(int tabId, bool addStdUrls, PortalSettings portalSettings, FriendlyUrlSettings settings) { TabInfo tab = TabController.Instance.GetTab(tabId, portalSettings.PortalId, false); if (addStdUrls) { // Add on the standard Urls that exist for a tab, based on settings like // replacing spaces, diacritic characters and languages // BuildFriendlyUrls(tab, true, portalSettings, settings); } return tab; } public static string CleanNameForUrl(string urlName, FriendlyUrlOptions options, out bool replacedUnwantedChars) { replacedUnwantedChars = false; // get options if (options == null) { options = new FriendlyUrlOptions(); } bool convertDiacritics = options.ConvertDiacriticChars; Regex regexMatch = options.RegexMatchRegex; string replaceWith = options.PunctuationReplacement; bool replaceDoubleChars = options.ReplaceDoubleChars; Dictionary<string, string> replacementChars = options.ReplaceCharWithChar; if (urlName == null) { urlName = string.Empty; } var result = new StringBuilder(urlName.Length); int i = 0; string normalisedUrl = urlName; if (convertDiacritics) { normalisedUrl = urlName.Normalize(NormalizationForm.FormD); if (!string.Equals(normalisedUrl, urlName, StringComparison.Ordinal)) { replacedUnwantedChars = true; // replaced an accented character } } int last = normalisedUrl.Length - 1; bool doublePeriod = false; foreach (char c in normalisedUrl) { // look for a double period in the name if (!doublePeriod && i > 0 && c == '.' && normalisedUrl[i - 1] == '.') { doublePeriod = true; } // use string for manipulation string ch = c.ToString(CultureInfo.InvariantCulture); // do replacement in pre-defined list? if (replacementChars != null && replacementChars.ContainsKey(ch)) { // replace with value ch = replacementChars[ch]; replacedUnwantedChars = true; } else if (convertDiacritics && CharUnicodeInfo.GetUnicodeCategory(c) == UnicodeCategory.NonSpacingMark) { ch = string.Empty; replacedUnwantedChars = true; } else { // Check if ch is in the replace list CheckCharsForReplace(options, ref ch, ref replacedUnwantedChars); // not in replacement list, check if valid char if (regexMatch.IsMatch(ch)) { ch = string.Empty; // not a replacement or allowed char, so doesn't go into Url replacedUnwantedChars = true; // if we are here, this character isn't going into the output Url } } // Check if the final ch is an illegal char CheckIllegalChars(options.IllegalChars, ref ch, ref replacedUnwantedChars); if (i == last) { // 834 : strip off last character if it is a '.' if (!(ch == "-" || ch == replaceWith || ch == ".")) { // only append if not the same as the replacement character result.Append(ch); } else { replacedUnwantedChars = true; // last char not added - effectively replaced with nothing. } } else { result.Append(ch); } i++; // increment counter } if (doublePeriod) { result = result.Replace("..", string.Empty); } // replace any duplicated replacement characters by doing replace twice // replaces -- with - or --- with - //749 : ampersand not completed replaced if (replaceDoubleChars && !string.IsNullOrEmpty(replaceWith)) { result = result.Replace(replaceWith + replaceWith, replaceWith); result = result.Replace(replaceWith + replaceWith, replaceWith); } return result.ToString(); } /// <summary> /// Ensures that the path starts with the leading character. /// </summary> /// <param name="leading"></param> /// <param name="path"></param> /// <returns></returns> public static string EnsureLeadingChar(string leading, string path) { if (leading != null && path != null && leading.Length <= path.Length && leading != string.Empty) { string start = path.Substring(0, leading.Length); if (string.Compare(start, leading, StringComparison.OrdinalIgnoreCase) != 0) { // not leading with this path = leading + path; } } return path; } public static string EnsureNotLeadingChar(string leading, string path) { if (leading != null && path != null && leading.Length <= path.Length && leading != string.Empty) { string start = path.Substring(0, leading.Length); if (string.Compare(start, leading, StringComparison.OrdinalIgnoreCase) == 0) { // matches start, take leading off path = path.Substring(leading.Length); } } return path; } // 737 : detect mobile and other types of browsers public static BrowserTypes GetBrowserType(HttpRequest request, HttpResponse response, FriendlyUrlSettings settings) { var browserType = BrowserTypes.Normal; if (request != null && settings != null) { bool isCookieSet = false; bool isMobile = false; if (CanUseMobileDevice(request, response)) { HttpCookie viewMobileCookie = response.Cookies[MobileViewSiteCookieName]; if (viewMobileCookie != null && bool.TryParse(viewMobileCookie.Value, out isMobile)) { isCookieSet = true; } if (isMobile == false) { if (!isCookieSet) { isMobile = IsMobileClient(); if (isMobile) { browserType = BrowserTypes.Mobile; } // Store the result as a cookie. if (viewMobileCookie == null) { response.Cookies.Add(new HttpCookie(MobileViewSiteCookieName, isMobile.ToString()) { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/" }); } else { viewMobileCookie.Value = isMobile.ToString(); } } } else { browserType = BrowserTypes.Mobile; } } } return browserType; } public static string ValidateUrl(string cleanUrl, int validateUrlForTabId, PortalSettings settings, out bool modified) { modified = false; bool isUnique; var uniqueUrl = cleanUrl; int counter = 0; do { if (counter > 0) { uniqueUrl = uniqueUrl + counter.ToString(CultureInfo.InvariantCulture); modified = true; } isUnique = ValidateUrl(uniqueUrl, validateUrlForTabId, settings); counter++; } while (!isUnique); return uniqueUrl; } internal static bool CanUseMobileDevice(HttpRequest request, HttpResponse response) { var canUseMobileDevice = true; int val; if (int.TryParse(request.QueryString[DisableMobileRedirectQueryStringName], out val)) { // the nomo value is in the querystring if (val == 1) { // no, can't do it canUseMobileDevice = false; var cookie = new HttpCookie(DisableMobileViewCookieName) { Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", }; response.Cookies.Set(cookie); } else { // check for disable mobile view cookie name var cookie = request.Cookies[DisableMobileViewCookieName]; if (cookie != null) { // if exists, expire cookie to allow redirect cookie = new HttpCookie(DisableMobileViewCookieName) { Expires = DateTime.Now.AddMinutes(-1), Path = !string.IsNullOrEmpty(Globals.ApplicationPath) ? Globals.ApplicationPath : "/", }; response.Cookies.Set(cookie); } // check the DotNetNuke cookies for allowed if (request.Cookies[DisableMobileRedirectCookieName] != null && request.Cookies[DisableRedirectPresistCookieName] != null) // check for cookie { // cookies exist, can't use mobile device canUseMobileDevice = false; } } } else { // look for disable mobile view cookie var cookie = request.Cookies[DisableMobileViewCookieName]; if (cookie != null) { canUseMobileDevice = false; } } return canUseMobileDevice; } /// <summary> /// Replaces the core IsAdminTab call which was decommissioned for DNN 5.0. /// </summary> /// <param name="tabPath">The path of the tab //admin//someothername.</param> /// <param name="settings"></param> /// <remarks>Duplicated in RewriteController.cs.</remarks> /// <returns></returns> internal static bool IsAdminTab(int portalId, string tabPath, FriendlyUrlSettings settings) { return RewriteController.IsAdminTab(portalId, tabPath, settings); } private static bool IsMobileClient() { return (HttpContext.Current.Request.Browser != null) && (ClientCapabilityProvider.Instance() != null) && ClientCapabilityProvider.CurrentClientCapability.IsMobile; } private static void CheckIllegalChars(string illegalChars, ref string ch, ref bool replacedUnwantedChars) { var resultingCh = new StringBuilder(ch.Length); foreach (char c in ch) // ch could contain several chars from the pre-defined replacement list { if (illegalChars.ToUpperInvariant().Contains(char.ToUpperInvariant(c))) { replacedUnwantedChars = true; } else { resultingCh.Append(c); } } ch = resultingCh.ToString(); } private static void CheckCharsForReplace(FriendlyUrlOptions options, ref string ch, ref bool replacedUnwantedChars) { if (!options.ReplaceChars.ToUpperInvariant().Contains(ch.ToUpperInvariant())) { return; } // if not replacing spaces, which are implied if (ch != " ") { replacedUnwantedChars = true; } ch = options.PunctuationReplacement; // in list of replacment chars // If we still have a space ensure it's encoded if (ch == " ") { ch = options.SpaceEncoding; } } private static bool ValidateUrl(string url, int validateUrlForTabId, PortalSettings settings) { // Try and get a user by the url var user = UserController.GetUserByVanityUrl(settings.PortalId, url); bool isUnique = user == null; if (isUnique) { // Try and get a tab by the url int tabId = TabController.GetTabByTabPath(settings.PortalId, "//" + url, settings.CultureCode); isUnique = tabId == -1 || tabId == validateUrlForTabId; } // check whether have a tab which use the url. if (isUnique) { var friendlyUrlSettings = GetCurrentSettings(settings.PortalId); var tabs = TabController.Instance.GetTabsByPortal(settings.PortalId).AsList(); // DNN-6492: if content localize enabled, only check tab names in current culture. if (settings.ContentLocalizationEnabled) { tabs = tabs.Where(t => t.CultureCode == settings.CultureCode).ToList(); } foreach (TabInfo tab in tabs) { if (tab.TabID == validateUrlForTabId) { continue; } if (tab.TabUrls.Count == 0) { var baseUrl = Globals.AddHTTP(settings.PortalAlias.HTTPAlias) + "/Default.aspx?TabId=" + tab.TabID; var path = AdvancedFriendlyUrlProvider.ImprovedFriendlyUrl( tab, baseUrl, Globals.glbDefaultPage, settings.PortalAlias.HTTPAlias, false, friendlyUrlSettings, Guid.Empty); var tabUrl = path.Replace(Globals.AddHTTP(settings.PortalAlias.HTTPAlias), string.Empty); if (tabUrl.Equals("/" + url, StringComparison.InvariantCultureIgnoreCase)) { isUnique = false; break; } } else if (tab.TabUrls.Any(u => u.Url.Equals("/" + url, StringComparison.InvariantCultureIgnoreCase))) { isUnique = false; break; } } } return isUnique; } } }
using CrystalDecisions.CrystalReports.Engine; using CrystalDecisions.Windows.Forms; using DpSdkEngLib; using DPSDKOPSLib; using Microsoft.VisualBasic; using System; using System.Collections; using System.Collections.Generic; using System.Drawing; using System.Diagnostics; using System.Windows.Forms; using System.Linq; using System.Xml.Linq; namespace _4PosBackOffice.NET { [Microsoft.VisualBasic.CompilerServices.DesignerGenerated()] partial class frmPOSSecurity { #region "Windows Form Designer generated code " [System.Diagnostics.DebuggerNonUserCode()] public frmPOSSecurity() : base() { FormClosed += frmPOSSecurity_FormClosed; KeyPress += frmPOSSecurity_KeyPress; //This call is required by the Windows Form Designer. InitializeComponent(); } //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()] protected override void Dispose(bool Disposing) { if (Disposing) { if ((components != null)) { components.Dispose(); } } base.Dispose(Disposing); } //Required by the Windows Form Designer private System.ComponentModel.IContainer components; public System.Windows.Forms.ToolTip ToolTip1; private System.Windows.Forms.CheckBox withEventsField_chkPosSecurity; public System.Windows.Forms.CheckBox chkPosSecurity { get { return withEventsField_chkPosSecurity; } set { if (withEventsField_chkPosSecurity != null) { withEventsField_chkPosSecurity.CheckStateChanged -= chkPosSecurity_CheckStateChanged; } withEventsField_chkPosSecurity = value; if (withEventsField_chkPosSecurity != null) { withEventsField_chkPosSecurity.CheckStateChanged += chkPosSecurity_CheckStateChanged; } } } private System.Windows.Forms.CheckedListBox withEventsField_lstChannel; public System.Windows.Forms.CheckedListBox lstChannel { get { return withEventsField_lstChannel; } set { if (withEventsField_lstChannel != null) { withEventsField_lstChannel.ItemCheck -= lstChannel_ItemCheck; } withEventsField_lstChannel = value; if (withEventsField_lstChannel != null) { withEventsField_lstChannel.ItemCheck += lstChannel_ItemCheck; } } } public System.Windows.Forms.CheckedListBox lstSecurity; private System.Windows.Forms.Button withEventsField_cmdExit; public System.Windows.Forms.Button cmdExit { get { return withEventsField_cmdExit; } set { if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click -= cmdExit_Click; } withEventsField_cmdExit = value; if (withEventsField_cmdExit != null) { withEventsField_cmdExit.Click += cmdExit_Click; } } } public System.Windows.Forms.Button cmdCancel; public System.Windows.Forms.Panel picButtons; public System.Windows.Forms.Label _Label1_2; public System.Windows.Forms.Label _Label1_1; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_1; public System.Windows.Forms.Label _Label1_0; public Microsoft.VisualBasic.PowerPacks.RectangleShape _Shape1_0; //Public WithEvents Label1 As Microsoft.VisualBasic.Compatibility.VB6.LabelArray public RectangleShapeArray Shape1; public Microsoft.VisualBasic.PowerPacks.ShapeContainer ShapeContainer1; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()] private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.ToolTip1 = new System.Windows.Forms.ToolTip(this.components); this.ShapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this._Shape1_1 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this._Shape1_0 = new Microsoft.VisualBasic.PowerPacks.RectangleShape(); this.chkPosSecurity = new System.Windows.Forms.CheckBox(); this.lstChannel = new System.Windows.Forms.CheckedListBox(); this.lstSecurity = new System.Windows.Forms.CheckedListBox(); this.picButtons = new System.Windows.Forms.Panel(); this.cmdExit = new System.Windows.Forms.Button(); this.cmdCancel = new System.Windows.Forms.Button(); this._Label1_2 = new System.Windows.Forms.Label(); this._Label1_1 = new System.Windows.Forms.Label(); this._Label1_0 = new System.Windows.Forms.Label(); this.picButtons.SuspendLayout(); this.SuspendLayout(); // //ShapeContainer1 // this.ShapeContainer1.Location = new System.Drawing.Point(0, 0); this.ShapeContainer1.Margin = new System.Windows.Forms.Padding(0); this.ShapeContainer1.Name = "ShapeContainer1"; this.ShapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] { this._Shape1_1, this._Shape1_0 }); this.ShapeContainer1.Size = new System.Drawing.Size(493, 486); this.ShapeContainer1.TabIndex = 9; this.ShapeContainer1.TabStop = false; // //_Shape1_1 // this._Shape1_1.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._Shape1_1.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_1.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_1.FillColor = System.Drawing.Color.Black; this._Shape1_1.Location = new System.Drawing.Point(252, 78); this._Shape1_1.Name = "_Shape1_1"; this._Shape1_1.Size = new System.Drawing.Size(232, 373); // //_Shape1_0 // this._Shape1_0.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(192)), Convert.ToInt32(Convert.ToByte(255))); this._Shape1_0.BackStyle = Microsoft.VisualBasic.PowerPacks.BackStyle.Opaque; this._Shape1_0.BorderColor = System.Drawing.SystemColors.WindowText; this._Shape1_0.FillColor = System.Drawing.Color.Black; this._Shape1_0.Location = new System.Drawing.Point(9, 78); this._Shape1_0.Name = "_Shape1_0"; this._Shape1_0.Size = new System.Drawing.Size(232, 373); // //chkPosSecurity // this.chkPosSecurity.BackColor = System.Drawing.SystemColors.Control; this.chkPosSecurity.Cursor = System.Windows.Forms.Cursors.Default; this.chkPosSecurity.ForeColor = System.Drawing.SystemColors.ControlText; this.chkPosSecurity.Location = new System.Drawing.Point(10, 456); this.chkPosSecurity.Name = "chkPosSecurity"; this.chkPosSecurity.RightToLeft = System.Windows.Forms.RightToLeft.No; this.chkPosSecurity.Size = new System.Drawing.Size(233, 19); this.chkPosSecurity.TabIndex = 8; this.chkPosSecurity.Text = "Select All"; this.chkPosSecurity.UseVisualStyleBackColor = false; // //lstChannel // this.lstChannel.BackColor = System.Drawing.SystemColors.Window; this.lstChannel.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lstChannel.Cursor = System.Windows.Forms.Cursors.Default; this.lstChannel.ForeColor = System.Drawing.SystemColors.WindowText; this.lstChannel.Location = new System.Drawing.Point(264, 90); this.lstChannel.Name = "lstChannel"; this.lstChannel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lstChannel.Size = new System.Drawing.Size(208, 347); this.lstChannel.TabIndex = 5; this.lstChannel.Tag = "0"; // //lstSecurity // this.lstSecurity.BackColor = System.Drawing.SystemColors.Window; this.lstSecurity.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.lstSecurity.Cursor = System.Windows.Forms.Cursors.Default; this.lstSecurity.ForeColor = System.Drawing.SystemColors.WindowText; this.lstSecurity.Location = new System.Drawing.Point(22, 90); this.lstSecurity.Name = "lstSecurity"; this.lstSecurity.RightToLeft = System.Windows.Forms.RightToLeft.No; this.lstSecurity.Size = new System.Drawing.Size(208, 347); this.lstSecurity.TabIndex = 3; this.lstSecurity.Tag = "0"; // //picButtons // this.picButtons.BackColor = System.Drawing.Color.Blue; this.picButtons.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.picButtons.Controls.Add(this.cmdExit); this.picButtons.Controls.Add(this.cmdCancel); this.picButtons.Cursor = System.Windows.Forms.Cursors.Default; this.picButtons.Dock = System.Windows.Forms.DockStyle.Top; this.picButtons.ForeColor = System.Drawing.SystemColors.ControlText; this.picButtons.Location = new System.Drawing.Point(0, 0); this.picButtons.Name = "picButtons"; this.picButtons.RightToLeft = System.Windows.Forms.RightToLeft.No; this.picButtons.Size = new System.Drawing.Size(493, 39); this.picButtons.TabIndex = 2; // //cmdExit // this.cmdExit.BackColor = System.Drawing.SystemColors.Control; this.cmdExit.Cursor = System.Windows.Forms.Cursors.Default; this.cmdExit.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdExit.Location = new System.Drawing.Point(411, 3); this.cmdExit.Name = "cmdExit"; this.cmdExit.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdExit.Size = new System.Drawing.Size(73, 29); this.cmdExit.TabIndex = 1; this.cmdExit.TabStop = false; this.cmdExit.Text = "E&xit"; this.cmdExit.UseVisualStyleBackColor = false; // //cmdCancel // this.cmdCancel.BackColor = System.Drawing.SystemColors.Control; this.cmdCancel.Cursor = System.Windows.Forms.Cursors.Default; this.cmdCancel.ForeColor = System.Drawing.SystemColors.ControlText; this.cmdCancel.Location = new System.Drawing.Point(5, 3); this.cmdCancel.Name = "cmdCancel"; this.cmdCancel.RightToLeft = System.Windows.Forms.RightToLeft.No; this.cmdCancel.Size = new System.Drawing.Size(73, 29); this.cmdCancel.TabIndex = 0; this.cmdCancel.TabStop = false; this.cmdCancel.Text = "&Undo"; this.cmdCancel.UseVisualStyleBackColor = false; // //_Label1_2 // this._Label1_2.AutoSize = true; this._Label1_2.BackColor = System.Drawing.Color.Transparent; this._Label1_2.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_2.ForeColor = System.Drawing.SystemColors.ControlText; this._Label1_2.Location = new System.Drawing.Point(12, 42); this._Label1_2.Name = "_Label1_2"; this._Label1_2.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_2.Size = new System.Drawing.Size(35, 13); this._Label1_2.TabIndex = 7; this._Label1_2.Text = "Name"; // //_Label1_1 // this._Label1_1.AutoSize = true; this._Label1_1.BackColor = System.Drawing.Color.Transparent; this._Label1_1.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_1.ForeColor = System.Drawing.SystemColors.ControlText; this._Label1_1.Location = new System.Drawing.Point(12, 63); this._Label1_1.Name = "_Label1_1"; this._Label1_1.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_1.Size = new System.Drawing.Size(74, 13); this._Label1_1.TabIndex = 6; this._Label1_1.Text = "&1. Permissions"; // //_Label1_0 // this._Label1_0.AutoSize = true; this._Label1_0.BackColor = System.Drawing.Color.Transparent; this._Label1_0.Cursor = System.Windows.Forms.Cursors.Default; this._Label1_0.ForeColor = System.Drawing.SystemColors.ControlText; this._Label1_0.Location = new System.Drawing.Point(255, 63); this._Label1_0.Name = "_Label1_0"; this._Label1_0.RightToLeft = System.Windows.Forms.RightToLeft.No; this._Label1_0.Size = new System.Drawing.Size(120, 13); this._Label1_0.TabIndex = 4; this._Label1_0.Text = "&2. Sale Channel Access"; // //frmPOSSecurity // this.AutoScaleDimensions = new System.Drawing.SizeF(6f, 13f); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224)), Convert.ToInt32(Convert.ToByte(224))); this.ClientSize = new System.Drawing.Size(493, 486); this.ControlBox = false; this.Controls.Add(this.chkPosSecurity); this.Controls.Add(this.lstChannel); this.Controls.Add(this.lstSecurity); this.Controls.Add(this.picButtons); this.Controls.Add(this._Label1_2); this.Controls.Add(this._Label1_1); this.Controls.Add(this._Label1_0); this.Controls.Add(this.ShapeContainer1); this.Cursor = System.Windows.Forms.Cursors.Default; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.KeyPreview = true; this.Location = new System.Drawing.Point(3, 22); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmPOSSecurity"; this.RightToLeft = System.Windows.Forms.RightToLeft.No; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Employee Point Of Sale Permissions"; this.picButtons.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion } }
// // ClientSessionCache.cs: Client-side cache for re-using sessions // // Author: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2006 Novell (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections; namespace Mono.Security.Protocol.Tls { internal class ClientSessionInfo : IDisposable { // (by default) we keep this item valid for 3 minutes (if unused) private const int DefaultValidityInterval = 3 * 60; private static readonly int ValidityInterval; private bool disposed; private DateTime validuntil; private string host; // see RFC2246 - Section 7 private byte[] sid; private byte[] masterSecret; static ClientSessionInfo () { #if MOONLIGHT ValidityInterval = DefaultValidityInterval; #else string user_cache_timeout = Environment.GetEnvironmentVariable ("MONO_TLS_SESSION_CACHE_TIMEOUT"); if (user_cache_timeout == null) { ValidityInterval = DefaultValidityInterval; } else { try { ValidityInterval = Int32.Parse (user_cache_timeout); } catch { ValidityInterval = DefaultValidityInterval; } } #endif } public ClientSessionInfo (string hostname, byte[] id) { host = hostname; sid = id; KeepAlive (); } ~ClientSessionInfo () { Dispose (false); } public string HostName { get { return host; } } public byte[] Id { get { return sid; } } public bool Valid { get { return ((masterSecret != null) && (validuntil > DateTime.UtcNow)); } } public void GetContext (Context context) { CheckDisposed (); if (context.MasterSecret != null) masterSecret = (byte[]) context.MasterSecret.Clone (); } public void SetContext (Context context) { CheckDisposed (); if (masterSecret != null) context.MasterSecret = (byte[]) masterSecret.Clone (); } public void KeepAlive () { CheckDisposed (); validuntil = DateTime.UtcNow.AddSeconds (ValidityInterval); } public void Dispose () { Dispose (true); GC.SuppressFinalize (this); } private void Dispose (bool disposing) { if (!disposed) { validuntil = DateTime.MinValue; host = null; sid = null; if (masterSecret != null) { Array.Clear (masterSecret, 0, masterSecret.Length); masterSecret = null; } } disposed = true; } private void CheckDisposed () { if (disposed) { string msg = Locale.GetText ("Cache session information were disposed."); throw new ObjectDisposedException (msg); } } } // note: locking is aggressive but isn't used often (and we gain much more :) internal class ClientSessionCache { static Hashtable cache; static object locker; static ClientSessionCache () { cache = new Hashtable (); locker = new object (); } // note: we may have multiple connections with a host, so // possibly multiple entries per host (each with a different // id), so we do not use the host as the hashtable key static public void Add (string host, byte[] id) { lock (locker) { string uid = BitConverter.ToString (id); ClientSessionInfo si = (ClientSessionInfo) cache[uid]; if (si == null) { cache.Add (uid, new ClientSessionInfo (host, id)); } else if (si.HostName == host) { // we already have this and it's still valid // on the server, so we'll keep it a little longer si.KeepAlive (); } else { // it's very unlikely but the same session id // could be used by more than one host. In this // case we replace the older one with the new one si.Dispose (); cache.Remove (uid); cache.Add (uid, new ClientSessionInfo (host, id)); } } } // return the first session us static public byte[] FromHost (string host) { lock (locker) { foreach (ClientSessionInfo si in cache.Values) { if (si.HostName == host) { if (si.Valid) { // ensure it's still valid when we really need it si.KeepAlive (); return si.Id; } } } return null; } } // only called inside the lock static private ClientSessionInfo FromContext (Context context, bool checkValidity) { if (context == null) return null; byte[] id = context.SessionId; if ((id == null) || (id.Length == 0)) return null; // do we have a session cached for this host ? string uid = BitConverter.ToString (id); ClientSessionInfo si = (ClientSessionInfo) cache[uid]; if (si == null) return null; // In the unlikely case of multiple hosts using the same // session id, we just act like we do not know about it if (context.ClientSettings.TargetHost != si.HostName) return null; // yes, so what's its status ? if (checkValidity && !si.Valid) { si.Dispose (); cache.Remove (uid); return null; } // ok, it make sense return si; } static public bool SetContextInCache (Context context) { lock (locker) { // Don't check the validity because the masterKey of the ClientSessionInfo // can still be null when this is called the first time ClientSessionInfo csi = FromContext (context, false); if (csi == null) return false; csi.GetContext (context); csi.KeepAlive (); return true; } } static public bool SetContextFromCache (Context context) { lock (locker) { ClientSessionInfo csi = FromContext (context, true); if (csi == null) return false; csi.SetContext (context); csi.KeepAlive (); return true; } } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.4927 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace WebsitePanel.Portal { public partial class HostingPlansEditPlan { /// <summary> /// HostingPlansEditPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel HostingPlansEditPanel; /// <summary> /// updatePanelUsers control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.UpdatePanel updatePanelUsers; /// <summary> /// lblMessage control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblMessage; /// <summary> /// lblPlanName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblPlanName; /// <summary> /// txtPlanName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtPlanName; /// <summary> /// valPlanName control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator valPlanName; /// <summary> /// lblPlanDescription control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblPlanDescription; /// <summary> /// txtPlanDescription control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.TextBox txtPlanDescription; /// <summary> /// secTarget control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secTarget; /// <summary> /// TargetPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel TargetPanel; /// <summary> /// rowTargetServer control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow rowTargetServer; /// <summary> /// lblTargetServer control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblTargetServer; /// <summary> /// ddlServer control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlServer; /// <summary> /// valRequireServer control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator valRequireServer; /// <summary> /// rowTargetSpace control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlTableRow rowTargetSpace; /// <summary> /// lblTargetSpace control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Label lblTargetSpace; /// <summary> /// ddlSpace control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.DropDownList ddlSpace; /// <summary> /// valRequireSpace control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.RequiredFieldValidator valRequireSpace; /// <summary> /// secQuotas control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.CollapsiblePanel secQuotas; /// <summary> /// QuotasPanel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Panel QuotasPanel; /// <summary> /// hostingPlansQuotas control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::WebsitePanel.Portal.HostingPlansQuotas hostingPlansQuotas; /// <summary> /// btnSave control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnSave; /// <summary> /// btnCancel control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnCancel; /// <summary> /// btnDelete control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Button btnDelete; } }
using System; using System.Diagnostics; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Providers.Azure; using Orleans.Runtime; using Orleans.Serialization; using LogLevel = Microsoft.Extensions.Logging.LogLevel; namespace Orleans.Storage { /// <summary> /// Simple storage provider for writing grain state data to Azure blob storage in JSON format. /// </summary> public class AzureBlobGrainStorage : IGrainStorage, ILifecycleParticipant<ISiloLifecycle> { private BlobContainerClient container; private ILogger logger; private readonly string name; private AzureBlobStorageOptions options; private IGrainStorageSerializer grainStorageSerializer; private readonly IServiceProvider services; /// <summary> Default constructor </summary> public AzureBlobGrainStorage( string name, AzureBlobStorageOptions options, IGrainStorageSerializer grainStorageSerializer, IServiceProvider services, ILogger<AzureBlobGrainStorage> logger) { this.name = name; this.options = options; this.grainStorageSerializer = options.GrainStorageSerializer; this.services = services; this.logger = logger; } /// <summary> Read state data function for this storage provider. </summary> /// <see cref="IGrainStorage.ReadStateAsync"/> public async Task ReadStateAsync<T>(string grainType, GrainReference grainId, IGrainState<T> grainState) { var blobName = GetBlobName(grainType, grainId); if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_Reading, "Reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); try { var blob = container.GetBlobClient(blobName); BinaryData contents; try { var response = await blob.DownloadContentAsync(); grainState.ETag = response.Value.Details.ETag.ToString(); contents = response.Value.Content; } catch (RequestFailedException exception) when (exception.IsBlobNotFound()) { if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_BlobNotFound, "BlobNotFound reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); return; } catch (RequestFailedException exception) when (exception.IsContainerNotFound()) { if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_ContainerNotFound, "ContainerNotFound reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); return; } if (contents == null) // TODO bpetit { if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_BlobEmpty, "BlobEmpty reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); grainState.RecordExists = false; return; } else { grainState.RecordExists = true; } var loadedState = this.ConvertFromStorageFormat<T>(contents); grainState.State = loadedState ?? Activator.CreateInstance<T>(); if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_DataRead, "Read: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); } catch (Exception ex) { logger.Error((int)AzureProviderErrorCode.AzureBlobProvider_ReadError, string.Format("Error reading: GrainType={0} Grainid={1} ETag={2} from BlobName={3} in Container={4} Exception={5}", grainType, grainId, grainState.ETag, blobName, container.Name, ex.Message), ex); throw; } } private static string GetBlobName(string grainType, GrainReference grainId) { return string.Format("{0}-{1}.json", grainType, grainId.ToKeyString()); } /// <summary> Write state data function for this storage provider. </summary> /// <see cref="IGrainStorage.WriteStateAsync"/> public async Task WriteStateAsync<T>(string grainType, GrainReference grainId, IGrainState<T> grainState) { var blobName = GetBlobName(grainType, grainId); try { if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_Writing, "Writing: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); var contents = ConvertToStorageFormat(grainState.State); var blob = container.GetBlobClient(blobName); await WriteStateAndCreateContainerIfNotExists(grainType, grainId, grainState, contents, "application/octet-stream", blob); if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Storage_DataRead, "Written: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); } catch (Exception ex) { logger.Error((int)AzureProviderErrorCode.AzureBlobProvider_WriteError, string.Format("Error writing: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4} Exception={5}", grainType, grainId, grainState.ETag, blobName, container.Name, ex.Message), ex); throw; } } /// <summary> Clear / Delete state data function for this storage provider. </summary> /// <see cref="IGrainStorage.ClearStateAsync"/> public async Task ClearStateAsync<T>(string grainType, GrainReference grainId, IGrainState<T> grainState) { var blobName = GetBlobName(grainType, grainId); try { if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_ClearingData, "Clearing: GrainType={0} Grainid={1} ETag={2} BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blobName, container.Name); var blob = container.GetBlobClient(blobName); var conditions = string.IsNullOrEmpty(grainState.ETag) ? new BlobRequestConditions { IfNoneMatch = ETag.All } : new BlobRequestConditions { IfMatch = new ETag(grainState.ETag) }; await DoOptimisticUpdate(() => blob.DeleteIfExistsAsync(DeleteSnapshotsOption.None, conditions: conditions), blob, grainState.ETag).ConfigureAwait(false); grainState.ETag = null; grainState.RecordExists = false; if (this.logger.IsEnabled(LogLevel.Trace)) { var properties = await blob.GetPropertiesAsync(); this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_Cleared, "Cleared: GrainType={0} Grainid={1} ETag={2} BlobName={3} in Container={4}", grainType, grainId, properties.Value.ETag, blobName, container.Name); } } catch (Exception ex) { logger.Error((int)AzureProviderErrorCode.AzureBlobProvider_ClearError, string.Format("Error clearing: GrainType={0} Grainid={1} ETag={2} BlobName={3} in Container={4} Exception={5}", grainType, grainId, grainState.ETag, blobName, container.Name, ex.Message), ex); throw; } } private async Task WriteStateAndCreateContainerIfNotExists<T>(string grainType, GrainReference grainId, IGrainState<T> grainState, BinaryData contents, string mimeType, BlobClient blob) { try { var conditions = string.IsNullOrEmpty(grainState.ETag) ? new BlobRequestConditions { IfNoneMatch = ETag.All } : new BlobRequestConditions { IfMatch = new ETag(grainState.ETag) }; var options = new BlobUploadOptions { HttpHeaders = new BlobHttpHeaders { ContentType = mimeType }, Conditions = conditions, }; var result = await DoOptimisticUpdate( () => blob.UploadAsync(contents, options), blob, grainState.ETag) .ConfigureAwait(false); grainState.ETag = result.Value.ETag.ToString(); grainState.RecordExists = true; } catch (RequestFailedException exception) when (exception.IsContainerNotFound()) { // if the container does not exist, create it, and make another attempt if (this.logger.IsEnabled(LogLevel.Trace)) this.logger.Trace((int)AzureProviderErrorCode.AzureBlobProvider_ContainerNotFound, "Creating container: GrainType={0} Grainid={1} ETag={2} to BlobName={3} in Container={4}", grainType, grainId, grainState.ETag, blob.Name, container.Name); await container.CreateIfNotExistsAsync().ConfigureAwait(false); await WriteStateAndCreateContainerIfNotExists(grainType, grainId, grainState, contents, mimeType, blob).ConfigureAwait(false); } } private static async Task<TResult> DoOptimisticUpdate<TResult>(Func<Task<TResult>> updateOperation, BlobClient blob, string currentETag) { try { return await updateOperation.Invoke().ConfigureAwait(false); } catch (RequestFailedException ex) when (ex.IsPreconditionFailed() || ex.IsConflict()) { throw new InconsistentStateException($"Blob storage condition not Satisfied. BlobName: {blob.Name}, Container: {blob.BlobContainerName}, CurrentETag: {currentETag}", "Unknown", currentETag, ex); } } public void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe(OptionFormattingUtilities.Name<AzureBlobGrainStorage>(this.name), this.options.InitStage, Init); } /// <summary> Initialization function for this storage provider. </summary> private async Task Init(CancellationToken ct) { var stopWatch = Stopwatch.StartNew(); try { this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, $"AzureBlobGrainStorage initializing: {this.options.ToString()}"); if (options.CreateClient is not { } createClient) { throw new OrleansConfigurationException($"No credentials specified. Use the {options.GetType().Name}.{nameof(AzureBlobStorageOptions.ConfigureBlobServiceClient)} method to configure the Azure Blob Service client."); } var client = await createClient(); container = client.GetBlobContainerClient(this.options.ContainerName); await container.CreateIfNotExistsAsync().ConfigureAwait(false); stopWatch.Stop(); this.logger.LogInformation((int)AzureProviderErrorCode.AzureBlobProvider_InitProvider, $"Initializing provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} took {stopWatch.ElapsedMilliseconds} Milliseconds."); } catch (Exception ex) { stopWatch.Stop(); this.logger.LogError((int)ErrorCode.Provider_ErrorFromInit, $"Initialization failed for provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} in {stopWatch.ElapsedMilliseconds} Milliseconds.", ex); throw; } } /// <summary> /// Serialize to the configured storage format /// </summary> /// <param name="grainState">The grain state data to be serialized</param> private BinaryData ConvertToStorageFormat<T>(T grainState) => this.grainStorageSerializer.Serialize(grainState); /// <summary> /// Deserialize from the configured storage format /// </summary> /// <param name="contents">The serialized contents.</param> private T ConvertFromStorageFormat<T>(BinaryData contents) => this.grainStorageSerializer.Deserialize<T>(contents); } public static class AzureBlobGrainStorageFactory { public static IGrainStorage Create(IServiceProvider services, string name) { var optionsMonitor = services.GetRequiredService<IOptionsMonitor<AzureBlobStorageOptions>>(); return ActivatorUtilities.CreateInstance<AzureBlobGrainStorage>(services, name, optionsMonitor.Get(name)); } } }
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 ODataDemo.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using Gallio.Common.Media; using MbUnit.Framework; namespace Gallio.Tests.Common.Media { [TestsOn(typeof(BitmapVideoFrame))] public class BitmapVideoFrameTest { [Test] public void Constructor_WhenBitmapIsNull_Throws() { Assert.Throws<ArgumentNullException>(() => new BitmapVideoFrame(null)); } [Test] public void Bitmap_ReturnsBitmapProvidedInConstructor() { var bitmap = new Bitmap(32, 32); var bitmapVideoFrame = new BitmapVideoFrame(bitmap); Assert.AreSame(bitmap, bitmapVideoFrame.Bitmap); } [Test] public void Width_ReturnsBitmapWidth() { var bitmap = new Bitmap(32, 16); var bitmapVideoFrame = new BitmapVideoFrame(bitmap); Assert.AreEqual(32, bitmapVideoFrame.Width); } [Test] public void Height_ReturnsBitmapHeight() { var bitmap = new Bitmap(32, 16); var bitmapVideoFrame = new BitmapVideoFrame(bitmap); Assert.AreEqual(16, bitmapVideoFrame.Height); } [Test] public void CopyPixels_WhenPixelBufferIsNull_Throws() { var bitmap = new Bitmap(32, 32); var bitmapVideoFrame = new BitmapVideoFrame(bitmap); var rectangle = new Rectangle(0, 0, 32, 32); int[] pixelBuffer = null; int startOffset = 0; int stride = 32; Assert.Throws<ArgumentNullException>(() => bitmapVideoFrame.CopyPixels(rectangle, pixelBuffer, startOffset, stride)); } [Test] [Row(-1, 0, 32, 32)] [Row(0, -1, 32, 32)] [Row(0, 0, -1, 32)] [Row(0, 0, 32, -1)] [Row(2, 2, 32, 30)] [Row(2, 2, 30, 32)] public void CopyPixels_WhenRectangleAreOutOfBounds_Throws(int x, int y, int width, int height) { var bitmap = new Bitmap(32, 32); var bitmapVideoFrame = new BitmapVideoFrame(bitmap); var rectangle = new Rectangle(x, y, width, height); int[] pixelBuffer = new int[32 * 32]; int startOffset = 0; int stride = 32; var ex = Assert.Throws<ArgumentOutOfRangeException>(() => bitmapVideoFrame.CopyPixels(rectangle, pixelBuffer, startOffset, stride)); Assert.Contains(ex.Message, "Rectangle position and dimensions must be within the bounds of the frame."); } [Test] [Row(-1)] [Row(32 * 32)] public void CopyPixels_WhenStartOffsetIsOutOfBounds_Throws(int startOffset) { var bitmap = new Bitmap(32, 32); var bitmapVideoFrame = new BitmapVideoFrame(bitmap); var rectangle = new Rectangle(0, 0, 32, 32); int[] pixelBuffer = new int[32 * 32]; int stride = 32; var ex = Assert.Throws<ArgumentOutOfRangeException>(() => bitmapVideoFrame.CopyPixels(rectangle, pixelBuffer, startOffset, stride)); Assert.Contains(ex.Message, "Start offset must be within the bounds of the pixel buffer."); } [Test] [Row(-1)] [Row(31)] public void CopyPixels_WhenStrideIsLessThanWidth_Throws(int stride) { var bitmap = new Bitmap(32, 32); var bitmapVideoFrame = new BitmapVideoFrame(bitmap); var rectangle = new Rectangle(0, 0, 32, 32); int[] pixelBuffer = new int[32 * 32]; int startOffset = 0; var ex = Assert.Throws<ArgumentOutOfRangeException>(() => bitmapVideoFrame.CopyPixels(rectangle, pixelBuffer, startOffset, stride)); Assert.Contains(ex.Message, "Stride must be at least as large as the width of the rectangle."); } [Test] [Row(32, 32, 0, 32, 32 * 32)] [Row(32, 32, 1, 32, 32 * 32 + 1)] [Row(13, 16, 0, 32, 13 + 15 * 32)] [Row(13, 16, 5, 32, 13 + 15 * 32 + 5)] [Row(0, 32, 0, 100, 1)] [Row(32, 0, 0, 100, 1)] [Row(0, 0, 0, 100, 1)] public void CopyPixels_WhenSpaceRequirementsExceedPixelBuffer_Throws(int width, int height, int startOffset, int stride, int exactPixelBufferLengthRequired) { var bitmap = new Bitmap(32, 32); var bitmapVideoFrame = new BitmapVideoFrame(bitmap); var rectangle = new Rectangle(0, 0, width, height); Assert.Multiple(() => { Assert.DoesNotThrow( () => bitmapVideoFrame.CopyPixels(rectangle, new int[exactPixelBufferLengthRequired], startOffset, stride), "Should not throw when pixel buffer is exactly the right size."); Assert.DoesNotThrow( () => bitmapVideoFrame.CopyPixels(rectangle, new int[exactPixelBufferLengthRequired + 1], startOffset, stride), "Should not throw when pixel buffer is one pixel too large."); if (width != 0 && height != 0) { var ex = Assert.Throws<ArgumentException>( () => bitmapVideoFrame.CopyPixels(rectangle, new int[exactPixelBufferLengthRequired - 1], startOffset, stride), "Should throw when pixel buffer is one pixel too small."); Assert.Contains(ex.Message, "The combined rectangle dimensions, start offset and stride would cause pixels to be written out of bounds of the pixel buffer."); } }); } [Test] [Row(0, 0, 2, 2, 0, 2, 4)] [Row(0, 0, 2, 2, 1, 2, 5)] [Row(0, 0, 2, 2, 0, 3, 5)] [Row(0, 0, 4, 4, 2, 8, 32)] [Row(1, 2, 3, 2, 3, 4, 32)] public void CopyPixels_WhenArgumentsValid_ShouldCopyTheRegion(int x, int y, int width, int height, int startOffset, int stride, int pixelBufferLength) { // Create a 4x4 bitmap initialized with an array of RGB pixel colors like this: // {000, 100, 200}, {001, 101, 201}, {002, 102, 202}, {003, 103, 203} // {010, 110, 210}, {011, 111, 211}, {012, 112, 212}, {013, 113, 213} // {020, 120, 220}, {021, 121, 221}, {022, 122, 222}, {023, 123, 223} // {030, 130, 230}, {031, 131, 231}, {032, 132, 232}, {033, 133, 233} var bitmap = new Bitmap(4, 4); for (int bx = 0; bx < bitmap.Width; bx++) { for (int by = 0; by < bitmap.Height; by++) { int component = bx + by * 10; Color color = Color.FromArgb(component, component + 100, component + 200); bitmap.SetPixel(bx, by, color); } } var bitmapVideoFrame = new BitmapVideoFrame(bitmap); var rectangle = new Rectangle(x, y, width, height); var pixelBuffer = new int[pixelBufferLength]; bitmapVideoFrame.CopyPixels(rectangle, pixelBuffer, startOffset, stride); for (int i = 0; i < pixelBufferLength; i++) { int bx = (i - startOffset) % stride + x; int by = (i - startOffset) / stride + y; if (bx < x || by < y || bx - x >= width || by - y >= height) { Assert.AreEqual(0, pixelBuffer[i], "i: {0}, bx: {1}, by: {2}", i, bx, by); } else { Assert.AreEqual(bitmap.GetPixel(bx, by).ToArgb(), pixelBuffer[i], "i: {0}, bx: {1}, by: {2}", i, bx, by); } } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion #if !(NET20 || NET35 || NET40 || PORTABLE40) using System; using System.Text; using System.Threading.Tasks; #if DNXCORE50 using Xunit; using Test = Xunit.FactAttribute; using Assert = Newtonsoft.Json.Tests.XUnitAssert; #else using NUnit.Framework; #endif using System.IO; #if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 using System.Numerics; #endif using Newtonsoft.Json.Linq; using Newtonsoft.Json.Tests.Serialization; using Newtonsoft.Json.Tests.TestObjects; namespace Newtonsoft.Json.Tests.Linq { [TestFixture] public class JTokenReaderAsyncTests : TestFixtureBase { #if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 [Test] public async Task ConvertBigIntegerToDoubleAsync() { var jObject = JObject.Parse("{ maxValue:10000000000000000000}"); JsonReader reader = jObject.CreateReader(); Assert.IsTrue(await reader.ReadAsync()); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(10000000000000000000d, await reader.ReadAsDoubleAsync()); Assert.IsTrue(await reader.ReadAsync()); } #endif [Test] public async Task YahooFinanceAsync() { JObject o = new JObject( new JProperty("Test1", new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc)), new JProperty("Test2", new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0))), new JProperty("Test3", "Test3Value"), new JProperty("Test4", null) ); using (JTokenReader jsonReader = new JTokenReader(o)) { IJsonLineInfo lineInfo = jsonReader; await jsonReader.ReadAsync(); Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); Assert.AreEqual(false, lineInfo.HasLineInfo()); await jsonReader.ReadAsync(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test1", jsonReader.Value); Assert.AreEqual(false, lineInfo.HasLineInfo()); await jsonReader.ReadAsync(); Assert.AreEqual(JsonToken.Date, jsonReader.TokenType); Assert.AreEqual(new DateTime(2000, 10, 15, 5, 5, 5, DateTimeKind.Utc), jsonReader.Value); Assert.AreEqual(false, lineInfo.HasLineInfo()); Assert.AreEqual(0, lineInfo.LinePosition); Assert.AreEqual(0, lineInfo.LineNumber); await jsonReader.ReadAsync(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test2", jsonReader.Value); await jsonReader.ReadAsync(); Assert.AreEqual(JsonToken.Date, jsonReader.TokenType); Assert.AreEqual(new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0)), jsonReader.Value); await jsonReader.ReadAsync(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test3", jsonReader.Value); await jsonReader.ReadAsync(); Assert.AreEqual(JsonToken.String, jsonReader.TokenType); Assert.AreEqual("Test3Value", jsonReader.Value); await jsonReader.ReadAsync(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test4", jsonReader.Value); await jsonReader.ReadAsync(); Assert.AreEqual(JsonToken.Null, jsonReader.TokenType); Assert.AreEqual(null, jsonReader.Value); Assert.IsTrue(await jsonReader.ReadAsync()); Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType); Assert.IsFalse(await jsonReader.ReadAsync()); Assert.AreEqual(JsonToken.None, jsonReader.TokenType); } using (JsonReader jsonReader = new JTokenReader(o.Property("Test2"))) { Assert.IsTrue(await jsonReader.ReadAsync()); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test2", jsonReader.Value); Assert.IsTrue(await jsonReader.ReadAsync()); Assert.AreEqual(JsonToken.Date, jsonReader.TokenType); Assert.AreEqual(new DateTimeOffset(2000, 10, 15, 5, 5, 5, new TimeSpan(11, 11, 0)), jsonReader.Value); Assert.IsFalse(await jsonReader.ReadAsync()); Assert.AreEqual(JsonToken.None, jsonReader.TokenType); } } [Test] public async Task ReadAsDateTimeOffsetBadStringAsync() { string json = @"{""Offset"":""blablahbla""}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); await ExceptionAssert.ThrowsAsync<JsonReaderException>(async () => { await reader.ReadAsDateTimeOffsetAsync(); }, "Could not convert string to DateTimeOffset: blablahbla. Path 'Offset', line 1, position 22."); } [Test] public async Task ReadAsDateTimeOffsetBooleanAsync() { string json = @"{""Offset"":true}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); await ExceptionAssert.ThrowsAsync<JsonReaderException>(async () => { await reader.ReadAsDateTimeOffsetAsync(); }, "Error reading date. Unexpected token: Boolean. Path 'Offset', line 1, position 14."); } [Test] public async Task ReadAsDateTimeOffsetStringAsync() { string json = @"{""Offset"":""2012-01-24T03:50Z""}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); await reader.ReadAsDateTimeOffsetAsync(); Assert.AreEqual(JsonToken.Date, reader.TokenType); Assert.AreEqual(typeof(DateTimeOffset), reader.ValueType); Assert.AreEqual(new DateTimeOffset(2012, 1, 24, 3, 50, 0, TimeSpan.Zero), reader.Value); } [Test] public async Task ReadLineInfoAsync() { string input = @"{ CPU: 'Intel', Drives: [ 'DVD read/writer', ""500 gigabyte hard drive"" ] }"; JObject o = JObject.Parse(input); using (JTokenReader jsonReader = new JTokenReader(o)) { IJsonLineInfo lineInfo = jsonReader; Assert.AreEqual(jsonReader.TokenType, JsonToken.None); Assert.AreEqual(0, lineInfo.LineNumber); Assert.AreEqual(0, lineInfo.LinePosition); Assert.AreEqual(false, lineInfo.HasLineInfo()); Assert.AreEqual(null, jsonReader.CurrentToken); await jsonReader.ReadAsync(); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartObject); Assert.AreEqual(1, lineInfo.LineNumber); Assert.AreEqual(1, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o, jsonReader.CurrentToken); await jsonReader.ReadAsync(); Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); Assert.AreEqual(jsonReader.Value, "CPU"); Assert.AreEqual(2, lineInfo.LineNumber); Assert.AreEqual(6, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o.Property("CPU"), jsonReader.CurrentToken); await jsonReader.ReadAsync(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "Intel"); Assert.AreEqual(2, lineInfo.LineNumber); Assert.AreEqual(14, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o.Property("CPU").Value, jsonReader.CurrentToken); await jsonReader.ReadAsync(); Assert.AreEqual(jsonReader.TokenType, JsonToken.PropertyName); Assert.AreEqual(jsonReader.Value, "Drives"); Assert.AreEqual(3, lineInfo.LineNumber); Assert.AreEqual(9, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o.Property("Drives"), jsonReader.CurrentToken); await jsonReader.ReadAsync(); Assert.AreEqual(jsonReader.TokenType, JsonToken.StartArray); Assert.AreEqual(3, lineInfo.LineNumber); Assert.AreEqual(11, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o.Property("Drives").Value, jsonReader.CurrentToken); await jsonReader.ReadAsync(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "DVD read/writer"); Assert.AreEqual(4, lineInfo.LineNumber); Assert.AreEqual(21, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o["Drives"][0], jsonReader.CurrentToken); await jsonReader.ReadAsync(); Assert.AreEqual(jsonReader.TokenType, JsonToken.String); Assert.AreEqual(jsonReader.Value, "500 gigabyte hard drive"); Assert.AreEqual(5, lineInfo.LineNumber); Assert.AreEqual(29, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o["Drives"][1], jsonReader.CurrentToken); await jsonReader.ReadAsync(); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndArray); Assert.AreEqual(3, lineInfo.LineNumber); Assert.AreEqual(11, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o["Drives"], jsonReader.CurrentToken); await jsonReader.ReadAsync(); Assert.AreEqual(jsonReader.TokenType, JsonToken.EndObject); Assert.AreEqual(1, lineInfo.LineNumber); Assert.AreEqual(1, lineInfo.LinePosition); Assert.AreEqual(true, lineInfo.HasLineInfo()); Assert.AreEqual(o, jsonReader.CurrentToken); await jsonReader.ReadAsync(); Assert.AreEqual(jsonReader.TokenType, JsonToken.None); Assert.AreEqual(null, jsonReader.CurrentToken); await jsonReader.ReadAsync(); Assert.AreEqual(jsonReader.TokenType, JsonToken.None); Assert.AreEqual(null, jsonReader.CurrentToken); } } [Test] public async Task ReadBytesAsync() { byte[] data = Encoding.UTF8.GetBytes("Hello world!"); JObject o = new JObject( new JProperty("Test1", data) ); using (JTokenReader jsonReader = new JTokenReader(o)) { await jsonReader.ReadAsync(); Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); await jsonReader.ReadAsync(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test1", jsonReader.Value); byte[] readBytes = await jsonReader.ReadAsBytesAsync(); Assert.AreEqual(data, readBytes); Assert.IsTrue(await jsonReader.ReadAsync()); Assert.AreEqual(JsonToken.EndObject, jsonReader.TokenType); Assert.IsFalse(await jsonReader.ReadAsync()); Assert.AreEqual(JsonToken.None, jsonReader.TokenType); } } [Test] public async Task ReadBytesFailureAsync() { await ExceptionAssert.ThrowsAsync<JsonReaderException>(async () => { JObject o = new JObject( new JProperty("Test1", 1) ); using (JTokenReader jsonReader = new JTokenReader(o)) { await jsonReader.ReadAsync(); Assert.AreEqual(JsonToken.StartObject, jsonReader.TokenType); await jsonReader.ReadAsync(); Assert.AreEqual(JsonToken.PropertyName, jsonReader.TokenType); Assert.AreEqual("Test1", jsonReader.Value); await jsonReader.ReadAsBytesAsync(); } }, "Error reading bytes. Unexpected token: Integer. Path 'Test1'."); } public class HasBytes { public byte[] Bytes { get; set; } } [Test] public async Task ReadAsDecimalIntAsync() { string json = @"{""Name"":1}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); await reader.ReadAsDecimalAsync(); Assert.AreEqual(JsonToken.Float, reader.TokenType); Assert.AreEqual(typeof(decimal), reader.ValueType); Assert.AreEqual(1m, reader.Value); } [Test] public async Task ReadAsInt32IntAsync() { string json = @"{""Name"":1}"; JObject o = JObject.Parse(json); JTokenReader reader = (JTokenReader)o.CreateReader(); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.AreEqual(o, reader.CurrentToken); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); Assert.AreEqual(o.Property("Name"), reader.CurrentToken); await reader.ReadAsInt32Async(); Assert.AreEqual(o["Name"], reader.CurrentToken); Assert.AreEqual(JsonToken.Integer, reader.TokenType); Assert.AreEqual(typeof(int), reader.ValueType); Assert.AreEqual(1, reader.Value); } [Test] public async Task ReadAsInt32BadStringAsync() { string json = @"{""Name"":""hi""}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); await ExceptionAssert.ThrowsAsync<JsonReaderException>(async () => { await reader.ReadAsInt32Async(); }, "Could not convert string to integer: hi. Path 'Name', line 1, position 12."); } [Test] public async Task ReadAsInt32BooleanAsync() { string json = @"{""Name"":true}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); await ExceptionAssert.ThrowsAsync<JsonReaderException>(async () => { await reader.ReadAsInt32Async(); }, "Error reading integer. Unexpected token: Boolean. Path 'Name', line 1, position 12."); } [Test] public async Task ReadAsDecimalStringAsync() { string json = @"{""Name"":""1.1""}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); await reader.ReadAsDecimalAsync(); Assert.AreEqual(JsonToken.Float, reader.TokenType); Assert.AreEqual(typeof(decimal), reader.ValueType); Assert.AreEqual(1.1m, reader.Value); } [Test] public async Task ReadAsDecimalBadStringAsync() { string json = @"{""Name"":""blah""}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); await ExceptionAssert.ThrowsAsync<JsonReaderException>(async () => { await reader.ReadAsDecimalAsync(); }, "Could not convert string to decimal: blah. Path 'Name', line 1, position 14."); } [Test] public async Task ReadAsDecimalBooleanAsync() { string json = @"{""Name"":true}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); await ExceptionAssert.ThrowsAsync<JsonReaderException>(async () => { await reader.ReadAsDecimalAsync(); }, "Error reading decimal. Unexpected token: Boolean. Path 'Name', line 1, position 12."); } [Test] public async Task ReadAsDecimalNullAsync() { string json = @"{""Name"":null}"; JObject o = JObject.Parse(json); JsonReader reader = o.CreateReader(); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.StartObject, reader.TokenType); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual(JsonToken.PropertyName, reader.TokenType); await reader.ReadAsDecimalAsync(); Assert.AreEqual(JsonToken.Null, reader.TokenType); Assert.AreEqual(null, reader.ValueType); Assert.AreEqual(null, reader.Value); } [Test] public async Task InitialPath_PropertyBase_PropertyTokenAsync() { JObject o = new JObject { { "prop1", true } }; JTokenReader reader = new JTokenReader(o, "baseprop"); Assert.AreEqual("baseprop", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("baseprop", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("baseprop.prop1", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("baseprop.prop1", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("baseprop", reader.Path); Assert.IsFalse(await reader.ReadAsync()); Assert.AreEqual("baseprop", reader.Path); } [Test] public async Task InitialPath_ArrayBase_PropertyTokenAsync() { JObject o = new JObject { { "prop1", true } }; JTokenReader reader = new JTokenReader(o, "[0]"); Assert.AreEqual("[0]", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("[0]", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("[0].prop1", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("[0].prop1", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("[0]", reader.Path); Assert.IsFalse(await reader.ReadAsync()); Assert.AreEqual("[0]", reader.Path); } [Test] public async Task InitialPath_PropertyBase_ArrayTokenAsync() { JArray a = new JArray { 1, 2 }; JTokenReader reader = new JTokenReader(a, "baseprop"); Assert.AreEqual("baseprop", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("baseprop", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("baseprop[0]", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("baseprop[1]", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("baseprop", reader.Path); Assert.IsFalse(await reader.ReadAsync()); Assert.AreEqual("baseprop", reader.Path); } [Test] public async Task InitialPath_ArrayBase_ArrayTokenAsync() { JArray a = new JArray { 1, 2 }; JTokenReader reader = new JTokenReader(a, "[0]"); Assert.AreEqual("[0]", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("[0]", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("[0][0]", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("[0][1]", reader.Path); Assert.IsTrue(await reader.ReadAsync()); Assert.AreEqual("[0]", reader.Path); Assert.IsFalse(await reader.ReadAsync()); Assert.AreEqual("[0]", reader.Path); } [Test] public async Task ReadAsDouble_InvalidTokenAsync() { JArray a = new JArray { 1, 2 }; JTokenReader reader = new JTokenReader(a); await ExceptionAssert.ThrowsAsync<JsonReaderException>( async () => { await reader.ReadAsDoubleAsync(); }, "Error reading double. Unexpected token: StartArray. Path ''."); } [Test] public async Task ReadAsBoolean_InvalidTokenAsync() { JArray a = new JArray { 1, 2 }; JTokenReader reader = new JTokenReader(a); await ExceptionAssert.ThrowsAsync<JsonReaderException>( async () => { await reader.ReadAsBooleanAsync(); }, "Error reading boolean. Unexpected token: StartArray. Path ''."); } [Test] public async Task ReadAsDateTime_InvalidTokenAsync() { JArray a = new JArray { 1, 2 }; JTokenReader reader = new JTokenReader(a); await ExceptionAssert.ThrowsAsync<JsonReaderException>( async () => { await reader.ReadAsDateTimeAsync(); }, "Error reading date. Unexpected token: StartArray. Path ''."); } [Test] public async Task ReadAsDateTimeOffset_InvalidTokenAsync() { JArray a = new JArray { 1, 2 }; JTokenReader reader = new JTokenReader(a); await ExceptionAssert.ThrowsAsync<JsonReaderException>( async () => { await reader.ReadAsDateTimeOffsetAsync(); }, "Error reading date. Unexpected token: StartArray. Path ''."); } [Test] public async Task ReadAsDateTimeOffset_DateTimeAsync() { JValue v = new JValue(new DateTime(2001, 12, 12, 12, 12, 12, DateTimeKind.Utc)); JTokenReader reader = new JTokenReader(v); Assert.AreEqual(new DateTimeOffset(2001, 12, 12, 12, 12, 12, TimeSpan.Zero), await reader.ReadAsDateTimeOffsetAsync()); } [Test] public async Task ReadAsDateTimeOffset_StringAsync() { JValue v = new JValue("2012-01-24T03:50Z"); JTokenReader reader = new JTokenReader(v); Assert.AreEqual(new DateTimeOffset(2012, 1, 24, 3, 50, 0, TimeSpan.Zero), await reader.ReadAsDateTimeOffsetAsync()); } [Test] public async Task ReadAsDateTime_DateTimeOffsetAsync() { JValue v = new JValue(new DateTimeOffset(2012, 1, 24, 3, 50, 0, TimeSpan.Zero)); JTokenReader reader = new JTokenReader(v); Assert.AreEqual(new DateTime(2012, 1, 24, 3, 50, 0, DateTimeKind.Utc), await reader.ReadAsDateTimeAsync()); } [Test] public async Task ReadAsDateTime_StringAsync() { JValue v = new JValue("2012-01-24T03:50Z"); JTokenReader reader = new JTokenReader(v); Assert.AreEqual(new DateTime(2012, 1, 24, 3, 50, 0, DateTimeKind.Utc), await reader.ReadAsDateTimeAsync()); } [Test] public async Task ReadAsDouble_String_SuccessAsync() { JValue s = JValue.CreateString("123.4"); JTokenReader reader = new JTokenReader(s); Assert.AreEqual(123.4d, await reader.ReadAsDoubleAsync()); } [Test] public async Task ReadAsDouble_Null_SuccessAsync() { JValue n = JValue.CreateNull(); JTokenReader reader = new JTokenReader(n); Assert.AreEqual(null, await reader.ReadAsDoubleAsync()); } [Test] public async Task ReadAsDouble_Integer_SuccessAsync() { JValue n = new JValue(1); JTokenReader reader = new JTokenReader(n); Assert.AreEqual(1d, await reader.ReadAsDoubleAsync()); } #if !PORTABLE || NETSTANDARD1_3 || NETSTANDARD2_0 [Test] public async Task ReadAsBoolean_BigInteger_SuccessAsync() { JValue s = new JValue(BigInteger.Parse("99999999999999999999999999999999999999999999999999999999999999999999999999")); JTokenReader reader = new JTokenReader(s); Assert.AreEqual(true, await reader.ReadAsBooleanAsync()); } #endif [Test] public async Task ReadAsBoolean_String_SuccessAsync() { JValue s = JValue.CreateString("true"); JTokenReader reader = new JTokenReader(s); Assert.AreEqual(true, await reader.ReadAsBooleanAsync()); } [Test] public async Task ReadAsBoolean_Null_SuccessAsync() { JValue n = JValue.CreateNull(); JTokenReader reader = new JTokenReader(n); Assert.AreEqual(null, await reader.ReadAsBooleanAsync()); } [Test] public async Task ReadAsBoolean_Integer_SuccessAsync() { JValue n = new JValue(1); JTokenReader reader = new JTokenReader(n); Assert.AreEqual(true, await reader.ReadAsBooleanAsync()); } [Test] public async Task ReadAsDateTime_Null_SuccessAsync() { JValue n = JValue.CreateNull(); JTokenReader reader = new JTokenReader(n); Assert.AreEqual(null, await reader.ReadAsDateTimeAsync()); } [Test] public async Task ReadAsDateTimeOffset_Null_SuccessAsync() { JValue n = JValue.CreateNull(); JTokenReader reader = new JTokenReader(n); Assert.AreEqual(null, await reader.ReadAsDateTimeOffsetAsync()); } [Test] public async Task ReadAsString_Integer_SuccessAsync() { JValue n = new JValue(1); JTokenReader reader = new JTokenReader(n); Assert.AreEqual("1", await reader.ReadAsStringAsync()); } [Test] public async Task ReadAsString_Guid_SuccessAsync() { JValue n = new JValue(new Uri("http://www.test.com")); JTokenReader reader = new JTokenReader(n); Assert.AreEqual("http://www.test.com", await reader.ReadAsStringAsync()); } [Test] public async Task ReadAsBytes_Integer_SuccessAsync() { JValue n = JValue.CreateNull(); JTokenReader reader = new JTokenReader(n); Assert.AreEqual(null, await reader.ReadAsBytesAsync()); } [Test] public async Task ReadAsBytes_ArrayAsync() { JArray a = new JArray { 1, 2 }; JTokenReader reader = new JTokenReader(a); byte[] bytes = await reader.ReadAsBytesAsync(); Assert.AreEqual(2, bytes.Length); Assert.AreEqual(1, bytes[0]); Assert.AreEqual(2, bytes[1]); } [Test] public async Task ReadAsBytes_NullAsync() { JValue n = JValue.CreateNull(); JTokenReader reader = new JTokenReader(n); Assert.AreEqual(null, await reader.ReadAsBytesAsync()); } } } #endif
// // cfold.cs: Constant Folding // // Author: // Miguel de Icaza (miguel@ximian.com) // Marek Safar (marek.safar@seznam.cz) // // Copyright 2002, 2003 Ximian, Inc. // Copyright 2003-2011, Novell, Inc. // using System; namespace Mono.CSharp { public static class ConstantFold { public static TypeSpec[] CreateBinaryPromotionsTypes (BuiltinTypes types) { return new TypeSpec[] { types.Decimal, types.Double, types.Float, types.ULong, types.Long, types.UInt }; } // // Performs the numeric promotions on the left and right expresions // and deposits the results on `lc' and `rc'. // // On success, the types of `lc' and `rc' on output will always match, // and the pair will be one of: // // TODO: BinaryFold should be called as an optimization step only, // error checking here is weak // static bool DoBinaryNumericPromotions (ResolveContext rc, ref Constant left, ref Constant right) { TypeSpec ltype = left.Type; TypeSpec rtype = right.Type; foreach (TypeSpec t in rc.BuiltinTypes.BinaryPromotionsTypes) { if (t == ltype) return t == rtype || ConvertPromotion (rc, ref right, ref left, t); if (t == rtype) return t == ltype || ConvertPromotion (rc, ref left, ref right, t); } left = left.ConvertImplicitly (rc.BuiltinTypes.Int); right = right.ConvertImplicitly (rc.BuiltinTypes.Int); return left != null && right != null; } static bool ConvertPromotion (ResolveContext rc, ref Constant prim, ref Constant second, TypeSpec type) { Constant c = prim.ConvertImplicitly (type); if (c != null) { prim = c; return true; } if (type.BuiltinType == BuiltinTypeSpec.Type.UInt) { type = rc.BuiltinTypes.Long; prim = prim.ConvertImplicitly (type); second = second.ConvertImplicitly (type); return prim != null && second != null; } return false; } internal static void Error_CompileTimeOverflow (ResolveContext rc, Location loc) { rc.Report.Error (220, loc, "The operation overflows at compile time in checked mode"); } /// <summary> /// Constant expression folder for binary operations. /// /// Returns null if the expression can not be folded. /// </summary> static public Constant BinaryFold (ResolveContext ec, Binary.Operator oper, Constant left, Constant right, Location loc) { Constant result = null; if (left is EmptyConstantCast) return BinaryFold (ec, oper, ((EmptyConstantCast)left).child, right, loc); if (left is SideEffectConstant) { result = BinaryFold (ec, oper, ((SideEffectConstant) left).value, right, loc); if (result == null) return null; return new SideEffectConstant (result, left, loc); } if (right is EmptyConstantCast) return BinaryFold (ec, oper, left, ((EmptyConstantCast)right).child, loc); if (right is SideEffectConstant) { result = BinaryFold (ec, oper, left, ((SideEffectConstant) right).value, loc); if (result == null) return null; return new SideEffectConstant (result, right, loc); } TypeSpec lt = left.Type; TypeSpec rt = right.Type; bool bool_res; if (lt.BuiltinType == BuiltinTypeSpec.Type.Bool && lt == rt) { bool lv = (bool) left.GetValue (); bool rv = (bool) right.GetValue (); switch (oper) { case Binary.Operator.BitwiseAnd: case Binary.Operator.LogicalAnd: return new BoolConstant (ec.BuiltinTypes, lv && rv, left.Location); case Binary.Operator.BitwiseOr: case Binary.Operator.LogicalOr: return new BoolConstant (ec.BuiltinTypes, lv || rv, left.Location); case Binary.Operator.ExclusiveOr: return new BoolConstant (ec.BuiltinTypes, lv ^ rv, left.Location); case Binary.Operator.Equality: return new BoolConstant (ec.BuiltinTypes, lv == rv, left.Location); case Binary.Operator.Inequality: return new BoolConstant (ec.BuiltinTypes, lv != rv, left.Location); } return null; } // // During an enum evaluation, none of the rules are valid // Not sure whether it is bug in csc or in documentation // if (ec.HasSet (ResolveContext.Options.EnumScope)){ if (left is EnumConstant) left = ((EnumConstant) left).Child; if (right is EnumConstant) right = ((EnumConstant) right).Child; } else if (left is EnumConstant && rt == lt) { switch (oper){ /// /// E operator |(E x, E y); /// E operator &(E x, E y); /// E operator ^(E x, E y); /// case Binary.Operator.BitwiseOr: case Binary.Operator.BitwiseAnd: case Binary.Operator.ExclusiveOr: result = BinaryFold (ec, oper, ((EnumConstant)left).Child, ((EnumConstant)right).Child, loc); if (result != null) result = result.TryReduce (ec, lt); return result; /// /// U operator -(E x, E y); /// case Binary.Operator.Subtraction: result = BinaryFold (ec, oper, ((EnumConstant)left).Child, ((EnumConstant)right).Child, loc); if (result != null) result = result.TryReduce (ec, EnumSpec.GetUnderlyingType (lt)); return result; /// /// bool operator ==(E x, E y); /// bool operator !=(E x, E y); /// bool operator <(E x, E y); /// bool operator >(E x, E y); /// bool operator <=(E x, E y); /// bool operator >=(E x, E y); /// case Binary.Operator.Equality: case Binary.Operator.Inequality: case Binary.Operator.LessThan: case Binary.Operator.GreaterThan: case Binary.Operator.LessThanOrEqual: case Binary.Operator.GreaterThanOrEqual: return BinaryFold(ec, oper, ((EnumConstant)left).Child, ((EnumConstant)right).Child, loc); } return null; } switch (oper){ case Binary.Operator.BitwiseOr: // // bool? operator &(bool? x, bool? y); // if ((lt.BuiltinType == BuiltinTypeSpec.Type.Bool && right is NullLiteral) || (rt.BuiltinType == BuiltinTypeSpec.Type.Bool && left is NullLiteral)) { var b = new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec); // false | null => null // null | false => null if ((right is NullLiteral && left.IsDefaultValue) || (left is NullLiteral && right.IsDefaultValue)) return Nullable.LiftedNull.CreateFromExpression (ec, b); // true | null => true // null | true => true return ReducedExpression.Create (new BoolConstant (ec.BuiltinTypes, true, loc), b); } if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; if (left is IntConstant){ int res = ((IntConstant) left).Value | ((IntConstant) right).Value; return new IntConstant (ec.BuiltinTypes, res, left.Location); } if (left is UIntConstant){ uint res = ((UIntConstant)left).Value | ((UIntConstant)right).Value; return new UIntConstant (ec.BuiltinTypes, res, left.Location); } if (left is LongConstant){ long res = ((LongConstant)left).Value | ((LongConstant)right).Value; return new LongConstant (ec.BuiltinTypes, res, left.Location); } if (left is ULongConstant){ ulong res = ((ULongConstant)left).Value | ((ULongConstant)right).Value; return new ULongConstant (ec.BuiltinTypes, res, left.Location); } break; case Binary.Operator.BitwiseAnd: // // bool? operator &(bool? x, bool? y); // if ((lt.BuiltinType == BuiltinTypeSpec.Type.Bool && right is NullLiteral) || (rt.BuiltinType == BuiltinTypeSpec.Type.Bool && left is NullLiteral)) { var b = new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec); // false & null => false // null & false => false if ((right is NullLiteral && left.IsDefaultValue) || (left is NullLiteral && right.IsDefaultValue)) return ReducedExpression.Create (new BoolConstant (ec.BuiltinTypes, false, loc), b); // true & null => null // null & true => null return Nullable.LiftedNull.CreateFromExpression (ec, b); } if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; /// /// int operator &(int x, int y); /// uint operator &(uint x, uint y); /// long operator &(long x, long y); /// ulong operator &(ulong x, ulong y); /// if (left is IntConstant){ int res = ((IntConstant) left).Value & ((IntConstant) right).Value; return new IntConstant (ec.BuiltinTypes, res, left.Location); } if (left is UIntConstant){ uint res = ((UIntConstant)left).Value & ((UIntConstant)right).Value; return new UIntConstant (ec.BuiltinTypes, res, left.Location); } if (left is LongConstant){ long res = ((LongConstant)left).Value & ((LongConstant)right).Value; return new LongConstant (ec.BuiltinTypes, res, left.Location); } if (left is ULongConstant){ ulong res = ((ULongConstant)left).Value & ((ULongConstant)right).Value; return new ULongConstant (ec.BuiltinTypes, res, left.Location); } break; case Binary.Operator.ExclusiveOr: if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; if (left is IntConstant){ int res = ((IntConstant) left).Value ^ ((IntConstant) right).Value; return new IntConstant (ec.BuiltinTypes, res, left.Location); } if (left is UIntConstant){ uint res = ((UIntConstant)left).Value ^ ((UIntConstant)right).Value; return new UIntConstant (ec.BuiltinTypes, res, left.Location); } if (left is LongConstant){ long res = ((LongConstant)left).Value ^ ((LongConstant)right).Value; return new LongConstant (ec.BuiltinTypes, res, left.Location); } if (left is ULongConstant){ ulong res = ((ULongConstant)left).Value ^ ((ULongConstant)right).Value; return new ULongConstant (ec.BuiltinTypes, res, left.Location); } break; case Binary.Operator.Addition: if (lt == InternalType.NullLiteral) return right; if (rt == InternalType.NullLiteral) return left; // // If both sides are strings, then concatenate, if // one is a string, and the other is not, then defer // to runtime concatenation // if (lt.BuiltinType == BuiltinTypeSpec.Type.String || rt.BuiltinType == BuiltinTypeSpec.Type.String){ if (lt == rt) return new StringConstant (ec.BuiltinTypes, (string)left.GetValue () + (string)right.GetValue (), left.Location); return null; } // // handle "E operator + (E x, U y)" // handle "E operator + (Y y, E x)" // EnumConstant lc = left as EnumConstant; EnumConstant rc = right as EnumConstant; if (lc != null || rc != null){ if (lc == null) { lc = rc; lt = lc.Type; right = left; } // U has to be implicitly convetible to E.base right = right.ConvertImplicitly (lc.Child.Type); if (right == null) return null; result = BinaryFold (ec, oper, lc.Child, right, loc); if (result == null) return null; result = result.TryReduce (ec, lt); if (result == null) return null; return new EnumConstant (result, lt); } if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; try { if (left is DoubleConstant){ double res; if (ec.ConstantCheckState) res = checked (((DoubleConstant) left).Value + ((DoubleConstant) right).Value); else res = unchecked (((DoubleConstant) left).Value + ((DoubleConstant) right).Value); return new DoubleConstant (ec.BuiltinTypes, res, left.Location); } if (left is FloatConstant){ float res; if (ec.ConstantCheckState) res = checked (((FloatConstant) left).Value + ((FloatConstant) right).Value); else res = unchecked (((FloatConstant) left).Value + ((FloatConstant) right).Value); result = new FloatConstant (ec.BuiltinTypes, res, left.Location); } else if (left is ULongConstant){ ulong res; if (ec.ConstantCheckState) res = checked (((ULongConstant) left).Value + ((ULongConstant) right).Value); else res = unchecked (((ULongConstant) left).Value + ((ULongConstant) right).Value); result = new ULongConstant (ec.BuiltinTypes, res, left.Location); } else if (left is LongConstant){ long res; if (ec.ConstantCheckState) res = checked (((LongConstant) left).Value + ((LongConstant) right).Value); else res = unchecked (((LongConstant) left).Value + ((LongConstant) right).Value); result = new LongConstant (ec.BuiltinTypes, res, left.Location); } else if (left is UIntConstant){ uint res; if (ec.ConstantCheckState) res = checked (((UIntConstant) left).Value + ((UIntConstant) right).Value); else res = unchecked (((UIntConstant) left).Value + ((UIntConstant) right).Value); result = new UIntConstant (ec.BuiltinTypes, res, left.Location); } else if (left is IntConstant){ int res; if (ec.ConstantCheckState) res = checked (((IntConstant) left).Value + ((IntConstant) right).Value); else res = unchecked (((IntConstant) left).Value + ((IntConstant) right).Value); result = new IntConstant (ec.BuiltinTypes, res, left.Location); } else if (left is DecimalConstant) { decimal res; if (ec.ConstantCheckState) res = checked (((DecimalConstant) left).Value + ((DecimalConstant) right).Value); else res = unchecked (((DecimalConstant) left).Value + ((DecimalConstant) right).Value); result = new DecimalConstant (ec.BuiltinTypes, res, left.Location); } } catch (OverflowException){ Error_CompileTimeOverflow (ec, loc); } return result; case Binary.Operator.Subtraction: // // handle "E operator - (E x, U y)" // handle "E operator - (Y y, E x)" // lc = left as EnumConstant; rc = right as EnumConstant; if (lc != null || rc != null){ if (lc == null) { lc = rc; lt = lc.Type; right = left; } // U has to be implicitly convetible to E.base right = right.ConvertImplicitly (lc.Child.Type); if (right == null) return null; result = BinaryFold (ec, oper, lc.Child, right, loc); if (result == null) return null; result = result.TryReduce (ec, lt); if (result == null) return null; return new EnumConstant (result, lt); } if (left is NullLiteral && right is NullLiteral) { var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc); lifted_int.ResolveAsType (ec); return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec); } if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; try { if (left is DoubleConstant){ double res; if (ec.ConstantCheckState) res = checked (((DoubleConstant) left).Value - ((DoubleConstant) right).Value); else res = unchecked (((DoubleConstant) left).Value - ((DoubleConstant) right).Value); result = new DoubleConstant (ec.BuiltinTypes, res, left.Location); } else if (left is FloatConstant){ float res; if (ec.ConstantCheckState) res = checked (((FloatConstant) left).Value - ((FloatConstant) right).Value); else res = unchecked (((FloatConstant) left).Value - ((FloatConstant) right).Value); result = new FloatConstant (ec.BuiltinTypes, res, left.Location); } else if (left is ULongConstant){ ulong res; if (ec.ConstantCheckState) res = checked (((ULongConstant) left).Value - ((ULongConstant) right).Value); else res = unchecked (((ULongConstant) left).Value - ((ULongConstant) right).Value); result = new ULongConstant (ec.BuiltinTypes, res, left.Location); } else if (left is LongConstant){ long res; if (ec.ConstantCheckState) res = checked (((LongConstant) left).Value - ((LongConstant) right).Value); else res = unchecked (((LongConstant) left).Value - ((LongConstant) right).Value); result = new LongConstant (ec.BuiltinTypes, res, left.Location); } else if (left is UIntConstant){ uint res; if (ec.ConstantCheckState) res = checked (((UIntConstant) left).Value - ((UIntConstant) right).Value); else res = unchecked (((UIntConstant) left).Value - ((UIntConstant) right).Value); result = new UIntConstant (ec.BuiltinTypes, res, left.Location); } else if (left is IntConstant){ int res; if (ec.ConstantCheckState) res = checked (((IntConstant) left).Value - ((IntConstant) right).Value); else res = unchecked (((IntConstant) left).Value - ((IntConstant) right).Value); result = new IntConstant (ec.BuiltinTypes, res, left.Location); } else if (left is DecimalConstant) { decimal res; if (ec.ConstantCheckState) res = checked (((DecimalConstant) left).Value - ((DecimalConstant) right).Value); else res = unchecked (((DecimalConstant) left).Value - ((DecimalConstant) right).Value); return new DecimalConstant (ec.BuiltinTypes, res, left.Location); } else { throw new Exception ( "Unexepected subtraction input: " + left); } } catch (OverflowException){ Error_CompileTimeOverflow (ec, loc); } return result; case Binary.Operator.Multiply: if (left is NullLiteral && right is NullLiteral) { var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc); lifted_int.ResolveAsType (ec); return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec); } if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; try { if (left is DoubleConstant){ double res; if (ec.ConstantCheckState) res = checked (((DoubleConstant) left).Value * ((DoubleConstant) right).Value); else res = unchecked (((DoubleConstant) left).Value * ((DoubleConstant) right).Value); return new DoubleConstant (ec.BuiltinTypes, res, left.Location); } else if (left is FloatConstant){ float res; if (ec.ConstantCheckState) res = checked (((FloatConstant) left).Value * ((FloatConstant) right).Value); else res = unchecked (((FloatConstant) left).Value * ((FloatConstant) right).Value); return new FloatConstant (ec.BuiltinTypes, res, left.Location); } else if (left is ULongConstant){ ulong res; if (ec.ConstantCheckState) res = checked (((ULongConstant) left).Value * ((ULongConstant) right).Value); else res = unchecked (((ULongConstant) left).Value * ((ULongConstant) right).Value); return new ULongConstant (ec.BuiltinTypes, res, left.Location); } else if (left is LongConstant){ long res; if (ec.ConstantCheckState) res = checked (((LongConstant) left).Value * ((LongConstant) right).Value); else res = unchecked (((LongConstant) left).Value * ((LongConstant) right).Value); return new LongConstant (ec.BuiltinTypes, res, left.Location); } else if (left is UIntConstant){ uint res; if (ec.ConstantCheckState) res = checked (((UIntConstant) left).Value * ((UIntConstant) right).Value); else res = unchecked (((UIntConstant) left).Value * ((UIntConstant) right).Value); return new UIntConstant (ec.BuiltinTypes, res, left.Location); } else if (left is IntConstant){ int res; if (ec.ConstantCheckState) res = checked (((IntConstant) left).Value * ((IntConstant) right).Value); else res = unchecked (((IntConstant) left).Value * ((IntConstant) right).Value); return new IntConstant (ec.BuiltinTypes, res, left.Location); } else if (left is DecimalConstant) { decimal res; if (ec.ConstantCheckState) res = checked (((DecimalConstant) left).Value * ((DecimalConstant) right).Value); else res = unchecked (((DecimalConstant) left).Value * ((DecimalConstant) right).Value); return new DecimalConstant (ec.BuiltinTypes, res, left.Location); } else { throw new Exception ( "Unexepected multiply input: " + left); } } catch (OverflowException){ Error_CompileTimeOverflow (ec, loc); } break; case Binary.Operator.Division: if (left is NullLiteral && right is NullLiteral) { var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc); lifted_int.ResolveAsType (ec); return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec); } if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; try { if (left is DoubleConstant){ double res; if (ec.ConstantCheckState) res = checked (((DoubleConstant) left).Value / ((DoubleConstant) right).Value); else res = unchecked (((DoubleConstant) left).Value / ((DoubleConstant) right).Value); return new DoubleConstant (ec.BuiltinTypes, res, left.Location); } else if (left is FloatConstant){ float res; if (ec.ConstantCheckState) res = checked (((FloatConstant) left).Value / ((FloatConstant) right).Value); else res = unchecked (((FloatConstant) left).Value / ((FloatConstant) right).Value); return new FloatConstant (ec.BuiltinTypes, res, left.Location); } else if (left is ULongConstant){ ulong res; if (ec.ConstantCheckState) res = checked (((ULongConstant) left).Value / ((ULongConstant) right).Value); else res = unchecked (((ULongConstant) left).Value / ((ULongConstant) right).Value); return new ULongConstant (ec.BuiltinTypes, res, left.Location); } else if (left is LongConstant){ long res; if (ec.ConstantCheckState) res = checked (((LongConstant) left).Value / ((LongConstant) right).Value); else res = unchecked (((LongConstant) left).Value / ((LongConstant) right).Value); return new LongConstant (ec.BuiltinTypes, res, left.Location); } else if (left is UIntConstant){ uint res; if (ec.ConstantCheckState) res = checked (((UIntConstant) left).Value / ((UIntConstant) right).Value); else res = unchecked (((UIntConstant) left).Value / ((UIntConstant) right).Value); return new UIntConstant (ec.BuiltinTypes, res, left.Location); } else if (left is IntConstant){ int res; if (ec.ConstantCheckState) res = checked (((IntConstant) left).Value / ((IntConstant) right).Value); else res = unchecked (((IntConstant) left).Value / ((IntConstant) right).Value); return new IntConstant (ec.BuiltinTypes, res, left.Location); } else if (left is DecimalConstant) { decimal res; if (ec.ConstantCheckState) res = checked (((DecimalConstant) left).Value / ((DecimalConstant) right).Value); else res = unchecked (((DecimalConstant) left).Value / ((DecimalConstant) right).Value); return new DecimalConstant (ec.BuiltinTypes, res, left.Location); } else { throw new Exception ( "Unexepected division input: " + left); } } catch (OverflowException){ Error_CompileTimeOverflow (ec, loc); } catch (DivideByZeroException) { ec.Report.Error (20, loc, "Division by constant zero"); } break; case Binary.Operator.Modulus: if (left is NullLiteral && right is NullLiteral) { var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc); lifted_int.ResolveAsType (ec); return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec); } if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; try { if (left is DoubleConstant){ double res; if (ec.ConstantCheckState) res = checked (((DoubleConstant) left).Value % ((DoubleConstant) right).Value); else res = unchecked (((DoubleConstant) left).Value % ((DoubleConstant) right).Value); return new DoubleConstant (ec.BuiltinTypes, res, left.Location); } else if (left is FloatConstant){ float res; if (ec.ConstantCheckState) res = checked (((FloatConstant) left).Value % ((FloatConstant) right).Value); else res = unchecked (((FloatConstant) left).Value % ((FloatConstant) right).Value); return new FloatConstant (ec.BuiltinTypes, res, left.Location); } else if (left is ULongConstant){ ulong res; if (ec.ConstantCheckState) res = checked (((ULongConstant) left).Value % ((ULongConstant) right).Value); else res = unchecked (((ULongConstant) left).Value % ((ULongConstant) right).Value); return new ULongConstant (ec.BuiltinTypes, res, left.Location); } else if (left is LongConstant){ long res; if (ec.ConstantCheckState) res = checked (((LongConstant) left).Value % ((LongConstant) right).Value); else res = unchecked (((LongConstant) left).Value % ((LongConstant) right).Value); return new LongConstant (ec.BuiltinTypes, res, left.Location); } else if (left is UIntConstant){ uint res; if (ec.ConstantCheckState) res = checked (((UIntConstant) left).Value % ((UIntConstant) right).Value); else res = unchecked (((UIntConstant) left).Value % ((UIntConstant) right).Value); return new UIntConstant (ec.BuiltinTypes, res, left.Location); } else if (left is IntConstant){ int res; if (ec.ConstantCheckState) res = checked (((IntConstant) left).Value % ((IntConstant) right).Value); else res = unchecked (((IntConstant) left).Value % ((IntConstant) right).Value); return new IntConstant (ec.BuiltinTypes, res, left.Location); } else { throw new Exception ( "Unexepected modulus input: " + left); } } catch (DivideByZeroException){ ec.Report.Error (20, loc, "Division by constant zero"); } catch (OverflowException){ Error_CompileTimeOverflow (ec, loc); } break; // // There is no overflow checking on left shift // case Binary.Operator.LeftShift: if (left is NullLiteral && right is NullLiteral) { var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc); lifted_int.ResolveAsType (ec); return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec); } IntConstant ic = right.ConvertImplicitly (ec.BuiltinTypes.Int) as IntConstant; if (ic == null){ Binary.Error_OperatorCannotBeApplied (ec, left, right, oper, loc); return null; } int lshift_val = ic.Value; switch (left.Type.BuiltinType) { case BuiltinTypeSpec.Type.ULong: return new ULongConstant (ec.BuiltinTypes, ((ULongConstant) left).Value << lshift_val, left.Location); case BuiltinTypeSpec.Type.Long: return new LongConstant (ec.BuiltinTypes, ((LongConstant) left).Value << lshift_val, left.Location); case BuiltinTypeSpec.Type.UInt: return new UIntConstant (ec.BuiltinTypes, ((UIntConstant) left).Value << lshift_val, left.Location); } // null << value => null if (left is NullLiteral) return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec); left = left.ConvertImplicitly (ec.BuiltinTypes.Int); if (left.Type.BuiltinType == BuiltinTypeSpec.Type.Int) return new IntConstant (ec.BuiltinTypes, ((IntConstant) left).Value << lshift_val, left.Location); Binary.Error_OperatorCannotBeApplied (ec, left, right, oper, loc); break; // // There is no overflow checking on right shift // case Binary.Operator.RightShift: if (left is NullLiteral && right is NullLiteral) { var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc); lifted_int.ResolveAsType (ec); return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec); } IntConstant sic = right.ConvertImplicitly (ec.BuiltinTypes.Int) as IntConstant; if (sic == null){ Binary.Error_OperatorCannotBeApplied (ec, left, right, oper, loc); ; return null; } int rshift_val = sic.Value; switch (left.Type.BuiltinType) { case BuiltinTypeSpec.Type.ULong: return new ULongConstant (ec.BuiltinTypes, ((ULongConstant) left).Value >> rshift_val, left.Location); case BuiltinTypeSpec.Type.Long: return new LongConstant (ec.BuiltinTypes, ((LongConstant) left).Value >> rshift_val, left.Location); case BuiltinTypeSpec.Type.UInt: return new UIntConstant (ec.BuiltinTypes, ((UIntConstant) left).Value >> rshift_val, left.Location); } // null >> value => null if (left is NullLiteral) return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec); left = left.ConvertImplicitly (ec.BuiltinTypes.Int); if (left.Type.BuiltinType == BuiltinTypeSpec.Type.Int) return new IntConstant (ec.BuiltinTypes, ((IntConstant) left).Value >> rshift_val, left.Location); Binary.Error_OperatorCannotBeApplied (ec, left, right, oper, loc); break; case Binary.Operator.Equality: if (TypeSpec.IsReferenceType (lt) && TypeSpec.IsReferenceType (rt) || (left is Nullable.LiftedNull && right.IsNull) || (right is Nullable.LiftedNull && left.IsNull)) { if (left.IsNull || right.IsNull) { return ReducedExpression.Create ( new BoolConstant (ec.BuiltinTypes, left.IsNull == right.IsNull, left.Location), new Binary (oper, left, right)); } if (left is StringConstant && right is StringConstant) return new BoolConstant (ec.BuiltinTypes, ((StringConstant) left).Value == ((StringConstant) right).Value, left.Location); return null; } if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; bool_res = false; if (left is DoubleConstant) bool_res = ((DoubleConstant) left).Value == ((DoubleConstant) right).Value; else if (left is FloatConstant) bool_res = ((FloatConstant) left).Value == ((FloatConstant) right).Value; else if (left is ULongConstant) bool_res = ((ULongConstant) left).Value == ((ULongConstant) right).Value; else if (left is LongConstant) bool_res = ((LongConstant) left).Value == ((LongConstant) right).Value; else if (left is UIntConstant) bool_res = ((UIntConstant) left).Value == ((UIntConstant) right).Value; else if (left is IntConstant) bool_res = ((IntConstant) left).Value == ((IntConstant) right).Value; else return null; return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location); case Binary.Operator.Inequality: if (TypeSpec.IsReferenceType (lt) && TypeSpec.IsReferenceType (rt) || (left is Nullable.LiftedNull && right.IsNull) || (right is Nullable.LiftedNull && left.IsNull)) { if (left.IsNull || right.IsNull) { return ReducedExpression.Create ( new BoolConstant (ec.BuiltinTypes, left.IsNull != right.IsNull, left.Location), new Binary (oper, left, right)); } if (left is StringConstant && right is StringConstant) return new BoolConstant (ec.BuiltinTypes, ((StringConstant) left).Value != ((StringConstant) right).Value, left.Location); return null; } if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; bool_res = false; if (left is DoubleConstant) bool_res = ((DoubleConstant) left).Value != ((DoubleConstant) right).Value; else if (left is FloatConstant) bool_res = ((FloatConstant) left).Value != ((FloatConstant) right).Value; else if (left is ULongConstant) bool_res = ((ULongConstant) left).Value != ((ULongConstant) right).Value; else if (left is LongConstant) bool_res = ((LongConstant) left).Value != ((LongConstant) right).Value; else if (left is UIntConstant) bool_res = ((UIntConstant) left).Value != ((UIntConstant) right).Value; else if (left is IntConstant) bool_res = ((IntConstant) left).Value != ((IntConstant) right).Value; else return null; return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location); case Binary.Operator.LessThan: if (right is NullLiteral) { if (left is NullLiteral) { var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc); lifted_int.ResolveAsType (ec); return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec); } if (left is Nullable.LiftedNull) { return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec); } } if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; bool_res = false; if (left is DoubleConstant) bool_res = ((DoubleConstant) left).Value < ((DoubleConstant) right).Value; else if (left is FloatConstant) bool_res = ((FloatConstant) left).Value < ((FloatConstant) right).Value; else if (left is ULongConstant) bool_res = ((ULongConstant) left).Value < ((ULongConstant) right).Value; else if (left is LongConstant) bool_res = ((LongConstant) left).Value < ((LongConstant) right).Value; else if (left is UIntConstant) bool_res = ((UIntConstant) left).Value < ((UIntConstant) right).Value; else if (left is IntConstant) bool_res = ((IntConstant) left).Value < ((IntConstant) right).Value; else return null; return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location); case Binary.Operator.GreaterThan: if (right is NullLiteral) { if (left is NullLiteral) { var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc); lifted_int.ResolveAsType (ec); return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec); } if (left is Nullable.LiftedNull) { return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec); } } if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; bool_res = false; if (left is DoubleConstant) bool_res = ((DoubleConstant) left).Value > ((DoubleConstant) right).Value; else if (left is FloatConstant) bool_res = ((FloatConstant) left).Value > ((FloatConstant) right).Value; else if (left is ULongConstant) bool_res = ((ULongConstant) left).Value > ((ULongConstant) right).Value; else if (left is LongConstant) bool_res = ((LongConstant) left).Value > ((LongConstant) right).Value; else if (left is UIntConstant) bool_res = ((UIntConstant) left).Value > ((UIntConstant) right).Value; else if (left is IntConstant) bool_res = ((IntConstant) left).Value > ((IntConstant) right).Value; else return null; return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location); case Binary.Operator.GreaterThanOrEqual: if (right is NullLiteral) { if (left is NullLiteral) { var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc); lifted_int.ResolveAsType (ec); return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec); } if (left is Nullable.LiftedNull) { return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec); } } if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; bool_res = false; if (left is DoubleConstant) bool_res = ((DoubleConstant) left).Value >= ((DoubleConstant) right).Value; else if (left is FloatConstant) bool_res = ((FloatConstant) left).Value >= ((FloatConstant) right).Value; else if (left is ULongConstant) bool_res = ((ULongConstant) left).Value >= ((ULongConstant) right).Value; else if (left is LongConstant) bool_res = ((LongConstant) left).Value >= ((LongConstant) right).Value; else if (left is UIntConstant) bool_res = ((UIntConstant) left).Value >= ((UIntConstant) right).Value; else if (left is IntConstant) bool_res = ((IntConstant) left).Value >= ((IntConstant) right).Value; else return null; return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location); case Binary.Operator.LessThanOrEqual: if (right is NullLiteral) { if (left is NullLiteral) { var lifted_int = new Nullable.NullableType (ec.BuiltinTypes.Int, loc); lifted_int.ResolveAsType (ec); return (Constant) new Nullable.LiftedBinaryOperator (oper, lifted_int, right).Resolve (ec); } if (left is Nullable.LiftedNull) { return (Constant) new Nullable.LiftedBinaryOperator (oper, left, right).Resolve (ec); } } if (!DoBinaryNumericPromotions (ec, ref left, ref right)) return null; bool_res = false; if (left is DoubleConstant) bool_res = ((DoubleConstant) left).Value <= ((DoubleConstant) right).Value; else if (left is FloatConstant) bool_res = ((FloatConstant) left).Value <= ((FloatConstant) right).Value; else if (left is ULongConstant) bool_res = ((ULongConstant) left).Value <= ((ULongConstant) right).Value; else if (left is LongConstant) bool_res = ((LongConstant) left).Value <= ((LongConstant) right).Value; else if (left is UIntConstant) bool_res = ((UIntConstant) left).Value <= ((UIntConstant) right).Value; else if (left is IntConstant) bool_res = ((IntConstant) left).Value <= ((IntConstant) right).Value; else return null; return new BoolConstant (ec.BuiltinTypes, bool_res, left.Location); } return null; } } }
//----------------------------------------------------------------------- // <copyright file="FanOut.cs" company="Akka.NET Project"> // Copyright (C) 2015-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Immutable; using System.Linq; using Akka.Actor; using Akka.Event; using Akka.Pattern; using Reactive.Streams; namespace Akka.Streams.Implementation { internal class OutputBunch<T> { #region internal classes private sealed class FanoutOutputs : SimpleOutputs { private readonly int _id; public FanoutOutputs(int id, IActorRef actor, IPump pump) : base(actor, pump) { _id = id; } public new ISubscription CreateSubscription() => new FanOut.SubstreamSubscription(Actor, _id); } #endregion private readonly int _outputCount; private bool _bunchCancelled; private readonly FanoutOutputs[] _outputs; private readonly bool[] _marked; private int _markedCount; private readonly bool[] _pending; private int _markedPending; private readonly bool[] _cancelled; private int _markedCanceled; private readonly bool[] _completed; private readonly bool[] _errored; private bool _unmarkCancelled = true; private int _preferredId; public OutputBunch(int outputCount, IActorRef impl, IPump pump) { _outputCount = outputCount; _outputs = new FanoutOutputs[outputCount]; for (var i = 0; i < outputCount; i++) _outputs[i] = new FanoutOutputs(i, impl, pump); _marked = new bool[outputCount]; _pending = new bool[outputCount]; _cancelled = new bool[outputCount]; _completed = new bool[outputCount]; _errored = new bool[outputCount]; AllOfMarkedOutputs = new LambdaTransferState( isCompleted: () => _markedCanceled > 0 || _markedCount == 0, isReady: () => _markedPending == _markedCount); AnyOfMarkedOutputs = new LambdaTransferState( isCompleted: () => _markedCanceled == _markedCount, isReady: () => _markedPending > 0); // FIXME: Eliminate re-wraps SubReceive = new SubReceive(message => message.Match() .With<FanOut.ExposedPublishers<T>>(exposed => { var publishers = exposed.Publishers.GetEnumerator(); var outputs = _outputs.AsEnumerable().GetEnumerator(); while (publishers.MoveNext() && outputs.MoveNext()) outputs.Current.SubReceive.CurrentReceive(new ExposedPublisher(publishers.Current)); }) .With<FanOut.SubstreamRequestMore>(more => { if (more.Demand < 1) // According to Reactive Streams Spec 3.9, with non-positive demand must yield onError Error(more.Id, ReactiveStreamsCompliance.NumberOfElementsInRequestMustBePositiveException); else { if (_marked[more.Id] && !_pending[more.Id]) _markedPending += 1; _pending[more.Id] = true; _outputs[more.Id].SubReceive.CurrentReceive(new RequestMore(null, more.Demand)); } }) .With<FanOut.SubstreamCancel>(cancel => { if (_unmarkCancelled) UnmarkOutput(cancel.Id); if (_marked[cancel.Id] && !_cancelled[cancel.Id]) _markedCanceled += 1; _cancelled[cancel.Id] = true; OnCancel(cancel.Id); _outputs[cancel.Id].SubReceive.CurrentReceive(new Cancel(null)); }) .With<FanOut.SubstreamSubscribePending>(pending => _outputs[pending.Id].SubReceive.CurrentReceive(SubscribePending.Instance)) .WasHandled); } /// <summary> /// Will only transfer an element when all marked outputs /// have demand, and will complete as soon as any of the marked /// outputs have canceled. /// </summary> public readonly TransferState AllOfMarkedOutputs; /// <summary> /// Will transfer an element when any of the marked outputs /// have demand, and will complete when all of the marked /// outputs have canceled. /// </summary> public readonly TransferState AnyOfMarkedOutputs; public readonly SubReceive SubReceive; public bool IsPending(int output) => _pending[output]; public bool IsCompleted(int output) => _completed[output]; public bool IsCancelled(int output) => _cancelled[output]; public bool IsErrored(int output) => _errored[output]; public void Complete() { if (!_bunchCancelled) { _bunchCancelled = true; for (var i = 0; i < _outputs.Length; i++) Complete(i); } } public void Complete(int output) { if (!_completed[output] && !_errored[output] && !_cancelled[output]) { _outputs[output].Complete(); _completed[output] = true; UnmarkOutput(output); } } public void Cancel(Exception e) { if (!_bunchCancelled) { _bunchCancelled = true; for (var i = 0; i < _outputs.Length; i++) Error(i, e); } } public void Error(int output, Exception e) { if (!_errored[output] && !_cancelled[output] && !_completed[output]) { _outputs[output].Error(e); _errored[output] = true; UnmarkOutput(output); } } public void MarkOutput(int output) { if (!_marked[output]) { if (_cancelled[output]) _markedCanceled += 1; if (_pending[output]) _markedPending += 1; _marked[output] = true; _markedCount += 1; } } public void UnmarkOutput(int output) { if (_marked[output]) { if (_cancelled[output]) _markedCanceled -= 1; if (_pending[output]) _markedPending -= 1; _marked[output] = false; _markedCount -= 1; } } public void MarkAllOutputs() { for (var i = 0; i < _outputCount; i++) MarkOutput(i); } public void UnmarkAllOutputs() { for (var i = 0; i < _outputCount; i++) UnmarkOutput(i); } public void UnmarkCancelledOutputs(bool enabled) => _unmarkCancelled = enabled; public int IdToEnqueue() { var id = _preferredId; while (!(_marked[id] && _pending[id])) { id += 1; if (id == _outputCount) id = 0; if (id != _preferredId) throw new ArgumentException("Tried to equeue without waiting for any demand"); } return id; } public void Enqueue(int id, T element) { var output = _outputs[id]; output.EnqueueOutputElement(element); if (!output.IsDemandAvailable) { if (_marked[id]) _markedPending -= 1; _pending[id] = false; } } public void EnqueueMarked(T element) { for (var id = 0; id < _outputCount; id++) if (_marked[id]) Enqueue(id, element); } public int IdToEnqueueAndYield() { var id = IdToEnqueue(); _preferredId = id + 1; if (_preferredId == _outputCount) _preferredId = 0; return id; } public void EnqueueAndYield(T element) => Enqueue(IdToEnqueueAndYield(), element); public void EnqueueAndPrefer(T element, int preferred) { var id = IdToEnqueue(); _preferredId = preferred; Enqueue(id, element); } public void OnCancel(int output) { } public TransferState DemandAvailableFor(int id) => new LambdaTransferState(isReady: () => _pending[id], isCompleted: () => _cancelled[id] || _completed[id] || _errored[id]); public TransferState DemandOrCancelAvailableFor(int id) => new LambdaTransferState(isReady: () => _pending[id] || _cancelled[id], isCompleted: () => false); } /// <summary> /// INTERNAL API /// </summary> internal static class FanOut { [Serializable] public struct SubstreamRequestMore : INoSerializationVerificationNeeded { public readonly int Id; public readonly long Demand; public SubstreamRequestMore(int id, long demand) { Id = id; Demand = demand; } } [Serializable] public struct SubstreamCancel : INoSerializationVerificationNeeded { public readonly int Id; public SubstreamCancel(int id) { Id = id; } } [Serializable] public struct SubstreamSubscribePending : INoSerializationVerificationNeeded { public readonly int Id; public SubstreamSubscribePending(int id) { Id = id; } } public class SubstreamSubscription : ISubscription { private readonly IActorRef _parent; private readonly int _id; public SubstreamSubscription(IActorRef parent, int id) { _parent = parent; _id = id; } public void Request(long elements) => _parent.Tell(new SubstreamRequestMore(_id, elements)); public void Cancel() => _parent.Tell(new SubstreamCancel(_id)); public override string ToString() => "SubstreamSubscription" + GetHashCode(); } [Serializable] public struct ExposedPublishers<T> : INoSerializationVerificationNeeded { public readonly ImmutableList<ActorPublisher<T>> Publishers; public ExposedPublishers(ImmutableList<ActorPublisher<T>> publishers) { Publishers = publishers; } } } /// <summary> /// INTERNAL API /// </summary> internal abstract class FanOut<T> : ActorBase, IPump { #region internal classes private sealed class AnonymousBatchingInputBuffer : BatchingInputBuffer { private readonly FanOut<T> _pump; public AnonymousBatchingInputBuffer(int count, FanOut<T> pump) : base(count, pump) { _pump = pump; } protected override void OnError(Exception e) => _pump.Fail(e); } #endregion private readonly ActorMaterializerSettings _settings; protected readonly OutputBunch<T> OutputBunch; protected readonly BatchingInputBuffer PrimaryInputs; protected FanOut(ActorMaterializerSettings settings, int outputCount) { _log = Context.GetLogger(); _settings = settings; OutputBunch = new OutputBunch<T>(outputCount, Self, this); PrimaryInputs = new AnonymousBatchingInputBuffer(settings.MaxInputBufferSize, this); this.Init(); } #region Actor implementation private ILoggingAdapter _log; protected ILoggingAdapter Log => _log ?? (_log = Context.GetLogger()); protected override void PostStop() { PrimaryInputs.Cancel(); OutputBunch.Cancel(new AbruptTerminationException(Self)); } protected override void PostRestart(Exception reason) { base.PostRestart(reason); throw new IllegalStateException("This actor cannot be restarted"); } protected void Fail(Exception e) { if (_settings.IsDebugLogging) Log.Debug($"fail due to: {e.Message}"); PrimaryInputs.Cancel(); OutputBunch.Cancel(e); Pump(); } protected override bool Receive(object message) { return PrimaryInputs.SubReceive.CurrentReceive(message) || OutputBunch.SubReceive.CurrentReceive(message); } #endregion #region Pump implementation public TransferState TransferState { get; set; } public Action CurrentAction { get; set; } public bool IsPumpFinished => this.IsPumpFinished(); public void InitialPhase(int waitForUpstream, TransferPhase andThen) => Pumps.InitialPhase(this, waitForUpstream, andThen); public void WaitForUpstream(int waitForUpstream) => Pumps.WaitForUpstream(this, waitForUpstream); public void GotUpstreamSubscription() => Pumps.GotUpstreamSubscription(this); public void NextPhase(TransferPhase phase) => Pumps.NextPhase(this, phase); public void Pump() => Pumps.Pump(this); public void PumpFailed(Exception e) => Fail(e); public void PumpFinished() { PrimaryInputs.Cancel(); OutputBunch.Complete(); Context.Stop(Self); } #endregion } /// <summary> /// INTERNAL API /// </summary> internal static class Unzip { public static Props Props<T>(ActorMaterializerSettings settings) => Actor.Props.Create(() => new Unzip<T>(settings, 2)).WithDeploy(Deploy.Local); } /// <summary> /// INTERNAL API /// TODO Find out where this class will be used and check if the type parameter fit /// since we need to cast messages into a tuple and therefore maybe need aditional type parameters /// </summary> internal sealed class Unzip<T> : FanOut<T> { public Unzip(ActorMaterializerSettings settings, int outputCount = 2) : base(settings, outputCount) { OutputBunch.MarkAllOutputs(); InitialPhase(1, new TransferPhase(PrimaryInputs.NeedsInput.And(OutputBunch.AllOfMarkedOutputs), () => { var message = PrimaryInputs.DequeueInputElement(); var tuple = message as Tuple<T, T>; if (tuple == null) throw new ArgumentException($"Unable to unzip elements of type {message.GetType().Name}"); OutputBunch.Enqueue(0, tuple.Item1); OutputBunch.Enqueue(1, tuple.Item2); })); } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * 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 Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System.Linq; using Boo.Lang.Compiler.Steps.Generators; using Boo.Lang.Compiler.TypeSystem.Builders; using Boo.Lang.Compiler.TypeSystem.Generics; using Boo.Lang.Compiler.TypeSystem.Internal; using Boo.Lang.Compiler.Ast; using Boo.Lang.Compiler.TypeSystem; namespace Boo.Lang.Compiler.Steps { using System.Collections.Generic; public class ProcessSharedLocals : AbstractTransformerCompilerStep { private Method _currentMethod; private ClassDefinition _sharedLocalsClass; private readonly Dictionary<IEntity, IField> _mappings = new Dictionary<IEntity, IField>(); private readonly List<ReferenceExpression> _references = new List<ReferenceExpression>(); private readonly List<ILocalEntity> _shared = new List<ILocalEntity>(); private int _closureDepth; public override void Dispose() { _shared.Clear(); _references.Clear(); _mappings.Clear(); base.Dispose(); } public override void OnField(Field node) { } public override void OnInterfaceDefinition(InterfaceDefinition node) { } public override void OnEnumDefinition(EnumDefinition node) { } public override void OnConstructor(Constructor node) { OnMethod(node); } public override void OnMethod(Method node) { _references.Clear(); _mappings.Clear(); _currentMethod = node; _sharedLocalsClass = null; _closureDepth = 0; Visit(node.Body); CreateSharedLocalsClass(); if (null != _sharedLocalsClass) { node.DeclaringType.Members.Add(_sharedLocalsClass); Map(); } } public override void OnBlockExpression(BlockExpression node) { ++_closureDepth; Visit(node.Body); --_closureDepth; } public override void OnGeneratorExpression(GeneratorExpression node) { ++_closureDepth; Visit(node.Iterator); Visit(node.Expression); Visit(node.Filter); --_closureDepth; } public override void OnReferenceExpression(ReferenceExpression node) { var local = node.Entity as ILocalEntity; if (null == local) return; if (local.IsPrivateScope) return; _references.Add(node); if (_closureDepth == 0) return; local.IsShared = _currentMethod.Locals.ContainsEntity(local) || _currentMethod.Parameters.ContainsEntity(local); } private void Map() { var type = GeneratorTypeReplacer.MapTypeInMethodContext((IType)_sharedLocalsClass.Entity, _currentMethod); var conType = type as GenericConstructedType; if (conType != null) { foreach (var key in _mappings.Keys.ToArray()) _mappings[key] = (IField)conType.ConstructedInfo.Map(_mappings[key]); } var locals = CodeBuilder.DeclareLocal(_currentMethod, "$locals", type); foreach (var reference in _references) { IField mapped; if (!_mappings.TryGetValue(reference.Entity, out mapped)) continue; reference.ParentNode.Replace( reference, CodeBuilder.CreateMemberReference( CodeBuilder.CreateReference(locals), mapped)); } var initializationBlock = new Block(); initializationBlock.Add(CodeBuilder.CreateAssignment( CodeBuilder.CreateReference(locals), CodeBuilder.CreateConstructorInvocation(type.GetConstructors().First()))); InitializeSharedParameters(initializationBlock, locals); _currentMethod.Body.Statements.Insert(0, initializationBlock); foreach (IEntity entity in _mappings.Keys) { _currentMethod.Locals.RemoveByEntity(entity); } } private void InitializeSharedParameters(Block block, InternalLocal locals) { foreach (var node in _currentMethod.Parameters) { var param = (InternalParameter)node.Entity; if (param.IsShared) { block.Add( CodeBuilder.CreateAssignment( CodeBuilder.CreateMemberReference( CodeBuilder.CreateReference(locals), _mappings[param]), CodeBuilder.CreateReference(param))); } } } private void CreateSharedLocalsClass() { _shared.Clear(); CollectSharedLocalEntities(_currentMethod.Locals); CollectSharedLocalEntities(_currentMethod.Parameters); if (_shared.Count > 0) { BooClassBuilder builder = CodeBuilder.CreateClass(Context.GetUniqueName(_currentMethod.Name, "locals")); builder.Modifiers |= TypeMemberModifiers.Internal; builder.AddBaseType(TypeSystemServices.ObjectType); var genericsSet = new HashSet<string>(); var replacer = new GeneratorTypeReplacer(); foreach (ILocalEntity local in _shared) { CheckTypeForGenericParams(local.Type, genericsSet, builder, replacer); Field field = builder.AddInternalField( string.Format("${0}", local.Name), replacer.MapType(local.Type)); _mappings[local] = (IField)field.Entity; } builder.AddConstructor().Body.Add( CodeBuilder.CreateSuperConstructorInvocation(TypeSystemServices.ObjectType)); _sharedLocalsClass = builder.ClassDefinition; } } private static void CheckTypeForGenericParams( IType type, HashSet<string> genericsSet, BooClassBuilder builder, GeneratorTypeReplacer mapper) { if (type is IGenericParameter) { if (!genericsSet.Contains(type.Name)) { builder.AddGenericParameter(type.Name); genericsSet.Add(type.Name); } if (!mapper.ContainsType(type)) { mapper.Replace( type, (IType)builder.ClassDefinition.GenericParameters .First(gp => gp.Name.Equals(type.Name)).Entity); } } else { var genType = type as IConstructedTypeInfo; if (genType != null) foreach (var arg in genType.GenericArguments) CheckTypeForGenericParams(arg, genericsSet, builder, mapper); } } private void CollectSharedLocalEntities<T>(IEnumerable<T> nodes) where T : Node { foreach (T node in nodes) { var local = (ILocalEntity)node.Entity; if (local.IsShared) _shared.Add(local); } } } }
using System; using System.Collections.Generic; using System.Drawing; using Core; using Entities; using Game; using Graphs; using IrrlichtNETCP; using Messaging; using DumbBotsNET.Api; using Misc; namespace Scripting { /// <summary> /// Static class that allows the script to call simplified methods /// </summary> public class DirectorMethods : IDirectorApi { internal TextSceneNode Text { get; set; } #region Extensibility public IUserEntity CreateCustomEntity(string modelFile, string textureFile, Point position) { return new UserEntity(SceneNodeManager.CreateCustomEntity(modelFile, textureFile, position)); } public bool RemoveCustomEntity(IUserEntity userEntity) { var customEntity = userEntity as UserEntity; if (SceneNodeManager.CustomEntities.Contains(customEntity.CustomEntity)) { SceneNodeManager.CustomEntities.Remove(customEntity.CustomEntity); Globals.Scene.AddToDeletionQueue(customEntity.CustomEntity.Node); return true; } return false; } #endregion Extensibility #region Messaging public void SendMessageToPlayers(string message, TimeSpan time) { SendMessageToPlayer(1, message, time); SendMessageToPlayer(2, message, time); } public void SendMessageToSelf(string message, TimeSpan time) { Message m = new Message(0, 0, message, Globals.Device.Timer.Time + ((uint)time.TotalMilliseconds)); MessageDispatcher.AddMessageToQueue(m); } public void SendMessageToPlayer(int player, string message, TimeSpan time) { Message m = new Message(0, GetPlayerFromInt(player).Node.ID, message, Globals.Device.Timer.Time + ((uint)time.TotalMilliseconds)); MessageDispatcher.AddMessageToQueue(m); } public string FetchMessage() { var msg = MessageDispatcher.TryFetchMessage(0, Globals.Device.Timer.Time); return msg != null ? msg.MessageString : String.Empty; } #endregion Messaging #region Rules public void SetBazookaRespawnTime(TimeSpan value) { RuleManager.BazookaRespawnTime = (int)value.TotalMilliseconds; } public void SetBulletDamage(int value) { RuleManager.BulletDamage = value; } public void SetBulletReloadTime(TimeSpan value) { RuleManager.BulletReloadTime = (int)value.TotalMilliseconds; } public void SetBulletSpeedModifier(int value) { RuleManager.BulletSpeedModifier = value; } public void SetDefaultAmmo(int value) { RuleManager.DefaultAmmo = value; } public void SetMaxAmmo(int value) { RuleManager.MaxAmmo = value; } public void SetMaxHealth(int value) { RuleManager.MaxHealth = value; } public void SetMedkitHealthBoost(int value) { RuleManager.MedkitHealthBoost = value; } public void SetMedkitRespawnTime(TimeSpan value) { RuleManager.MedkitRespawnTime = (int)value.TotalMilliseconds; } public void SetRocketDamage(int value) { RuleManager.RocketDamage = value; } public void SetRocketReloadTime(TimeSpan value) { RuleManager.RocketReloadTime = (int)value.TotalMilliseconds; } public void SetRocketSpeedModifier(int value) { RuleManager.RocketSpeed = value; } public void SetPlayerSpeed(int player, double value) { RuleManager.PlayerSpeedModifier[GetPlayerFromInt(player).Team] = value; } public void SetPlayerDamageModifier(int player, double modifier) { RuleManager.PlayerSpeedModifier[GetPlayerFromInt(player).Team] = modifier; } public void SetGameSpeed(float value) { RuleManager.GameSpeed = value; Globals.GameSpeed = RuleManager.GameSpeed; } #endregion Rules #region Player Interaction public Point GetPlayerPosition(int player) { return new Point((int)GetPlayerFromInt(player).Node.Position.X, (int)GetPlayerFromInt(player).Node.Position.Z); } public void SetPlayerPosition(int player, Point position) { SetPlayerPosition(GetPlayerFromInt(player), position); } public void HealPlayer(int player, int health) { GetPlayerFromInt(player).Health += health; } public void GivePlayerAmmo(int player, int ammo) { GetPlayerFromInt(player).Ammo += ammo; } public int GetPlayerScore(int player) { return GetPlayerFromInt(player).Score; } public void SetPlayerScore(int player, int score) { GetPlayerFromInt(player).Score = score; } public int GetPlayerHealth(int player) { return GetPlayerFromInt(player).Health; } public int GetPlayerAmmo(int player) { return GetPlayerFromInt(player).Ammo; } public int GetPlayerCustomEntitiesDestroyed(int player) { return GetPlayerFromInt(player).CustomEntitiesDestroyed; } #endregion Player Interaction #region Game Information public TimeSpan GetGameTime() { return new TimeSpan(Globals.Device.Timer.Time); } public Point GetPositionFromMapPoint(int x, int y) { var position = GetNodes.GetPositionFromMapPoint(new Point(x, y)); return new Point((int)position.X, (int)position.Z); } #endregion Game Information #region Sound public void PlaySound(string filename) { if (SoundManager.PlaySound) { SoundManager.PlayCustom(filename); } } #endregion Sound #region Text public void SayText(string message, System.Drawing.Color color, Point position) { if (Text != null) Globals.Scene.AddToDeletionQueue(Text); GUIFont font = Globals.Gui.GetFont("Textures\\roboto.png"); Text = Globals.Scene.AddBillboardTextSceneNode(font, message, null, new Dimension2Df(message.Length * 40, 150), new Vector3D(position.X, 100, position.Y), -1, IrrlichtNETCP.Color.FromBCL(color), IrrlichtNETCP.Color.FromBCL(color)); Text.SetMaterialFlag(MaterialFlag.Lighting, false); } #endregion Text #region Keyboard public bool IsKeyDown(params System.Windows.Forms.Keys[] keys) { return KeyboardHelper.KeyIsDown(keys); } #endregion Keyboard #region Helpers private void SetPlayerPosition(CombatEntity player, Point position) { var temp = GetNodes.GetNearestNodeToPosition(new Vector3D(position.X, 30, position.Y)); player.Destination = LevelManager.SparseGraph.GetNode(temp).Position; player.Route = new List<int>(); player.Node.RemoveAnimators(); Animator anim = Globals.Scene.CreateFlyStraightAnimator(player.Node.Position, player.Destination, 0, false); player.Node.AddAnimator(anim); } private CombatEntity GetPlayerFromInt(int player) { switch (player) { case (1): return SceneNodeManager.Player1; case (2): return SceneNodeManager.Player2; default: throw new NotSupportedException(player.ToString()); } } #endregion Helpers } }
// Copyright (c) 1995-2009 held by the author(s). All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1998 { /// <summary> /// Section 5.2.5.6. Sent after repair complete PDU. COMPLETE /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(EntityID))] public partial class RepairResponsePdu : LogisticsFamilyPdu, IEquatable<RepairResponsePdu> { /// <summary> /// Entity that is receiving service /// </summary> private EntityID _receivingEntityID = new EntityID(); /// <summary> /// Entity that is supplying /// </summary> private EntityID _repairingEntityID = new EntityID(); /// <summary> /// Result of repair operation /// </summary> private byte _repairResult; /// <summary> /// padding /// </summary> private short _padding1; /// <summary> /// padding /// </summary> private byte _padding2; /// <summary> /// Initializes a new instance of the <see cref="RepairResponsePdu"/> class. /// </summary> public RepairResponsePdu() { PduType = (byte)10; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(RepairResponsePdu left, RepairResponsePdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(RepairResponsePdu left, RepairResponsePdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += this._receivingEntityID.GetMarshalledSize(); // this._receivingEntityID marshalSize += this._repairingEntityID.GetMarshalledSize(); // this._repairingEntityID marshalSize += 1; // this._repairResult marshalSize += 2; // this._padding1 marshalSize += 1; // this._padding2 return marshalSize; } /// <summary> /// Gets or sets the Entity that is receiving service /// </summary> [XmlElement(Type = typeof(EntityID), ElementName = "receivingEntityID")] public EntityID ReceivingEntityID { get { return this._receivingEntityID; } set { this._receivingEntityID = value; } } /// <summary> /// Gets or sets the Entity that is supplying /// </summary> [XmlElement(Type = typeof(EntityID), ElementName = "repairingEntityID")] public EntityID RepairingEntityID { get { return this._repairingEntityID; } set { this._repairingEntityID = value; } } /// <summary> /// Gets or sets the Result of repair operation /// </summary> [XmlElement(Type = typeof(byte), ElementName = "repairResult")] public byte RepairResult { get { return this._repairResult; } set { this._repairResult = value; } } /// <summary> /// Gets or sets the padding /// </summary> [XmlElement(Type = typeof(short), ElementName = "padding1")] public short Padding1 { get { return this._padding1; } set { this._padding1 = value; } } /// <summary> /// Gets or sets the padding /// </summary> [XmlElement(Type = typeof(byte), ElementName = "padding2")] public byte Padding2 { get { return this._padding2; } set { this._padding2 = value; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { this._receivingEntityID.Marshal(dos); this._repairingEntityID.Marshal(dos); dos.WriteUnsignedByte((byte)this._repairResult); dos.WriteShort((short)this._padding1); dos.WriteByte((byte)this._padding2); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._receivingEntityID.Unmarshal(dis); this._repairingEntityID.Unmarshal(dis); this._repairResult = dis.ReadUnsignedByte(); this._padding1 = dis.ReadShort(); this._padding2 = dis.ReadByte(); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<RepairResponsePdu>"); base.Reflection(sb); try { sb.AppendLine("<receivingEntityID>"); this._receivingEntityID.Reflection(sb); sb.AppendLine("</receivingEntityID>"); sb.AppendLine("<repairingEntityID>"); this._repairingEntityID.Reflection(sb); sb.AppendLine("</repairingEntityID>"); sb.AppendLine("<repairResult type=\"byte\">" + this._repairResult.ToString(CultureInfo.InvariantCulture) + "</repairResult>"); sb.AppendLine("<padding1 type=\"short\">" + this._padding1.ToString(CultureInfo.InvariantCulture) + "</padding1>"); sb.AppendLine("<padding2 type=\"byte\">" + this._padding2.ToString(CultureInfo.InvariantCulture) + "</padding2>"); sb.AppendLine("</RepairResponsePdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as RepairResponsePdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(RepairResponsePdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (!this._receivingEntityID.Equals(obj._receivingEntityID)) { ivarsEqual = false; } if (!this._repairingEntityID.Equals(obj._repairingEntityID)) { ivarsEqual = false; } if (this._repairResult != obj._repairResult) { ivarsEqual = false; } if (this._padding1 != obj._padding1) { ivarsEqual = false; } if (this._padding2 != obj._padding2) { ivarsEqual = false; } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._receivingEntityID.GetHashCode(); result = GenerateHash(result) ^ this._repairingEntityID.GetHashCode(); result = GenerateHash(result) ^ this._repairResult.GetHashCode(); result = GenerateHash(result) ^ this._padding1.GetHashCode(); result = GenerateHash(result) ^ this._padding2.GetHashCode(); return result; } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // BatchedJoinBlock.cs // // // A propagator block that groups individual messages of multiple types // into tuples of arrays of those messages. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Threading.Tasks.Dataflow.Internal; namespace System.Threading.Tasks.Dataflow { /// <summary> /// Provides a dataflow block that batches a specified number of inputs of potentially differing types /// provided to one or more of its targets. /// </summary> /// <typeparam name="T1">Specifies the type of data accepted by the block's first target.</typeparam> /// <typeparam name="T2">Specifies the type of data accepted by the block's second target.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(BatchedJoinBlock<,>.DebugView))] public sealed class BatchedJoinBlock<T1, T2> : IReceivableSourceBlock<Tuple<IList<T1>, IList<T2>>>, IDebuggerDisplay { /// <summary>The size of the batches generated by this BatchedJoin.</summary> private readonly int _batchSize; /// <summary>State shared among the targets.</summary> private readonly BatchedJoinBlockTargetSharedResources _sharedResources; /// <summary>The target providing inputs of type T1.</summary> private readonly BatchedJoinBlockTarget<T1> _target1; /// <summary>The target providing inputs of type T2.</summary> private readonly BatchedJoinBlockTarget<T2> _target2; /// <summary>The source side.</summary> private readonly SourceCore<Tuple<IList<T1>, IList<T2>>> _source; /// <summary>Initializes this <see cref="BatchedJoinBlock{T1,T2}"/> with the specified configuration.</summary> /// <param name="batchSize">The number of items to group into a batch.</param> /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="batchSize"/> must be positive.</exception> public BatchedJoinBlock(Int32 batchSize) : this(batchSize, GroupingDataflowBlockOptions.Default) { } /// <summary>Initializes this <see cref="BatchedJoinBlock{T1,T2}"/> with the specified configuration.</summary> /// <param name="batchSize">The number of items to group into a batch.</param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="BatchedJoinBlock{T1,T2}"/>.</param> /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="batchSize"/> must be positive.</exception> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public BatchedJoinBlock(Int32 batchSize, GroupingDataflowBlockOptions dataflowBlockOptions) { // Validate arguments if (batchSize < 1) throw new ArgumentOutOfRangeException("batchSize", SR.ArgumentOutOfRange_GenericPositive); if (dataflowBlockOptions == null) throw new ArgumentNullException("dataflowBlockOptions"); if (!dataflowBlockOptions.Greedy) throw new ArgumentException(SR.Argument_NonGreedyNotSupported, "dataflowBlockOptions"); if (dataflowBlockOptions.BoundedCapacity != DataflowBlockOptions.Unbounded) throw new ArgumentException(SR.Argument_BoundedCapacityNotSupported, "dataflowBlockOptions"); Contract.EndContractBlock(); // Store arguments _batchSize = batchSize; dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); // Configure the source _source = new SourceCore<Tuple<IList<T1>, IList<T2>>>( this, dataflowBlockOptions, owningSource => ((BatchedJoinBlock<T1, T2>)owningSource).CompleteEachTarget()); // The action to run when a batch should be created. This is typically called // when we have a full batch, but it will also be called when we're done receiving // messages, and thus when there may be a few stragglers we need to make a batch out of. Action createBatchAction = () => { if (_target1.Count > 0 || _target2.Count > 0) { _source.AddMessage(Tuple.Create(_target1.GetAndEmptyMessages(), _target2.GetAndEmptyMessages())); } }; // Configure the targets _sharedResources = new BatchedJoinBlockTargetSharedResources( batchSize, dataflowBlockOptions, createBatchAction, () => { createBatchAction(); _source.Complete(); }, _source.AddException, Complete); _target1 = new BatchedJoinBlockTarget<T1>(_sharedResources); _target2 = new BatchedJoinBlockTarget<T2>(_sharedResources); // It is possible that the source half may fault on its own, e.g. due to a task scheduler exception. // In those cases we need to fault the target half to drop its buffered messages and to release its // reservations. This should not create an infinite loop, because all our implementations are designed // to handle multiple completion requests and to carry over only one. _source.Completion.ContinueWith((completed, state) => { var thisBlock = ((BatchedJoinBlock<T1, T2>)state) as IDataflowBlock; Debug.Assert(completed.IsFaulted, "The source must be faulted in order to trigger a target completion."); thisBlock.Fault(completed.Exception); }, this, CancellationToken.None, Common.GetContinuationOptions() | TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); // Handle async cancellation requests by declining on the target Common.WireCancellationToComplete( dataflowBlockOptions.CancellationToken, _source.Completion, state => ((BatchedJoinBlock<T1, T2>)state).CompleteEachTarget(), this); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCreated(this, dataflowBlockOptions); } #endif } /// <summary>Gets the size of the batches generated by this <see cref="BatchedJoinBlock{T1,T2}"/>.</summary> public Int32 BatchSize { get { return _batchSize; } } /// <summary>Gets a target that may be used to offer messages of the first type.</summary> public ITargetBlock<T1> Target1 { get { return _target1; } } /// <summary>Gets a target that may be used to offer messages of the second type.</summary> public ITargetBlock<T2> Target2 { get { return _target2; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public IDisposable LinkTo(ITargetBlock<Tuple<IList<T1>, IList<T2>>> target, DataflowLinkOptions linkOptions) { return _source.LinkTo(target, linkOptions); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public Boolean TryReceive(Predicate<Tuple<IList<T1>, IList<T2>>> filter, out Tuple<IList<T1>, IList<T2>> item) { return _source.TryReceive(filter, out item); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public bool TryReceiveAll(out IList<Tuple<IList<T1>, IList<T2>>> items) { return _source.TryReceiveAll(out items); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="OutputCount"]/*' /> public int OutputCount { get { return _source.OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> public Task Completion { get { return _source.Completion; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { Debug.Assert(_target1 != null, "_target1 not initialized"); Debug.Assert(_target2 != null, "_target2 not initialized"); _target1.Complete(); _target2.Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException("exception"); Contract.EndContractBlock(); Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._incomingLock != null, "_sharedResources._incomingLock not initialized"); Debug.Assert(_source != null, "_source not initialized"); lock (_sharedResources._incomingLock) { if (!_sharedResources._decliningPermanently) _source.AddException(exception); } Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' /> Tuple<IList<T1>, IList<T2>> ISourceBlock<Tuple<IList<T1>, IList<T2>>>.ConsumeMessage( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>>> target, out Boolean messageConsumed) { return _source.ConsumeMessage(messageHeader, target, out messageConsumed); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' /> bool ISourceBlock<Tuple<IList<T1>, IList<T2>>>.ReserveMessage( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>>> target) { return _source.ReserveMessage(messageHeader, target); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' /> void ISourceBlock<Tuple<IList<T1>, IList<T2>>>.ReleaseReservation( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>>> target) { _source.ReleaseReservation(messageHeader, target); } /// <summary> /// Invokes Complete on each target /// </summary> private void CompleteEachTarget() { _target1.Complete(); _target2.Complete(); } /// <summary>Gets the number of messages waiting to be processed. This must only be used from the debugger as it avoids taking necessary locks.</summary> private int OutputCountForDebugger { get { return _source.GetDebuggingInformation().OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' /> public override string ToString() { return Common.GetNameForDebugger(this, _source.DataflowBlockOptions); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0}, BatchSize={1}, OutputCount={2}", Common.GetNameForDebugger(this, _source.DataflowBlockOptions), BatchSize, OutputCountForDebugger); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for the Transform.</summary> private sealed class DebugView { /// <summary>The block being viewed.</summary> private readonly BatchedJoinBlock<T1, T2> _batchedJoinBlock; /// <summary>The source half of the block being viewed.</summary> private readonly SourceCore<Tuple<IList<T1>, IList<T2>>>.DebuggingInformation _sourceDebuggingInformation; /// <summary>Initializes the debug view.</summary> /// <param name="batchedJoinBlock">The batched join being viewed.</param> public DebugView(BatchedJoinBlock<T1, T2> batchedJoinBlock) { Contract.Requires(batchedJoinBlock != null, "Need a block with which to construct the debug view."); _batchedJoinBlock = batchedJoinBlock; _sourceDebuggingInformation = batchedJoinBlock._source.GetDebuggingInformation(); } /// <summary>Gets the messages waiting to be received.</summary> public IEnumerable<Tuple<IList<T1>, IList<T2>>> OutputQueue { get { return _sourceDebuggingInformation.OutputQueue; } } /// <summary>Gets the number of batches created.</summary> public long BatchesCreated { get { return _batchedJoinBlock._sharedResources._batchesCreated; } } /// <summary>Gets the number of items remaining to form a batch.</summary> public int RemainingItemsForBatch { get { return _batchedJoinBlock._sharedResources._remainingItemsInBatch; } } /// <summary>Gets the size of the batches generated by this BatchedJoin.</summary> public Int32 BatchSize { get { return _batchedJoinBlock._batchSize; } } /// <summary>Gets the first target.</summary> public ITargetBlock<T1> Target1 { get { return _batchedJoinBlock._target1; } } /// <summary>Gets the second target.</summary> public ITargetBlock<T2> Target2 { get { return _batchedJoinBlock._target2; } } /// <summary>Gets the task being used for output processing.</summary> public Task TaskForOutputProcessing { get { return _sourceDebuggingInformation.TaskForOutputProcessing; } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> public GroupingDataflowBlockOptions DataflowBlockOptions { get { return (GroupingDataflowBlockOptions)_sourceDebuggingInformation.DataflowBlockOptions; } } /// <summary>Gets whether the block is completed.</summary> public bool IsCompleted { get { return _sourceDebuggingInformation.IsCompleted; } } /// <summary>Gets the block's Id.</summary> public int Id { get { return Common.GetBlockId(_batchedJoinBlock); } } /// <summary>Gets the set of all targets linked from this block.</summary> public TargetRegistry<Tuple<IList<T1>, IList<T2>>> LinkedTargets { get { return _sourceDebuggingInformation.LinkedTargets; } } /// <summary>Gets the target that holds a reservation on the next message, if any.</summary> public ITargetBlock<Tuple<IList<T1>, IList<T2>>> NextMessageReservedFor { get { return _sourceDebuggingInformation.NextMessageReservedFor; } } } } /// <summary> /// Provides a dataflow block that batches a specified number of inputs of potentially differing types /// provided to one or more of its targets. /// </summary> /// <typeparam name="T1">Specifies the type of data accepted by the block's first target.</typeparam> /// <typeparam name="T2">Specifies the type of data accepted by the block's second target.</typeparam> /// <typeparam name="T3">Specifies the type of data accepted by the block's third target.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(BatchedJoinBlock<,,>.DebugView))] [SuppressMessage("Microsoft.Design", "CA1005:AvoidExcessiveParametersOnGenericTypes")] public sealed class BatchedJoinBlock<T1, T2, T3> : IReceivableSourceBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>>, IDebuggerDisplay { /// <summary>The size of the batches generated by this BatchedJoin.</summary> private readonly int _batchSize; /// <summary>State shared among the targets.</summary> private readonly BatchedJoinBlockTargetSharedResources _sharedResources; /// <summary>The target providing inputs of type T1.</summary> private readonly BatchedJoinBlockTarget<T1> _target1; /// <summary>The target providing inputs of type T2.</summary> private readonly BatchedJoinBlockTarget<T2> _target2; /// <summary>The target providing inputs of type T3.</summary> private readonly BatchedJoinBlockTarget<T3> _target3; /// <summary>The source side.</summary> private readonly SourceCore<Tuple<IList<T1>, IList<T2>, IList<T3>>> _source; /// <summary>Initializes this <see cref="BatchedJoinBlock{T1,T2,T3}"/> with the specified configuration.</summary> /// <param name="batchSize">The number of items to group into a batch.</param> /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="batchSize"/> must be positive.</exception> public BatchedJoinBlock(Int32 batchSize) : this(batchSize, GroupingDataflowBlockOptions.Default) { } /// <summary>Initializes this <see cref="BatchedJoinBlock{T1,T2,T3}"/> with the specified configuration.</summary> /// <param name="batchSize">The number of items to group into a batch.</param> /// <param name="dataflowBlockOptions">The options with which to configure this <see cref="BatchedJoinBlock{T1,T2}"/>.</param> /// <exception cref="System.ArgumentOutOfRangeException">The <paramref name="batchSize"/> must be positive.</exception> /// <exception cref="System.ArgumentNullException">The <paramref name="dataflowBlockOptions"/> is null (Nothing in Visual Basic).</exception> public BatchedJoinBlock(Int32 batchSize, GroupingDataflowBlockOptions dataflowBlockOptions) { // Validate arguments if (batchSize < 1) throw new ArgumentOutOfRangeException("batchSize", SR.ArgumentOutOfRange_GenericPositive); if (dataflowBlockOptions == null) throw new ArgumentNullException("dataflowBlockOptions"); if (!dataflowBlockOptions.Greedy || dataflowBlockOptions.BoundedCapacity != DataflowBlockOptions.Unbounded) { throw new ArgumentException(SR.Argument_NonGreedyNotSupported, "dataflowBlockOptions"); } Contract.EndContractBlock(); // Store arguments _batchSize = batchSize; dataflowBlockOptions = dataflowBlockOptions.DefaultOrClone(); // Configure the source _source = new SourceCore<Tuple<IList<T1>, IList<T2>, IList<T3>>>( this, dataflowBlockOptions, owningSource => ((BatchedJoinBlock<T1, T2, T3>)owningSource).CompleteEachTarget()); // The action to run when a batch should be created. This is typically called // when we have a full batch, but it will also be called when we're done receiving // messages, and thus when there may be a few stragglers we need to make a batch out of. Action createBatchAction = () => { if (_target1.Count > 0 || _target2.Count > 0 || _target3.Count > 0) { _source.AddMessage(Tuple.Create(_target1.GetAndEmptyMessages(), _target2.GetAndEmptyMessages(), _target3.GetAndEmptyMessages())); } }; // Configure the targets _sharedResources = new BatchedJoinBlockTargetSharedResources( batchSize, dataflowBlockOptions, createBatchAction, () => { createBatchAction(); _source.Complete(); }, _source.AddException, Complete); _target1 = new BatchedJoinBlockTarget<T1>(_sharedResources); _target2 = new BatchedJoinBlockTarget<T2>(_sharedResources); _target3 = new BatchedJoinBlockTarget<T3>(_sharedResources); // It is possible that the source half may fault on its own, e.g. due to a task scheduler exception. // In those cases we need to fault the target half to drop its buffered messages and to release its // reservations. This should not create an infinite loop, because all our implementations are designed // to handle multiple completion requests and to carry over only one. _source.Completion.ContinueWith((completed, state) => { var thisBlock = ((BatchedJoinBlock<T1, T2, T3>)state) as IDataflowBlock; Debug.Assert(completed.IsFaulted, "The source must be faulted in order to trigger a target completion."); thisBlock.Fault(completed.Exception); }, this, CancellationToken.None, Common.GetContinuationOptions() | TaskContinuationOptions.OnlyOnFaulted, TaskScheduler.Default); // Handle async cancellation requests by declining on the target Common.WireCancellationToComplete( dataflowBlockOptions.CancellationToken, _source.Completion, state => ((BatchedJoinBlock<T1, T2, T3>)state).CompleteEachTarget(), this); #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCreated(this, dataflowBlockOptions); } #endif } /// <summary>Gets the size of the batches generated by this <see cref="BatchedJoinBlock{T1,T2,T3}"/>.</summary> public Int32 BatchSize { get { return _batchSize; } } /// <summary>Gets a target that may be used to offer messages of the first type.</summary> public ITargetBlock<T1> Target1 { get { return _target1; } } /// <summary>Gets a target that may be used to offer messages of the second type.</summary> public ITargetBlock<T2> Target2 { get { return _target2; } } /// <summary>Gets a target that may be used to offer messages of the third type.</summary> public ITargetBlock<T3> Target3 { get { return _target3; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="LinkTo"]/*' /> public IDisposable LinkTo(ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> target, DataflowLinkOptions linkOptions) { return _source.LinkTo(target, linkOptions); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceive"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public Boolean TryReceive(Predicate<Tuple<IList<T1>, IList<T2>, IList<T3>>> filter, out Tuple<IList<T1>, IList<T2>, IList<T3>> item) { return _source.TryReceive(filter, out item); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="TryReceiveAll"]/*' /> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public bool TryReceiveAll(out IList<Tuple<IList<T1>, IList<T2>, IList<T3>>> items) { return _source.TryReceiveAll(out items); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="OutputCount"]/*' /> public int OutputCount { get { return _source.OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> public Task Completion { get { return _source.Completion; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { Debug.Assert(_target1 != null, "_target1 not initialized"); Debug.Assert(_target2 != null, "_target2 not initialized"); Debug.Assert(_target3 != null, "_target3 not initialized"); _target1.Complete(); _target2.Complete(); _target3.Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException("exception"); Contract.EndContractBlock(); Debug.Assert(_sharedResources != null, "_sharedResources not initialized"); Debug.Assert(_sharedResources._incomingLock != null, "_sharedResources._incomingLock not initialized"); Debug.Assert(_source != null, "_source not initialized"); lock (_sharedResources._incomingLock) { if (!_sharedResources._decliningPermanently) _source.AddException(exception); } Complete(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ConsumeMessage"]/*' /> Tuple<IList<T1>, IList<T2>, IList<T3>> ISourceBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>>.ConsumeMessage( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> target, out Boolean messageConsumed) { return _source.ConsumeMessage(messageHeader, target, out messageConsumed); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReserveMessage"]/*' /> bool ISourceBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>>.ReserveMessage( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> target) { return _source.ReserveMessage(messageHeader, target); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Sources/Member[@name="ReleaseReservation"]/*' /> void ISourceBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>>.ReleaseReservation( DataflowMessageHeader messageHeader, ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> target) { _source.ReleaseReservation(messageHeader, target); } /// <summary> /// Invokes Complete on each target /// </summary> private void CompleteEachTarget() { _target1.Complete(); _target2.Complete(); _target3.Complete(); } /// <summary>Gets the number of messages waiting to be processed. This must only be used from the debugger as it avoids taking necessary locks.</summary> private int OutputCountForDebugger { get { return _source.GetDebuggingInformation().OutputCount; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="ToString"]/*' /> public override string ToString() { return Common.GetNameForDebugger(this, _source.DataflowBlockOptions); } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0}, BatchSize={1}, OutputCount={2}", Common.GetNameForDebugger(this, _source.DataflowBlockOptions), BatchSize, OutputCountForDebugger); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for the Transform.</summary> private sealed class DebugView { /// <summary>The block being viewed.</summary> private readonly BatchedJoinBlock<T1, T2, T3> _batchedJoinBlock; /// <summary>The source half of the block being viewed.</summary> private readonly SourceCore<Tuple<IList<T1>, IList<T2>, IList<T3>>>.DebuggingInformation _sourceDebuggingInformation; /// <summary>Initializes the debug view.</summary> /// <param name="batchedJoinBlock">The batched join being viewed.</param> public DebugView(BatchedJoinBlock<T1, T2, T3> batchedJoinBlock) { Contract.Requires(batchedJoinBlock != null, "Need a block with which to construct the debug view."); _sourceDebuggingInformation = batchedJoinBlock._source.GetDebuggingInformation(); _batchedJoinBlock = batchedJoinBlock; } /// <summary>Gets the messages waiting to be received.</summary> public IEnumerable<Tuple<IList<T1>, IList<T2>, IList<T3>>> OutputQueue { get { return _sourceDebuggingInformation.OutputQueue; } } /// <summary>Gets the number of batches created.</summary> public long BatchesCreated { get { return _batchedJoinBlock._sharedResources._batchesCreated; } } /// <summary>Gets the number of items remaining to form a batch.</summary> public int RemainingItemsForBatch { get { return _batchedJoinBlock._sharedResources._remainingItemsInBatch; } } /// <summary>Gets the size of the batches generated by this BatchedJoin.</summary> public Int32 BatchSize { get { return _batchedJoinBlock._batchSize; } } /// <summary>Gets the first target.</summary> public ITargetBlock<T1> Target1 { get { return _batchedJoinBlock._target1; } } /// <summary>Gets the second target.</summary> public ITargetBlock<T2> Target2 { get { return _batchedJoinBlock._target2; } } /// <summary>Gets the second target.</summary> public ITargetBlock<T3> Target3 { get { return _batchedJoinBlock._target3; } } /// <summary>Gets the task being used for output processing.</summary> public Task TaskForOutputProcessing { get { return _sourceDebuggingInformation.TaskForOutputProcessing; } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> public GroupingDataflowBlockOptions DataflowBlockOptions { get { return (GroupingDataflowBlockOptions)_sourceDebuggingInformation.DataflowBlockOptions; } } /// <summary>Gets whether the block is completed.</summary> public bool IsCompleted { get { return _sourceDebuggingInformation.IsCompleted; } } /// <summary>Gets the block's Id.</summary> public int Id { get { return Common.GetBlockId(_batchedJoinBlock); } } /// <summary>Gets the set of all targets linked from this block.</summary> public TargetRegistry<Tuple<IList<T1>, IList<T2>, IList<T3>>> LinkedTargets { get { return _sourceDebuggingInformation.LinkedTargets; } } /// <summary>Gets the target that holds a reservation on the next message, if any.</summary> public ITargetBlock<Tuple<IList<T1>, IList<T2>, IList<T3>>> NextMessageReservedFor { get { return _sourceDebuggingInformation.NextMessageReservedFor; } } } } } namespace System.Threading.Tasks.Dataflow.Internal { /// <summary>Provides the target used in a BatchedJoin.</summary> /// <typeparam name="T">Specifies the type of data accepted by this target.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] [DebuggerTypeProxy(typeof(BatchedJoinBlockTarget<>.DebugView))] internal sealed class BatchedJoinBlockTarget<T> : ITargetBlock<T>, IDebuggerDisplay { /// <summary>The shared resources used by all targets associated with the same batched join instance.</summary> private readonly BatchedJoinBlockTargetSharedResources _sharedResources; /// <summary>Whether this target is declining future messages.</summary> private bool _decliningPermanently; /// <summary>Input messages for the next batch.</summary> private IList<T> _messages = new List<T>(); /// <summary>Initializes the target.</summary> /// <param name="sharedResources">The shared resources used by all targets associated with this batched join.</param> internal BatchedJoinBlockTarget(BatchedJoinBlockTargetSharedResources sharedResources) { Contract.Requires(sharedResources != null, "Targets require a shared resources through which to communicate."); // Store the shared resources, and register with it to let it know there's // another target. This is done in a non-thread-safe manner and must be done // during construction of the batched join instance. _sharedResources = sharedResources; sharedResources._remainingAliveTargets++; } /// <summary>Gets the number of messages buffered in this target.</summary> internal int Count { get { return _messages.Count; } } /// <summary>Gets the messages buffered by this target and then empties the collection.</summary> /// <returns>The messages from the target.</returns> internal IList<T> GetAndEmptyMessages() { Common.ContractAssertMonitorStatus(_sharedResources._incomingLock, held: true); IList<T> toReturn = _messages; _messages = new List<T>(); return toReturn; } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> public DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, T messageValue, ISourceBlock<T> source, Boolean consumeToAccept) { // Validate arguments if (!messageHeader.IsValid) throw new ArgumentException(SR.Argument_InvalidMessageHeader, "messageHeader"); if (source == null && consumeToAccept) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, "consumeToAccept"); Contract.EndContractBlock(); lock (_sharedResources._incomingLock) { // If we've already stopped accepting messages, decline permanently if (_decliningPermanently || _sharedResources._decliningPermanently) return DataflowMessageStatus.DecliningPermanently; // Consume the message from the source if necessary, and store the message if (consumeToAccept) { Debug.Assert(source != null, "We must have thrown if source == null && consumeToAccept == true."); bool consumed; messageValue = source.ConsumeMessage(messageHeader, this, out consumed); if (!consumed) return DataflowMessageStatus.NotAvailable; } _messages.Add(messageValue); // If this message makes a batch, notify the shared resources that a batch has been completed if (--_sharedResources._remainingItemsInBatch == 0) _sharedResources._batchSizeReachedAction(); return DataflowMessageStatus.Accepted; } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Complete"]/*' /> public void Complete() { lock (_sharedResources._incomingLock) { // If this is the first time Complete is being called, // note that there's now one fewer targets receiving messages for the batched join. if (!_decliningPermanently) { _decliningPermanently = true; if (--_sharedResources._remainingAliveTargets == 0) _sharedResources._allTargetsDecliningPermanentlyAction(); } } } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Fault"]/*' /> void IDataflowBlock.Fault(Exception exception) { if (exception == null) throw new ArgumentNullException("exception"); Contract.EndContractBlock(); lock (_sharedResources._incomingLock) { if (!_decliningPermanently && !_sharedResources._decliningPermanently) _sharedResources._exceptionAction(exception); } _sharedResources._completionAction(); } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> Task IDataflowBlock.Completion { get { throw new NotSupportedException(SR.NotSupported_MemberNotNeeded); } } /// <summary>The data to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { return string.Format("{0} InputCount={1}", Common.GetNameForDebugger(this), _messages.Count); } } /// <summary>Gets the data to display in the debugger display attribute for this instance.</summary> object IDebuggerDisplay.Content { get { return DebuggerDisplayContent; } } /// <summary>Provides a debugger type proxy for the Transform.</summary> private sealed class DebugView { /// <summary>The batched join block target being viewed.</summary> private readonly BatchedJoinBlockTarget<T> _batchedJoinBlockTarget; /// <summary>Initializes the debug view.</summary> /// <param name="batchedJoinBlockTarget">The batched join target being viewed.</param> public DebugView(BatchedJoinBlockTarget<T> batchedJoinBlockTarget) { Contract.Requires(batchedJoinBlockTarget != null, "Need a block with which to construct the debug view."); _batchedJoinBlockTarget = batchedJoinBlockTarget; } /// <summary>Gets the messages waiting to be processed.</summary> public IEnumerable<T> InputQueue { get { return _batchedJoinBlockTarget._messages; } } /// <summary>Gets whether the block is declining further messages.</summary> public bool IsDecliningPermanently { get { return _batchedJoinBlockTarget._decliningPermanently || _batchedJoinBlockTarget._sharedResources._decliningPermanently; } } } } /// <summary>Provides a container for resources shared across all targets used by the same BatchedJoinBlock instance.</summary> internal sealed class BatchedJoinBlockTargetSharedResources { /// <summary>Initializes the shared resources.</summary> /// <param name="batchSize">The size of a batch to create.</param> /// <param name="dataflowBlockOptions">The options used to configure the shared resources. Assumed to be immutable.</param> /// <param name="batchSizeReachedAction">The action to invoke when a batch is completed.</param> /// <param name="allTargetsDecliningAction">The action to invoke when no more targets are accepting input.</param> /// <param name="exceptionAction">The action to invoke when an exception needs to be logged.</param> /// <param name="completionAction">The action to invoke when completing, typically invoked due to a call to Fault.</param> internal BatchedJoinBlockTargetSharedResources( int batchSize, GroupingDataflowBlockOptions dataflowBlockOptions, Action batchSizeReachedAction, Action allTargetsDecliningAction, Action<Exception> exceptionAction, Action completionAction) { Debug.Assert(batchSize >= 1, "A positive batch size is required."); Debug.Assert(batchSizeReachedAction != null, "Need an action to invoke for each batch."); Debug.Assert(allTargetsDecliningAction != null, "Need an action to invoke when all targets have declined."); _incomingLock = new object(); _batchSize = batchSize; // _remainingAliveTargets will be incremented when targets are added. // They must be added during construction of the BatchedJoin<...>. _remainingAliveTargets = 0; _remainingItemsInBatch = batchSize; // Configure what to do when batches are completed and/or all targets start declining _allTargetsDecliningPermanentlyAction = () => { // Invoke the caller's action allTargetsDecliningAction(); // Don't accept any more messages. We should already // be doing this anyway through each individual target's declining flag, // so setting it to true is just a precaution and is also helpful // when onceOnly is true. _decliningPermanently = true; }; _batchSizeReachedAction = () => { // Invoke the caller's action batchSizeReachedAction(); _batchesCreated++; // If this batched join is meant to be used for only a single // batch, invoke the completion logic. if (_batchesCreated >= dataflowBlockOptions.ActualMaxNumberOfGroups) _allTargetsDecliningPermanentlyAction(); // Otherwise, get ready for the next batch. else _remainingItemsInBatch = _batchSize; }; _exceptionAction = exceptionAction; _completionAction = completionAction; } /// <summary> /// A lock used to synchronize all incoming messages on all targets. It protects all of the rest /// of the shared Resources's state and will be held while invoking the delegates. /// </summary> internal readonly object _incomingLock; /// <summary>The size of the batches to generate.</summary> internal readonly int _batchSize; /// <summary>The action to invoke when enough elements have been accumulated to make a batch.</summary> internal readonly Action _batchSizeReachedAction; /// <summary>The action to invoke when all targets are declining further messages.</summary> internal readonly Action _allTargetsDecliningPermanentlyAction; /// <summary>The action to invoke when an exception has to be logged.</summary> internal readonly Action<Exception> _exceptionAction; /// <summary>The action to invoke when the owning block has to be completed.</summary> internal readonly Action _completionAction; /// <summary>The number of items remaining to form a batch.</summary> internal int _remainingItemsInBatch; /// <summary>The number of targets still alive (i.e. not declining all further messages).</summary> internal int _remainingAliveTargets; /// <summary>Whether all targets should decline all further messages.</summary> internal bool _decliningPermanently; /// <summary>The number of batches created.</summary> internal long _batchesCreated; } }
using AutoMapper.Internal; using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; namespace AutoMapper.QueryableExtensions.Impl { [EditorBrowsable(EditorBrowsableState.Never)] public class QueryMapperVisitor : ExpressionVisitor { private readonly IQueryable _destQuery; private readonly ParameterExpression _instanceParameter; private readonly Type _sourceType; private readonly Type _destinationType; private readonly Stack<object> _tree = new Stack<object>(); private readonly Stack<object> _newTree = new Stack<object>(); private readonly MemberAccessQueryMapperVisitor _memberVisitor; internal QueryMapperVisitor(Type sourceType, Type destinationType, IQueryable destQuery, IGlobalConfiguration config) { _sourceType = sourceType; _destinationType = destinationType; _destQuery = destQuery; _instanceParameter = Expression.Parameter(destinationType, "dto"); _memberVisitor = new MemberAccessQueryMapperVisitor(this, config); } public static IQueryable<TDestination> Map<TSource, TDestination>(IQueryable<TSource> sourceQuery, IQueryable<TDestination> destQuery, IGlobalConfiguration config) { var visitor = new QueryMapperVisitor(typeof(TSource), typeof(TDestination), destQuery, config); var expr = visitor.Visit(sourceQuery.Expression); var newDestQuery = destQuery.Provider.CreateQuery<TDestination>(expr); return newDestQuery; } public override Expression Visit(Expression node) { _tree.Push(node); // OData Client DataServiceQuery initial expression node type if (node != null && (int)node.NodeType == 10000) { return node; } var newNode = base.Visit(node); _newTree.Push(newNode); return newNode; } protected override Expression VisitParameter(ParameterExpression node) => _instanceParameter; protected override Expression VisitConstant(ConstantExpression node) { // It is data source of queryable object instance if (node.Value is IQueryable query && query.ElementType == _sourceType) return _destQuery.Expression; return node; } protected override Expression VisitBinary(BinaryExpression node) { var left = Visit(node.Left); var right = Visit(node.Right); // Convert Right expression value to left expr type // It is needed when PropertyMap is changing type of property if (left.Type != right.Type && right.NodeType == ExpressionType.Constant) { var value = Convert.ChangeType(((ConstantExpression)right).Value, left.Type, CultureInfo.CurrentCulture); right = Expression.Constant(value, left.Type); } return Expression.MakeBinary(node.NodeType, left, right); } protected override Expression VisitLambda<T>(Expression<T> node) { var newBody = Visit(node.Body); var newParams = node.Parameters.Select(p => (ParameterExpression)Visit(p)); var delegateType = ChangeLambdaArgTypeFormSourceToDest(node.Type, newBody.Type); var newLambda = Expression.Lambda(delegateType, newBody, newParams); return newLambda; } protected override Expression VisitMethodCall(MethodCallExpression node) { if (node.Method.Name == "OrderBy" || node.Method.Name == "OrderByDescending" || node.Method.Name == "ThenBy" || node.Method.Name == "ThenByDescending") { return VisitOrderBy(node); } var args = node.Arguments.Select(Visit).ToList(); var newObject = Visit(node.Object); var method = ChangeMethodArgTypeFormSourceToDest(node.Method); var newMethodCall = Expression.Call(newObject, method, args); return newMethodCall; } private Expression VisitOrderBy(MethodCallExpression node) { var query = node.Arguments[0]; var orderByExpr = node.Arguments[1]; var newQuery = Visit(query); var newOrderByExpr = Visit(orderByExpr); var newObject = Visit(node.Object); var genericMethod = node.Method.GetGenericMethodDefinition(); var methodArgs = node.Method.GetGenericArguments(); methodArgs[0] = methodArgs[0].ReplaceItemType(_sourceType, _destinationType); // for typical orderby expression, a unaryexpression is used that contains a // func which in turn defines the type of the field that has to be used for ordering/sorting if (newOrderByExpr is UnaryExpression unary && unary.Operand.Type.IsGenericType) { methodArgs[1] = methodArgs[1].ReplaceItemType(typeof(string), unary.Operand.Type.GenericTypeArguments.Last()); } else { methodArgs[1] = methodArgs[1].ReplaceItemType(typeof(string), typeof(int)); } var orderByMethod = genericMethod.MakeGenericMethod(methodArgs); return Expression.Call(newObject, orderByMethod, newQuery, newOrderByExpr); } protected override Expression VisitMember(MemberExpression node) => _memberVisitor.Visit(node); private MethodInfo ChangeMethodArgTypeFormSourceToDest(MethodInfo mi) { if (!mi.IsGenericMethod) return mi; var genericMethod = mi.GetGenericMethodDefinition(); var methodArgs = mi.GetGenericArguments(); methodArgs = methodArgs.Select(t => t.ReplaceItemType(_sourceType, _destinationType)).ToArray(); return genericMethod.MakeGenericMethod(methodArgs); } private Type ChangeLambdaArgTypeFormSourceToDest(Type lambdaType, Type returnType) { if (lambdaType.IsGenericType) { var genArgs = lambdaType.GetTypeInfo().GenericTypeArguments; var newGenArgs = genArgs.Select(t => t.ReplaceItemType(_sourceType, _destinationType)).ToArray(); var genericTypeDef = lambdaType.GetGenericTypeDefinition(); if (genericTypeDef.FullName.StartsWith("System.Func")) { newGenArgs[newGenArgs.Length - 1] = returnType; } return genericTypeDef.MakeGenericType(newGenArgs); } return lambdaType; } } public class MemberAccessQueryMapperVisitor : ExpressionVisitor { private readonly ExpressionVisitor _rootVisitor; private readonly IGlobalConfiguration _config; public MemberAccessQueryMapperVisitor(ExpressionVisitor rootVisitor, IGlobalConfiguration config) { _rootVisitor = rootVisitor; _config = config; } protected override Expression VisitMember(MemberExpression node) { var parentExpr = _rootVisitor.Visit(node.Expression); if (parentExpr != null) { var propertyMap = _config.GetPropertyMap(node.Member, parentExpr.Type); var newMember = Expression.MakeMemberAccess(parentExpr, propertyMap.DestinationMember); return newMember; } return node; } } [EditorBrowsable(EditorBrowsableState.Never)] public static class QueryMapperHelper { /// <summary> /// if targetType is oldType, method will return newType /// if targetType is not oldType, method will return targetType /// if targetType is generic type with oldType arguments, method will replace all oldType arguments on newType /// </summary> /// <param name="targetType"></param> /// <param name="oldType"></param> /// <param name="newType"></param> /// <returns></returns> public static Type ReplaceItemType(this Type targetType, Type oldType, Type newType) { if (targetType == oldType) return newType; if (targetType.IsGenericType) { var genSubArgs = targetType.GetTypeInfo().GenericTypeArguments; var newGenSubArgs = new Type[genSubArgs.Length]; for (var i = 0; i < genSubArgs.Length; i++) newGenSubArgs[i] = ReplaceItemType(genSubArgs[i], oldType, newType); return targetType.GetGenericTypeDefinition().MakeGenericType(newGenSubArgs); } return targetType; } public static PropertyMap GetPropertyMap(this IGlobalConfiguration config, MemberInfo sourceMemberInfo, Type destinationMemberType) { var typeMap = config.CheckIfMapExists(sourceMemberInfo.DeclaringType, destinationMemberType); var propertyMap = typeMap.PropertyMaps .FirstOrDefault(pm => pm.CanResolveValue && pm.SourceMember != null && pm.SourceMember.Name == sourceMemberInfo.Name); if (propertyMap == null) throw PropertyConfigurationException(typeMap, sourceMemberInfo.Name); return propertyMap; } public static TypeMap CheckIfMapExists(this IGlobalConfiguration config, Type sourceType, Type destinationType) { var typeMap = config.ResolveTypeMap(sourceType, destinationType); if (typeMap == null) { throw MissingMapException(sourceType, destinationType); } return typeMap; } public static Exception PropertyConfigurationException(TypeMap typeMap, params string[] unmappedPropertyNames) => new AutoMapperConfigurationException(new[] { new AutoMapperConfigurationException.TypeMapConfigErrors(typeMap, unmappedPropertyNames, true) }); public static Exception MissingMapException(TypePair types) => MissingMapException(types.SourceType, types.DestinationType); public static Exception MissingMapException(Type sourceType, Type destinationType) => new InvalidOperationException($"Missing map from {sourceType} to {destinationType}. Create using CreateMap<{sourceType.Name}, {destinationType.Name}>."); } }
// 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. // // Don't override IsAlwaysNormalized because it is just a Unicode Transformation and could be confused. // using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; namespace System.Text { // Encodes text into and out of UTF-32. UTF-32 is a way of writing // Unicode characters with a single storage unit (32 bits) per character, // // The UTF-32 byte order mark is simply the Unicode byte order mark // (0x00FEFF) written in UTF-32 (0x0000FEFF or 0xFFFE0000). The byte order // mark is used mostly to distinguish UTF-32 text from other encodings, and doesn't // switch the byte orderings. public sealed class UTF32Encoding : Encoding { /* words bits UTF-32 representation ----- ---- ----------------------------------- 1 16 00000000 00000000 xxxxxxxx xxxxxxxx 2 21 00000000 000xxxxx hhhhhhll llllllll ----- ---- ----------------------------------- Surrogate: Real Unicode value = (HighSurrogate - 0xD800) * 0x400 + (LowSurrogate - 0xDC00) + 0x10000 */ // Used by Encoding.UTF32/BigEndianUTF32 for lazy initialization // The initialization code will not be run until a static member of the class is referenced internal static readonly UTF32Encoding s_default = new UTF32Encoding(bigEndian: false, byteOrderMark: true); internal static readonly UTF32Encoding s_bigEndianDefault = new UTF32Encoding(bigEndian: true, byteOrderMark: true); private readonly bool _emitUTF32ByteOrderMark = false; private readonly bool _isThrowException = false; private readonly bool _bigEndian = false; public UTF32Encoding() : this(false, true) { } public UTF32Encoding(bool bigEndian, bool byteOrderMark) : base(bigEndian ? 12001 : 12000) { _bigEndian = bigEndian; _emitUTF32ByteOrderMark = byteOrderMark; } public UTF32Encoding(bool bigEndian, bool byteOrderMark, bool throwOnInvalidCharacters) : this(bigEndian, byteOrderMark) { _isThrowException = throwOnInvalidCharacters; // Encoding constructor already did this, but it'll be wrong if we're throwing exceptions if (_isThrowException) SetDefaultFallbacks(); } internal override void SetDefaultFallbacks() { // For UTF-X encodings, we use a replacement fallback with an empty string if (_isThrowException) { this.encoderFallback = EncoderFallback.ExceptionFallback; this.decoderFallback = DecoderFallback.ExceptionFallback; } else { this.encoderFallback = new EncoderReplacementFallback("\xFFFD"); this.decoderFallback = new DecoderReplacementFallback("\xFFFD"); } } // The following methods are copied from EncodingNLS.cs. // Unfortunately EncodingNLS.cs is internal and we're public, so we have to re-implement them here. // These should be kept in sync for the following classes: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // Returns the number of bytes required to encode a range of characters in // a character array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(char[] chars, int index, int count) { // Validate input parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - index < count) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input, return 0, avoid fixed empty array problem if (count == 0) return 0; // Just call the pointer version fixed (char* pChars = chars) return GetByteCount(pChars + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetByteCount(string s) { // Validate input if (s==null) throw new ArgumentNullException(nameof(s)); fixed (char* pChars = s) return GetByteCount(pChars, s.Length, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetByteCount(char* chars, int count) { // Validate Parameters if (chars == null) throw new ArgumentNullException(nameof(chars), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); // Call it with empty encoder return GetByteCount(chars, count, null); } // Parent method is safe. // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding public override unsafe int GetBytes(string s, int charIndex, int charCount, byte[] bytes, int byteIndex) { if (s == null || bytes == null) throw new ArgumentNullException((s == null ? nameof(s) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (s.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(s), SR.ArgumentOutOfRange_IndexCount); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); int byteCount = bytes.Length - byteIndex; fixed (char* pChars = s) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // Encodes a range of characters in a character array into a range of bytes // in a byte array. An exception occurs if the byte array is not large // enough to hold the complete encoding of the characters. The // GetByteCount method can be used to determine the exact number of // bytes that will be produced for a given range of characters. // Alternatively, the GetMaxByteCount method can be used to // determine the maximum number of bytes that will be produced for a given // number of characters, regardless of the actual character values. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), SR.ArgumentNull_Array); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); if (byteIndex < 0 || byteIndex > bytes.Length) throw new ArgumentOutOfRangeException(nameof(byteIndex), SR.ArgumentOutOfRange_Index); // If nothing to encode return 0, avoid fixed problem if (charCount == 0) return 0; // Just call pointer version int byteCount = bytes.Length - byteIndex; fixed (char* pChars = chars) fixed (byte* pBytes = &MemoryMarshal.GetReference((Span<byte>)bytes)) // Remember that byteCount is # to decode, not size of array. return GetBytes(pChars + charIndex, charCount, pBytes + byteIndex, byteCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetBytes(chars, charCount, bytes, byteCount, null); } // Returns the number of characters produced by decoding a range of bytes // in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetCharCount(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // If no input just return 0, fixed doesn't like 0 length arrays. if (count == 0) return 0; // Just call pointer version fixed (byte* pBytes = bytes) return GetCharCount(pBytes + index, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public override unsafe int GetCharCount(byte* bytes, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); return GetCharCount(bytes, count, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if ( bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), SR.ArgumentOutOfRange_Index); // If no input, return 0 & avoid fixed problem if (byteCount == 0) return 0; // Just call pointer version int charCount = chars.Length - charIndex; fixed (byte* pBytes = bytes) fixed (char* pChars = &MemoryMarshal.GetReference((Span<char>)chars)) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, null); } // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding [CLSCompliant(false)] public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), SR.ArgumentNull_Array); if (charCount < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((charCount < 0 ? nameof(charCount) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); return GetChars(bytes, byteCount, chars, charCount, null); } // Returns a string containing the decoded representation of a range of // bytes in a byte array. // // All of our public Encodings that don't use EncodingNLS must have this (including EncodingNLS) // So if you fix this, fix the others. Currently those include: // EncodingNLS, UTF7Encoding, UTF8Encoding, UTF32Encoding, ASCIIEncoding, UnicodeEncoding // parent method is safe public override unsafe string GetString(byte[] bytes, int index, int count) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); // Avoid problems with empty input buffer if (count == 0) return string.Empty; fixed (byte* pBytes = bytes) return string.CreateStringFromEncoding( pBytes + index, count, this); } // // End of standard methods copied from EncodingNLS.cs // internal override unsafe int GetByteCount(char* chars, int count, EncoderNLS encoder) { Debug.Assert(chars != null, "[UTF32Encoding.GetByteCount]chars!=null"); Debug.Assert(count >= 0, "[UTF32Encoding.GetByteCount]count >=0"); char* end = chars + count; char* charStart = chars; int byteCount = 0; char highSurrogate = '\0'; // For fallback we may need a fallback buffer EncoderFallbackBuffer fallbackBuffer = null; char* charsForFallback; if (encoder != null) { highSurrogate = encoder._charLeftOver; fallbackBuffer = encoder.FallbackBuffer; // We mustn't have left over fallback data when counting if (fallbackBuffer.Remaining > 0) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); } else { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, end, encoder, false); char ch; TryAgain: while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < end) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Do we need a low surrogate? if (highSurrogate != '\0') { // // In previous char, we encounter a high surrogate, so we are expecting a low surrogate here. // if (char.IsLowSurrogate(ch)) { // They're all legal highSurrogate = '\0'; // // One surrogate pair will be translated into 4 bytes UTF32. // byteCount += 4; continue; } // We are missing our low surrogate, decrement chars and fallback the high surrogate // The high surrogate may have come from the encoder, but nothing else did. Debug.Assert(chars > charStart, "[UTF32Encoding.GetByteCount]Expected chars to have advanced if no low surrogate"); chars--; // Do the fallback charsForFallback = chars; fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback); chars = charsForFallback; // We're going to fallback the old high surrogate. highSurrogate = '\0'; continue; } // Do we have another high surrogate? if (char.IsHighSurrogate(ch)) { // // We'll have a high surrogate to check next time. // highSurrogate = ch; continue; } // Check for illegal characters if (char.IsLowSurrogate(ch)) { // We have a leading low surrogate, do the fallback charsForFallback = chars; fallbackBuffer.InternalFallback(ch, ref charsForFallback); chars = charsForFallback; // Try again with fallback buffer continue; } // We get to add the character (4 bytes UTF32) byteCount += 4; } // May have to do our last surrogate if ((encoder == null || encoder.MustFlush) && highSurrogate > 0) { // We have to do the fallback for the lonely high surrogate charsForFallback = chars; fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback); chars = charsForFallback; highSurrogate = (char)0; goto TryAgain; } // Check for overflows. if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GetByteCountOverflow); // Shouldn't have anything in fallback buffer for GetByteCount // (don't have to check _throwOnOverflow for count) Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetByteCount]Expected empty fallback buffer at end"); // Return our count return byteCount; } internal override unsafe int GetBytes(char* chars, int charCount, byte* bytes, int byteCount, EncoderNLS encoder) { Debug.Assert(chars != null, "[UTF32Encoding.GetBytes]chars!=null"); Debug.Assert(bytes != null, "[UTF32Encoding.GetBytes]bytes!=null"); Debug.Assert(byteCount >= 0, "[UTF32Encoding.GetBytes]byteCount >=0"); Debug.Assert(charCount >= 0, "[UTF32Encoding.GetBytes]charCount >=0"); char* charStart = chars; char* charEnd = chars + charCount; byte* byteStart = bytes; byte* byteEnd = bytes + byteCount; char highSurrogate = '\0'; // For fallback we may need a fallback buffer EncoderFallbackBuffer fallbackBuffer = null; char* charsForFallback; if (encoder != null) { highSurrogate = encoder._charLeftOver; fallbackBuffer = encoder.FallbackBuffer; // We mustn't have left over fallback data when not converting if (encoder._throwOnOverflow && fallbackBuffer.Remaining > 0) throw new ArgumentException(SR.Format(SR.Argument_EncoderFallbackNotEmpty, this.EncodingName, encoder.Fallback.GetType())); } else { fallbackBuffer = this.encoderFallback.CreateFallbackBuffer(); } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(charStart, charEnd, encoder, true); char ch; TryAgain: while (((ch = fallbackBuffer.InternalGetNextChar()) != 0) || chars < charEnd) { // First unwind any fallback if (ch == 0) { // No fallback, just get next char ch = *chars; chars++; } // Do we need a low surrogate? if (highSurrogate != '\0') { // // In previous char, we encountered a high surrogate, so we are expecting a low surrogate here. // if (char.IsLowSurrogate(ch)) { // Is it a legal one? uint iTemp = GetSurrogate(highSurrogate, ch); highSurrogate = '\0'; // // One surrogate pair will be translated into 4 bytes UTF32. // if (bytes + 3 >= byteEnd) { // Don't have 4 bytes if (fallbackBuffer.bFallingBack) { fallbackBuffer.MovePrevious(); // Aren't using these 2 fallback chars fallbackBuffer.MovePrevious(); } else { // If we don't have enough room, then either we should've advanced a while // or we should have bytes==byteStart and throw below Debug.Assert(chars > charStart + 1 || bytes == byteStart, "[UnicodeEncoding.GetBytes]Expected chars to have when no room to add surrogate pair"); chars -= 2; // Aren't using those 2 chars } ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written) highSurrogate = (char)0; // Nothing left over (we backed up to start of pair if supplimentary) break; } if (_bigEndian) { *(bytes++) = (byte)(0x00); *(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0 *(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF *(bytes++) = (byte)(iTemp); // Implies & 0xFF } else { *(bytes++) = (byte)(iTemp); // Implies & 0xFF *(bytes++) = (byte)(iTemp >> 8); // Implies & 0xFF *(bytes++) = (byte)(iTemp >> 16); // Implies & 0xFF, which isn't needed cause high are all 0 *(bytes++) = (byte)(0x00); } continue; } // We are missing our low surrogate, decrement chars and fallback the high surrogate // The high surrogate may have come from the encoder, but nothing else did. Debug.Assert(chars > charStart, "[UTF32Encoding.GetBytes]Expected chars to have advanced if no low surrogate"); chars--; // Do the fallback charsForFallback = chars; fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback); chars = charsForFallback; // We're going to fallback the old high surrogate. highSurrogate = '\0'; continue; } // Do we have another high surrogate?, if so remember it if (char.IsHighSurrogate(ch)) { // // We'll have a high surrogate to check next time. // highSurrogate = ch; continue; } // Check for illegal characters (low surrogate) if (char.IsLowSurrogate(ch)) { // We have a leading low surrogate, do the fallback charsForFallback = chars; fallbackBuffer.InternalFallback(ch, ref charsForFallback); chars = charsForFallback; // Try again with fallback buffer continue; } // We get to add the character, yippee. if (bytes + 3 >= byteEnd) { // Don't have 4 bytes if (fallbackBuffer.bFallingBack) fallbackBuffer.MovePrevious(); // Aren't using this fallback char else { // Must've advanced already Debug.Assert(chars > charStart, "[UTF32Encoding.GetBytes]Expected chars to have advanced if normal character"); chars--; // Aren't using this char } ThrowBytesOverflow(encoder, bytes == byteStart); // Throw maybe (if no bytes written) break; // Didn't throw, stop } if (_bigEndian) { *(bytes++) = (byte)(0x00); *(bytes++) = (byte)(0x00); *(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF *(bytes++) = (byte)(ch); // Implies & 0xFF } else { *(bytes++) = (byte)(ch); // Implies & 0xFF *(bytes++) = (byte)((uint)ch >> 8); // Implies & 0xFF *(bytes++) = (byte)(0x00); *(bytes++) = (byte)(0x00); } } // May have to do our last surrogate if ((encoder == null || encoder.MustFlush) && highSurrogate > 0) { // We have to do the fallback for the lonely high surrogate charsForFallback = chars; fallbackBuffer.InternalFallback(highSurrogate, ref charsForFallback); chars = charsForFallback; highSurrogate = (char)0; goto TryAgain; } // Fix our encoder if we have one Debug.Assert(highSurrogate == 0 || (encoder != null && !encoder.MustFlush), "[UTF32Encoding.GetBytes]Expected encoder to be flushed."); if (encoder != null) { // Remember our left over surrogate (or 0 if flushing) encoder._charLeftOver = highSurrogate; // Need # chars used encoder._charsUsed = (int)(chars - charStart); } // return the new length return (int)(bytes - byteStart); } internal override unsafe int GetCharCount(byte* bytes, int count, DecoderNLS baseDecoder) { Debug.Assert(bytes != null, "[UTF32Encoding.GetCharCount]bytes!=null"); Debug.Assert(count >= 0, "[UTF32Encoding.GetCharCount]count >=0"); UTF32Decoder decoder = (UTF32Decoder)baseDecoder; // None so far! int charCount = 0; byte* end = bytes + count; byte* byteStart = bytes; // Set up decoder int readCount = 0; uint iChar = 0; // For fallback we may need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; // See if there's anything in our decoder if (decoder != null) { readCount = decoder.readByteCount; iChar = (uint)decoder.iChar; fallbackBuffer = decoder.FallbackBuffer; // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check _throwOnOverflow for chars or count) Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetCharCount]Expected empty fallback buffer at start"); } else { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(byteStart, null); // Loop through our input, 4 characters at a time! while (bytes < end && charCount >= 0) { // Get our next character if (_bigEndian) { // Scoot left and add it to the bottom iChar <<= 8; iChar += *(bytes++); } else { // Scoot right and add it to the top iChar >>= 8; iChar += (uint)(*(bytes++)) << 24; } readCount++; // See if we have all the bytes yet if (readCount < 4) continue; // Have the bytes readCount = 0; // See if its valid to encode if (iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF)) { // Need to fall back these 4 bytes byte[] fallbackBytes; if (_bigEndian) { fallbackBytes = new byte[] { unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) }; } else { fallbackBytes = new byte[] { unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)), unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) }; } charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes); // Ignore the illegal character iChar = 0; continue; } // Ok, we have something we can add to our output if (iChar >= 0x10000) { // Surrogates take 2 charCount++; } // Add the rest of the surrogate or our normal character charCount++; // iChar is back to 0 iChar = 0; } // See if we have something left over that has to be decoded if (readCount > 0 && (decoder == null || decoder.MustFlush)) { // Oops, there's something left over with no place to go. byte[] fallbackBytes = new byte[readCount]; if (_bigEndian) { while (readCount > 0) { fallbackBytes[--readCount] = unchecked((byte)iChar); iChar >>= 8; } } else { while (readCount > 0) { fallbackBytes[--readCount] = unchecked((byte)(iChar >> 24)); iChar <<= 8; } } charCount += fallbackBuffer.InternalFallback(fallbackBytes, bytes); } // Check for overflows. if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_GetByteCountOverflow); // Shouldn't have anything in fallback buffer for GetCharCount // (don't have to check _throwOnOverflow for chars or count) Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetCharCount]Expected empty fallback buffer at end"); // Return our count return charCount; } internal override unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, DecoderNLS baseDecoder) { Debug.Assert(chars != null, "[UTF32Encoding.GetChars]chars!=null"); Debug.Assert(bytes != null, "[UTF32Encoding.GetChars]bytes!=null"); Debug.Assert(byteCount >= 0, "[UTF32Encoding.GetChars]byteCount >=0"); Debug.Assert(charCount >= 0, "[UTF32Encoding.GetChars]charCount >=0"); UTF32Decoder decoder = (UTF32Decoder)baseDecoder; // None so far! char* charStart = chars; char* charEnd = chars + charCount; byte* byteStart = bytes; byte* byteEnd = bytes + byteCount; // See if there's anything in our decoder (but don't clear it yet) int readCount = 0; uint iChar = 0; // For fallback we may need a fallback buffer DecoderFallbackBuffer fallbackBuffer = null; char* charsForFallback; // See if there's anything in our decoder if (decoder != null) { readCount = decoder.readByteCount; iChar = (uint)decoder.iChar; fallbackBuffer = baseDecoder.FallbackBuffer; // Shouldn't have anything in fallback buffer for GetChars // (don't have to check _throwOnOverflow for chars) Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetChars]Expected empty fallback buffer at start"); } else { fallbackBuffer = this.decoderFallback.CreateFallbackBuffer(); } // Set our internal fallback interesting things. fallbackBuffer.InternalInitialize(bytes, chars + charCount); // Loop through our input, 4 characters at a time! while (bytes < byteEnd) { // Get our next character if (_bigEndian) { // Scoot left and add it to the bottom iChar <<= 8; iChar += *(bytes++); } else { // Scoot right and add it to the top iChar >>= 8; iChar += (uint)(*(bytes++)) << 24; } readCount++; // See if we have all the bytes yet if (readCount < 4) continue; // Have the bytes readCount = 0; // See if its valid to encode if (iChar > 0x10FFFF || (iChar >= 0xD800 && iChar <= 0xDFFF)) { // Need to fall back these 4 bytes byte[] fallbackBytes; if (_bigEndian) { fallbackBytes = new byte[] { unchecked((byte)(iChar>>24)), unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>8)), unchecked((byte)(iChar)) }; } else { fallbackBytes = new byte[] { unchecked((byte)(iChar)), unchecked((byte)(iChar>>8)), unchecked((byte)(iChar>>16)), unchecked((byte)(iChar>>24)) }; } // Chars won't be updated unless this works. charsForFallback = chars; bool fallbackResult = fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref charsForFallback); chars = charsForFallback; if (!fallbackResult) { // Couldn't fallback, throw or wait til next time // We either read enough bytes for bytes-=4 to work, or we're // going to throw in ThrowCharsOverflow because chars == charStart Debug.Assert(bytes >= byteStart + 4 || chars == charStart, "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (bad surrogate)"); bytes -= 4; // get back to where we were iChar = 0; // Remembering nothing fallbackBuffer.InternalReset(); ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output break; // Stop here, didn't throw } // Ignore the illegal character iChar = 0; continue; } // Ok, we have something we can add to our output if (iChar >= 0x10000) { // Surrogates take 2 if (chars >= charEnd - 1) { // Throwing or stopping // We either read enough bytes for bytes-=4 to work, or we're // going to throw in ThrowCharsOverflow because chars == charStart Debug.Assert(bytes >= byteStart + 4 || chars == charStart, "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (surrogate)"); bytes -= 4; // get back to where we were iChar = 0; // Remembering nothing ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output break; // Stop here, didn't throw } *(chars++) = GetHighSurrogate(iChar); iChar = GetLowSurrogate(iChar); } // Bounds check for normal character else if (chars >= charEnd) { // Throwing or stopping // We either read enough bytes for bytes-=4 to work, or we're // going to throw in ThrowCharsOverflow because chars == charStart Debug.Assert(bytes >= byteStart + 4 || chars == charStart, "[UTF32Encoding.GetChars]Expected to have consumed bytes or throw (normal char)"); bytes -= 4; // get back to where we were iChar = 0; // Remembering nothing ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output break; // Stop here, didn't throw } // Add the rest of the surrogate or our normal character *(chars++) = (char)iChar; // iChar is back to 0 iChar = 0; } // See if we have something left over that has to be decoded if (readCount > 0 && (decoder == null || decoder.MustFlush)) { // Oops, there's something left over with no place to go. byte[] fallbackBytes = new byte[readCount]; int tempCount = readCount; if (_bigEndian) { while (tempCount > 0) { fallbackBytes[--tempCount] = unchecked((byte)iChar); iChar >>= 8; } } else { while (tempCount > 0) { fallbackBytes[--tempCount] = unchecked((byte)(iChar >> 24)); iChar <<= 8; } } charsForFallback = chars; bool fallbackResult = fallbackBuffer.InternalFallback(fallbackBytes, bytes, ref charsForFallback); chars = charsForFallback; if (!fallbackResult) { // Couldn't fallback. fallbackBuffer.InternalReset(); ThrowCharsOverflow(decoder, chars == charStart);// Might throw, if no chars output // Stop here, didn't throw, backed up, so still nothing in buffer } else { // Don't clear our decoder unless we could fall it back. // If we caught the if above, then we're a convert() and will catch this next time. readCount = 0; iChar = 0; } } // Remember any left over stuff, clearing buffer as well for MustFlush if (decoder != null) { decoder.iChar = (int)iChar; decoder.readByteCount = readCount; decoder._bytesUsed = (int)(bytes - byteStart); } // Shouldn't have anything in fallback buffer for GetChars // (don't have to check _throwOnOverflow for chars) Debug.Assert(fallbackBuffer.Remaining == 0, "[UTF32Encoding.GetChars]Expected empty fallback buffer at end"); // Return our count return (int)(chars - charStart); } private uint GetSurrogate(char cHigh, char cLow) { return (((uint)cHigh - 0xD800) * 0x400) + ((uint)cLow - 0xDC00) + 0x10000; } private char GetHighSurrogate(uint iChar) { return (char)((iChar - 0x10000) / 0x400 + 0xD800); } private char GetLowSurrogate(uint iChar) { return (char)((iChar - 0x10000) % 0x400 + 0xDC00); } public override Decoder GetDecoder() { return new UTF32Decoder(this); } public override Encoder GetEncoder() { return new EncoderNLS(this); } public override int GetMaxByteCount(int charCount) { if (charCount < 0) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_NeedNonNegNum); // Characters would be # of characters + 1 in case left over high surrogate is ? * max fallback long byteCount = (long)charCount + 1; if (EncoderFallback.MaxCharCount > 1) byteCount *= EncoderFallback.MaxCharCount; // 4 bytes per char byteCount *= 4; if (byteCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(charCount), SR.ArgumentOutOfRange_GetByteCountOverflow); return (int)byteCount; } public override int GetMaxCharCount(int byteCount) { if (byteCount < 0) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_NeedNonNegNum); // A supplementary character becomes 2 surrogate characters, so 4 input bytes becomes 2 chars, // plus we may have 1 surrogate char left over if the decoder has 3 bytes in it already for a non-bmp char. // Have to add another one because 1/2 == 0, but 3 bytes left over could be 2 char surrogate pair int charCount = (byteCount / 2) + 2; // Also consider fallback because our input bytes could be out of range of unicode. // Since fallback would fallback 4 bytes at a time, we'll only fall back 1/2 of MaxCharCount. if (DecoderFallback.MaxCharCount > 2) { // Multiply time fallback size charCount *= DecoderFallback.MaxCharCount; // We were already figuring 2 chars per 4 bytes, but fallback will be different # charCount /= 2; } if (charCount > 0x7fffffff) throw new ArgumentOutOfRangeException(nameof(byteCount), SR.ArgumentOutOfRange_GetCharCountOverflow); return (int)charCount; } public override byte[] GetPreamble() { if (_emitUTF32ByteOrderMark) { // Allocate new array to prevent users from modifying it. if (_bigEndian) { return new byte[4] { 0x00, 0x00, 0xFE, 0xFF }; } else { return new byte[4] { 0xFF, 0xFE, 0x00, 0x00 }; // 00 00 FE FF } } else return Array.Empty<byte>(); } public override ReadOnlySpan<byte> Preamble => GetType() != typeof(UTF32Encoding) ? new ReadOnlySpan<byte>(GetPreamble()) : // in case a derived UTF32Encoding overrode GetPreamble !_emitUTF32ByteOrderMark ? default : _bigEndian ? (ReadOnlySpan<byte>)new byte[4] { 0x00, 0x00, 0xFE, 0xFF } : // uses C# compiler's optimization for static byte[] data (ReadOnlySpan<byte>)new byte[4] { 0xFF, 0xFE, 0x00, 0x00 }; public override bool Equals(object value) { if (value is UTF32Encoding that) { return (_emitUTF32ByteOrderMark == that._emitUTF32ByteOrderMark) && (_bigEndian == that._bigEndian) && (EncoderFallback.Equals(that.EncoderFallback)) && (DecoderFallback.Equals(that.DecoderFallback)); } return (false); } public override int GetHashCode() { //Not great distribution, but this is relatively unlikely to be used as the key in a hashtable. return this.EncoderFallback.GetHashCode() + this.DecoderFallback.GetHashCode() + CodePage + (_emitUTF32ByteOrderMark ? 4 : 0) + (_bigEndian ? 8 : 0); } private sealed class UTF32Decoder : DecoderNLS { // Need a place to store any extra bytes we may have picked up internal int iChar = 0; internal int readByteCount = 0; public UTF32Decoder(UTF32Encoding encoding) : base(encoding) { // base calls reset } public override void Reset() { this.iChar = 0; this.readByteCount = 0; if (_fallbackBuffer != null) _fallbackBuffer.Reset(); } // Anything left in our decoder? internal override bool HasState { get { // ReadByteCount is our flag. (iChar==0 doesn't mean much). return (this.readByteCount != 0); } } } } }
#pragma warning disable 1587 #region Header /// /// JsonWriter.cs /// Stream-like facility to output JSON text. /// /// The authors disclaim copyright to this source code. For more details, see /// the COPYING file included with this distribution. /// #endregion using Amazon.Util.Internal; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace ThirdParty.Json.LitJson { internal enum Condition { InArray, InObject, NotAProperty, Property, Value } internal class WriterContext { public int Count; public bool InArray; public bool InObject; public bool ExpectingValue; public int Padding; } internal class JsonWriter { #region Fields private static NumberFormatInfo number_format; private WriterContext context; private Stack<WriterContext> ctx_stack; private bool has_reached_end; private char[] hex_seq; private int indentation; private int indent_value; private StringBuilder inst_string_builder; private bool pretty_print; private bool validate; private TextWriter writer; #endregion #region Properties public int IndentValue { get { return indent_value; } set { indentation = (indentation / indent_value) * value; indent_value = value; } } public bool PrettyPrint { get { return pretty_print; } set { pretty_print = value; } } public TextWriter TextWriter { get { return writer; } } public bool Validate { get { return validate; } set { validate = value; } } #endregion #region Constructors static JsonWriter () { number_format = NumberFormatInfo.InvariantInfo; } public JsonWriter () { inst_string_builder = new StringBuilder (); writer = new StringWriter (inst_string_builder); Init (); } public JsonWriter (StringBuilder sb) : this (new StringWriter (sb)) { } public JsonWriter (TextWriter writer) { if (writer == null) throw new ArgumentNullException ("writer"); this.writer = writer; Init (); } #endregion #region Private Methods private void DoValidation (Condition cond) { if (! context.ExpectingValue) context.Count++; if (! validate) return; if (has_reached_end) throw new JsonException ( "A complete JSON symbol has already been written"); switch (cond) { case Condition.InArray: if (! context.InArray) throw new JsonException ( "Can't close an array here"); break; case Condition.InObject: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't close an object here"); break; case Condition.NotAProperty: if (context.InObject && ! context.ExpectingValue) throw new JsonException ( "Expected a property"); break; case Condition.Property: if (! context.InObject || context.ExpectingValue) throw new JsonException ( "Can't add a property here"); break; case Condition.Value: if (! context.InArray && (! context.InObject || ! context.ExpectingValue)) throw new JsonException ( "Can't add a value here"); break; } } private void Init () { has_reached_end = false; hex_seq = new char[4]; indentation = 0; indent_value = 4; pretty_print = false; validate = true; ctx_stack = new Stack<WriterContext> (); context = new WriterContext (); ctx_stack.Push (context); } private static void IntToHex (int n, char[] hex) { int num; for (int i = 0; i < 4; i++) { num = n % 16; if (num < 10) hex[3 - i] = (char) ('0' + num); else hex[3 - i] = (char) ('A' + (num - 10)); n >>= 4; } } private void Indent () { if (pretty_print) indentation += indent_value; } private void Put (string str) { if (pretty_print && ! context.ExpectingValue) for (int i = 0; i < indentation; i++) writer.Write (' '); writer.Write (str); } private void PutNewline () { PutNewline (true); } private void PutNewline (bool add_comma) { if (add_comma && ! context.ExpectingValue && context.Count > 1) writer.Write (','); if (pretty_print && ! context.ExpectingValue) writer.Write ("\r\n"); } private void PutString (string str) { Put (String.Empty); writer.Write ('"'); int n = str.Length; for (int i = 0; i < n; i++) { char c = str[i]; switch (c) { case '\n': writer.Write ("\\n"); continue; case '\r': writer.Write ("\\r"); continue; case '\t': writer.Write ("\\t"); continue; case '"': case '\\': writer.Write ('\\'); writer.Write (c); continue; case '\f': writer.Write ("\\f"); continue; case '\b': writer.Write ("\\b"); continue; } if ((int) c >= 32 && (int) c <= 126) { writer.Write (c); continue; } if (c < ' ' || (c >= '\u0080' && c < '\u00a0')) { // Turn into a \uXXXX sequence IntToHex((int)c, hex_seq); writer.Write("\\u"); writer.Write(hex_seq); } else { writer.Write(c); } } writer.Write ('"'); } private void Unindent () { if (pretty_print) indentation -= indent_value; } #endregion public override string ToString () { if (inst_string_builder == null) return String.Empty; return inst_string_builder.ToString (); } public void Reset () { has_reached_end = false; ctx_stack.Clear (); context = new WriterContext (); ctx_stack.Push (context); if (inst_string_builder != null) inst_string_builder.Remove (0, inst_string_builder.Length); } public void Write (bool boolean) { DoValidation (Condition.Value); PutNewline (); Put (boolean ? "true" : "false"); context.ExpectingValue = false; } public void Write (decimal number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write (double number) { DoValidation (Condition.Value); PutNewline (); // Modified to support roundtripping of double.MaxValue string str = number.ToString("R", CultureInfo.InvariantCulture); Put (str); if (str.IndexOf ('.') == -1 && str.IndexOf ('E') == -1) writer.Write (".0"); context.ExpectingValue = false; } public void Write (int number) { DoValidation(Condition.Value); PutNewline (); Put(Convert.ToString(number, number_format)); context.ExpectingValue = false; } public void Write(uint number) { DoValidation(Condition.Value); PutNewline(); Put(Convert.ToString(number, number_format)); context.ExpectingValue = false; } public void Write(long number) { DoValidation(Condition.Value); PutNewline(); Put(Convert.ToString(number, number_format)); context.ExpectingValue = false; } public void Write (string str) { DoValidation (Condition.Value); PutNewline (); if (str == null) Put ("null"); else PutString (str); context.ExpectingValue = false; } public void WriteRaw(string str) { DoValidation(Condition.Value); PutNewline(); if (str == null) Put("null"); else Put(str); context.ExpectingValue = false; } public void Write (ulong number) { DoValidation (Condition.Value); PutNewline (); Put (Convert.ToString (number, number_format)); context.ExpectingValue = false; } public void Write(DateTime date) { DoValidation(Condition.Value); PutNewline(); Put(AmazonUtils.ConvertToUnixEpochMilliSeconds(date).ToString(CultureInfo.InvariantCulture)); context.ExpectingValue = false; } public void WriteArrayEnd () { DoValidation (Condition.InArray); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("]"); } public void WriteArrayStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("["); context = new WriterContext (); context.InArray = true; ctx_stack.Push (context); Indent (); } public void WriteObjectEnd () { DoValidation (Condition.InObject); PutNewline (false); ctx_stack.Pop (); if (ctx_stack.Count == 1) has_reached_end = true; else { context = ctx_stack.Peek (); context.ExpectingValue = false; } Unindent (); Put ("}"); } public void WriteObjectStart () { DoValidation (Condition.NotAProperty); PutNewline (); Put ("{"); context = new WriterContext (); context.InObject = true; ctx_stack.Push (context); Indent (); } public void WritePropertyName (string property_name) { DoValidation (Condition.Property); PutNewline (); PutString (property_name); if (pretty_print) { if (property_name.Length > context.Padding) context.Padding = property_name.Length; for (int i = context.Padding - property_name.Length; i >= 0; i--) writer.Write (' '); writer.Write (": "); } else writer.Write (':'); context.ExpectingValue = true; } } }
// 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. // <spec>http://www.w3.org/TR/xpath#exprlex</spec> //------------------------------------------------------------------------------ using System.Diagnostics; namespace System.Xml.Xsl.XPath { // Extends XPathOperator enumeration internal enum LexKind { Unknown, // Unknown lexeme Or, // Operator 'or' And, // Operator 'and' Eq, // Operator '=' Ne, // Operator '!=' Lt, // Operator '<' Le, // Operator '<=' Gt, // Operator '>' Ge, // Operator '>=' Plus, // Operator '+' Minus, // Operator '-' Multiply, // Operator '*' Divide, // Operator 'div' Modulo, // Operator 'mod' UnaryMinus, // Not used Union, // Operator '|' LastOperator = Union, DotDot, // '..' ColonColon, // '::' SlashSlash, // Operator '//' Number, // Number (numeric literal) Axis, // AxisName Name, // NameTest, NodeType, FunctionName, AxisName, second part of VariableReference String, // Literal (string literal) Eof, // End of the expression FirstStringable = Name, LastNonChar = Eof, LParens = '(', RParens = ')', LBracket = '[', RBracket = ']', Dot = '.', At = '@', Comma = ',', Star = '*', // NameTest Slash = '/', // Operator '/' Dollar = '$', // First part of VariableReference RBrace = '}', // Used for AVTs }; internal sealed class XPathScanner { private string _xpathExpr; private int _curIndex; private char _curChar; private LexKind _kind; private string _name; private string _prefix; private string _stringValue; private bool _canBeFunction; private int _lexStart; private int _prevLexEnd; private LexKind _prevKind; private XPathAxis _axis; private XmlCharType _xmlCharType = XmlCharType.Instance; public XPathScanner(string xpathExpr) : this(xpathExpr, 0) { } public XPathScanner(string xpathExpr, int startFrom) { Debug.Assert(xpathExpr != null); _xpathExpr = xpathExpr; _kind = LexKind.Unknown; SetSourceIndex(startFrom); NextLex(); } public string Source { get { return _xpathExpr; } } public LexKind Kind { get { return _kind; } } public int LexStart { get { return _lexStart; } } public int LexSize { get { return _curIndex - _lexStart; } } public int PrevLexEnd { get { return _prevLexEnd; } } private void SetSourceIndex(int index) { Debug.Assert(0 <= index && index <= _xpathExpr.Length); _curIndex = index - 1; NextChar(); } private void NextChar() { Debug.Assert(-1 <= _curIndex && _curIndex < _xpathExpr.Length); _curIndex++; if (_curIndex < _xpathExpr.Length) { _curChar = _xpathExpr[_curIndex]; } else { Debug.Assert(_curIndex == _xpathExpr.Length); _curChar = '\0'; } } #if XML10_FIFTH_EDITION private char PeekNextChar() { Debug.Assert(-1 <= curIndex && curIndex <= xpathExpr.Length); if (curIndex + 1 < xpathExpr.Length) { return xpathExpr[curIndex + 1]; } else { return '\0'; } } #endif public string Name { get { Debug.Assert(_kind == LexKind.Name); Debug.Assert(_name != null); return _name; } } public string Prefix { get { Debug.Assert(_kind == LexKind.Name); Debug.Assert(_prefix != null); return _prefix; } } public string RawValue { get { if (_kind == LexKind.Eof) { return LexKindToString(_kind); } else { return _xpathExpr.Substring(_lexStart, _curIndex - _lexStart); } } } public string StringValue { get { Debug.Assert(_kind == LexKind.String); Debug.Assert(_stringValue != null); return _stringValue; } } // Returns true if the character following an QName (possibly after intervening // ExprWhitespace) is '('. In this case the token must be recognized as a NodeType // or a FunctionName unless it is an OperatorName. This distinction cannot be done // without knowing the previous lexeme. For example, "or" in "... or (1 != 0)" may // be an OperatorName or a FunctionName. public bool CanBeFunction { get { Debug.Assert(_kind == LexKind.Name); return _canBeFunction; } } public XPathAxis Axis { get { Debug.Assert(_kind == LexKind.Axis); Debug.Assert(_axis != XPathAxis.Unknown); return _axis; } } private void SkipSpace() { while (_xmlCharType.IsWhiteSpace(_curChar)) { NextChar(); } } private static bool IsAsciiDigit(char ch) { return unchecked((uint)(ch - '0')) <= 9; } public void NextLex() { _prevLexEnd = _curIndex; _prevKind = _kind; SkipSpace(); _lexStart = _curIndex; switch (_curChar) { case '\0': _kind = LexKind.Eof; return; case '(': case ')': case '[': case ']': case '@': case ',': case '$': case '}': _kind = (LexKind)_curChar; NextChar(); break; case '.': NextChar(); if (_curChar == '.') { _kind = LexKind.DotDot; NextChar(); } else if (IsAsciiDigit(_curChar)) { SetSourceIndex(_lexStart); goto case '0'; } else { _kind = LexKind.Dot; } break; case ':': NextChar(); if (_curChar == ':') { _kind = LexKind.ColonColon; NextChar(); } else { _kind = LexKind.Unknown; } break; case '*': _kind = LexKind.Star; NextChar(); CheckOperator(true); break; case '/': NextChar(); if (_curChar == '/') { _kind = LexKind.SlashSlash; NextChar(); } else { _kind = LexKind.Slash; } break; case '|': _kind = LexKind.Union; NextChar(); break; case '+': _kind = LexKind.Plus; NextChar(); break; case '-': _kind = LexKind.Minus; NextChar(); break; case '=': _kind = LexKind.Eq; NextChar(); break; case '!': NextChar(); if (_curChar == '=') { _kind = LexKind.Ne; NextChar(); } else { _kind = LexKind.Unknown; } break; case '<': NextChar(); if (_curChar == '=') { _kind = LexKind.Le; NextChar(); } else { _kind = LexKind.Lt; } break; case '>': NextChar(); if (_curChar == '=') { _kind = LexKind.Ge; NextChar(); } else { _kind = LexKind.Gt; } break; case '"': case '\'': _kind = LexKind.String; ScanString(); break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': _kind = LexKind.Number; ScanNumber(); break; default: if (_xmlCharType.IsStartNCNameSingleChar(_curChar) #if XML10_FIFTH_EDITION || xmlCharType.IsNCNameHighSurrogateChar(curChar) #endif ) { _kind = LexKind.Name; _name = ScanNCName(); _prefix = string.Empty; _canBeFunction = false; _axis = XPathAxis.Unknown; bool colonColon = false; int saveSourceIndex = _curIndex; // "foo:bar" or "foo:*" -- one lexeme (no spaces allowed) // "foo::" or "foo ::" -- two lexemes, reported as one (AxisName) // "foo:?" or "foo :?" -- lexeme "foo" reported if (_curChar == ':') { NextChar(); if (_curChar == ':') { // "foo::" -> OperatorName, AxisName NextChar(); colonColon = true; SetSourceIndex(saveSourceIndex); } else { // "foo:bar", "foo:*" or "foo:?" if (_curChar == '*') { NextChar(); _prefix = _name; _name = "*"; } else if (_xmlCharType.IsStartNCNameSingleChar(_curChar) #if XML10_FIFTH_EDITION || xmlCharType.IsNCNameHighSurrogateChar(curChar) #endif ) { _prefix = _name; _name = ScanNCName(); // Look ahead for '(' to determine whether QName can be a FunctionName saveSourceIndex = _curIndex; SkipSpace(); _canBeFunction = (_curChar == '('); SetSourceIndex(saveSourceIndex); } else { // "foo:?" -> OperatorName, NameTest // Return "foo" and leave ":" to be reported later as an unknown lexeme SetSourceIndex(saveSourceIndex); } } } else { SkipSpace(); if (_curChar == ':') { // "foo ::" or "foo :?" NextChar(); if (_curChar == ':') { NextChar(); colonColon = true; } SetSourceIndex(saveSourceIndex); } else { _canBeFunction = (_curChar == '('); } } if (!CheckOperator(false) && colonColon) { _axis = CheckAxis(); } } else { _kind = LexKind.Unknown; NextChar(); } break; } } private bool CheckOperator(bool star) { LexKind opKind; if (star) { opKind = LexKind.Multiply; } else { if (_prefix.Length != 0 || _name.Length > 3) return false; switch (_name) { case "or": opKind = LexKind.Or; break; case "and": opKind = LexKind.And; break; case "div": opKind = LexKind.Divide; break; case "mod": opKind = LexKind.Modulo; break; default: return false; } } // If there is a preceding token and the preceding token is not one of '@', '::', '(', '[', ',' or an Operator, // then a '*' must be recognized as a MultiplyOperator and an NCName must be recognized as an OperatorName. if (_prevKind <= LexKind.LastOperator) return false; switch (_prevKind) { case LexKind.Slash: case LexKind.SlashSlash: case LexKind.At: case LexKind.ColonColon: case LexKind.LParens: case LexKind.LBracket: case LexKind.Comma: case LexKind.Dollar: return false; } _kind = opKind; return true; } private XPathAxis CheckAxis() { _kind = LexKind.Axis; switch (_name) { case "ancestor": return XPathAxis.Ancestor; case "ancestor-or-self": return XPathAxis.AncestorOrSelf; case "attribute": return XPathAxis.Attribute; case "child": return XPathAxis.Child; case "descendant": return XPathAxis.Descendant; case "descendant-or-self": return XPathAxis.DescendantOrSelf; case "following": return XPathAxis.Following; case "following-sibling": return XPathAxis.FollowingSibling; case "namespace": return XPathAxis.Namespace; case "parent": return XPathAxis.Parent; case "preceding": return XPathAxis.Preceding; case "preceding-sibling": return XPathAxis.PrecedingSibling; case "self": return XPathAxis.Self; default: _kind = LexKind.Name; return XPathAxis.Unknown; } } private void ScanNumber() { Debug.Assert(IsAsciiDigit(_curChar) || _curChar == '.'); while (IsAsciiDigit(_curChar)) { NextChar(); } if (_curChar == '.') { NextChar(); while (IsAsciiDigit(_curChar)) { NextChar(); } } if ((_curChar & (~0x20)) == 'E') { NextChar(); if (_curChar == '+' || _curChar == '-') { NextChar(); } while (IsAsciiDigit(_curChar)) { NextChar(); } throw CreateException(SR.XPath_ScientificNotation); } } private void ScanString() { int startIdx = _curIndex + 1; int endIdx = _xpathExpr.IndexOf(_curChar, startIdx); if (endIdx < 0) { SetSourceIndex(_xpathExpr.Length); throw CreateException(SR.XPath_UnclosedString); } _stringValue = _xpathExpr.Substring(startIdx, endIdx - startIdx); SetSourceIndex(endIdx + 1); } private string ScanNCName() { Debug.Assert(_xmlCharType.IsStartNCNameSingleChar(_curChar) #if XML10_FIFTH_EDITION || xmlCharType.IsNCNameHighSurrogateChar(curChar) #endif ); int start = _curIndex; for (;;) { if (_xmlCharType.IsNCNameSingleChar(_curChar)) { NextChar(); } #if XML10_FIFTH_EDITION else if (xmlCharType.IsNCNameSurrogateChar(PeekNextChar(), curChar)) { NextChar(); NextChar(); } #endif else { break; } } return _xpathExpr.Substring(start, _curIndex - start); } public void PassToken(LexKind t) { CheckToken(t); NextLex(); } public void CheckToken(LexKind t) { Debug.Assert(LexKind.FirstStringable <= t); if (_kind != t) { if (t == LexKind.Eof) { throw CreateException(SR.XPath_EofExpected, RawValue); } else { throw CreateException(SR.XPath_TokenExpected, LexKindToString(t), RawValue); } } } // May be called for the following tokens: Name, String, Eof, Comma, LParens, RParens, LBracket, RBracket, RBrace private string LexKindToString(LexKind t) { Debug.Assert(LexKind.FirstStringable <= t); if (LexKind.LastNonChar < t) { Debug.Assert("()[].@,*/$}".IndexOf((char)t) >= 0); return new String((char)t, 1); } switch (t) { case LexKind.Name: return "<name>"; case LexKind.String: return "<string literal>"; case LexKind.Eof: return "<eof>"; default: Debug.Fail("Unexpected LexKind: " + t.ToString()); return string.Empty; } } public XPathCompileException CreateException(string resId, params string[] args) { return new XPathCompileException(_xpathExpr, _lexStart, _curIndex, resId, args); } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type WorkbookChartLegendRequest. /// </summary> public partial class WorkbookChartLegendRequest : BaseRequest, IWorkbookChartLegendRequest { /// <summary> /// Constructs a new WorkbookChartLegendRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public WorkbookChartLegendRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified WorkbookChartLegend using POST. /// </summary> /// <param name="workbookChartLegendToCreate">The WorkbookChartLegend to create.</param> /// <returns>The created WorkbookChartLegend.</returns> public System.Threading.Tasks.Task<WorkbookChartLegend> CreateAsync(WorkbookChartLegend workbookChartLegendToCreate) { return this.CreateAsync(workbookChartLegendToCreate, CancellationToken.None); } /// <summary> /// Creates the specified WorkbookChartLegend using POST. /// </summary> /// <param name="workbookChartLegendToCreate">The WorkbookChartLegend to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created WorkbookChartLegend.</returns> public async System.Threading.Tasks.Task<WorkbookChartLegend> CreateAsync(WorkbookChartLegend workbookChartLegendToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<WorkbookChartLegend>(workbookChartLegendToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified WorkbookChartLegend. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified WorkbookChartLegend. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<WorkbookChartLegend>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified WorkbookChartLegend. /// </summary> /// <returns>The WorkbookChartLegend.</returns> public System.Threading.Tasks.Task<WorkbookChartLegend> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified WorkbookChartLegend. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The WorkbookChartLegend.</returns> public async System.Threading.Tasks.Task<WorkbookChartLegend> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<WorkbookChartLegend>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified WorkbookChartLegend using PATCH. /// </summary> /// <param name="workbookChartLegendToUpdate">The WorkbookChartLegend to update.</param> /// <returns>The updated WorkbookChartLegend.</returns> public System.Threading.Tasks.Task<WorkbookChartLegend> UpdateAsync(WorkbookChartLegend workbookChartLegendToUpdate) { return this.UpdateAsync(workbookChartLegendToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified WorkbookChartLegend using PATCH. /// </summary> /// <param name="workbookChartLegendToUpdate">The WorkbookChartLegend to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated WorkbookChartLegend.</returns> public async System.Threading.Tasks.Task<WorkbookChartLegend> UpdateAsync(WorkbookChartLegend workbookChartLegendToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<WorkbookChartLegend>(workbookChartLegendToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartLegendRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartLegendRequest Expand(Expression<Func<WorkbookChartLegend, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartLegendRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IWorkbookChartLegendRequest Select(Expression<Func<WorkbookChartLegend, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="workbookChartLegendToInitialize">The <see cref="WorkbookChartLegend"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(WorkbookChartLegend workbookChartLegendToInitialize) { } } }
// dnlib: See LICENSE.txt for more info using System; using System.Diagnostics; using System.Threading; using dnlib.Utils; using dnlib.DotNet.MD; using dnlib.DotNet.Pdb; using System.Collections.Generic; namespace dnlib.DotNet { /// <summary> /// A high-level representation of a row in the GenericParam table /// </summary> [DebuggerDisplay("{Name.String}")] public abstract class GenericParam : IHasCustomAttribute, IHasCustomDebugInformation, IMemberDef, IListListener<GenericParamConstraint> { /// <summary> /// The row id in its table /// </summary> protected uint rid; /// <inheritdoc/> public MDToken MDToken => new MDToken(Table.GenericParam, rid); /// <inheritdoc/> public uint Rid { get => rid; set => rid = value; } /// <inheritdoc/> public int HasCustomAttributeTag => 19; /// <summary> /// Gets the owner type/method /// </summary> public ITypeOrMethodDef Owner { get => owner; internal set => owner = value; } /// <summary/> protected ITypeOrMethodDef owner; /// <summary> /// Gets the declaring type or <c>null</c> if none or if <see cref="Owner"/> is /// not a <see cref="TypeDef"/> /// </summary> public TypeDef DeclaringType => owner as TypeDef; /// <inheritdoc/> ITypeDefOrRef IMemberRef.DeclaringType => owner as TypeDef; /// <summary> /// Gets the declaring method or <c>null</c> if none or if <see cref="Owner"/> is /// not a <see cref="MethodDef"/> /// </summary> public MethodDef DeclaringMethod => owner as MethodDef; /// <summary> /// From column GenericParam.Number /// </summary> public ushort Number { get => number; set => number = value; } /// <summary/> protected ushort number; /// <summary> /// From column GenericParam.Flags /// </summary> public GenericParamAttributes Flags { get => (GenericParamAttributes)attributes; set => attributes = (int)value; } /// <summary>Attributes</summary> protected int attributes; /// <summary> /// From column GenericParam.Name /// </summary> public UTF8String Name { get => name; set => name = value; } /// <summary>Name</summary> protected UTF8String name; /// <summary> /// From column GenericParam.Kind (v1.1 only) /// </summary> public ITypeDefOrRef Kind { get => kind; set => kind = value; } /// <summary/> protected ITypeDefOrRef kind; /// <summary> /// Gets the generic param constraints /// </summary> public IList<GenericParamConstraint> GenericParamConstraints { get { if (genericParamConstraints is null) InitializeGenericParamConstraints(); return genericParamConstraints; } } /// <summary/> protected LazyList<GenericParamConstraint> genericParamConstraints; /// <summary>Initializes <see cref="genericParamConstraints"/></summary> protected virtual void InitializeGenericParamConstraints() => Interlocked.CompareExchange(ref genericParamConstraints, new LazyList<GenericParamConstraint>(this), null); /// <summary> /// Gets all custom attributes /// </summary> public CustomAttributeCollection CustomAttributes { get { if (customAttributes is null) InitializeCustomAttributes(); return customAttributes; } } /// <summary/> protected CustomAttributeCollection customAttributes; /// <summary>Initializes <see cref="customAttributes"/></summary> protected virtual void InitializeCustomAttributes() => Interlocked.CompareExchange(ref customAttributes, new CustomAttributeCollection(), null); /// <inheritdoc/> public bool HasCustomAttributes => CustomAttributes.Count > 0; /// <inheritdoc/> public int HasCustomDebugInformationTag => 19; /// <inheritdoc/> public bool HasCustomDebugInfos => CustomDebugInfos.Count > 0; /// <summary> /// Gets all custom debug infos /// </summary> public IList<PdbCustomDebugInfo> CustomDebugInfos { get { if (customDebugInfos is null) InitializeCustomDebugInfos(); return customDebugInfos; } } /// <summary/> protected IList<PdbCustomDebugInfo> customDebugInfos; /// <summary>Initializes <see cref="customDebugInfos"/></summary> protected virtual void InitializeCustomDebugInfos() => Interlocked.CompareExchange(ref customDebugInfos, new List<PdbCustomDebugInfo>(), null); /// <summary> /// <c>true</c> if <see cref="GenericParamConstraints"/> is not empty /// </summary> public bool HasGenericParamConstraints => GenericParamConstraints.Count > 0; /// <inheritdoc/> public ModuleDef Module => owner?.Module; /// <inheritdoc/> public string FullName => UTF8String.ToSystemStringOrEmpty(name); bool IIsTypeOrMethod.IsType => false; bool IIsTypeOrMethod.IsMethod => false; bool IMemberRef.IsField => false; bool IMemberRef.IsTypeSpec => false; bool IMemberRef.IsTypeRef => false; bool IMemberRef.IsTypeDef => false; bool IMemberRef.IsMethodSpec => false; bool IMemberRef.IsMethodDef => false; bool IMemberRef.IsMemberRef => false; bool IMemberRef.IsFieldDef => false; bool IMemberRef.IsPropertyDef => false; bool IMemberRef.IsEventDef => false; bool IMemberRef.IsGenericParam => true; /// <summary> /// Modify <see cref="attributes"/> property: <see cref="attributes"/> = /// (<see cref="attributes"/> &amp; <paramref name="andMask"/>) | <paramref name="orMask"/>. /// </summary> /// <param name="andMask">Value to <c>AND</c></param> /// <param name="orMask">Value to OR</param> void ModifyAttributes(GenericParamAttributes andMask, GenericParamAttributes orMask) => attributes = (attributes & (int)andMask) | (int)orMask; /// <summary> /// Set or clear flags in <see cref="attributes"/> /// </summary> /// <param name="set"><c>true</c> if flags should be set, <c>false</c> if flags should /// be cleared</param> /// <param name="flags">Flags to set or clear</param> void ModifyAttributes(bool set, GenericParamAttributes flags) { if (set) attributes |= (int)flags; else attributes &= ~(int)flags; } /// <summary> /// Gets/sets variance (non, contra, co) /// </summary> public GenericParamAttributes Variance { get => (GenericParamAttributes)attributes & GenericParamAttributes.VarianceMask; set => ModifyAttributes(~GenericParamAttributes.VarianceMask, value & GenericParamAttributes.VarianceMask); } /// <summary> /// <c>true</c> if <see cref="GenericParamAttributes.NonVariant"/> is set /// </summary> public bool IsNonVariant => Variance == GenericParamAttributes.NonVariant; /// <summary> /// <c>true</c> if <see cref="GenericParamAttributes.Covariant"/> is set /// </summary> public bool IsCovariant => Variance == GenericParamAttributes.Covariant; /// <summary> /// <c>true</c> if <see cref="GenericParamAttributes.Contravariant"/> is set /// </summary> public bool IsContravariant => Variance == GenericParamAttributes.Contravariant; /// <summary> /// Gets/sets the special constraint /// </summary> public GenericParamAttributes SpecialConstraint { get => (GenericParamAttributes)attributes & GenericParamAttributes.SpecialConstraintMask; set => ModifyAttributes(~GenericParamAttributes.SpecialConstraintMask, value & GenericParamAttributes.SpecialConstraintMask); } /// <summary> /// <c>true</c> if there are no special constraints /// </summary> public bool HasNoSpecialConstraint => ((GenericParamAttributes)attributes & GenericParamAttributes.SpecialConstraintMask) == GenericParamAttributes.NoSpecialConstraint; /// <summary> /// Gets/sets the <see cref="GenericParamAttributes.ReferenceTypeConstraint"/> bit /// </summary> public bool HasReferenceTypeConstraint { get => ((GenericParamAttributes)attributes & GenericParamAttributes.ReferenceTypeConstraint) != 0; set => ModifyAttributes(value, GenericParamAttributes.ReferenceTypeConstraint); } /// <summary> /// Gets/sets the <see cref="GenericParamAttributes.NotNullableValueTypeConstraint"/> bit /// </summary> public bool HasNotNullableValueTypeConstraint { get => ((GenericParamAttributes)attributes & GenericParamAttributes.NotNullableValueTypeConstraint) != 0; set => ModifyAttributes(value, GenericParamAttributes.NotNullableValueTypeConstraint); } /// <summary> /// Gets/sets the <see cref="GenericParamAttributes.DefaultConstructorConstraint"/> bit /// </summary> public bool HasDefaultConstructorConstraint { get => ((GenericParamAttributes)attributes & GenericParamAttributes.DefaultConstructorConstraint) != 0; set => ModifyAttributes(value, GenericParamAttributes.DefaultConstructorConstraint); } /// <inheritdoc/> void IListListener<GenericParamConstraint>.OnLazyAdd(int index, ref GenericParamConstraint value) => OnLazyAdd2(index, ref value); internal virtual void OnLazyAdd2(int index, ref GenericParamConstraint value) { #if DEBUG if (value.Owner != this) throw new InvalidOperationException("Added generic param constraint's Owner != this"); #endif } /// <inheritdoc/> void IListListener<GenericParamConstraint>.OnAdd(int index, GenericParamConstraint value) { if (value.Owner is not null) throw new InvalidOperationException("Generic param constraint is already owned by another generic param. Set Owner to null first."); value.Owner = this; } /// <inheritdoc/> void IListListener<GenericParamConstraint>.OnRemove(int index, GenericParamConstraint value) => value.Owner = null; /// <inheritdoc/> void IListListener<GenericParamConstraint>.OnResize(int index) { } /// <inheritdoc/> void IListListener<GenericParamConstraint>.OnClear() { foreach (var gpc in genericParamConstraints.GetEnumerable_NoLock()) gpc.Owner = null; } /// <inheritdoc/> public override string ToString() { var o = owner; if (o is TypeDef) return $"!{number}"; if (o is MethodDef) return $"!!{number}"; return $"??{number}"; } } /// <summary> /// A GenericParam row created by the user and not present in the original .NET file /// </summary> public class GenericParamUser : GenericParam { /// <summary> /// Default constructor /// </summary> public GenericParamUser() { } /// <summary> /// Constructor /// </summary> /// <param name="number">The generic param number</param> public GenericParamUser(ushort number) : this(number, 0) { } /// <summary> /// Constructor /// </summary> /// <param name="number">The generic param number</param> /// <param name="flags">Flags</param> public GenericParamUser(ushort number, GenericParamAttributes flags) : this(number, flags, UTF8String.Empty) { } /// <summary> /// Constructor /// </summary> /// <param name="number">The generic param number</param> /// <param name="flags">Flags</param> /// <param name="name">Name</param> public GenericParamUser(ushort number, GenericParamAttributes flags, UTF8String name) { genericParamConstraints = new LazyList<GenericParamConstraint>(this); this.number = number; attributes = (int)flags; this.name = name; } } /// <summary> /// Created from a row in the GenericParam table /// </summary> sealed class GenericParamMD : GenericParam, IMDTokenProviderMD { /// <summary>The module where this instance is located</summary> readonly ModuleDefMD readerModule; readonly uint origRid; /// <inheritdoc/> public uint OrigRid => origRid; /// <inheritdoc/> protected override void InitializeCustomAttributes() { var list = readerModule.Metadata.GetCustomAttributeRidList(Table.GenericParam, origRid); var tmp = new CustomAttributeCollection(list.Count, list, (list2, index) => readerModule.ReadCustomAttribute(list[index])); Interlocked.CompareExchange(ref customAttributes, tmp, null); } /// <inheritdoc/> protected override void InitializeCustomDebugInfos() { var list = new List<PdbCustomDebugInfo>(); readerModule.InitializeCustomDebugInfos(new MDToken(MDToken.Table, origRid), GetGenericParamContext(owner), list); Interlocked.CompareExchange(ref customDebugInfos, list, null); } /// <inheritdoc/> protected override void InitializeGenericParamConstraints() { var list = readerModule.Metadata.GetGenericParamConstraintRidList(origRid); var tmp = new LazyList<GenericParamConstraint, RidList>(list.Count, this, list, (list2, index) => readerModule.ResolveGenericParamConstraint(list2[index], GetGenericParamContext(owner))); Interlocked.CompareExchange(ref genericParamConstraints, tmp, null); } static GenericParamContext GetGenericParamContext(ITypeOrMethodDef tmOwner) { if (tmOwner is MethodDef md) return GenericParamContext.Create(md); return new GenericParamContext(tmOwner as TypeDef); } /// <summary> /// Constructor /// </summary> /// <param name="readerModule">The module which contains this <c>GenericParam</c> row</param> /// <param name="rid">Row ID</param> /// <exception cref="ArgumentNullException">If <paramref name="readerModule"/> is <c>null</c></exception> /// <exception cref="ArgumentException">If <paramref name="rid"/> is invalid</exception> public GenericParamMD(ModuleDefMD readerModule, uint rid) { #if DEBUG if (readerModule is null) throw new ArgumentNullException("readerModule"); if (readerModule.TablesStream.GenericParamTable.IsInvalidRID(rid)) throw new BadImageFormatException($"GenericParam rid {rid} does not exist"); #endif origRid = rid; this.rid = rid; this.readerModule = readerModule; bool b = readerModule.TablesStream.TryReadGenericParamRow(origRid, out var row); Debug.Assert(b); number = row.Number; attributes = row.Flags; name = readerModule.StringsStream.ReadNoNull(row.Name); owner = readerModule.GetOwner(this); if (row.Kind != 0) kind = readerModule.ResolveTypeDefOrRef(row.Kind, GetGenericParamContext(owner)); } internal GenericParamMD InitializeAll() { MemberMDInitializer.Initialize(Owner); MemberMDInitializer.Initialize(Number); MemberMDInitializer.Initialize(Flags); MemberMDInitializer.Initialize(Name); MemberMDInitializer.Initialize(Kind); MemberMDInitializer.Initialize(CustomAttributes); MemberMDInitializer.Initialize(GenericParamConstraints); return this; } /// <inheritdoc/> internal override void OnLazyAdd2(int index, ref GenericParamConstraint value) { if (value.Owner != this) { // More than one owner... This module has invalid metadata. value = readerModule.ForceUpdateRowId(readerModule.ReadGenericParamConstraint(value.Rid, GetGenericParamContext(owner)).InitializeAll()); value.Owner = this; } } } }
// 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.Text; using System.Threading; using System.Collections.Generic; using Xunit; namespace System.Diagnostics.Tests { [SkipOnTargetFramework(TargetFrameworkMonikers.UapNotUapAot, "https://github.com/dotnet/corefx/issues/22174")] public class ProcessStreamReadTests : ProcessTestBase { [Fact] public void TestSyncErrorStream() { Process p = CreateProcess(ErrorProcessBody); p.StartInfo.RedirectStandardError = true; p.Start(); string expected = TestConsoleApp + " started error stream" + Environment.NewLine + TestConsoleApp + " closed error stream" + Environment.NewLine; Assert.Equal(expected, p.StandardError.ReadToEnd()); Assert.True(p.WaitForExit(WaitInMS)); } [Fact] public void TestAsyncErrorStream() { for (int i = 0; i < 2; ++i) { StringBuilder sb = new StringBuilder(); Process p = CreateProcess(ErrorProcessBody); p.StartInfo.RedirectStandardError = true; p.ErrorDataReceived += (s, e) => { sb.Append(e.Data); if (i == 1) { ((Process)s).CancelErrorRead(); } }; p.Start(); p.BeginErrorReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. string expected = TestConsoleApp + " started error stream" + (i == 1 ? "" : TestConsoleApp + " closed error stream"); Assert.Equal(expected, sb.ToString()); } } private static int ErrorProcessBody() { Console.Error.WriteLine(TestConsoleApp + " started error stream"); Console.Error.WriteLine(TestConsoleApp + " closed error stream"); return SuccessExitCode; } [Fact] public void TestSyncOutputStream() { Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.Start(); string s = p.StandardOutput.ReadToEnd(); Assert.True(p.WaitForExit(WaitInMS)); Assert.Equal(TestConsoleApp + " started" + Environment.NewLine + TestConsoleApp + " closed" + Environment.NewLine, s); } [Fact] public void TestAsyncOutputStream() { for (int i = 0; i < 2; ++i) { StringBuilder sb = new StringBuilder(); Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (s, e) => { sb.Append(e.Data); if (i == 1) { ((Process)s).CancelOutputRead(); } }; p.Start(); p.BeginOutputReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. string expected = TestConsoleApp + " started" + (i == 1 ? "" : TestConsoleApp + " closed"); Assert.Equal(expected, sb.ToString()); } } private static int StreamBody() { Console.WriteLine(TestConsoleApp + " started"); Console.WriteLine(TestConsoleApp + " closed"); return SuccessExitCode; } [Fact] public void TestSyncStreams() { const string expected = "This string should come as output"; Process p = CreateProcess(() => { Console.ReadLine(); return SuccessExitCode; }); p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (s, e) => { Assert.Equal(expected, e.Data); }; p.Start(); using (StreamWriter writer = p.StandardInput) { writer.WriteLine(expected); } Assert.True(p.WaitForExit(WaitInMS)); } [Fact] public void TestEOFReceivedWhenStdInClosed() { // This is the test for the fix of dotnet/corefx issue #13447. // // Summary of the issue: // When an application starts more than one child processes with their standard inputs redirected on Unix, // closing the standard input stream of the first child process won't unblock the 'Console.ReadLine()' call // in the first child process (it's expected to receive EOF). // // Root cause of the issue: // The file descriptor for the write end of the first child process standard input redirection pipe gets // inherited by the second child process, which makes the reference count of the pipe write end become 2. // When closing the standard input stream of the first child process, the file descriptor held by the parent // process is released, but the one inherited by the second child process is still referencing the pipe // write end, which cause the 'Console.ReadLine()' continue to be blocked in the first child process. // // Fix: // Set the O_CLOEXEC flag when creating the redirection pipes. So that no child process would inherit the // file descriptors referencing those pipes. const string ExpectedLine = "NULL"; Process p1 = CreateProcess(() => { string line = Console.ReadLine(); Console.WriteLine(line == null ? ExpectedLine : "NOT_" + ExpectedLine); return SuccessExitCode; }); Process p2 = CreateProcess(() => { Console.ReadLine(); return SuccessExitCode; }); // Start the first child process p1.StartInfo.RedirectStandardInput = true; p1.StartInfo.RedirectStandardOutput = true; p1.OutputDataReceived += (s, e) => Assert.Equal(ExpectedLine, e.Data); p1.Start(); // Start the second child process p2.StartInfo.RedirectStandardInput = true; p2.Start(); try { // Close the standard input stream of the first child process. // The first child process should be unblocked and write out 'NULL', and then exit. p1.StandardInput.Close(); Assert.True(p1.WaitForExit(WaitInMS)); } finally { // Cleanup: kill the second child process p2.Kill(); } // Cleanup Assert.True(p2.WaitForExit(WaitInMS)); p2.Dispose(); p1.Dispose(); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "There is 2 bugs in Desktop in this codepath, see: dotnet/corefx #18437 and #18436")] public void TestAsyncHalfCharacterAtATime() { var receivedOutput = false; var collectedExceptions = new List<Exception>(); Process p = CreateProcess(() => { var stdout = Console.OpenStandardOutput(); var bytes = new byte[] { 97, 0 }; //Encoding.Unicode.GetBytes("a"); for (int i = 0; i != bytes.Length; ++i) { stdout.WriteByte(bytes[i]); stdout.Flush(); Thread.Sleep(100); } return SuccessExitCode; }); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.StandardOutputEncoding = Encoding.Unicode; p.OutputDataReceived += (s, e) => { try { if (!receivedOutput) { receivedOutput = true; Assert.Equal(e.Data, "a"); } } catch (Exception ex) { // This ensures that the exception in event handlers does not break // the whole unittest collectedExceptions.Add(ex); } }; p.Start(); p.BeginOutputReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. Assert.True(receivedOutput); if (collectedExceptions.Count > 0) { // Re-throw collected exceptions throw new AggregateException(collectedExceptions); } } [Fact] public void TestManyOutputLines() { const int ExpectedLineCount = 144; int nonWhitespaceLinesReceived = 0; int totalLinesReceived = 0; Process p = CreateProcess(() => { for (int i = 0; i < ExpectedLineCount; i++) { Console.WriteLine("This is line #" + i + "."); } return SuccessExitCode; }); p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (s, e) => { if (!string.IsNullOrWhiteSpace(e.Data)) { nonWhitespaceLinesReceived++; } totalLinesReceived++; }; p.Start(); p.BeginOutputReadLine(); Assert.True(p.WaitForExit(WaitInMS)); p.WaitForExit(); // This ensures async event handlers are finished processing. Assert.Equal(ExpectedLineCount, nonWhitespaceLinesReceived); Assert.Equal(ExpectedLineCount + 1, totalLinesReceived); } [Fact] public void TestStreamNegativeTests() { { Process p = new Process(); Assert.Throws<InvalidOperationException>(() => p.StandardOutput); Assert.Throws<InvalidOperationException>(() => p.StandardError); Assert.Throws<InvalidOperationException>(() => p.BeginOutputReadLine()); Assert.Throws<InvalidOperationException>(() => p.BeginErrorReadLine()); Assert.Throws<InvalidOperationException>(() => p.CancelOutputRead()); Assert.Throws<InvalidOperationException>(() => p.CancelErrorRead()); } { Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.OutputDataReceived += (s, e) => {}; p.ErrorDataReceived += (s, e) => {}; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); Assert.Throws<InvalidOperationException>(() => p.StandardOutput); Assert.Throws<InvalidOperationException>(() => p.StandardError); Assert.True(p.WaitForExit(WaitInMS)); } { Process p = CreateProcess(StreamBody); p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.OutputDataReceived += (s, e) => {}; p.ErrorDataReceived += (s, e) => {}; p.Start(); StreamReader output = p.StandardOutput; StreamReader error = p.StandardError; Assert.Throws<InvalidOperationException>(() => p.BeginOutputReadLine()); Assert.Throws<InvalidOperationException>(() => p.BeginErrorReadLine()); Assert.True(p.WaitForExit(WaitInMS)); } } } }
// // Puller.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2014 Xamarin Inc // Copyright (c) 2014 .NET Foundation // // 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. // // // Copyright (c) 2014 Couchbase, 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 System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Text; using System.Threading; using System.Threading.Tasks; using Couchbase.Lite; using Couchbase.Lite.Internal; using Couchbase.Lite.Replicator; using Couchbase.Lite.Support; using Couchbase.Lite.Util; using Couchbase.Lite.Revisions; #if !NET_3_5 using System.Net; using StringEx = System.String; #else using System.Net.Couchbase; #endif namespace Couchbase.Lite.Replicator { internal sealed class Puller : Replication, IChangeTrackerClient { #region Constants // Maximum number of revision IDs to pass in an "?atts_since=" query param internal const int MaxAttsSince = 10; internal const int CHANGE_TRACKER_RESTART_DELAY_MS = 10000; private const string TAG = "Puller"; #endregion #region Variables private bool _caughtUp; private bool _canBulkGet; private Batcher<RevisionInternal> _downloadsToInsert; private IList<RevisionInternal> _revsToPull; private IList<RevisionInternal> _deletedRevsToPull; private IList<RevisionInternal> _bulkRevsToPull; private ChangeTracker _changeTracker; private SequenceMap _pendingSequences; private readonly object _locker = new object (); #endregion #region Properties protected override bool IsSafeToStop { get { return (Batcher == null || Batcher.Count() == 0) && (Continuous || _changeTracker != null && !_changeTracker.IsRunning); } } #endregion #region Constructors internal Puller(Database db, Uri remote, bool continuous, TaskFactory workExecutor) : this(db, remote, continuous, null, workExecutor) { } internal Puller(Database db, Uri remote, bool continuous, IHttpClientFactory clientFactory, TaskFactory workExecutor) : base(db, remote, continuous, clientFactory, workExecutor) { } #endregion #region Private Methods private void PauseOrResume() { var pending = 0; if(Batcher != null) { pending += Batcher.Count(); } if(_pendingSequences != null) { pending += _pendingSequences.Count; } if(_changeTracker != null) { #if __IOS__ || __ANDROID__ || UNITY _changeTracker.Paused = pending >= 200; #else _changeTracker.Paused = pending >= 2000; #endif } } private void StartChangeTracker() { var mode = ChangeTrackerMode.OneShot; var pollInterval = ReplicationOptions.PollInterval; if (Continuous && pollInterval == TimeSpan.Zero && ReplicationOptions.UseWebSocket) { mode = ChangeTrackerMode.WebSocket; } _canBulkGet = mode == ChangeTrackerMode.WebSocket; Log.To.Sync.V(TAG, "{0} starting ChangeTracker: mode={0} since={1}", this, mode, LastSequence); var initialSync = LocalDatabase.IsOpen && LocalDatabase.GetDocumentCount() == 0; var changeTrackerOptions = new ChangeTrackerOptions { DatabaseUri = RemoteUrl, Mode = mode, IncludeConflicts = true, LastSequenceID = LastSequence, Client = this, RemoteSession = _remoteSession, RetryStrategy = ReplicationOptions.RetryStrategy, WorkExecutor = WorkExecutor, UsePost = CheckServerCompatVersion("0.9.3") }; _changeTracker = ChangeTrackerFactory.Create(changeTrackerOptions); _changeTracker.ActiveOnly = initialSync; _changeTracker.Continuous = Continuous; _changeTracker.PollInterval = pollInterval; _changeTracker.Heartbeat = ReplicationOptions.Heartbeat; if(DocIds != null) { if(ServerType != null && ServerType.Name == "CouchDB") { _changeTracker.DocIDs = DocIds.ToList(); } else { Log.To.Sync.W(TAG, "DocIds parameter only supported on CouchDB"); } } if (Filter != null) { _changeTracker.FilterName = Filter; if (FilterParams != null) { _changeTracker.FilterParameters = FilterParams.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); } } _changeTracker.Start(); } private void ProcessChangeTrackerStopped(ChangeTracker tracker, ErrorResolution resolution) { var webSocketTracker = tracker as WebSocketChangeTracker; if (webSocketTracker != null && !webSocketTracker.CanConnect) { ReplicationOptions.UseWebSocket = false; _canBulkGet = false; Log.To.Sync.I(TAG, "Server doesn't support web socket changes feed, switching " + "to regular HTTP"); StartChangeTracker(); return; } Log.To.Sync.I(TAG, "Change tracker for {0} stopped; error={1}", ReplicatorID, tracker.Error); if (LastError == null && tracker.Error != null) { LastError = tracker.Error; } Batcher.FlushAll(); if(resolution == ErrorResolution.RetryLater) { Log.To.Sync.I(TAG, "Change tracked stopped, entering retry loop..."); ScheduleRetryIfReady(); } else if(resolution == ErrorResolution.GoOffline) { GoOffline(); } else if(resolution == ErrorResolution.Stop) { if(Continuous || (ChangesCount == CompletedChangesCount && IsSafeToStop)) { Log.To.Sync.V(TAG, "Change tracker stopped, firing StopGraceful..."); FireTrigger(ReplicationTrigger.StopGraceful); } } } private string JoinQuotedEscaped(IList<string> strings) { if (strings.Count == 0) { return "[]"; } string json = null; try { json = Manager.GetObjectMapper().WriteValueAsString(strings); } catch (Exception e) { Log.To.Sync.E(TAG, "Unable to serialize json, returning null", e); return null; } return Uri.EscapeUriString(json); } private void QueueRemoteRevision(RevisionInternal rev) { if (rev.Deleted) { if (_deletedRevsToPull == null) { _deletedRevsToPull = new List<RevisionInternal>(100); } _deletedRevsToPull.Add(rev); } else { if (_revsToPull == null) { _revsToPull = new List<RevisionInternal>(100); } _revsToPull.Add(rev); } } /// <summary> /// Start up some HTTP GETs, within our limit on the maximum simultaneous number /// The entire method is not synchronized, only the portion pulling work off the list /// Important to not hold the synchronized block while we do network access /// </summary> private void PullRemoteRevisions() { //find the work to be done in a synchronized block var workToStartNow = new List<RevisionInternal>(); var bulkWorkToStartNow = new List<RevisionInternal>(); lock (_locker) { while (LocalDatabase.IsOpen) { int nBulk = 0; if (_bulkRevsToPull != null) { nBulk = Math.Min(_bulkRevsToPull.Count, ReplicationOptions.MaxRevsToGetInBulk); } if (nBulk == 1) { // Rather than pulling a single revision in 'bulk', just pull it normally: QueueRemoteRevision(_bulkRevsToPull[0]); _bulkRevsToPull.RemoveAt(0); nBulk = 0; } if (nBulk > 0) { // Prefer to pull bulk revisions: var range = new Couchbase.Lite.Util.ArraySegment<RevisionInternal>(_bulkRevsToPull.ToArray(), 0, nBulk); bulkWorkToStartNow.AddRange(range); foreach (var val in range) { _bulkRevsToPull.Remove(val); } } else { // Prefer to pull an existing revision over a deleted one: IList<RevisionInternal> queue = _revsToPull; if (queue == null || queue.Count == 0) { queue = _deletedRevsToPull; if (queue == null || queue.Count == 0) { break; // both queues are empty } } workToStartNow.Add(queue[0]); queue.RemoveAt(0); } } } //actually run it outside the synchronized block if (bulkWorkToStartNow.Count > 0) { PullBulkRevisions(bulkWorkToStartNow); } foreach (var rev in workToStartNow) { PullRemoteRevision(rev); } } // Get a bunch of revisions in one bulk request. Will use _bulk_get if possible. private void PullBulkRevisions(IList<RevisionInternal> bulkRevs) { var nRevs = bulkRevs == null ? 0 : bulkRevs.Count; if (nRevs == 0) { return; } Log.To.Sync.I(TAG, "{0} bulk-fetching {1} remote revisions...", ReplicatorID, nRevs); if(!_canBulkGet) { PullBulkWithAllDocs(bulkRevs); return; } Log.To.SyncPerf.I(TAG, "{0} bulk-getting {1} remote revisions...", ReplicatorID, nRevs); var remainingRevs = new List<RevisionInternal>(bulkRevs); BulkDownloader dl = new BulkDownloader(new BulkDownloaderOptions { Session = _remoteSession, DatabaseUri = RemoteUrl, Revisions = bulkRevs, Database = LocalDatabase, RetryStrategy = ReplicationOptions.RetryStrategy, CookieStore = CookieContainer }); dl.DocumentDownloaded += (sender, args) => { var props = args.DocumentProperties; var rev = props.CblID() != null ? new RevisionInternal(props) : new RevisionInternal(props.GetCast<string>("id"), props.GetCast<string>("rev").AsRevID(), false); var pos = remainingRevs.IndexOf(rev); if(pos > -1) { rev.Sequence = remainingRevs[pos].Sequence; remainingRevs.RemoveAt(pos); } else { Log.To.Sync.W(TAG, "Received unexpected rev {0}; ignoring", rev); return; } if(props.CblID() != null) { // Add to batcher ... eventually it will be fed to -insertRevisions:. QueueDownloadedRevision(rev); } else { var status = StatusFromBulkDocsResponseItem(props); Log.To.Sync.W(TAG, "Error downloading {0}", rev); var error = new CouchbaseLiteException(status.Code); LastError = error; RevisionFailed(); SafeIncrementCompletedChangesCount(); if(IsDocumentError(error)) { Log.To.Sync.W(TAG, $"Error is permanent, {rev} will NOT be downloaded!"); _pendingSequences.RemoveSequence(rev.Sequence); } else { Log.To.Sync.I(TAG, $"Will try again later to get {rev}"); } } }; dl.Complete += (sender, args) => { if(args != null && args.Error != null) { RevisionFailed(); if(remainingRevs.Count == 0) { LastError = args.Error; } } else if(remainingRevs.Count > 0) { Log.To.Sync.W(TAG, "{0} revs not returned from _bulk_get: {1}", remainingRevs.Count, remainingRevs); for(int i = 0; i < remainingRevs.Count; i++) { var rev = remainingRevs[i]; if(ShouldRetryDownload(rev.DocID)) { _bulkRevsToPull.Add(remainingRevs[i]); } else { LastError = args.Error; SafeIncrementCompletedChangesCount(); } } } SafeAddToCompletedChangesCount(remainingRevs.Count); LastSequence = _pendingSequences.GetCheckpointedValue(); PullRemoteRevisions(); }; dl.Authenticator = Authenticator; WorkExecutor.StartNew(dl.Start, CancellationTokenSource.Token, TaskCreationOptions.None, WorkExecutor.Scheduler); } // Get as many revisions as possible in one _all_docs request. // This is compatible with CouchDB, but it only works for revs of generation 1 without attachments. private void PullBulkWithAllDocs(IList<RevisionInternal> bulkRevs) { // http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API var remainingRevs = new List<RevisionInternal>(bulkRevs); var keys = bulkRevs.Select(rev => rev.DocID).ToArray(); var body = new Dictionary<string, object>(); body["keys"] = keys; _remoteSession.SendAsyncRequest(HttpMethod.Post, "/_all_docs?include_docs=true", body, (result, e) => { var res = result.AsDictionary<string, object>(); if(e != null) { LastError = e; RevisionFailed(); SafeAddToCompletedChangesCount(bulkRevs.Count); } else { // Process the resulting rows' documents. // We only add a document if it doesn't have attachments, and if its // revID matches the one we asked for. var rows = res.Get("rows").AsList<IDictionary<string, object>>(); Log.To.Sync.I(TAG, "{0} checking {1} bulk-fetched remote revisions", ReplicatorID, rows.Count); foreach(var row in rows) { var doc = row.Get("doc").AsDictionary<string, object>(); if(doc != null && doc.Get("_attachments") == null) { var rev = new RevisionInternal(doc); var pos = remainingRevs.IndexOf(rev); if(pos > -1) { rev.Sequence = remainingRevs[pos].Sequence; remainingRevs.RemoveAt(pos); QueueDownloadedRevision(rev); } } } } // Any leftover revisions that didn't get matched will be fetched individually: if(remainingRevs.Count > 0) { Log.To.Sync.I(TAG, "Bulk-fetch didn't work for {0} of {1} revs; getting individually for {2}", remainingRevs.Count, bulkRevs.Count, ReplicatorID); foreach(var rev in remainingRevs) { QueueRemoteRevision(rev); } PullRemoteRevisions(); } // Start another task if there are still revisions waiting to be pulled: PullRemoteRevisions(); }); } private bool ShouldRetryDownload(string docId) { if (!LocalDatabase.IsOpen) { return false; } var localDoc = LocalDatabase.GetExistingLocalDocument(docId); if (localDoc == null) { LocalDatabase.PutLocalDocument(docId, new Dictionary<string, object> { {"retryCount", 1} }); return true; } var retryCount = (long)localDoc["retryCount"]; if (retryCount >= ReplicationOptions.RetryStrategy.MaxRetries) { PruneFailedDownload(docId); return false; } localDoc["retryCount"] = (long)localDoc["retryCount"] + 1; LocalDatabase.PutLocalDocument(docId, localDoc); return true; } private void PruneFailedDownload(string docId) { LocalDatabase.DeleteLocalDocument(docId); } // This invokes the tranformation block if one is installed and queues the resulting Revision private void QueueDownloadedRevision(RevisionInternal rev) { if (RevisionBodyTransformationFunction != null) { // Add 'file' properties to attachments pointing to their bodies: foreach (var entry in rev.GetProperties().Get("_attachments").AsDictionary<string,object>()) { var attachment = entry.Value as IDictionary<string, object>; attachment.Remove("file"); if (attachment.Get("follows") != null && attachment.Get("data") == null) { var filePath = LocalDatabase.FileForAttachmentDict(attachment).AbsolutePath; if (filePath != null) { attachment["file"] = filePath; } } } var xformed = TransformRevision(rev); if (xformed == null) { Log.To.Sync.I(TAG, "Transformer rejected revision {0}", rev); _pendingSequences.RemoveSequence(rev.Sequence); LastSequence = _pendingSequences.GetCheckpointedValue(); PauseOrResume(); return; } rev = xformed; var attachments = (IDictionary<string, IDictionary<string, object>>)rev.GetProperties().Get("_attachments"); foreach (var entry in attachments) { var attachment = entry.Value; attachment.Remove("file"); } } //TODO: rev.getBody().compact(); if (_downloadsToInsert != null) { if(!_downloadsToInsert.QueueObject(rev)) { Log.To.Sync.W(TAG, "{0} failed to queue {1} for download because it is already queued, marking completed...", this, rev); SafeIncrementCompletedChangesCount(); } } else { Log.To.Sync.W(TAG, "{0} is finished and cannot accept download requests", this); } } /// <summary>Fetches the contents of a revision from the remote db, including its parent revision ID. /// </summary> /// <remarks> /// Fetches the contents of a revision from the remote db, including its parent revision ID. /// The contents are stored into rev.properties. /// </remarks> private void PullRemoteRevision(RevisionInternal rev) { // Construct a query. We want the revision history, and the bodies of attachments that have // been added since the latest revisions we have locally. // See: http://wiki.apache.org/couchdb/HTTP_Document_API#Getting_Attachments_With_a_Document var path = new StringBuilder($"/{Uri.EscapeUriString(rev.DocID)}?rev={Uri.EscapeUriString(rev.RevID.ToString())}&revs=true"); var attachments = ManagerOptions.Default.DownloadAttachmentsOnSync; if(attachments) { // TODO: deferred attachments path.Append("&attachments=true"); } // Include atts_since with a list of possible ancestor revisions of rev. If getting attachments, // this allows the server to skip the bodies of attachments that have not changed since the // local ancestor. The server can also trim the revision history it returns, to not extend past // the local ancestor (not implemented yet in SG but will be soon.) var knownRevs = default(IList<RevisionID>); ValueTypePtr<bool> haveBodies = false; try { knownRevs = LocalDatabase.Storage.GetPossibleAncestors(rev, MaxAttsSince, haveBodies)?.ToList(); } catch(Exception e) { Log.To.Sync.W(TAG, "Error getting possible ancestors (probably database closed)", e); } if(knownRevs != null) { path.Append(haveBodies ? "&atts_since=" : "&revs_from="); path.Append(JoinQuotedEscaped(knownRevs.Select(x => x.ToString()).ToList())); } else { // If we don't have any revisions at all, at least tell the server how long a history we // can keep track of: var maxRevTreeDepth = LocalDatabase.GetMaxRevTreeDepth(); if(rev.Generation > maxRevTreeDepth) { path.AppendFormat("&revs_limit={0}", maxRevTreeDepth); } } var pathInside = path.ToString(); Log.To.SyncPerf.I(TAG, "{0} getting {1}", this, rev); Log.To.Sync.V(TAG, "{0} GET {1}", this, new SecureLogString(pathInside, LogMessageSensitivity.PotentiallyInsecure)); _remoteSession.SendAsyncMultipartDownloaderRequest(HttpMethod.Get, pathInside, null, LocalDatabase, (result, e) => { // OK, now we've got the response revision: Log.To.SyncPerf.I(TAG, "{0} got {1}", this, rev); if (e != null) { Log.To.Sync.I (TAG, String.Format("{0} error pulling remote revision", this), e); LastError = e; RevisionFailed(); SafeIncrementCompletedChangesCount(); if(IsDocumentError(e)) { // Make sure this document is skipped because it is not available // even though the server is functioning _pendingSequences.RemoveSequence(rev.Sequence); LastSequence = _pendingSequences.GetCheckpointedValue(); } } else { var properties = result.AsDictionary<string, object>(); var gotRev = new PulledRevision(properties); gotRev.Sequence = rev.Sequence; if (_downloadsToInsert != null) { if (!_downloadsToInsert.QueueObject (gotRev)) { Log.To.Sync.W(TAG, "{0} failed to queue {1} for download because it is already queued, marking completed...", this, rev); SafeIncrementCompletedChangesCount (); } } else { Log.To.Sync.E (TAG, "downloadsToInsert is null"); } } // Note that we've finished this task; then start another one if there // are still revisions waiting to be pulled: PullRemoteRevisions (); }); } private static bool IsDocumentError(Exception e) { foreach (var inner in Misc.Flatten(e)) { if (IsDocumentError(inner as HttpResponseException) || IsDocumentError(inner as CouchbaseLiteException)) { return true; } } return false; } private static bool IsDocumentError(HttpResponseException e) { if (e == null) { return false; } return e.StatusCode == System.Net.HttpStatusCode.NotFound || e.StatusCode == System.Net.HttpStatusCode.Forbidden || e.StatusCode == System.Net.HttpStatusCode.Gone; } private static bool IsDocumentError(CouchbaseLiteException e) { if (e == null) { return false; } return e.Code == StatusCode.NotFound || e.Code == StatusCode.Forbidden; } /// <summary>This will be called when _revsToInsert fills up:</summary> private void InsertDownloads(IList<RevisionInternal> downloads) { Log.To.SyncPerf.I(TAG, "{0} inserting {1} revisions into db...", this, downloads.Count); Log.To.Sync.V(TAG, "{0} inserting {1} revisions...", this, downloads.Count); var time = DateTime.UtcNow; downloads.Sort(new RevisionComparer()); if (!LocalDatabase.IsOpen) { return; } try { var success = LocalDatabase.RunInTransaction(() => { foreach (var rev in downloads) { var fakeSequence = rev.Sequence; rev.Sequence = 0L; var history = Database.ParseCouchDBRevisionHistory(rev.GetProperties()); if ((history == null || history.Count == 0) && rev.Generation > 1) { Log.To.Sync.W(TAG, "{0} missing revision history in response for: {0}", this, rev); LastError = new CouchbaseLiteException(StatusCode.UpStreamError); RevisionFailed(); continue; } Log.To.Sync.V(TAG, String.Format("Inserting {0} {1}", new SecureLogString(rev.DocID, LogMessageSensitivity.PotentiallyInsecure), new LogJsonString(history))); // Insert the revision: try { LocalDatabase.ForceInsert(rev, history, RemoteUrl); } catch (CouchbaseLiteException e) { if (e.Code == StatusCode.Forbidden) { Log.To.Sync.I(TAG, "{0} remote rev failed validation: {1}", this, rev); } else if(e.Code == StatusCode.AttachmentError) { // Revision with broken _attachments metadata (i.e. bogus revpos) // should not stop replication. Warn and skip it. Log.To.Sync.W(TAG, "{0} revision {1} has invalid attachment metadata: {2}", this, rev, new SecureLogJsonString(rev.GetAttachments(), LogMessageSensitivity.PotentiallyInsecure)); } else if(e.Code == StatusCode.DbBusy) { Log.To.Sync.I(TAG, "Database is busy, will retry soon..."); // abort transaction; RunInTransaction will retry return false; } else { Log.To.Sync.W(TAG, "{0} failed to write {1}: status={2}", this, rev, e.Code); RevisionFailed(); LastError = e; continue; } } catch (Exception e) { throw Misc.CreateExceptionAndLog(Log.To.Sync, e, TAG, "Error inserting downloads"); } _pendingSequences.RemoveSequence(fakeSequence); } Log.To.Sync.V(TAG, "{0} finished inserting {1} revisions", this, downloads.Count); return true; }); Log.To.Sync.V(TAG, "Finished inserting {0} revisions. Success == {1}", downloads.Count, success); } catch (Exception e) { Log.To.Sync.E(TAG, "Exception inserting revisions, continuing...", e); } // Checkpoint: LastSequence = _pendingSequences.GetCheckpointedValue(); var delta = (DateTime.UtcNow - time).TotalMilliseconds; Log.To.Sync.I(TAG, "Inserted {0} revs in {1} milliseconds", downloads.Count, delta); Log.To.SyncPerf.I(TAG, "Inserted {0} revs in {1} milliseconds", downloads.Count, delta); SafeAddToCompletedChangesCount(downloads.Count); PauseOrResume(); } #endregion #region Overrides public override bool CreateTarget { get { return false; } set { return; /* No-op intended. Only used in Pusher. */ } } public override bool IsPull { get { return true; } } public override bool IsAttachmentPull { get { return true; } } public override IEnumerable<string> DocIds { get; set; } public override IDictionary<string, string> Headers { get { return _remoteSession.RequestHeaders; } set { _remoteSession.RequestHeaders = value; } } protected override void Retry() { if (_changeTracker != null) { _changeTracker.Stop(ErrorResolution.Ignore); } base.Retry(); } protected override void StopGraceful() { var changeTrackerCopy = _changeTracker; if (changeTrackerCopy != null) { Log.D(TAG, "stopping changetracker " + _changeTracker); changeTrackerCopy.Client = null; // stop it from calling my changeTrackerStopped() changeTrackerCopy.Stop(ErrorResolution.Ignore); _changeTracker = null; } lock (_locker) { _revsToPull = null; _deletedRevsToPull = null; _bulkRevsToPull = null; } if (_downloadsToInsert != null) { _downloadsToInsert.FlushAll(); } base.StopGraceful(); } protected override void PerformGoOffline() { base.PerformGoOffline(); if (_changeTracker != null) { _changeTracker.Stop(ErrorResolution.GoOffline); } _remoteSession.CancelRequests(); } protected override void PerformGoOnline() { base.PerformGoOnline(); BeginReplicating(); } internal override void ProcessInbox(RevisionList inbox) { if (Status == ReplicationStatus.Offline) { Log.To.Sync.I(TAG, "{0} is offline, so skipping inbox process", this); return; } Debug.Assert(inbox != null); if (!_canBulkGet) { _canBulkGet = CheckServerCompatVersion("0.81"); } Log.To.SyncPerf.I(TAG, "{0} processing {1} changes", this, inbox.Count); Log.To.Sync.V(TAG, "{0} looking up {1}", this, inbox); // Ask the local database which of the revs are not known to it: var lastInboxSequence = ((PulledRevision)inbox[inbox.Count - 1]).GetRemoteSequenceID(); var numRevisionsRemoved = 0; try { // findMissingRevisions is the local equivalent of _revs_diff. it looks at the // array of revisions in inbox and removes the ones that already exist. So whatever's left in inbox // afterwards are the revisions that need to be downloaded. numRevisionsRemoved = LocalDatabase.Storage.FindMissingRevisions(inbox); } catch (Exception e) { Log.To.Sync.E(TAG, String.Format("{0} failed to look up local revs, aborting...", this), e); inbox = null; } var inboxCount = 0; if (inbox != null) { inboxCount = inbox.Count; } if (numRevisionsRemoved > 0) { // Some of the revisions originally in the inbox aren't missing; treat those as processed: Log.To.Sync.I (TAG, "{0} Removed {1} already present revisions", this, numRevisionsRemoved); SafeAddToCompletedChangesCount(numRevisionsRemoved); } if (inboxCount == 0) { // Nothing to do; just count all the revisions as processed. // Instead of adding and immediately removing the revs to _pendingSequences, // just do the latest one (equivalent but faster): Log.To.Sync.V(TAG, "{0} no new remote revisions to fetch", this); var seq = _pendingSequences.AddValue(lastInboxSequence); _pendingSequences.RemoveSequence(seq); LastSequence = _pendingSequences.GetCheckpointedValue(); PauseOrResume(); return; } Log.To.SyncPerf.I(TAG, "{0} queuing download requests for {1} revisions", this, inboxCount); Log.To.Sync.V(TAG, "{0} queuing remote revisions {1}", this, inbox); // Dump the revs into the queue of revs to pull from the remote db: lock (_locker) { int numBulked = 0; for (int i = 0; i < inboxCount; i++) { var rev = (PulledRevision)inbox[i]; if (_canBulkGet || (rev.Generation == 1 && !rev.Deleted && !rev.IsConflicted)) { //optimistically pull 1st-gen revs in bulk if (_bulkRevsToPull == null) { _bulkRevsToPull = new List<RevisionInternal>(100); } _bulkRevsToPull.Add(rev); ++numBulked; } else { QueueRemoteRevision(rev); } rev.Sequence = _pendingSequences.AddValue(rev.GetRemoteSequenceID()); } Log.To.Sync.I(TAG, "{4} queued {0} remote revisions from seq={1} ({2} in bulk, {3} individually)", inboxCount, ((PulledRevision)inbox[0]).GetRemoteSequenceID(), numBulked, inboxCount - numBulked, this); } PullRemoteRevisions(); PauseOrResume(); } internal override void BeginReplicating() { Log.To.Sync.I(TAG, "{2} will use MaxOpenHttpConnections({0}), MaxRevsToGetInBulk({1})", ReplicationOptions.MaxOpenHttpConnections, ReplicationOptions.MaxRevsToGetInBulk, this); if (_downloadsToInsert == null) { const int capacity = InboxCapacity * 2; TimeSpan delay = TimeSpan.FromSeconds(1); _downloadsToInsert = new Batcher<RevisionInternal>(new BatcherOptions<RevisionInternal> { WorkExecutor = WorkExecutor, Capacity = capacity, Delay = delay, Processor = InsertDownloads }); } if (_pendingSequences == null) { _pendingSequences = new SequenceMap(); if (LastSequence != null) { // Prime _pendingSequences so its checkpointedValue will reflect the last known seq: var seq = _pendingSequences.AddValue(LastSequence); _pendingSequences.RemoveSequence(seq); Debug.Assert((_pendingSequences.GetCheckpointedValue().Equals(LastSequence))); } } _caughtUp = false; StartChangeTracker(); } internal override void Stopping() { _downloadsToInsert = null; base.Stopping(); } public override string ToString() { return String.Format("Puller {0}", ReplicatorID); } #endregion #region IChangeTrackerClient public void ChangeTrackerCaughtUp(ChangeTracker tracker) { if (!_caughtUp) { Log.To.Sync.I(TAG, "{0} caught up with changes", this); _caughtUp = true; } if (Continuous && ChangesCount == CompletedChangesCount) { FireTrigger (ReplicationTrigger.WaitingForChanges); } } public void ChangeTrackerFinished(ChangeTracker tracker) { ChangeTrackerCaughtUp(tracker); } public void ChangeTrackerReceivedChange(IDictionary<string, object> change) { if (ServerType == null) { ServerType = _remoteSession.ServerType; } var lastSequence = change.Get("seq").ToString(); var docID = (string)change.Get("id"); if (docID == null) { Log.To.Sync.W (TAG, "{0} Change received with no id, ignoring...", this); return; } var removed = change.Get("removed") != null; if (removed) { Log.To.Sync.V(TAG, "Removed entry received, body may not be available"); } if (!Document.IsValidDocumentId(docID)) { if (!docID.StartsWith("_user/", StringComparison.InvariantCultureIgnoreCase)) { Log.To.Sync.W(TAG, "{0}: Received invalid doc ID from _changes: {1} ({2})", this, new SecureLogString(docID, LogMessageSensitivity.PotentiallyInsecure), new LogJsonString(change)); } return; } var deleted = change.GetCast<bool>("deleted"); var changes = change.Get("changes").AsList<object>(); SafeAddToChangesCount(changes.Count); foreach (var changeObj in changes) { var changeDict = changeObj.AsDictionary<string, object>(); var revID = changeDict.GetCast<string>("rev").AsRevID(); if (revID == null) { Log.To.Sync.W (TAG, "{0} missing revID for entry, skipping..."); SafeIncrementCompletedChangesCount (); continue; } var rev = new PulledRevision(docID, revID, deleted, LocalDatabase); rev.SetRemoteSequenceID(lastSequence); if (changes.Count > 1) { rev.IsConflicted = true; } Log.To.Sync.D(TAG, "Adding rev to inbox " + rev); if(!AddToInbox(rev)) { Log.To.Sync.W (TAG, "{0} Failed to add {1} to inbox, probably already added. Marking completed", this, rev); SafeIncrementCompletedChangesCount (); } } PauseOrResume(); while (_revsToPull != null && _revsToPull.Count > 1000) { try { // Presumably we are letting 1 or more other threads do something while we wait. Thread.Sleep(500); } catch (Exception e) { Log.To.Sync.W(TAG, "Swallowing exception while sleeping after receiving changetracker changes.", e); // swallow } } } public void ChangeTrackerStopped(ChangeTracker tracker, ErrorResolution resolution) { WorkExecutor.StartNew(() => ProcessChangeTrackerStopped(tracker, resolution)); } public CookieContainer GetCookieStore() { return CookieContainer; } #endregion #region Nested Classes private sealed class RevisionComparer : IComparer<RevisionInternal> { public RevisionComparer() { } public int Compare(RevisionInternal reva, RevisionInternal revb) { return Misc.TDSequenceCompare(reva != null ? reva.Sequence : -1L, revb != null ? revb.Sequence : -1L); } } #endregion } }
using Serilog.Events; using Serilog.Formatting.Display; using Serilog.Tests.Support; using System; using System.Globalization; using System.IO; using System.Linq; using Xunit; namespace Serilog.Tests.Formatting.Display { public class MessageTemplateTextFormatterTests { [Fact] public void UsesFormatProvider() { var french = new CultureInfo("fr-FR"); var formatter = new MessageTemplateTextFormatter("{Message}", french); var evt = DelegatingSink.GetLogEvent(l => l.Information("{0}", 12.345)); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal("12,345", sw.ToString()); } [Fact] public void MessageTemplatesContainingFormatStringPropertiesRenderCorrectly() { var formatter = new MessageTemplateTextFormatter("{Message}", CultureInfo.InvariantCulture); var evt = DelegatingSink.GetLogEvent(l => l.Information("{Message}", "Hello, world!")); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal("\"Hello, world!\"", sw.ToString()); } [Fact] public void UppercaseFormatSpecifierIsSupportedForStrings() { var formatter = new MessageTemplateTextFormatter("{Name:u}", CultureInfo.InvariantCulture); var evt = DelegatingSink.GetLogEvent(l => l.Information("{Name}", "Nick")); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal("NICK", sw.ToString()); } [Fact] public void LowercaseFormatSpecifierIsSupportedForStrings() { var formatter = new MessageTemplateTextFormatter("{Name:w}", CultureInfo.InvariantCulture); var evt = DelegatingSink.GetLogEvent(l => l.Information("{Name}", "Nick")); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal("nick", sw.ToString()); } [Theory] [InlineData(LogEventLevel.Verbose, 1, "V")] [InlineData(LogEventLevel.Verbose, 2, "Vb")] [InlineData(LogEventLevel.Verbose, 3, "Vrb")] [InlineData(LogEventLevel.Verbose, 4, "Verb")] [InlineData(LogEventLevel.Verbose, 5, "Verbo")] [InlineData(LogEventLevel.Verbose, 6, "Verbos")] [InlineData(LogEventLevel.Verbose, 7, "Verbose")] [InlineData(LogEventLevel.Verbose, 8, "Verbose")] [InlineData(LogEventLevel.Debug, 1, "D")] [InlineData(LogEventLevel.Debug, 2, "De")] [InlineData(LogEventLevel.Debug, 3, "Dbg")] [InlineData(LogEventLevel.Debug, 4, "Dbug")] [InlineData(LogEventLevel.Debug, 5, "Debug")] [InlineData(LogEventLevel.Debug, 6, "Debug")] [InlineData(LogEventLevel.Information, 1, "I")] [InlineData(LogEventLevel.Information, 2, "In")] [InlineData(LogEventLevel.Information, 3, "Inf")] [InlineData(LogEventLevel.Information, 4, "Info")] [InlineData(LogEventLevel.Information, 5, "Infor")] [InlineData(LogEventLevel.Information, 6, "Inform")] [InlineData(LogEventLevel.Information, 7, "Informa")] [InlineData(LogEventLevel.Information, 8, "Informat")] [InlineData(LogEventLevel.Information, 9, "Informati")] [InlineData(LogEventLevel.Information, 10, "Informatio")] [InlineData(LogEventLevel.Information, 11, "Information")] [InlineData(LogEventLevel.Information, 12, "Information")] [InlineData(LogEventLevel.Error, 1, "E")] [InlineData(LogEventLevel.Error, 2, "Er")] [InlineData(LogEventLevel.Error, 3, "Err")] [InlineData(LogEventLevel.Error, 4, "Eror")] [InlineData(LogEventLevel.Error, 5, "Error")] [InlineData(LogEventLevel.Error, 6, "Error")] [InlineData(LogEventLevel.Fatal, 1, "F")] [InlineData(LogEventLevel.Fatal, 2, "Fa")] [InlineData(LogEventLevel.Fatal, 3, "Ftl")] [InlineData(LogEventLevel.Fatal, 4, "Fatl")] [InlineData(LogEventLevel.Fatal, 5, "Fatal")] [InlineData(LogEventLevel.Fatal, 6, "Fatal")] [InlineData(LogEventLevel.Warning, 1, "W")] [InlineData(LogEventLevel.Warning, 2, "Wn")] [InlineData(LogEventLevel.Warning, 3, "Wrn")] [InlineData(LogEventLevel.Warning, 4, "Warn")] [InlineData(LogEventLevel.Warning, 5, "Warni")] [InlineData(LogEventLevel.Warning, 6, "Warnin")] [InlineData(LogEventLevel.Warning, 7, "Warning")] [InlineData(LogEventLevel.Warning, 8, "Warning")] public void FixedLengthLevelIsSupported( LogEventLevel level, int width, string expected) { var formatter = new MessageTemplateTextFormatter($"{{Level:t{width}}}", CultureInfo.InvariantCulture); var evt = DelegatingSink.GetLogEvent(l => l.Write(level, "Hello")); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal(expected, sw.ToString()); } [Fact] public void FixedLengthLevelSupportsUpperCasing() { var formatter = new MessageTemplateTextFormatter("{Level:u3}", CultureInfo.InvariantCulture); var evt = DelegatingSink.GetLogEvent(l => l.Information("Hello")); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal("INF", sw.ToString()); } [Fact] public void FixedLengthLevelSupportsLowerCasing() { var formatter = new MessageTemplateTextFormatter("{Level:w3}", CultureInfo.InvariantCulture); var evt = DelegatingSink.GetLogEvent(l => l.Information("Hello")); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal("inf", sw.ToString()); } [Fact] public void DefaultLevelLengthIsFullText() { var formatter = new MessageTemplateTextFormatter("{Level}", CultureInfo.InvariantCulture); var evt = DelegatingSink.GetLogEvent(l => l.Information("Hello")); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal("Information", sw.ToString()); } [Fact] public void AlignmentAndWidthCanBeCombined() { var formatter = new MessageTemplateTextFormatter("{Level,5:w3}", CultureInfo.InvariantCulture); var evt = DelegatingSink.GetLogEvent(l => l.Information("Hello")); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal(" inf", sw.ToString()); } enum Size { Large } class SizeFormatter : IFormatProvider, ICustomFormatter { readonly IFormatProvider _innerFormatProvider; public SizeFormatter(IFormatProvider innerFormatProvider) { _innerFormatProvider = innerFormatProvider; } public object? GetFormat(Type? formatType) { return formatType == typeof(ICustomFormatter) ? this : _innerFormatProvider.GetFormat(formatType); } public string Format(string? format, object? arg, IFormatProvider? formatProvider) { if (arg == null) { throw new ArgumentNullException(nameof(arg)); } if (arg is Size size) return size == Size.Large ? "Huge" : size.ToString(); if (arg is IFormattable formattable) return formattable.ToString(format, _innerFormatProvider); return arg.ToString()!; } } [Fact] public void AppliesCustomFormatterToEnums() { var formatter = new MessageTemplateTextFormatter("{Message}", new SizeFormatter(CultureInfo.InvariantCulture)); var evt = DelegatingSink.GetLogEvent(l => l.Information("Size {Size}", Size.Large)); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal("Size Huge", sw.ToString()); } [Fact] public void NonMessagePropertiesAreRendered() { var formatter = new MessageTemplateTextFormatter("{Properties}", CultureInfo.InvariantCulture); var evt = DelegatingSink.GetLogEvent(l => l.ForContext("Foo", 42).Information("Hello from {Bar}!", "bar")); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal("{ Foo: 42 }", sw.ToString()); } [Fact] public void NonMessagePositionalPropertiesAreRendered() { var formatter = new MessageTemplateTextFormatter("{Properties}", CultureInfo.InvariantCulture); var evt = DelegatingSink.GetLogEvent(l => l.ForContext("Foo", 42).Information("Hello from {0}!", "bar")); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal("{ Foo: 42 }", sw.ToString()); } [Fact] public void DoNotDuplicatePropertiesAlreadyRenderedInOutputTemplate() { var formatter = new MessageTemplateTextFormatter("{Foo} {Properties}", CultureInfo.InvariantCulture); var evt = DelegatingSink.GetLogEvent(l => l.ForContext("Foo", 42).ForContext("Bar", 42).Information("Hello from bar!")); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal("42 { Bar: 42 }", sw.ToString()); } [Theory] [InlineData("", "Hello, \"World\"!")] [InlineData(":j", "Hello, \"World\"!")] [InlineData(":l", "Hello, World!")] [InlineData(":lj", "Hello, World!")] [InlineData(":jl", "Hello, World!")] public void AppliesLiteralFormattingToMessageStringsWhenSpecified(string format, string expected) { var formatter = new MessageTemplateTextFormatter("{Message" + format + "}", null); var evt = DelegatingSink.GetLogEvent(l => l.Information("Hello, {Name}!", "World")); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal(expected, sw.ToString()); } [Theory] [InlineData("", "{ Name: \"World\" }")] [InlineData(":j", "{\"Name\":\"World\"}")] [InlineData(":lj", "{\"Name\":\"World\"}")] [InlineData(":jl", "{\"Name\":\"World\"}")] public void AppliesJsonFormattingToMessageStructuresWhenSpecified(string format, string expected) { var formatter = new MessageTemplateTextFormatter("{Message" + format + "}", null); var evt = DelegatingSink.GetLogEvent(l => l.Information("{@Obj}", new { Name = "World" })); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal(expected, sw.ToString()); } [Theory] [InlineData("", "{ Name: \"World\" }")] [InlineData(":j", "{\"Name\":\"World\"}")] [InlineData(":lj", "{\"Name\":\"World\"}")] [InlineData(":jl", "{\"Name\":\"World\"}")] public void AppliesJsonFormattingToPropertiesTokenWhenSpecified(string format, string expected) { var formatter = new MessageTemplateTextFormatter("{Properties" + format + "}", null); var evt = DelegatingSink.GetLogEvent(l => l.ForContext("Name", "World").Information("Hello")); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal(expected, sw.ToString()); } [Fact] public void AnEmptyPropertiesTokenIsAnEmptyStructureValueWithDefaultFormatting() { var formatter = new MessageTemplateTextFormatter("{Properties}", null); var evt = DelegatingSink.GetLogEvent(l => l.Information("Hello")); var sw = new StringWriter(); formatter.Format(evt, sw); var expected = new StructureValue(Enumerable.Empty<LogEventProperty>()).ToString(); Assert.Equal(expected, sw.ToString()); } [Theory] [InlineData("", true)] [InlineData(":lj", false)] [InlineData(":jl", false)] [InlineData(":j", false)] [InlineData(":l", true)] public void FormatProviderWithScalarProperties(string format, bool shouldUseCustomFormatter) { var frenchFormatProvider = new CultureInfo("fr-FR"); var defaultFormatProvider = CultureInfo.InvariantCulture; var date = new DateTime(2018, 01, 01); var number = 12.345; var expectedFormattedDate = shouldUseCustomFormatter ? date.ToString(frenchFormatProvider) : date.ToString("O", defaultFormatProvider); var expectedFormattedNumber = shouldUseCustomFormatter ? number.ToString(frenchFormatProvider) : number.ToString(defaultFormatProvider); var formatter = new MessageTemplateTextFormatter("{Message" + format + "}", frenchFormatProvider); var evt = DelegatingSink.GetLogEvent(l => { l.Information("{MyDate}{MyNumber}", date, number); }); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Contains(expectedFormattedDate, sw.ToString()); Assert.Contains(expectedFormattedNumber, sw.ToString()); } [Theory] [InlineData("", true)] [InlineData(":lj", false)] [InlineData(":jl", false)] [InlineData(":j", false)] [InlineData(":l", true)] public void FormatProviderWithDestructuredProperties(string format, bool shouldUseCustomFormatter) { var frenchFormatProvider = new CultureInfo("fr-FR"); var defaultFormatProvider = CultureInfo.InvariantCulture; var date = new DateTime(2018, 01, 01); var number = 12.345; var expectedFormattedDate = shouldUseCustomFormatter ? date.ToString(frenchFormatProvider) : date.ToString("O", defaultFormatProvider); var expectedFormattedNumber = shouldUseCustomFormatter ? number.ToString(frenchFormatProvider) : number.ToString(defaultFormatProvider); var formatter = new MessageTemplateTextFormatter("{Message" + format + "}", frenchFormatProvider); var evt = DelegatingSink.GetLogEvent(l => { l.Information("{@Item}", new { MyDate = date, MyNumber = number }); }); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Contains(expectedFormattedDate, sw.ToString()); Assert.Contains(expectedFormattedNumber, sw.ToString()); } [Theory] [InlineData(15, "", "15")] [InlineData(15, ",5", " 15")] [InlineData(15, ",-5", "15 ")] public void PaddingIsApplied(int n, string format, string expected) { var formatter = new MessageTemplateTextFormatter("{ThreadId" + format + "}", null); var evt = Some.InformationEvent(); evt.AddOrUpdateProperty(new LogEventProperty("ThreadId", new ScalarValue(n))); var sw = new StringWriter(); formatter.Format(evt, sw); Assert.Equal(expected, sw.ToString()); } } }
/** * SmithNgine Game Framework * * Copyright (C) 2013 by Erno Pakarinen / Codesmith (www.codesmith.fi) * All Rights Reserved */ namespace Codesmith.SmithNgine.Gfx { using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Codesmith.SmithNgine.Input; using Codesmith.SmithNgine.Collision; using Codesmith.SmithNgine.General; /// <summary> /// A base Sprite class. Draws a texture with no animation but can report events. /// /// Sprite is a graphics entity which has several properties like: /// <list type="bullet"> /// <item> /// <term>Texture</term> /// <description>Texture to be drawn when drawing the Sprite</description> /// </item> /// <item> /// <term>Position</term> /// <description>Position of the sprite (Sprite origin affects how position is used)</description> /// </item> /// <item> /// <term>Origin</term> /// <description>Sprite origin, default origin is the centre of the sprite bounds</description> /// </item> /// <item> /// <term>Rotation</term> /// <description>Rotation of the sprite, 0.0f is no rotation</description> /// </item> /// <item> /// <term>Scale</term> /// <description>Scale factor of the Sprite, 1.0f is normal scale</description> /// </item> /// <item> /// <term>Color</term> /// <description>Default is Color.White, sprite color is tinted towards the set color</description> /// </item> /// <item> /// <term>Order</term> /// <description>Order of sprite entity in the Sprite base, can be used to control in which order the sprites are drawn</description> /// </item> /// </list> /// /// Sprite can report several events for example: /// - Dragging (Mouse is dragged with mouse) /// - Focusing (Mouse was clicked on it) /// - Loosing focus (Mouse was clicked outside the sprite) /// - Changing of position, rotation, order /// - Hovering (Mouse is moving on top of the sprite) /// /// </summary> public class Sprite : DrawableGameObject, IOrderableObject, IRotatableObject, IFocusableObject, IHoverableObject { #region Fields // Input source for this Sprite private IInputEventSource inputSource; // Rotation of the sprite private float rotation = 0.0f; // Scale factor of the sprite private float scale = 1.0f; // Order of the sprite private float order = 1.0f; // Original frame size of the sprite private Rectangle frameSize; // Texture to be used protected Texture2D texture; // Set when drag is enabled protected bool dragEnabled = false; #endregion #region Events public event EventHandler<PositionEventArgs> PositionChanged; public event EventHandler<OrderEventArgs> OrderChanged; public event EventHandler<RotationEventArgs> RotationChanged; public event EventHandler<ScaleEventArgs> ScaleChanged; public event EventHandler<EventArgs> FocusGained; public event EventHandler<EventArgs> FocusLost; public event EventHandler<HoverEventArgs> BeingHovered; public event EventHandler<DragEventArgs> BeingDragged; public event EventHandler<DragEventArgs> LostDrag; #endregion #region Properties /// <summary> /// <value>True if Sprite has focus (mouse was clicked inside the Sprite)</value> /// </summary> public bool HasFocus { get; protected set; } /// <summary> /// Default origin is set to the center of the sprite. /// Origin is drawn to the Sprites position. /// Origin affects also to the rotation, Sprite is rotated around the Origin point /// <value>Sprite origin</value> /// </summary> public Vector2 Origin { get; set; } /// <summary> /// Color of the sprite, default is Color.White /// Sprite texture is tinted towards the given color when drawn. White = no effect /// <value>Color</value> /// </summary> public Color Color { get; set; } /// <summary> /// Set or Get sprite position. /// <value>Position of the sprite</value> /// </summary> /// <remarks> /// Setting a new position causes PositionChanged event /// </remarks> public override Vector2 Position { get { return base.Position; } set { Vector2 oldPos = base.Position; if (oldPos != value) { base.Position = value; // Call event after changing the position this.OnPositionChanged(oldPos, base.Position); } } } /// <summary> /// Set or Get sprite rotation/orientation. Default is 0.0f (no rotation) /// <value>Rotation of the sprite</value> /// </summary> /// <remarks> /// Setting a new rotation causes RotationChanged event /// </remarks> public float Rotation { get { return this.rotation; } set { float oldRotation = this.rotation; if (oldRotation != value) { this.rotation = value; this.OnRotationChanged(oldRotation, this.rotation); } } } /// <summary> /// Set or Get sprite scale. /// <value>Scale of the sprite, Default is 1.0f (=no scaling)</value> /// </summary> /// <remarks> /// Setting a new value for scale, causes ScaleChanged event /// </remarks> public float Scale { get { return this.scale; } set { float oldScale = this.scale; if (oldScale != value) { this.scale = value; this.OnScaleChanged(oldScale, this.scale); } } } /// <summary> /// Set or Get the order value of the sprite. /// <value>Order, between 0.0f and 1.0f</value> /// </summary> /// <remarks> /// Setting a new value for Order causes OrderChanged event /// </remarks> public float Order { get { return this.order; } set { float oldOrder = this.order; if (oldOrder != value) { this.order = MathHelper.Clamp(value, 0.0f, 1.0f); this.OnOrderChanged(oldOrder, this.order); } } } /// <summary> /// <value>True if sprite is being hovered</value> /// </summary> public bool IsHovered { get; private set; } /// <summary> /// Return Bounds of the sprite taking account of origin and scale /// </summary> public Rectangle Bounds { get { Vector2 pos = Position - ( Origin * Scale ); float width = (float)FrameSize.Width * Scale; float height = (float)FrameSize.Height * Scale; return new Rectangle((int)pos.X, (int)pos.Y, (int)width, (int)height); } } /// <summary> /// Set or get the input event source for this Sprite /// </summary> /// <remarks> /// When set, Sprite starts to listen for mouse button press/release and mouse change /// so it can report activation, focus and dragging etc. /// If not set, sprite can not report mouse/touch related events /// </remarks> public IInputEventSource InputEventSource { get { return inputSource; } set { inputSource = value; if (value == null) { inputSource.MouseButtonPressed -= mouseSource_MouseButtonPressed; inputSource.MouseButtonReleased -= inputSource_MouseButtonReleased; inputSource.MousePositionChanged -= mouseSource_MousePositionChanged; } else { inputSource.MouseButtonPressed += mouseSource_MouseButtonPressed; inputSource.MouseButtonReleased += inputSource_MouseButtonReleased; inputSource.MousePositionChanged += mouseSource_MousePositionChanged; } } } /// <summary> /// Return or set the unscaled size of the original texture /// </summary> public Rectangle FrameSize { get { return this.frameSize; } protected set { frameSize = value; // By default, sprite origin is the center Origin = new Vector2(frameSize.Width / 2, frameSize.Height / 2); } } /// <summary> /// Set or get the texture of the sprite /// </summary> public Texture2D Texture { get { return this.texture; } protected set { this.texture = value; if (this.texture != null) { InitSprite(texture.Bounds); } } } #endregion #region Constructors /// <summary> /// Instantiate the sprite and initialize a texture for it. /// It also calculates bounds etc for the sprite /// </summary> /// <param name="texture">The texture to set for this sprite</param> public Sprite(Texture2D texture) { Texture = texture; } /// <summary> /// Instantiate the sprite, does not initialize any texture for it. /// Sets the bounds and other parameters depending on the given param. /// </summary> /// <param name="spriteBounds">Bounds for the new sprite, size</param> public Sprite(Rectangle spriteBounds) { InitSprite(spriteBounds); } #endregion #region New methods - can be overridden public virtual void GainFocus() { if (FocusGained != null && !HasFocus) { FocusGained(this, EventArgs.Empty); } HasFocus = true; } public virtual void LooseFocus() { if (FocusLost != null && HasFocus) { FocusLost(this, EventArgs.Empty); } HasFocus = false; } protected virtual void OnDrag(Vector2 delta) { if( BeingDragged != null) { BeingDragged(this, new DragEventArgs(delta)); } } protected virtual void OnDragLost(Vector2 delta) { if (LostDrag != null) { LostDrag(this, new DragEventArgs(delta)); } } protected virtual void OnHover(Vector2 position) { if (this.BeingHovered != null) { HoverEventArgs args = new HoverEventArgs(); args.position = position; BeingHovered(this, args); } } #endregion #region From Base class public override void Draw(SpriteBatch spriteBatch, GameTime gameTime) { if (this.texture != null) { spriteBatch.Draw(this.texture, Position, null, Color, Rotation, Origin, Scale, SpriteEffects.None, Order); } } public override void Dispose() { //commented out for now //this.texture.Dispose(); base.Dispose(); } #endregion #region Private methods private void OnPositionChanged(Vector2 oldPosition, Vector2 newPosition) { if (PositionChanged != null) { PositionEventArgs args = new PositionEventArgs(oldPosition, newPosition); PositionChanged(this, args); } } private void OnRotationChanged(float oldRotation, float newRotation) { if (RotationChanged != null) { RotationEventArgs args = new RotationEventArgs(oldRotation, newRotation); RotationChanged(this, args); } } private void OnScaleChanged(float oldScale, float newScale) { if (ScaleChanged != null) { ScaleEventArgs args = new ScaleEventArgs(oldScale, newScale); ScaleChanged(this, args); } } private void OnOrderChanged(float oldOrder, float newOrder) { if (OrderChanged != null) { OrderEventArgs args = new OrderEventArgs(oldOrder, newOrder); OrderChanged(this, args); } } void mouseSource_MousePositionChanged(object sender, MouseEventArgs e) { if (ObjectIsActive) { Point p = new Point(e.State.X, e.State.Y); bool contained = Bounds.Contains(p); // Is this sprite being dragged? if (e.State.LeftButton && e.PreviousState.LeftButton && dragEnabled) { OnDrag(e.State.Position - e.PreviousState.Position); } if (contained) { // Handle hovering, coords are relative to the object Vector2 innerPos = new Vector2(p.X - Bounds.X, p.Y - Bounds.Y); OnHover(innerPos); this.IsHovered = true; } else { this.IsHovered = false; } } } void inputSource_MouseButtonReleased(object sender, MouseEventArgs e) { if (dragEnabled) { // Report loosing the drag status and report last delta of movement OnDragLost(e.State.Position - e.PreviousState.Position); } } private void mouseSource_MouseButtonPressed(object sender, MouseEventArgs e) { if (ObjectIsActive) { Point p = new Point(e.State.X, (int)e.State.Y); if (Bounds.Contains(p)) { HandleMouseInsideClick(e); } else if (HasFocus) { HandleMouseOutsideClick(e); } } } private void InitSprite(Rectangle spriteBounds) { FrameSize = spriteBounds; Position = Vector2.Zero; Scale = 1.0f; this.Color = Color.White; } // Handles mouseclick on this button protected virtual void HandleMouseInsideClick(MouseEventArgs args) { if (args.State.LeftButton) { dragEnabled = true; GainFocus(); } } protected virtual void HandleMouseOutsideClick(MouseEventArgs args) { if (args.State.LeftButton && HasFocus) { dragEnabled = false; LooseFocus(); } } #endregion } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // //#define COLLECT_PERFORMANCE_DATA namespace Microsoft.Zelig.PerformanceCounters { using System; using System.Collections.Generic; #if COLLECT_PERFORMANCE_DATA public struct ContextualTiming : IDisposable { class State { // // State // internal object m_context; internal string m_reason; internal Timing m_counter; internal int m_recursionCount; internal GrowOnlyHashTable< State, Timing.Nested > m_children; // // Constructor Methods // internal State( object context , string reason ) { m_context = context; m_reason = reason; } // // Equality Methods // public override bool Equals( object obj ) { if(obj is State) { State other = (State)obj; if(m_reason == other.m_reason) { return Object.ReferenceEquals( m_context, other.m_context ); } } return false; } public override int GetHashCode() { return m_context.GetHashCode(); } // // Helper Methods // internal void Include( State other , long exclusiveTime ) { if(m_children == null) { m_children = HashTableFactory.New< State, Timing.Nested >(); } Timing.Nested child; if(m_children.TryGetValue( other, out child ) == false) { child = new Timing.Nested(); m_children[other] = child; } child.Sum( exclusiveTime ); } } // // State // /************/ static List < GrowOnlySet< State > > s_threads; [ThreadStatic] static GrowOnlySet< State > s_states; [ThreadStatic] static List < State > s_activeStates; State m_state; int m_gcCount; // // Constructor Methods // public ContextualTiming( object context , string reason ) { if(context == null) { m_state = null; m_gcCount = 0; return; } Timing.Suspend(); if(s_states == null) { s_states = SetFactory.New< State >(); s_activeStates = new List< State >(); lock(typeof(State)) { if(s_threads == null) { s_threads = new List< GrowOnlySet< State > >(); } s_threads.Add( s_states ); } } State state = new State( context, reason ); if(s_states.Contains( state, out m_state ) == false) { m_state = state; s_states.Insert( state ); } if(m_state.m_recursionCount++ == 0) { s_activeStates.Add( m_state ); Timing.Resume(); m_state.m_counter.Start(); m_gcCount = GC.CollectionCount( 0 ); } else { Timing.Resume(); m_gcCount = 0; } } // // Helper Methods // public void Dispose() { if(m_state != null) { if(m_state.m_recursionCount-- == 1) { long exclusiveTime = m_state.m_counter.Stop( false ); int gcCount = GC.CollectionCount( 0 ); Timing.Suspend(); int top = s_activeStates.Count - 1; CHECKS.ASSERT( s_activeStates[top].Equals( m_state ), "Incorrect nesting of contextual timing" ); s_activeStates.RemoveAt( top ); while(--top >= 0) { State other = s_activeStates[top]; other.Include( m_state, exclusiveTime ); if(m_gcCount == gcCount) { other.m_counter.SetGcCount( gcCount ); } } Timing.Resume(); } } } // // Access Methods // public long TotalInclusiveTicks { get { return m_state.m_counter.TotalInclusiveTicks; } } public long TotalInclusiveMicroSeconds { get { return m_state.m_counter.TotalInclusiveMicroSeconds; } } public long TotalExclusiveTicks { get { return m_state.m_counter.TotalExclusiveTicks; } } public long TotalExclusiveMicroSeconds { get { return m_state.m_counter.TotalExclusiveMicroSeconds; } } public int Hits { get { return m_state.m_counter.Hits; } } // // Debug Methods // public static bool IsEnabled() { return true; } public static void DumpAllByType( System.IO.TextWriter textWriter ) { GrowOnlyHashTable< string, List< State > > lookup = HashTableFactory.New< string, List< State > >(); GrowOnlyHashTable< string, long > lookupCost = HashTableFactory.New< string, long >(); foreach(GrowOnlySet< State > set in s_threads) { foreach(State st in set) { string key = st.m_context.ToString();; if(HashTableWithListFactory.Add( lookup, key, st ).Count == 1) { lookupCost[key] = 0; } lookupCost[key] += st.m_counter.TotalInclusiveMicroSeconds; } } string[] keyArray = lookup.KeysToArray(); Array.Sort( keyArray, delegate ( string left, string right ) { return lookupCost[right].CompareTo( lookupCost[left] ); } ); foreach(string key in keyArray) { State[] states = SortByMostExpensive( lookup[key].ToArray() ); //--// long totalInclusiveMicroSeconds = 0; long totalExclusiveMicroSeconds = 0; int totalHits = 0; foreach(State st in states) { totalInclusiveMicroSeconds += st.m_counter.TotalInclusiveMicroSeconds; totalExclusiveMicroSeconds += st.m_counter.TotalExclusiveMicroSeconds; totalHits += st.m_counter.Hits; } textWriter.Write( "Key = {0}: ", key ); Emit( textWriter, "Exclusive", false, totalExclusiveMicroSeconds, totalHits ); Emit( textWriter, "Inclusive", false, totalInclusiveMicroSeconds, totalHits ); textWriter.WriteLine(); foreach(State st in states) { long inclusiveMicroSeconds = st.m_counter.TotalInclusiveMicroSeconds; long exclusiveMicroSeconds = st.m_counter.TotalExclusiveMicroSeconds; int hits = st.m_counter.Hits; textWriter.Write( " " ); Emit( textWriter, "Exclusive", true, exclusiveMicroSeconds, hits ); Emit( textWriter, "Inclusive", true, inclusiveMicroSeconds, hits ); textWriter.WriteLine( " | {0}", st.m_reason ); if(st.m_children != null) { GrowOnlyHashTable< Timing.Nested, State > childrenInverted = GetInvertedHashTable( st.m_children ); foreach(Timing.Nested childCounter in SortByMostExpensive( childrenInverted.KeysToArray() )) { State child = childrenInverted[childCounter]; textWriter.Write( " " ); Emit( textWriter, "Child Exc", true, childCounter.TotalExclusiveMicroSeconds, childCounter.Hits ); if(child.m_context != st.m_context) { textWriter.WriteLine( " | {0,-30} / {1}", child.m_reason, child.m_context ); } else { textWriter.WriteLine( " | {0}", child.m_reason ); } } } textWriter.WriteLine(); } textWriter.WriteLine(); } } public static void DumpAllByReason( System.IO.TextWriter textWriter ) { GrowOnlyHashTable< string, List< State > > lookup = HashTableFactory.New< string, List< State > >(); GrowOnlyHashTable< string, long > lookupCost = HashTableFactory.New< string, long >(); foreach(GrowOnlySet< State > set in s_threads) { foreach(State st in set) { string key = st.m_reason; List< State > lst; if(lookup.TryGetValue( key, out lst ) == false) { lst = new List< State >(); lookup [key] = lst; lookupCost[key] = 0; } lookupCost[key] += st.m_counter.TotalInclusiveMicroSeconds; lst.Add( st ); } } string[] keyArray = lookup.KeysToArray(); Array.Sort( keyArray, delegate ( string left, string right ) { return lookupCost[right].CompareTo( lookupCost[left] ); } ); foreach(string key in keyArray) { State[] states = SortByMostExpensive( lookup[key].ToArray() ); //--// long totalInclusiveMicroSeconds = 0; long totalExclusiveMicroSeconds = 0; int totalHits = 0; foreach(State st in states) { totalInclusiveMicroSeconds += st.m_counter.TotalInclusiveMicroSeconds; totalExclusiveMicroSeconds += st.m_counter.TotalExclusiveMicroSeconds; totalHits += st.m_counter.Hits; } textWriter.Write( "Key = {0}: ", key ); Emit( textWriter, "Exclusive", false, totalExclusiveMicroSeconds, totalHits ); Emit( textWriter, "Inclusive", false, totalInclusiveMicroSeconds, totalHits ); textWriter.WriteLine(); foreach(State st in states) { long inclusiveMicroSeconds = st.m_counter.TotalInclusiveMicroSeconds; long exclusiveMicroSeconds = st.m_counter.TotalExclusiveMicroSeconds; int hits = st.m_counter.Hits; textWriter.Write( " " ); Emit( textWriter, "Exclusive", true, exclusiveMicroSeconds, hits ); Emit( textWriter, "Inclusive", true, inclusiveMicroSeconds, hits ); textWriter.WriteLine( " | {0}", st.m_context ); if(st.m_children != null) { GrowOnlyHashTable< Timing.Nested, State > childrenInverted = GetInvertedHashTable( st.m_children ); foreach(Timing.Nested childCounter in SortByMostExpensive( childrenInverted.KeysToArray() )) { State child = childrenInverted[childCounter]; textWriter.Write( " " ); Emit( textWriter, "Child Exc", true, childCounter.TotalExclusiveMicroSeconds, childCounter.Hits ); if(child.m_context != st.m_context) { textWriter.WriteLine( " | {0,-30} / {1}", child.m_reason, child.m_context ); } else { textWriter.WriteLine( " | {0}", child.m_reason ); } } } textWriter.WriteLine(); } textWriter.WriteLine(); } } private static GrowOnlyHashTable< Timing.Nested, State > GetInvertedHashTable( GrowOnlyHashTable< State, Timing.Nested > ht ) { GrowOnlyHashTable< Timing.Nested, State > htInverted = HashTableFactory.NewWithReferenceEquality< Timing.Nested, State >(); htInverted.Load( ht.ValuesToArray(), ht.KeysToArray() ); return htInverted; } private static Timing.Nested[] SortByMostExpensive( Timing.Nested[] children ) { Array.Sort( children, delegate ( Timing.Nested left, Timing.Nested right ) { long leftUSec = left .TotalExclusiveMicroSeconds; long rightUSec = right.TotalExclusiveMicroSeconds; return rightUSec.CompareTo( leftUSec ); } ); return children; } private static State[] SortByMostExpensive( State[] states ) { Array.Sort( states, delegate ( State left, State right ) { long leftUSec = left .m_counter.TotalInclusiveMicroSeconds; long rightUSec = right.m_counter.TotalInclusiveMicroSeconds; return rightUSec.CompareTo( leftUSec ); } ); return states; } private static State[] SortByReason( State[] states ) { Array.Sort( states, delegate ( State left, State right ) { return left.m_reason.CompareTo( right.m_reason ); } ); return states; } private static void Emit( System.IO.TextWriter textWriter , string text , bool fAlign , long totalMicroSeconds , int totalHits ) { string fmt; if(fAlign) { fmt = " {0} => {1,10} uSec/{2,10} [{3,10:F1} uSec per hit]"; } else { fmt = " {0} => {1} uSec/{2} [{3} uSec per hit]"; } textWriter.Write( fmt, text, totalMicroSeconds, totalHits, totalHits > 0 ? (float)totalMicroSeconds / (float)totalHits : 0 ); } } #else public struct ContextualTiming : IDisposable { public ContextualTiming( object context , string reason ) { } public void Dispose() { } // // Access Methods // public long TotalInclusiveTicks { get { return 0; } } public long TotalInclusiveMicroSeconds { get { return 0; } } public long TotalExclusiveTicks { get { return 0; } } public long TotalExclusiveMicroSeconds { get { return 0; } } // // Debug Methods // public static bool IsEnabled() { return false; } public static void DumpAllByType( System.IO.TextWriter textWriter ) { } public static void DumpAllByReason( System.IO.TextWriter textWriter ) { } } #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.Linq; using Xunit; namespace System.IO.Tests { public class Directory_CreateDirectory : FileSystemTest { #region Utilities public virtual DirectoryInfo Create(string path) { return Directory.CreateDirectory(path); } #endregion #region UniversalTests [Fact] public void NullAsPath_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>(() => Create(null)); } [Fact] public void EmptyAsPath_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Create(string.Empty)); } [Fact] public void PathWithInvalidCharactersAsPath_ThrowsArgumentException() { var paths = IOInputs.GetPathsWithInvalidCharacters(); Assert.All(paths, (path) => { Assert.Throws<ArgumentException>(() => Create(path)); }); } [Fact] public void PathAlreadyExistsAsFile() { string path = GetTestFilePath(); File.Create(path).Dispose(); Assert.Throws<IOException>(() => Create(path)); Assert.Throws<IOException>(() => Create(IOServices.AddTrailingSlashIfNeeded(path))); Assert.Throws<IOException>(() => Create(IOServices.RemoveTrailingSlash(path))); } [Theory] [InlineData(FileAttributes.Hidden)] [InlineData(FileAttributes.ReadOnly)] [InlineData(FileAttributes.Normal)] public void PathAlreadyExistsAsDirectory(FileAttributes attributes) { DirectoryInfo testDir = Create(GetTestFilePath()); FileAttributes original = testDir.Attributes; try { testDir.Attributes = attributes; Assert.Equal(testDir.FullName, Create(testDir.FullName).FullName); } finally { testDir.Attributes = original; } } [Fact] public void RootPath() { string dirName = Path.GetPathRoot(Directory.GetCurrentDirectory()); DirectoryInfo dir = Create(dirName); Assert.Equal(dir.FullName, dirName); } [Fact] public void DotIsCurrentDirectory() { string path = GetTestFilePath(); DirectoryInfo result = Create(Path.Combine(path, ".")); Assert.Equal(IOServices.RemoveTrailingSlash(path), result.FullName); result = Create(Path.Combine(path, ".") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(path), result.FullName); } [Fact] public void CreateCurrentDirectory() { DirectoryInfo result = Create(Directory.GetCurrentDirectory()); Assert.Equal(Directory.GetCurrentDirectory(), result.FullName); } [Fact] public void DotDotIsParentDirectory() { DirectoryInfo result = Create(Path.Combine(GetTestFilePath(), "..")); Assert.Equal(IOServices.RemoveTrailingSlash(TestDirectory), result.FullName); result = Create(Path.Combine(GetTestFilePath(), "..") + Path.DirectorySeparatorChar); Assert.Equal(IOServices.AddTrailingSlashIfNeeded(TestDirectory), result.FullName); } [Fact] public void ValidPathWithTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetValidPathComponentNames(); Assert.All(components, (component) => { string path = IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component)); DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(result.Exists); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void ValidExtendedPathWithTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetValidPathComponentNames(); Assert.All(components, (component) => { string path = IOInputs.ExtendedPrefix + IOServices.AddTrailingSlashIfNeeded(Path.Combine(testDir.FullName, component)); DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(result.Exists); }); } [Fact] public void ValidPathWithoutTrailingSlash() { DirectoryInfo testDir = Directory.CreateDirectory(GetTestFilePath()); var components = IOInputs.GetValidPathComponentNames(); Assert.All(components, (component) => { string path = testDir.FullName + Path.DirectorySeparatorChar + component; DirectoryInfo result = Create(path); Assert.Equal(path, result.FullName); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] public void ValidPathWithMultipleSubdirectories() { string dirName = Path.Combine(GetTestFilePath(), "Test", "Test", "Test"); DirectoryInfo dir = Create(dirName); Assert.Equal(dir.FullName, dirName); } [Fact] public void AllowedSymbols() { string dirName = Path.Combine(TestDirectory, Path.GetRandomFileName() + "!@#$%^&"); DirectoryInfo dir = Create(dirName); Assert.Equal(dir.FullName, dirName); } [Fact] public void DirectoryEqualToMaxDirectory_CanBeCreated() { DirectoryInfo testDir = Create(GetTestFilePath()); PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, IOInputs.MaxComponent); Assert.All(path.SubPaths, (subpath) => { DirectoryInfo result = Create(subpath); Assert.Equal(subpath, result.FullName); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] public void DirectoryEqualToMaxDirectory_CanBeCreatedAllAtOnce() { DirectoryInfo testDir = Create(GetTestFilePath()); PathInfo path = IOServices.GetPath(testDir.FullName, IOInputs.MaxDirectory, maxComponent: 10); DirectoryInfo result = Create(path.FullPath); Assert.Equal(path.FullPath, result.FullName); Assert.True(Directory.Exists(result.FullName)); } [Fact] public void DirectoryWithComponentLongerThanMaxComponentAsPath_ThrowsPathTooLongException() { // While paths themselves can be up to 260 characters including trailing null, file systems // limit each components of the path to a total of 255 characters. var paths = IOInputs.GetPathsWithComponentLongerThanMaxComponent(); Assert.All(paths, (path) => { Assert.Throws<PathTooLongException>(() => Create(path)); }); } #endregion #region PlatformSpecific [Fact] [PlatformSpecific(PlatformID.Windows)] public void PathWithInvalidColons_ThrowsNotSupportedException() { var paths = IOInputs.GetPathsWithInvalidColons(); Assert.All(paths, (path) => { Assert.Throws<NotSupportedException>(() => Create(path)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void DirectoryLongerThanMaxPath_Succeeds() { var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath()); Assert.All(paths, (path) => { DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void DirectoryLongerThanMaxLongPath_ThrowsPathTooLongException() { var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath()); Assert.All(paths, (path) => { Assert.Throws<PathTooLongException>(() => Create(path)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void DirectoryLongerThanMaxLongPathWithExtendedSyntax_ThrowsPathTooLongException() { var paths = IOInputs.GetPathsLongerThanMaxLongPath(GetTestFilePath(), useExtendedSyntax: true); Assert.All(paths, (path) => { Assert.Throws<PathTooLongException>(() => Create(path)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void ExtendedDirectoryLongerThanLegacyMaxPath_Succeeds() { var paths = IOInputs.GetPathsLongerThanMaxPath(GetTestFilePath(), useExtendedSyntax: true); Assert.All(paths, (path) => { Assert.True(Create(path).Exists); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void DirectoryLongerThanMaxDirectoryAsPath_Succeeds() { var paths = IOInputs.GetPathsLongerThanMaxDirectory(GetTestFilePath()); Assert.All(paths, (path) => { var result = Create(path); Assert.True(Directory.Exists(result.FullName)); }); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixPathLongerThan256_Allowed() { DirectoryInfo testDir = Create(GetTestFilePath()); PathInfo path = IOServices.GetPath(testDir.FullName, 257, IOInputs.MaxComponent); DirectoryInfo result = Create(path.FullPath); Assert.Equal(path.FullPath, result.FullName); Assert.True(Directory.Exists(result.FullName)); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixPathWithDeeplyNestedDirectories() { DirectoryInfo parent = Create(GetTestFilePath()); for (int i = 1; i <= 100; i++) // 100 == arbitrarily large number of directories { parent = Create(Path.Combine(parent.FullName, "dir" + i)); Assert.True(Directory.Exists(parent.FullName)); } } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsWhiteSpaceAsPath_ThrowsArgumentException() { var paths = IOInputs.GetWhiteSpace(); Assert.All(paths, (path) => { Assert.Throws<ArgumentException>(() => Create(path)); }); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixWhiteSpaceAsPath_Allowed() { var paths = IOInputs.GetWhiteSpace(); Assert.All(paths, (path) => { Create(Path.Combine(TestDirectory, path)); Assert.True(Directory.Exists(Path.Combine(TestDirectory, path))); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsTrailingWhiteSpace() { // Windows will remove all nonsignificant whitespace in a path DirectoryInfo testDir = Create(GetTestFilePath()); var components = IOInputs.GetWhiteSpace(); Assert.All(components, (component) => { string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component; DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); Assert.Equal(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void WindowsExtendedSyntaxWhiteSpace() { var paths = IOInputs.GetSimpleWhiteSpace(); using (TemporaryDirectory directory = new TemporaryDirectory()) { foreach (var path in paths) { string extendedPath = Path.Combine(IOInputs.ExtendedPrefix + directory.Path, path); Directory.CreateDirectory(extendedPath); Assert.True(Directory.Exists(extendedPath), extendedPath); } } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public void UnixNonSignificantTrailingWhiteSpace() { // Unix treats trailing/prename whitespace as significant and a part of the name. DirectoryInfo testDir = Create(GetTestFilePath()); var components = IOInputs.GetWhiteSpace(); Assert.All(components, (component) => { string path = IOServices.RemoveTrailingSlash(testDir.FullName) + component; DirectoryInfo result = Create(path); Assert.True(Directory.Exists(result.FullName)); Assert.NotEqual(testDir.FullName, IOServices.RemoveTrailingSlash(result.FullName)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // alternate data streams public void PathWithAlternateDataStreams_ThrowsNotSupportedException() { var paths = IOInputs.GetPathsWithAlternativeDataStreams(); Assert.All(paths, (path) => { Assert.Throws<NotSupportedException>(() => Create(path)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // device name prefixes public void PathWithReservedDeviceNameAsPath_ThrowsDirectoryNotFoundException() { // Throws DirectoryNotFoundException, when the behavior really should be an invalid path var paths = IOInputs.GetPathsWithReservedDeviceNames(); Assert.All(paths, (path) => { Assert.Throws<DirectoryNotFoundException>(() => Create(path)); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // device name prefixes public void PathWithReservedDeviceNameAsExtendedPath() { var paths = IOInputs.GetReservedDeviceNames(); using (TemporaryDirectory directory = new TemporaryDirectory()) { Assert.All(paths, (path) => { Assert.True(Create(IOInputs.ExtendedPrefix + Path.Combine(directory.Path, path)).Exists, path); }); } } [Fact] [PlatformSpecific(PlatformID.Windows)] // UNC shares public void UncPathWithoutShareNameAsPath_ThrowsArgumentException() { var paths = IOInputs.GetUncPathsWithoutShareName(); foreach (var path in paths) { Assert.Throws<ArgumentException>(() => Create(path)); } } [Fact] [PlatformSpecific(PlatformID.Windows)] // UNC shares public void UNCPathWithOnlySlashes() { Assert.Throws<ArgumentException>(() => Create("//")); } [Fact] [PlatformSpecific(PlatformID.Windows)] // drive labels public void CDriveCase() { DirectoryInfo dir = Create("c:\\"); DirectoryInfo dir2 = Create("C:\\"); Assert.NotEqual(dir.FullName, dir2.FullName); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void DriveLetter_Windows() { // On Windows, DirectoryInfo will replace "<DriveLetter>:" with "." var driveLetter = Create(Directory.GetCurrentDirectory()[0] + ":"); var current = Create("."); Assert.Equal(current.Name, driveLetter.Name); Assert.Equal(current.FullName, driveLetter.FullName); } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] [ActiveIssue(2459)] public void DriveLetter_Unix() { // On Unix, there's no special casing for drive letters, which are valid file names var driveLetter = Create("C:"); var current = Create("."); Assert.Equal("C:", driveLetter.Name); Assert.Equal(Path.Combine(current.FullName, "C:"), driveLetter.FullName); Directory.Delete("C:"); } [Fact] [PlatformSpecific(PlatformID.Windows)] // testing drive labels public void NonExistentDriveAsPath_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => { Create(IOServices.GetNonExistentDrive()); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // testing drive labels public void SubdirectoryOnNonExistentDriveAsPath_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => { Create(Path.Combine(IOServices.GetNonExistentDrive(), "Subdirectory")); }); } [Fact] [ActiveIssue(1221)] [PlatformSpecific(PlatformID.Windows)] // testing drive labels public void NotReadyDriveAsPath_ThrowsDirectoryNotFoundException() { // Behavior is suspect, should really have thrown IOException similar to the SubDirectory case var drive = IOServices.GetNotReadyDrive(); if (drive == null) { Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted."); return; } Assert.Throws<DirectoryNotFoundException>(() => { Create(drive); }); } [Fact] [PlatformSpecific(PlatformID.Windows)] // testing drive labels [ActiveIssue(1221)] public void SubdirectoryOnNotReadyDriveAsPath_ThrowsIOException() { var drive = IOServices.GetNotReadyDrive(); if (drive == null) { Console.WriteLine("Skipping test. Unable to find a not-ready drive, such as CD-Rom with no disc inserted."); return; } // 'Device is not ready' Assert.Throws<IOException>(() => { Create(Path.Combine(drive, "Subdirectory")); }); } #if !TEST_WINRT // Cannot set current directory to root from appcontainer with it's default ACL /* [Fact] [ActiveIssue(1220)] // SetCurrentDirectory public void DotDotAsPath_WhenCurrentDirectoryIsRoot_DoesNotThrow() { string root = Path.GetPathRoot(Directory.GetCurrentDirectory()); using (CurrentDirectoryContext context = new CurrentDirectoryContext(root)) { DirectoryInfo result = Create(".."); Assert.True(Directory.Exists(result.FullName)); Assert.Equal(root, result.FullName); } } */ #endif #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 Xunit; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace System.Runtime.Loader.Tests { public class SecondaryLoadContext : AssemblyLoadContext { protected override Assembly Load(AssemblyName assemblyName) { return null; } } public class FallbackLoadContext : AssemblyLoadContext { protected override Assembly Load(AssemblyName assemblyName) { // Return null since we expect the DefaultContext to be used to bind // the assembly bind request. return null; } } public class OverrideDefaultLoadContext : AssemblyLoadContext { public bool LoadedFromContext { get; set; } = false; protected override Assembly Load(AssemblyName assemblyName) { // Override the assembly that was loaded in DefaultContext. string assemblyPath = Path.Combine(Path.GetDirectoryName(typeof(string).Assembly.Location), assemblyName.Name + ".dll"); Assembly assembly = LoadFromAssemblyPath(assemblyPath); LoadedFromContext = true; return assembly; } } public class DefaultLoadContextTests { private const string TestAssemblyName = "System.Runtime.Loader.Noop.Assembly"; private string _assemblyPath; private string _defaultLoadDirectory; // Since the first non-Null returning callback should stop Resolving event processing, // this counter is used to assert the same. private int _numNonNullResolutions = 0; public DefaultLoadContextTests() { _defaultLoadDirectory = GetDefaultAssemblyLoadDirectory(); _assemblyPath = Path.Combine(_defaultLoadDirectory, "System.Runtime.Loader.Noop.Assembly_test.dll"); } private static string GetDefaultAssemblyLoadDirectory() { return Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); } private Assembly ResolveAssembly(AssemblyLoadContext sender, AssemblyName assembly) { string resolvedAssemblyPath = Path.Combine(_defaultLoadDirectory, assembly.Name + "_test.dll"); _numNonNullResolutions++; return sender.LoadFromAssemblyPath(resolvedAssemblyPath); } private Assembly ResolveAssemblyAgain(AssemblyLoadContext sender, AssemblyName assembly) { return ResolveAssembly(sender, assembly); } private Assembly ResolveNullAssembly(AssemblyLoadContext sender, AssemblyName assembly) { return null; } [Fact] public void LoadInDefaultContext() { // This will attempt to load an assembly, by path, in the Default Load context via the Resolving event var assemblyName = new AssemblyName(TestAssemblyName); // By default, the assembly should not be found in DefaultContext at all Assert.Throws<FileNotFoundException>(() => Assembly.Load(assemblyName)); // Create a secondary load context and wireup its resolving event SecondaryLoadContext slc = new SecondaryLoadContext(); slc.Resolving += ResolveAssembly; Assert.Contains(slc, AssemblyLoadContext.All); // Attempt to load the assembly in secondary load context var slcLoadedAssembly = slc.LoadFromAssemblyName(assemblyName); // We should have successfully loaded the assembly in secondary load context. Assert.NotNull(slcLoadedAssembly); Assert.Contains(slcLoadedAssembly, slc.Assemblies); // And make sure the simple name matches Assert.Equal(TestAssemblyName, slcLoadedAssembly.GetName().Name); // We should have only invoked non-Null returning handler once Assert.Equal(1, _numNonNullResolutions); slc.Resolving -= ResolveAssembly; // Reset the non-Null resolution counter _numNonNullResolutions = 0; // Now, wireup the Resolving event of default context to locate the assembly via multiple handlers AssemblyLoadContext.Default.Resolving += ResolveNullAssembly; AssemblyLoadContext.Default.Resolving += ResolveAssembly; AssemblyLoadContext.Default.Resolving += ResolveAssemblyAgain; // This will invoke the resolution via VM requiring to bind using the TPA binder var assemblyExpectedFromLoad = Assembly.Load(assemblyName); // We should have successfully loaded the assembly in default context. Assert.NotNull(assemblyExpectedFromLoad); Assert.Contains(assemblyExpectedFromLoad, AssemblyLoadContext.Default.Assemblies); // We should have only invoked non-Null returning handler once Assert.Equal(1, _numNonNullResolutions); // And make sure the simple name matches Assert.Equal(TestAssemblyName, assemblyExpectedFromLoad.GetName().Name); // The assembly loaded in DefaultContext should have a different reference from the one in secondary load context Assert.NotEqual(slcLoadedAssembly, assemblyExpectedFromLoad); // Reset the non-Null resolution counter _numNonNullResolutions = 0; // Since the assembly is already loaded in TPA Binder, we will get that back without invoking any Resolving event handlers var assemblyExpected = AssemblyLoadContext.Default.LoadFromAssemblyName(assemblyName); Assert.Equal(0, _numNonNullResolutions); // We should have successfully loaded the assembly in default context. Assert.NotNull(assemblyExpected); // What we got via Assembly.Load and LoadFromAssemblyName should be the same Assert.Equal(assemblyExpected, assemblyExpectedFromLoad); // And make sure the simple name matches Assert.Equal(assemblyExpected.GetName().Name, TestAssemblyName); // Unwire the Resolving event. AssemblyLoadContext.Default.Resolving -= ResolveAssemblyAgain; AssemblyLoadContext.Default.Resolving -= ResolveAssembly; AssemblyLoadContext.Default.Resolving -= ResolveNullAssembly; // Unwire the Resolving event and attempt to load the assembly again. This time // it should be found in the Default Load Context. var assemblyLoaded = Assembly.Load(new AssemblyName(TestAssemblyName)); // We should have successfully found the assembly in default context. Assert.NotNull(assemblyLoaded); // Ensure that we got the same assembly reference back. Assert.Equal(assemblyExpected, assemblyLoaded); // Run tests for binding from DefaultContext when custom load context does not have TPA overrides. DefaultContextFallback(); // Run tests for overriding DefaultContext when custom load context has TPA overrides. DefaultContextOverrideTPA(); } [Fact] public static void LoadNonExistentInDefaultContext() { // Now, try to load an assembly that does not exist Assert.Throws<FileNotFoundException>(() => AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName("System.Runtime.Loader.NonExistent.Assembly"))); } private void DefaultContextFallback() { var lcDefault = AssemblyLoadContext.Default; // Load the assembly in custom load context FallbackLoadContext flc = new FallbackLoadContext(); var asmTargetAsm = flc.LoadFromAssemblyPath(_assemblyPath); var loadedContext = AssemblyLoadContext.GetLoadContext(asmTargetAsm); // LoadContext of the assembly should be the custom context and not DefaultContext Assert.NotEqual(lcDefault, flc); Assert.Equal(flc, loadedContext); // Get reference to the helper method that will load assemblies (actually, resolve them) // from DefaultContext Type type = asmTargetAsm.GetType("System.Runtime.Loader.Tests.TestClass"); var method = System.Reflection.TypeExtensions.GetMethod(type, "LoadFromDefaultContext"); // Load System.Runtime - since this is on TPA, it should get resolved from DefaultContext // since FallbackLoadContext does not override the Load method to specify its location. var assemblyName = "System.Runtime, Version=4.0.0.0"; Assembly asmLoaded = (Assembly)method.Invoke(null, new object[] {assemblyName}); loadedContext = AssemblyLoadContext.GetLoadContext(asmLoaded); // Confirm assembly Loaded from DefaultContext Assert.Equal(lcDefault, loadedContext); Assert.NotEqual(flc, loadedContext); // Now, do the same from an assembly that we explicitly had loaded in DefaultContext // in the caller of this method. We should get it from FallbackLoadContext since we // explicitly loaded it there as well. assemblyName = TestAssemblyName; Assembly asmLoaded2 = (Assembly)method.Invoke(null, new object[] {assemblyName}); loadedContext = AssemblyLoadContext.GetLoadContext(asmLoaded2); Assert.NotEqual(lcDefault, loadedContext); Assert.Equal(flc, loadedContext); // Attempt to bind an assembly that has not been loaded in DefaultContext and is not // present on TPA as well. Such an assembly will not trigger a load since we only consult // the DefaultContext cache (including assemblies on TPA list) in an attempt to bind. assemblyName = "System.Runtime.Loader.Noop.Assembly.NonExistent"; Exception ex = null; try { method.Invoke(null, new object[] {assemblyName}); } catch (TargetInvocationException tie) { ex = tie.InnerException; } Assert.Equal(typeof(FileNotFoundException), ex.GetType()); } private void DefaultContextOverrideTPA() { var lcDefault = AssemblyLoadContext.Default; // Load the assembly in custom load context OverrideDefaultLoadContext olc = new OverrideDefaultLoadContext(); var asmTargetAsm = olc.LoadFromAssemblyPath(_assemblyPath); var loadedContext = AssemblyLoadContext.GetLoadContext(asmTargetAsm); olc.LoadedFromContext = false; // LoadContext of the assembly should be the custom context and not DefaultContext Assert.NotEqual(lcDefault, olc); Assert.Equal(olc, loadedContext); // Get reference to the helper method that will load assemblies (actually, resolve them) // from DefaultContext Type type = asmTargetAsm.GetType("System.Runtime.Loader.Tests.TestClass", true); var method = System.Reflection.TypeExtensions.GetMethod(type, "LoadFromDefaultContext"); // Load System.Runtime - since this is on TPA, it should get resolved from our custom load context // since the Load method has been implemented to override TPA assemblies. var assemblyName = "System.Runtime, Version=4.0.0.0"; Assembly asmLoaded = (Assembly)method.Invoke(null, new object[] {assemblyName}); loadedContext = AssemblyLoadContext.GetLoadContext(asmLoaded); // Confirm assembly did not load from DefaultContext Assert.NotEqual(lcDefault, loadedContext); Assert.Equal(olc, loadedContext); Assert.True(olc.LoadedFromContext); // Now, do the same for an assembly that we explicitly had loaded in DefaultContext // in the caller of this method and ALSO loaded in the current load context. We should get it from our LoadContext, // without invoking the Load override, since it is already loaded. assemblyName = TestAssemblyName; olc.LoadedFromContext = false; Assembly asmLoaded2 = (Assembly)method.Invoke(null, new object[] {assemblyName}); loadedContext = AssemblyLoadContext.GetLoadContext(asmLoaded2); // Confirm assembly loaded from the intended LoadContext Assert.NotEqual(lcDefault, loadedContext); Assert.Equal(olc, loadedContext); Assert.False(olc.LoadedFromContext); } } }
// 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.Globalization; using System.IO; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public class CSharpCommandLineParser : CommandLineParser { public static CSharpCommandLineParser Default { get; } = new CSharpCommandLineParser(); internal static CSharpCommandLineParser ScriptRunner { get; } = new CSharpCommandLineParser(isScriptRunner: true); internal CSharpCommandLineParser(bool isScriptRunner = false) : base(CSharp.MessageProvider.Instance, isScriptRunner) { } protected override string RegularFileExtension { get { return ".cs"; } } protected override string ScriptFileExtension { get { return ".csx"; } } internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectoryOpt, string additionalReferenceDirectories) { return Parse(args, baseDirectory, sdkDirectoryOpt, additionalReferenceDirectories); } /// <summary> /// Parses a command line. /// </summary> /// <param name="args">A collection of strings representing the command line arguments.</param> /// <param name="baseDirectory">The base directory used for qualifying file locations.</param> /// <param name="sdkDirectory">The directory to search for mscorlib, or null if not available.</param> /// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param> /// <returns>a commandlinearguments object representing the parsed command line.</returns> public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null) { List<Diagnostic> diagnostics = new List<Diagnostic>(); List<string> flattenedArgs = new List<string>(); List<string> scriptArgs = IsScriptRunner ? new List<string>() : null; FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory); string appConfigPath = null; bool displayLogo = true; bool displayHelp = false; bool optimize = false; bool checkOverflow = false; bool allowUnsafe = false; bool concurrentBuild = true; bool deterministic = false; // TODO(5431): Enable deterministic mode by default bool emitPdb = false; DebugInformationFormat debugInformationFormat = DebugInformationFormat.Pdb; bool debugPlus = false; string pdbPath = null; bool noStdLib = IsScriptRunner; // don't add mscorlib from sdk dir when running scripts string outputDirectory = baseDirectory; ImmutableArray<KeyValuePair<string, string>> pathMap = ImmutableArray<KeyValuePair<string, string>>.Empty; string outputFileName = null; string documentationPath = null; string errorLogPath = null; bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid. bool utf8output = false; OutputKind outputKind = OutputKind.ConsoleApplication; SubsystemVersion subsystemVersion = SubsystemVersion.None; LanguageVersion languageVersion = CSharpParseOptions.Default.LanguageVersion; string mainTypeName = null; string win32ManifestFile = null; string win32ResourceFile = null; string win32IconFile = null; bool noWin32Manifest = false; Platform platform = Platform.AnyCpu; ulong baseAddress = 0; int fileAlignment = 0; bool? delaySignSetting = null; string keyFileSetting = null; string keyContainerSetting = null; List<ResourceDescription> managedResources = new List<ResourceDescription>(); List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>(); bool sourceFilesSpecified = false; bool resourcesOrModulesSpecified = false; Encoding codepage = null; var checksumAlgorithm = SourceHashAlgorithm.Sha1; var defines = ArrayBuilder<string>.GetInstance(); List<CommandLineReference> metadataReferences = new List<CommandLineReference>(); List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>(); List<string> libPaths = new List<string>(); List<string> sourcePaths = new List<string>(); List<string> keyFileSearchPaths = new List<string>(); List<string> usings = new List<string>(); var generalDiagnosticOption = ReportDiagnostic.Default; var diagnosticOptions = new Dictionary<string, ReportDiagnostic>(); var noWarns = new Dictionary<string, ReportDiagnostic>(); var warnAsErrors = new Dictionary<string, ReportDiagnostic>(); int warningLevel = 4; bool highEntropyVA = false; bool printFullPaths = false; string moduleAssemblyName = null; string moduleName = null; List<string> features = new List<string>(); string runtimeMetadataVersion = null; bool errorEndLocation = false; bool reportAnalyzer = false; string instrument = ""; CultureInfo preferredUILang = null; string touchedFilesPath = null; bool optionsEnded = false; bool interactiveMode = false; bool publicSign = false; // Process ruleset files first so that diagnostic severity settings specified on the command line via // /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file. if (!IsScriptRunner) { foreach (string arg in flattenedArgs) { string name, value; if (TryParseOption(arg, out name, out value) && (name == "ruleset")) { var unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory); } } } } foreach (string arg in flattenedArgs) { Debug.Assert(optionsEnded || !arg.StartsWith("@", StringComparison.Ordinal)); string name, value; if (optionsEnded || !TryParseOption(arg, out name, out value)) { sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics)); if (sourceFiles.Count > 0) { sourceFilesSpecified = true; } continue; } switch (name) { case "?": case "help": displayHelp = true; continue; case "r": case "reference": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false)); continue; case "features": if (value == null) { features.Clear(); } else { features.Add(value); } continue; case "lib": case "libpath": case "libpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics); continue; #if DEBUG case "attachdebugger": Debugger.Launch(); continue; #endif } if (IsScriptRunner) { switch (name) { case "-": // csi -- script.csx if (value != null) break; // Indicates that the remaining arguments should not be treated as options. optionsEnded = true; continue; case "i": case "i+": if (value != null) break; interactiveMode = true; continue; case "i-": if (value != null) break; interactiveMode = false; continue; case "loadpath": case "loadpaths": ParseAndResolveReferencePaths(name, value, baseDirectory, sourcePaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics); continue; case "u": case "using": case "usings": case "import": case "imports": usings.AddRange(ParseUsings(arg, value, diagnostics)); continue; } } else { switch (name) { case "a": case "analyzer": analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics)); continue; case "d": case "define": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } IEnumerable<Diagnostic> defineDiagnostics; defines.AddRange(ParseConditionalCompilationSymbols(RemoveQuotesAndSlashes(value), out defineDiagnostics)); diagnostics.AddRange(defineDiagnostics); continue; case "codepage": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var encoding = TryParseEncodingName(value); if (encoding == null) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value); continue; } codepage = encoding; continue; case "checksumalgorithm": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var newChecksumAlgorithm = TryParseHashAlgorithmName(value); if (newChecksumAlgorithm == SourceHashAlgorithm.None) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value); continue; } checksumAlgorithm = newChecksumAlgorithm; continue; case "checked": case "checked+": if (value != null) { break; } checkOverflow = true; continue; case "checked-": if (value != null) break; checkOverflow = false; continue; case "instrument": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { instrument = value; } continue; case "noconfig": // It is already handled (see CommonCommandLineCompiler.cs). continue; case "sqmsessionguid": // The use of SQM is deprecated in the compiler but we still support the parsing of the option for // back compat reasons. if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name); } else { Guid sqmSessionGuid; if (!Guid.TryParse(value, out sqmSessionGuid)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name); } } continue; case "preferreduilang": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } try { preferredUILang = new CultureInfo(value); if (CorLightup.Desktop.IsUserCustomCulture(preferredUILang) ?? false) { // Do not use user custom cultures. preferredUILang = null; } } catch (CultureNotFoundException) { } if (preferredUILang == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value); } continue; case "out": if (string.IsNullOrWhiteSpace(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory); } continue; case "t": case "target": if (value == null) { break; // force 'unrecognized option' } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); } else { outputKind = ParseTarget(value, diagnostics); } continue; case "moduleassemblyname": value = value != null ? value.Unquote() : null; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); } else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value)) { // Dev11 C# doesn't check the name (VB does) AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg); } else { moduleAssemblyName = value; } continue; case "modulename": var unquotedModuleName = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquotedModuleName)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename"); continue; } else { moduleName = unquotedModuleName; } continue; case "platform": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg); } else { platform = ParsePlatform(value, diagnostics); } continue; case "recurse": value = RemoveQuotesAndSlashes(value); if (value == null) { break; // force 'unrecognized option' } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { int before = sourceFiles.Count; sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics)); if (sourceFiles.Count > before) { sourceFilesSpecified = true; } } continue; case "doc": parseDocumentationComments = true; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); continue; } string unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { // CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out) // if we just let the next case handle /doc:"". AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument. } else { documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "addmodule": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:"); } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. // An error will be reported by the assembly manager anyways. metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module))); resourcesOrModulesSpecified = true; } continue; case "l": case "link": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true)); continue; case "win32res": win32ResourceFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32icon": win32IconFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32manifest": win32ManifestFile = GetWin32Setting(arg, value, diagnostics); noWin32Manifest = false; continue; case "nowin32manifest": noWin32Manifest = true; win32ManifestFile = null; continue; case "res": case "resource": if (value == null) { break; // Dev11 reports unrecognized option } var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true); if (embeddedResource != null) { managedResources.Add(embeddedResource); resourcesOrModulesSpecified = true; } continue; case "linkres": case "linkresource": if (value == null) { break; // Dev11 reports unrecognized option } var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false); if (linkedResource != null) { managedResources.Add(linkedResource); resourcesOrModulesSpecified = true; } continue; case "debug": emitPdb = true; // unused, parsed for backward compat only value = RemoveQuotesAndSlashes(value); if (value != null) { if (value.IsEmpty()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name); continue; } switch (value.ToLower()) { case "full": case "pdbonly": debugInformationFormat = DebugInformationFormat.Pdb; break; case "portable": debugInformationFormat = DebugInformationFormat.PortablePdb; break; case "embedded": debugInformationFormat = DebugInformationFormat.Embedded; break; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value); break; } } continue; case "debug+": //guard against "debug+:xx" if (value != null) break; emitPdb = true; debugPlus = true; continue; case "debug-": if (value != null) break; emitPdb = false; debugPlus = false; continue; case "o": case "optimize": case "o+": case "optimize+": if (value != null) break; optimize = true; continue; case "o-": case "optimize-": if (value != null) break; optimize = false; continue; case "deterministic": case "deterministic+": if (value != null) break; deterministic = true; continue; case "deterministic-": if (value != null) break; deterministic = false; continue; case "p": case "parallel": case "p+": case "parallel+": if (value != null) break; concurrentBuild = true; continue; case "p-": case "parallel-": if (value != null) break; concurrentBuild = false; continue; case "warnaserror": case "warnaserror+": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Error; // Reset specific warnaserror options (since last /warnaserror flag on the command line always wins), // and bump warnings to errors. warnAsErrors.Clear(); foreach (var key in diagnosticOptions.Keys) { if (diagnosticOptions[key] == ReportDiagnostic.Warn) { warnAsErrors[key] = ReportDiagnostic.Error; } } continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value)); } continue; case "warnaserror-": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Default; // Clear specific warnaserror options (since last /warnaserror flag on the command line always wins). warnAsErrors.Clear(); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { foreach (var id in ParseWarnings(value)) { ReportDiagnostic ruleSetValue; if (diagnosticOptions.TryGetValue(id, out ruleSetValue)) { warnAsErrors[id] = ruleSetValue; } else { warnAsErrors[id] = ReportDiagnostic.Default; } } } continue; case "w": case "warn": value = RemoveQuotesAndSlashes(value); if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } int newWarningLevel; if (string.IsNullOrEmpty(value) || !int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (newWarningLevel < 0 || newWarningLevel > 4) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name); } else { warningLevel = newWarningLevel; } continue; case "nowarn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value)); } continue; case "unsafe": case "unsafe+": if (value != null) break; allowUnsafe = true; continue; case "unsafe-": if (value != null) break; allowUnsafe = false; continue; case "langversion": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:"); } else if (!TryParseLanguageVersion(value, CSharpParseOptions.Default.LanguageVersion, out languageVersion)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value); } continue; case "delaysign": case "delaysign+": if (value != null) { break; } delaySignSetting = true; continue; case "delaysign-": if (value != null) { break; } delaySignSetting = false; continue; case "publicsign": case "publicsign+": if (value != null) { break; } publicSign = true; continue; case "publicsign-": if (value != null) { break; } publicSign = false; continue; case "keyfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile"); } else { keyFileSetting = RemoveQuotesAndSlashes(value); } // NOTE: Dev11/VB also clears "keycontainer", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "keycontainer": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer"); } else { keyContainerSetting = value; } // NOTE: Dev11/VB also clears "keyfile", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "highentropyva": case "highentropyva+": if (value != null) break; highEntropyVA = true; continue; case "highentropyva-": if (value != null) break; highEntropyVA = false; continue; case "nologo": displayLogo = false; continue; case "baseaddress": value = RemoveQuotesAndSlashes(value); ulong newBaseAddress; if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress)) { if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value); } } else { baseAddress = newBaseAddress; } continue; case "subsystemversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion"); continue; } // It seems VS 2012 just silently corrects invalid values and suppresses the error message SubsystemVersion version = SubsystemVersion.None; if (SubsystemVersion.TryParse(value, out version)) { subsystemVersion = version; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value); } continue; case "touchedfiles": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles"); continue; } else { touchedFilesPath = unquoted; } continue; case "bugreport": UnimplementedSwitch(diagnostics, name); continue; case "utf8output": if (value != null) break; utf8output = true; continue; case "m": case "main": // Remove any quotes for consistent behavior as MSBuild can return quoted or // unquoted main. unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } mainTypeName = unquoted; continue; case "fullpaths": if (value != null) break; printFullPaths = true; continue; case "pathmap": // "/pathmap:K1=V1,K2=V2..." { if (value == null) break; pathMap = pathMap.Concat(ParsePathMap(value, diagnostics)); } continue; case "filealign": value = RemoveQuotesAndSlashes(value); ushort newAlignment; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (!TryParseUInt16(value, out newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else if (!CompilationOptions.IsValidFileAlignment(newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else { fileAlignment = newAlignment; } continue; case "pdb": value = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { pdbPath = ParsePdbPath(value, diagnostics, baseDirectory); } continue; case "errorendlocation": errorEndLocation = true; continue; case "reportanalyzer": reportAnalyzer = true; continue; case "nostdlib": case "nostdlib+": if (value != null) break; noStdLib = true; continue; case "nostdlib-": if (value != null) break; noStdLib = false; continue; case "errorreport": continue; case "errorlog": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveQuotesAndSlashes(arg)); } else { errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "appconfig": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveQuotesAndSlashes(arg)); } else { appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "runtimemetadataversion": unquoted = RemoveQuotesAndSlashes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } runtimeMetadataVersion = unquoted; continue; case "ruleset": // The ruleset arg has already been processed in a separate pass above. continue; case "additionalfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name); continue; } additionalFiles.AddRange(ParseAdditionalFileArgument(value, baseDirectory, diagnostics)); continue; } } AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg); } foreach (var o in warnAsErrors) { diagnosticOptions[o.Key] = o.Value; } // Specific nowarn options always override specific warnaserror options. foreach (var o in noWarns) { diagnosticOptions[o.Key] = o.Value; } if (!IsScriptRunner && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified)) { AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources); } if (!noStdLib && sdkDirectory != null) { metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly)); } if (!platform.Requires64Bit()) { if (baseAddress > uint.MaxValue - 0x8000) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress)); baseAddress = 0; } } // add additional reference paths if specified if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories)) { ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics); } ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths); ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics); // Dev11 searches for the key file in the current directory and assembly output directory. // We always look to base directory and then examine the search paths. keyFileSearchPaths.Add(baseDirectory); if (baseDirectory != outputDirectory) { keyFileSearchPaths.Add(outputDirectory); } // Public sign doesn't use the legacy search path settings if (publicSign && !string.IsNullOrWhiteSpace(keyFileSetting)) { keyFileSetting = ParseGenericPathToFile(keyFileSetting, diagnostics, baseDirectory); } var parsedFeatures = CompilerOptionParseUtilities.ParseFeatures(features); string compilationName; GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName); var parseOptions = new CSharpParseOptions ( languageVersion: languageVersion, preprocessorSymbols: defines.ToImmutableAndFree(), documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None, kind: SourceCodeKind.Regular, features: parsedFeatures ); var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); // We want to report diagnostics with source suppression in the error log file. // However, these diagnostics won't be reported on the command line. var reportSuppressedDiagnostics = errorLogPath != null; var options = new CSharpCompilationOptions ( outputKind: outputKind, moduleName: moduleName, mainTypeName: mainTypeName, scriptClassName: WellKnownMemberNames.DefaultScriptClassName, usings: usings, optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug, checkOverflow: checkOverflow, allowUnsafe: allowUnsafe, deterministic: deterministic, concurrentBuild: concurrentBuild, cryptoKeyContainer: keyContainerSetting, cryptoKeyFile: keyFileSetting, delaySign: delaySignSetting, platform: platform, generalDiagnosticOption: generalDiagnosticOption, warningLevel: warningLevel, specificDiagnosticOptions: diagnosticOptions, reportSuppressedDiagnostics: reportSuppressedDiagnostics, publicSign: publicSign ); if (debugPlus) { options = options.WithDebugPlusMode(debugPlus); } var emitOptions = new EmitOptions ( metadataOnly: false, debugInformationFormat: debugInformationFormat, pdbFilePath: null, // to be determined later outputNameOverride: null, // to be determined later baseAddress: baseAddress, highEntropyVirtualAddressSpace: highEntropyVA, fileAlignment: fileAlignment, subsystemVersion: subsystemVersion, runtimeMetadataVersion: runtimeMetadataVersion, instrument: instrument ); // add option incompatibility errors if any diagnostics.AddRange(options.Errors); return new CSharpCommandLineArguments { IsScriptRunner = IsScriptRunner, InteractiveMode = interactiveMode || IsScriptRunner && sourceFiles.Count == 0, BaseDirectory = baseDirectory, PathMap = pathMap, Errors = diagnostics.AsImmutable(), Utf8Output = utf8output, CompilationName = compilationName, OutputFileName = outputFileName, PdbPath = pdbPath, EmitPdb = emitPdb, OutputDirectory = outputDirectory, DocumentationPath = documentationPath, ErrorLogPath = errorLogPath, AppConfigPath = appConfigPath, SourceFiles = sourceFiles.AsImmutable(), Encoding = codepage, ChecksumAlgorithm = checksumAlgorithm, MetadataReferences = metadataReferences.AsImmutable(), AnalyzerReferences = analyzers.AsImmutable(), AdditionalFiles = additionalFiles.AsImmutable(), ReferencePaths = referencePaths, SourcePaths = sourcePaths.AsImmutable(), KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), Win32ResourceFile = win32ResourceFile, Win32Icon = win32IconFile, Win32Manifest = win32ManifestFile, NoWin32Manifest = noWin32Manifest, DisplayLogo = displayLogo, DisplayHelp = displayHelp, ManifestResources = managedResources.AsImmutable(), CompilationOptions = options, ParseOptions = IsScriptRunner ? scriptParseOptions : parseOptions, EmitOptions = emitOptions, ScriptArguments = scriptArgs.AsImmutableOrEmpty(), TouchedFilesPath = touchedFilesPath, PrintFullPaths = printFullPaths, ShouldIncludeErrorEndLocation = errorEndLocation, PreferredUILang = preferredUILang, ReportAnalyzer = reportAnalyzer }; } private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics) { if (string.IsNullOrEmpty(switchValue)) { Debug.Assert(!string.IsNullOrEmpty(switchName)); AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName); return; } foreach (string path in ParseSeparatedPaths(switchValue)) { string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (resolvedPath == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize()); } else if (!PortableShim.Directory.Exists(resolvedPath)) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize()); } else { builder.Add(resolvedPath); } } } private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { string noQuotes = RemoveQuotesAndSlashes(value); if (string.IsNullOrWhiteSpace(noQuotes)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { return noQuotes; } } return null; } private void GetCompilationAndModuleNames( List<Diagnostic> diagnostics, OutputKind outputKind, List<CommandLineSourceFile> sourceFiles, bool sourceFilesSpecified, string moduleAssemblyName, ref string outputFileName, ref string moduleName, out string compilationName) { string simpleName; if (outputFileName == null) { // In C#, if the output file name isn't specified explicitly, then executables take their // names from the files containing their entrypoints and libraries derive their names from // their first input files. if (!IsScriptRunner && !sourceFilesSpecified) { AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName); simpleName = null; } else if (outputKind.IsApplication()) { simpleName = null; } else { simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path)); outputFileName = simpleName + outputKind.GetDefaultExtension(); if (simpleName.Length == 0 && !outputKind.IsNetModule()) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } } else { simpleName = PathUtilities.RemoveExtension(outputFileName); if (simpleName.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } if (outputKind.IsNetModule()) { Debug.Assert(!IsScriptRunner); compilationName = moduleAssemblyName; } else { if (moduleAssemblyName != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule); } compilationName = simpleName; } if (moduleName == null) { moduleName = outputFileName; } } private static ImmutableArray<string> BuildSearchPaths(string sdkDirectoryOpt, List<string> libPaths) { var builder = ArrayBuilder<string>.GetInstance(); // Match how Dev11 builds the list of search paths // see PCWSTR LangCompiler::GetSearchPath() // current folder first -- base directory is searched by default // Add SDK directory if it is available if (sdkDirectoryOpt != null) { builder.Add(sdkDirectoryOpt); } // libpath builder.AddRange(libPaths); return builder.ToImmutableAndFree(); } public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics) { Diagnostic myDiagnostic = null; value = value.TrimEnd(null); // Allow a trailing semicolon or comma in the options if (!value.IsEmpty() && (value.Last() == ';' || value.Last() == ',')) { value = value.Substring(0, value.Length - 1); } string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/); var defines = new ArrayBuilder<string>(values.Length); foreach (string id in values) { string trimmedId = id.Trim(); if (SyntaxFacts.IsValidIdentifier(trimmedId)) { defines.Add(trimmedId); } else if (myDiagnostic == null) { myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId); } } diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>() : SpecializedCollections.SingletonEnumerable(myDiagnostic); return defines.AsEnumerable(); } private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "x86": return Platform.X86; case "x64": return Platform.X64; case "itanium": return Platform.Itanium; case "anycpu": return Platform.AnyCpu; case "anycpu32bitpreferred": return Platform.AnyCpu32BitPreferred; case "arm": return Platform.Arm; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value); return Platform.AnyCpu; } } private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "exe": return OutputKind.ConsoleApplication; case "winexe": return OutputKind.WindowsApplication; case "library": return OutputKind.DynamicallyLinkedLibrary; case "module": return OutputKind.NetModule; case "appcontainerexe": return OutputKind.WindowsRuntimeApplication; case "winmdobj": return OutputKind.WindowsRuntimeMetadata; default: AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); return OutputKind.ConsoleApplication; } } private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics) { if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg); yield break; } foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { yield return u; } } private IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); foreach (string path in paths) { yield return new CommandLineAnalyzerReference(path); } } private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } // /r:"reference" // /r:alias=reference // /r:alias="reference" // /r:reference;reference // /r:"path;containing;semicolons" // /r:"unterminated_quotes // /r:"quotes"in"the"middle // /r:alias=reference;reference ... error 2034 // /r:nonidf=reference ... error 1679 int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' }); string alias; if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=') { alias = value.Substring(0, eqlOrQuote); value = value.Substring(eqlOrQuote + 1); if (!SyntaxFacts.IsValidIdentifier(alias)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias); yield break; } } else { alias = null; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); if (alias != null) { if (paths.Count > 1) { AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value); yield break; } if (paths.Count == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias); yield break; } } foreach (string path in paths) { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty; var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); yield return new CommandLineReference(path, properties); } } private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics) { if (win32ResourceFile != null) { if (win32IconResourceFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon); } if (win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest); } } if (outputKind.IsNetModule() && win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule); } } internal static ResourceDescription ParseResourceDescription( string arg, string resourceDescriptor, string baseDirectory, IList<Diagnostic> diagnostics, bool embedded) { string filePath; string fullPath; string fileName; string resourceName; string accessibility; ParseResourceDescription( resourceDescriptor, baseDirectory, false, out filePath, out fullPath, out fileName, out resourceName, out accessibility); bool isPublic; if (accessibility == null) { // If no accessibility is given, we default to "public". // NOTE: Dev10 distinguishes between null and empty/whitespace-only. isPublic = true; } else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase)) { isPublic = true; } else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase)) { isPublic = false; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility); return null; } if (string.IsNullOrEmpty(filePath)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); return null; } if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath); return null; } Func<Stream> dataProvider = () => { // Use FileShare.ReadWrite because the file could be opened by the current process. // For example, it is an XML doc file produced by the build. return PortableShim.FileStream.Create(fullPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read, PortableShim.FileShare.ReadWrite); }; return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false); } private static bool TryParseLanguageVersion(string str, LanguageVersion defaultVersion, out LanguageVersion version) { if (str == null) { version = defaultVersion; return true; } switch (str.ToLowerInvariant()) { case "iso-1": version = LanguageVersion.CSharp1; return true; case "iso-2": version = LanguageVersion.CSharp2; return true; case "default": version = defaultVersion; return true; default: int versionNumber; if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && ((LanguageVersion)versionNumber).IsValid()) { version = (LanguageVersion)versionNumber; return true; } version = defaultVersion; return false; } } private static IEnumerable<string> ParseWarnings(string value) { value = value.Unquote(); string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string id in values) { ushort number; if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) && ErrorFacts.IsWarning((ErrorCode)number)) { // The id refers to a compiler warning. yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number); } else { // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in /nowarn or // /warnaserror. We no longer generate a warning in such cases. // Instead we assume that the unrecognized id refers to a custom diagnostic. yield return id; } } } private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items) { foreach (var id in items) { ReportDiagnostic existing; if (d.TryGetValue(id, out existing)) { // Rewrite the existing value with the latest one unless it is for /nowarn. if (existing != ReportDiagnostic.Suppress) d[id] = kind; } else { d.Add(id, kind); } } } private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName); } internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics) { // no error in csc.exe } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode)); } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments)); } /// <summary> /// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode. /// </summary> private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments) { int code = (int)errorCode; ReportDiagnostic value; warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value); if (value != ReportDiagnostic.Suppress) { AddDiagnostic(diagnostics, errorCode, arguments); } } } }
// 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.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.EventHub { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; /// <summary> /// NamespacesOperations operations. /// </summary> public partial interface INamespacesOperations { /// <summary> /// Lists all the available namespaces within the subscription /// irrespective of the resourceGroups. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListBySubscriptionWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the available namespaces within a resourceGroup. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates Updates namespace. Once created, this namespace's resource /// manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Namespace Resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<NamespaceResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates Updates namespace. Once created, this namespace's resource /// manifest is immutable. This operation is idempotent. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='parameters'> /// Parameters supplied to create a Namespace Resource. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<NamespaceResource>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, NamespaceCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an existing namespace. This operation also removes all /// associated resources under the namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Returns the description for the specified namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<NamespaceResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Authorization rules for a namespace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates an authorization rule for a namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Namespace Aauthorization Rule Name. /// </param> /// <param name='parameters'> /// The shared access authorization rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes a namespace authorization rule /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// Authorization Rule Name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Authorization rule for a namespace by name. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name /// </param> /// <param name='authorizationRuleName'> /// Authorization rule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Primary and Secondary ConnectionStrings to the namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerats the Primary or Secondary ConnectionStrings to the /// namespace /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='namespaceName'> /// The namespace name. /// </param> /// <param name='authorizationRuleName'> /// The authorizationRule name. /// </param> /// <param name='parameters'> /// Parameters supplied to regenerate Auth Rule. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string authorizationRuleName, RegenerateKeysParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists all the available namespaces within the subscription /// irrespective of the resourceGroups. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListBySubscriptionNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Lists the available namespaces within a resourceGroup. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<NamespaceResource>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Authorization rules for a namespace. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: operations/pbx_events/recorded_phone_call.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Operations.PBXEvents { /// <summary>Holder for reflection information generated from operations/pbx_events/recorded_phone_call.proto</summary> public static partial class RecordedPhoneCallReflection { #region Descriptor /// <summary>File descriptor for operations/pbx_events/recorded_phone_call.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static RecordedPhoneCallReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Ci9vcGVyYXRpb25zL3BieF9ldmVudHMvcmVjb3JkZWRfcGhvbmVfY2FsbC5w", "cm90bxIhaG9sbXMudHlwZXMub3BlcmF0aW9ucy5wYnhfZXZlbnRzGh5nb29n", "bGUvcHJvdG9idWYvZHVyYXRpb24ucHJvdG8aH2dvb2dsZS9wcm90b2J1Zi90", "aW1lc3RhbXAucHJvdG8aL29wZXJhdGlvbnMvcGJ4X2V2ZW50cy9wYnhfZXZl", "bnRfaW5kaWNhdG9yLnByb3RvGh9wcmltaXRpdmUvbW9uZXRhcnlfYW1vdW50", "LnByb3RvGjJ0ZW5hbmN5X2NvbmZpZy9pbmRpY2F0b3JzL3Byb3BlcnR5X2lu", "ZGljYXRvci5wcm90byLnAgoRUmVjb3JkZWRQaG9uZUNhbGwSQAoCaWQYASAB", "KAsyNC5ob2xtcy50eXBlcy5vcGVyYXRpb25zLnBieF9ldmVudHMuUGJ4RXZl", "bnRJbmRpY2F0b3ISKQoGbGVuZ3RoGAIgASgLMhkuZ29vZ2xlLnByb3RvYnVm", "LkR1cmF0aW9uEhkKEW9yaWdpbmF0aW5nX3RydW5rGAMgASgJEhUKDW51bWJl", "cl9kaWFsZWQYBCABKAkSNgoHY2hhcmdlZBgFIAEoCzIlLmhvbG1zLnR5cGVz", "LnByaW1pdGl2ZS5Nb25ldGFyeUFtb3VudBJKCghwcm9wZXJ0eRgGIAEoCzI4", "LmhvbG1zLnR5cGVzLnRlbmFuY3lfY29uZmlnLmluZGljYXRvcnMuUHJvcGVy", "dHlJbmRpY2F0b3ISLwoLcmVjb3JkZWRfYXQYByABKAsyGi5nb29nbGUucHJv", "dG9idWYuVGltZXN0YW1wQjlaFG9wZXJhdGlvbnMvcGJ4ZXZlbnRzqgIgSE9M", "TVMuVHlwZXMuT3BlcmF0aW9ucy5QQlhFdmVudHNiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.WellKnownTypes.DurationReflection.Descriptor, global::Google.Protobuf.WellKnownTypes.TimestampReflection.Descriptor, global::HOLMS.Types.Operations.PBXEvents.PbxEventIndicatorReflection.Descriptor, global::HOLMS.Types.Primitive.MonetaryAmountReflection.Descriptor, global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicatorReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.PBXEvents.RecordedPhoneCall), global::HOLMS.Types.Operations.PBXEvents.RecordedPhoneCall.Parser, new[]{ "Id", "Length", "OriginatingTrunk", "NumberDialed", "Charged", "Property", "RecordedAt" }, null, null, null) })); } #endregion } #region Messages public sealed partial class RecordedPhoneCall : pb::IMessage<RecordedPhoneCall> { private static readonly pb::MessageParser<RecordedPhoneCall> _parser = new pb::MessageParser<RecordedPhoneCall>(() => new RecordedPhoneCall()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<RecordedPhoneCall> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Operations.PBXEvents.RecordedPhoneCallReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RecordedPhoneCall() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RecordedPhoneCall(RecordedPhoneCall other) : this() { Id = other.id_ != null ? other.Id.Clone() : null; Length = other.length_ != null ? other.Length.Clone() : null; originatingTrunk_ = other.originatingTrunk_; numberDialed_ = other.numberDialed_; Charged = other.charged_ != null ? other.Charged.Clone() : null; Property = other.property_ != null ? other.Property.Clone() : null; RecordedAt = other.recordedAt_ != null ? other.RecordedAt.Clone() : null; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public RecordedPhoneCall Clone() { return new RecordedPhoneCall(this); } /// <summary>Field number for the "id" field.</summary> public const int IdFieldNumber = 1; private global::HOLMS.Types.Operations.PBXEvents.PbxEventIndicator id_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Operations.PBXEvents.PbxEventIndicator Id { get { return id_; } set { id_ = value; } } /// <summary>Field number for the "length" field.</summary> public const int LengthFieldNumber = 2; private global::Google.Protobuf.WellKnownTypes.Duration length_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Duration Length { get { return length_; } set { length_ = value; } } /// <summary>Field number for the "originating_trunk" field.</summary> public const int OriginatingTrunkFieldNumber = 3; private string originatingTrunk_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string OriginatingTrunk { get { return originatingTrunk_; } set { originatingTrunk_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "number_dialed" field.</summary> public const int NumberDialedFieldNumber = 4; private string numberDialed_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string NumberDialed { get { return numberDialed_; } set { numberDialed_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "charged" field.</summary> public const int ChargedFieldNumber = 5; private global::HOLMS.Types.Primitive.MonetaryAmount charged_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.MonetaryAmount Charged { get { return charged_; } set { charged_ = value; } } /// <summary>Field number for the "property" field.</summary> public const int PropertyFieldNumber = 6; private global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator property_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator Property { get { return property_; } set { property_ = value; } } /// <summary>Field number for the "recorded_at" field.</summary> public const int RecordedAtFieldNumber = 7; private global::Google.Protobuf.WellKnownTypes.Timestamp recordedAt_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::Google.Protobuf.WellKnownTypes.Timestamp RecordedAt { get { return recordedAt_; } set { recordedAt_ = value; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as RecordedPhoneCall); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(RecordedPhoneCall other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Id, other.Id)) return false; if (!object.Equals(Length, other.Length)) return false; if (OriginatingTrunk != other.OriginatingTrunk) return false; if (NumberDialed != other.NumberDialed) return false; if (!object.Equals(Charged, other.Charged)) return false; if (!object.Equals(Property, other.Property)) return false; if (!object.Equals(RecordedAt, other.RecordedAt)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (id_ != null) hash ^= Id.GetHashCode(); if (length_ != null) hash ^= Length.GetHashCode(); if (OriginatingTrunk.Length != 0) hash ^= OriginatingTrunk.GetHashCode(); if (NumberDialed.Length != 0) hash ^= NumberDialed.GetHashCode(); if (charged_ != null) hash ^= Charged.GetHashCode(); if (property_ != null) hash ^= Property.GetHashCode(); if (recordedAt_ != null) hash ^= RecordedAt.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (id_ != null) { output.WriteRawTag(10); output.WriteMessage(Id); } if (length_ != null) { output.WriteRawTag(18); output.WriteMessage(Length); } if (OriginatingTrunk.Length != 0) { output.WriteRawTag(26); output.WriteString(OriginatingTrunk); } if (NumberDialed.Length != 0) { output.WriteRawTag(34); output.WriteString(NumberDialed); } if (charged_ != null) { output.WriteRawTag(42); output.WriteMessage(Charged); } if (property_ != null) { output.WriteRawTag(50); output.WriteMessage(Property); } if (recordedAt_ != null) { output.WriteRawTag(58); output.WriteMessage(RecordedAt); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (id_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Id); } if (length_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Length); } if (OriginatingTrunk.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(OriginatingTrunk); } if (NumberDialed.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(NumberDialed); } if (charged_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Charged); } if (property_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Property); } if (recordedAt_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(RecordedAt); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(RecordedPhoneCall other) { if (other == null) { return; } if (other.id_ != null) { if (id_ == null) { id_ = new global::HOLMS.Types.Operations.PBXEvents.PbxEventIndicator(); } Id.MergeFrom(other.Id); } if (other.length_ != null) { if (length_ == null) { length_ = new global::Google.Protobuf.WellKnownTypes.Duration(); } Length.MergeFrom(other.Length); } if (other.OriginatingTrunk.Length != 0) { OriginatingTrunk = other.OriginatingTrunk; } if (other.NumberDialed.Length != 0) { NumberDialed = other.NumberDialed; } if (other.charged_ != null) { if (charged_ == null) { charged_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } Charged.MergeFrom(other.Charged); } if (other.property_ != null) { if (property_ == null) { property_ = new global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator(); } Property.MergeFrom(other.Property); } if (other.recordedAt_ != null) { if (recordedAt_ == null) { recordedAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } RecordedAt.MergeFrom(other.RecordedAt); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (id_ == null) { id_ = new global::HOLMS.Types.Operations.PBXEvents.PbxEventIndicator(); } input.ReadMessage(id_); break; } case 18: { if (length_ == null) { length_ = new global::Google.Protobuf.WellKnownTypes.Duration(); } input.ReadMessage(length_); break; } case 26: { OriginatingTrunk = input.ReadString(); break; } case 34: { NumberDialed = input.ReadString(); break; } case 42: { if (charged_ == null) { charged_ = new global::HOLMS.Types.Primitive.MonetaryAmount(); } input.ReadMessage(charged_); break; } case 50: { if (property_ == null) { property_ = new global::HOLMS.Types.TenancyConfig.Indicators.PropertyIndicator(); } input.ReadMessage(property_); break; } case 58: { if (recordedAt_ == null) { recordedAt_ = new global::Google.Protobuf.WellKnownTypes.Timestamp(); } input.ReadMessage(recordedAt_); break; } } } } } #endregion } #endregion Designer generated code
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Windows.Forms; using System.Runtime.InteropServices; using Microsoft.Ink; namespace gInk { public partial class FormDisplay : Form { public Root Root; IntPtr Canvus; IntPtr canvusDc; IntPtr OneStrokeCanvus; IntPtr onestrokeDc; IntPtr BlankCanvus; IntPtr blankcanvusDc; Graphics gCanvus; public Graphics gOneStrokeCanvus; //Bitmap ScreenBitmap; IntPtr hScreenBitmap; IntPtr memscreenDc; Bitmap gpButtonsImage; Bitmap gpPenWidthImage; SolidBrush TransparentBrush; SolidBrush SemiTransparentBrush; byte[] screenbits; byte[] lastscreenbits; // http://www.csharp411.com/hide-form-from-alttab/ protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; // turn on WS_EX_TOOLWINDOW style bit cp.ExStyle |= 0x80; return cp; } } public FormDisplay(Root root) { Root = root; InitializeComponent(); this.Left = SystemInformation.VirtualScreen.Left; this.Top = SystemInformation.VirtualScreen.Top; //int targetbottom = 0; //foreach (Screen screen in Screen.AllScreens) //{ // if (screen.WorkingArea.Bottom > targetbottom) // targetbottom = screen.WorkingArea.Bottom; //} //int virwidth = SystemInformation.VirtualScreen.Width; //this.Width = virwidth; //this.Height = targetbottom - this.Top; this.Width = SystemInformation.VirtualScreen.Width; this.Height = SystemInformation.VirtualScreen.Height - 2; Bitmap InitCanvus = new Bitmap(this.Width, this.Height); Canvus = InitCanvus.GetHbitmap(Color.FromArgb(0)); OneStrokeCanvus = InitCanvus.GetHbitmap(Color.FromArgb(0)); //BlankCanvus = InitCanvus.GetHbitmap(Color.FromArgb(0)); IntPtr screenDc = GetDC(IntPtr.Zero); canvusDc = CreateCompatibleDC(screenDc); SelectObject(canvusDc, Canvus); onestrokeDc = CreateCompatibleDC(screenDc); SelectObject(onestrokeDc, OneStrokeCanvus); //blankcanvusDc = CreateCompatibleDC(screenDc); //SelectObject(blankcanvusDc, BlankCanvus); gCanvus = Graphics.FromHdc(canvusDc); gCanvus.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; gOneStrokeCanvus = Graphics.FromHdc(onestrokeDc); gOneStrokeCanvus.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; if (Root.AutoScroll) { hScreenBitmap = InitCanvus.GetHbitmap(Color.FromArgb(0)); memscreenDc = CreateCompatibleDC(screenDc); SelectObject(memscreenDc, hScreenBitmap); screenbits = new byte[50000000]; lastscreenbits = new byte[50000000]; } ReleaseDC(IntPtr.Zero, screenDc); InitCanvus.Dispose(); //this.DoubleBuffered = true; int gpheight = (int)(Screen.PrimaryScreen.Bounds.Height * Root.ToolbarHeight); gpButtonsImage = new Bitmap(2400, gpheight); gpPenWidthImage = new Bitmap(200, gpheight); TransparentBrush = new SolidBrush(Color.Transparent); SemiTransparentBrush = new SolidBrush(Color.FromArgb(120, 255, 255, 255)); ToTopMostThrough(); } public void ToTopMostThrough() { UInt32 dwExStyle = GetWindowLong(this.Handle, -20); SetWindowLong(this.Handle, -20, dwExStyle | 0x00080000); SetWindowPos(this.Handle, (IntPtr)0, 0, 0, 0, 0, 0x0002 | 0x0001 | 0x0004 | 0x0010 | 0x0020); //SetLayeredWindowAttributes(this.Handle, 0x00FFFFFF, 1, 0x2); SetWindowLong(this.Handle, -20, dwExStyle | 0x00080000 | 0x00000020); SetWindowPos(this.Handle, (IntPtr)(-1), 0, 0, 0, 0, 0x0002 | 0x0001 | 0x0010 | 0x0020); } public void ClearCanvus() { gCanvus.Clear(Color.Transparent); } public void ClearCanvus(Graphics g) { g.Clear(Color.Transparent); } public void DrawSnapping(Rectangle rect) { gCanvus.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; if (rect.Width > 0 && rect.Height > 0) { gCanvus.FillRectangle(SemiTransparentBrush, new Rectangle(0, 0, rect.Left, this.Height)); gCanvus.FillRectangle(SemiTransparentBrush, new Rectangle(rect.Right, 0, this.Width - rect.Right, this.Height)); gCanvus.FillRectangle(SemiTransparentBrush, new Rectangle(rect.Left, 0, rect.Width, rect.Top)); gCanvus.FillRectangle(SemiTransparentBrush, new Rectangle(rect.Left, rect.Bottom, rect.Width, this.Height - rect.Bottom)); Pen pen = new Pen(Color.FromArgb(200, 80, 80, 80)); pen.Width = 3; gCanvus.DrawRectangle(pen, rect); } else { gCanvus.FillRectangle(SemiTransparentBrush, new Rectangle(0, 0, this.Width, this.Height)); } gCanvus.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; } public void DrawButtons(bool redrawbuttons, bool exiting = false) { if (Root.AlwaysHideToolbar) return; int top, height, left, width; int fullwidth; int gpbl; int drawwidth; top = Root.FormCollection.gpButtons.Top; height = Root.FormCollection.gpButtons.Height; left = Root.FormCollection.gpButtons.Left; width = Root.FormCollection.gpButtons.Width; fullwidth = Root.FormCollection.gpButtonsWidth; drawwidth = width; gpbl = Root.FormCollection.gpButtonsLeft; if (left + width > gpbl + fullwidth) drawwidth = gpbl + fullwidth - left; if (redrawbuttons) Root.FormCollection.gpButtons.DrawToBitmap(gpButtonsImage, new Rectangle(0, 0, width, height)); if (exiting) { int clearleft = Math.Max(left - 120, gpbl); //gCanvus.FillRectangle(TransparentBrush, clearleft, top, fullwidth * 2, height); gCanvus.FillRectangle(TransparentBrush, clearleft, top, drawwidth, height); } gCanvus.DrawImage(gpButtonsImage, left, top, new Rectangle(0, 0, drawwidth, height), GraphicsUnit.Pixel); if (Root.gpPenWidthVisible) { top = Root.FormCollection.gpPenWidth.Top; height = Root.FormCollection.gpPenWidth.Height; left = Root.FormCollection.gpPenWidth.Left; width = Root.FormCollection.gpPenWidth.Width; if (redrawbuttons) Root.FormCollection.gpPenWidth.DrawToBitmap(gpPenWidthImage, new Rectangle(0, 0, width, height)); gCanvus.DrawImage(gpPenWidthImage, left, top); } } public void DrawButtons(Graphics g, bool redrawbuttons, bool exiting = false) { int top, height, left, width; int fullwidth; int gpbl; int drawwidth; top = Root.FormCollection.gpButtons.Top; height = Root.FormCollection.gpButtons.Height; left = Root.FormCollection.gpButtons.Left; width = Root.FormCollection.gpButtons.Width; fullwidth = Root.FormCollection.gpButtonsWidth; drawwidth = width; gpbl = Root.FormCollection.gpButtonsLeft; if (left + width > gpbl + fullwidth) drawwidth = gpbl + fullwidth - left; if (redrawbuttons) Root.FormCollection.gpButtons.DrawToBitmap(gpButtonsImage, new Rectangle(0, 0, width, height)); if (exiting) { int clearleft = Math.Max(left - 120, gpbl); //g.FillRectangle(TransparentBrush, clearleft, top, width + 80, height); g.FillRectangle(TransparentBrush, clearleft, top, drawwidth, height); } g.DrawImage(gpButtonsImage, left, top); if (Root.gpPenWidthVisible) { top = Root.FormCollection.gpPenWidth.Top; height = Root.FormCollection.gpPenWidth.Height; left = Root.FormCollection.gpPenWidth.Left; width = Root.FormCollection.gpPenWidth.Width; if (redrawbuttons) Root.FormCollection.gpPenWidth.DrawToBitmap(gpPenWidthImage, new Rectangle(0, 0, width, height)); g.DrawImage(gpPenWidthImage, left, top); } } public void DrawStrokes() { if (Root.InkVisible) Root.FormCollection.IC.Renderer.Draw(gCanvus, Root.FormCollection.IC.Ink.Strokes); } public void DrawStrokes(Graphics g) { if (Root.InkVisible) Root.FormCollection.IC.Renderer.Draw(g, Root.FormCollection.IC.Ink.Strokes); } public void MoveStrokes(int dy) { Point pt1 = new Point(0, 0); Point pt2 = new Point(0, 100); Root.FormCollection.IC.Renderer.PixelToInkSpace(gCanvus, ref pt1); Root.FormCollection.IC.Renderer.PixelToInkSpace(gCanvus, ref pt2); float unitperpixel = (pt2.Y - pt1.Y) / 100.0f; float shouldmove = dy * unitperpixel; foreach (Stroke stroke in Root.FormCollection.IC.Ink.Strokes) if (!stroke.Deleted) stroke.Move(0, shouldmove); } protected override void OnPaint(PaintEventArgs e) { UpdateFormDisplay(true); } public uint N1(int i, int j) { //return BitConverter.ToUInt32(screenbits, (this.Width * j + i) * 4); Nlastp1 = (this.Width * j + i) * 4 + 1; return screenbits[Nlastp1]; } public uint N2(int i, int j) { //return BitConverter.ToUInt32(screenbits, (this.Width * j + i) * 4); Nlastp2 = (this.Width * j + i) * 4 + 1; return screenbits[Nlastp2]; } public uint L(int i, int j) { //return BitConverter.ToUInt32(lastscreenbits, (this.Width * j + i) * 4); Llastp = (this.Width * j + i) * 4 + 1; return lastscreenbits[Llastp]; } int Nlastp1, Nlastp2, Llastp; public uint Nnext1() { Nlastp1 += 40; return screenbits[Nlastp1]; } public uint Nnext2() { Nlastp2 += 40; return screenbits[Nlastp2]; } public uint Lnext() { Llastp += 40; return lastscreenbits[Llastp]; } public void SnapShot(Rectangle rect) { string snapbasepath = Root.SnapshotBasePath; snapbasepath = Environment.ExpandEnvironmentVariables(snapbasepath); if (Root.SnapshotBasePath == "%USERPROFILE%/Pictures/gInk/") if (!System.IO.Directory.Exists(snapbasepath)) System.IO.Directory.CreateDirectory(snapbasepath); if (System.IO.Directory.Exists(snapbasepath)) { IntPtr screenDc = GetDC(IntPtr.Zero); const int VERTRES = 10; const int DESKTOPVERTRES = 117; int LogicalScreenHeight = GetDeviceCaps(screenDc, VERTRES); int PhysicalScreenHeight = GetDeviceCaps(screenDc, DESKTOPVERTRES); float ScreenScalingFactor = (float)PhysicalScreenHeight / (float)LogicalScreenHeight; rect.X = (int)(rect.X * ScreenScalingFactor); rect.Y = (int)(rect.Y * ScreenScalingFactor); rect.Width = (int)(rect.Width * ScreenScalingFactor); rect.Height = (int)(rect.Height * ScreenScalingFactor); Bitmap tempbmp = new Bitmap(rect.Width, rect.Height); Graphics g = Graphics.FromImage(tempbmp); g.Clear(Color.Red); IntPtr hDest = CreateCompatibleDC(screenDc); IntPtr hBmp = tempbmp.GetHbitmap(); SelectObject(hDest, hBmp); bool b = BitBlt(hDest, 0, 0, rect.Width, rect.Height, screenDc, rect.Left, rect.Top, (uint)(CopyPixelOperation.SourceCopy | CopyPixelOperation.CaptureBlt)); tempbmp = Bitmap.FromHbitmap(hBmp); if (!b) { g = Graphics.FromImage(tempbmp); g.Clear(Color.Blue); g.CopyFromScreen(rect.Left, rect.Top, 0, 0, new Size(rect.Width, rect.Height)); } Clipboard.SetImage(tempbmp); DateTime now = DateTime.Now; string nowstr = now.Year.ToString() + "-" + now.Month.ToString("D2") + "-" + now.Day.ToString("D2") + " " + now.Hour.ToString("D2") + "-" + now.Minute.ToString("D2") + "-" + now.Second.ToString("D2"); string savefilename = nowstr + ".png"; Root.SnapshotFileFullPath = snapbasepath + savefilename; tempbmp.Save(Root.SnapshotFileFullPath, System.Drawing.Imaging.ImageFormat.Png); tempbmp.Dispose(); DeleteObject(hBmp); ReleaseDC(IntPtr.Zero, screenDc); DeleteDC(hDest); Root.UponBalloonSnap = true; } } public int Test() { IntPtr screenDc = GetDC(IntPtr.Zero); // big time consuming, but not CPU consuming BitBlt(memscreenDc, Width / 4, 0, Width / 2, this.Height, screenDc, Width / 4, 0, 0x00CC0020); // <1% CPU GetBitmapBits(hScreenBitmap, this.Width * this.Height * 4, screenbits); int dj; int maxidpixels = 0; float maxidchdrio = 0; int maxdj = 0; // 25% CPU with 1x10x10 sample rate? int istart = Width / 2 - Width / 4; int iend = Width / 2 + Width / 4; for (dj = -Height * 3 / 8 + 1; dj < Height * 3 / 8 - 1; dj++) { int chdpixels = 0, idpixels = 0; for (int j = Height / 2 - Height / 8; j < Height / 2 + Height / 8; j += 10) { L(istart - 10, j); N1(istart - 10, j); N2(istart - 10, j + dj); for (int i = istart; i < iend; i += 10) { //uint l = Lnext(); //uint n1 = Nnext1(); //uint n2 = Nnext2(); //if (l != n1) //{ // chdpixels++; // if (l == n2) // idpixels++; //} if (Lnext() == Nnext2()) idpixels++; } } //float idchdrio = (float)idpixels / chdpixels; if (idpixels > maxidpixels) //if (idchdrio > maxidchdrio) { //maxidchdrio = idchdrio; maxidpixels = idpixels; maxdj = dj; } } //if (maxidchdrio < 0.1 || maxidpixels < 30) if (maxidpixels < 100) maxdj = 0; // 2% CPU IntPtr pscreenbits = Marshal.UnsafeAddrOfPinnedArrayElement(screenbits, (int)(this.Width * this.Height * 4 * 0.375)); IntPtr plastscreenbits = Marshal.UnsafeAddrOfPinnedArrayElement(lastscreenbits, (int)(this.Width * this.Height * 4 * 0.375)); memcpy(plastscreenbits, pscreenbits, this.Width * this.Height * 4 / 4); ReleaseDC(IntPtr.Zero, screenDc); return maxdj; } public void UpdateFormDisplay(bool draw) { IntPtr screenDc = GetDC(IntPtr.Zero); //Display-rectangle Size size = new Size(this.Width, this.Height); Point pointSource = new Point(0, 0); Point topPos = new Point(this.Left, this.Top); //Set up blending options BLENDFUNCTION blend = new BLENDFUNCTION(); blend.BlendOp = AC_SRC_OVER; blend.BlendFlags = 0; blend.SourceConstantAlpha = 255; // additional alpha multiplier to the whole image. value 255 means multiply with 1. blend.AlphaFormat = AC_SRC_ALPHA; if (draw) UpdateLayeredWindow(this.Handle, screenDc, ref topPos, ref size, canvusDc, ref pointSource, 0, ref blend, ULW_ALPHA); else UpdateLayeredWindow(this.Handle, screenDc, ref topPos, ref size, blankcanvusDc, ref pointSource, 0, ref blend, ULW_ALPHA); //Clean-up ReleaseDC(IntPtr.Zero, screenDc); } int stackmove = 0; int Tick = 0; DateTime TickStartTime; private void timer1_Tick(object sender, EventArgs e) { Tick++; /* if (Tick == 1) TickStartTime = DateTime.Now; else if (Tick % 60 == 0) { Console.WriteLine(60 / (DateTime.Now - TickStartTime).TotalMilliseconds * 1000); TickStartTime = DateTime.Now; } */ if (Root.UponAllDrawingUpdate) { ClearCanvus(); DrawStrokes(); DrawButtons(true); if (Root.Snapping > 0) DrawSnapping(Root.SnappingRect); UpdateFormDisplay(true); Root.UponAllDrawingUpdate = false; } else if (Root.UponTakingSnap) { if (Root.SnappingRect.Width == this.Width && Root.SnappingRect.Height == this.Height) System.Threading.Thread.Sleep(200); ClearCanvus(); DrawStrokes(); //DrawButtons(false); UpdateFormDisplay(true); SnapShot(Root.SnappingRect); Root.UponTakingSnap = false; if (Root.CloseOnSnap == "true") { Root.FormCollection.RetreatAndExit(); } else if (Root.CloseOnSnap == "blankonly") { if ((Root.FormCollection.IC.Ink.Strokes.Count == 0)) Root.FormCollection.RetreatAndExit(); } } else if (Root.Snapping == 2) { if (Root.MouseMovedUnderSnapshotDragging) { ClearCanvus(); DrawStrokes(); DrawButtons(false); DrawSnapping(Root.SnappingRect); UpdateFormDisplay(true); Root.MouseMovedUnderSnapshotDragging = false; } } else if (Root.FormCollection.IC.CollectingInk && Root.EraserMode == false && Root.InkVisible) { //ClearCanvus(); //DrawStrokes(); //DrawButtons(false); //UpdateFormDisplay(); if (Root.FormCollection.IC.Ink.Strokes.Count > 0) { Stroke stroke = Root.FormCollection.IC.Ink.Strokes[Root.FormCollection.IC.Ink.Strokes.Count - 1]; if (!stroke.Deleted) { Rectangle box = stroke.GetBoundingBox(); Point lt = new Point(box.Left, box.Top); Point rb = new Point(box.Right + 1, box.Bottom + 1); Root.FormCollection.IC.Renderer.InkSpaceToPixel(gCanvus, ref lt); Root.FormCollection.IC.Renderer.InkSpaceToPixel(gCanvus, ref rb); BitBlt(canvusDc, lt.X, lt.Y, rb.X - lt.X, rb.Y - lt.Y, onestrokeDc, lt.X, lt.Y, (uint)CopyPixelOperation.SourceCopy); Root.FormCollection.IC.Renderer.Draw(gCanvus, stroke, Root.FormCollection.IC.DefaultDrawingAttributes); } UpdateFormDisplay(true); } } else if (Root.FormCollection.IC.CollectingInk && Root.EraserMode == true) { ClearCanvus(); DrawStrokes(); DrawButtons(false); UpdateFormDisplay(true); } else if (Root.Snapping < -58) { ClearCanvus(); DrawStrokes(); DrawButtons(false); UpdateFormDisplay(true); } else if (Root.UponButtonsUpdate > 0) { if ((Root.UponButtonsUpdate & 0x2) > 0) DrawButtons(true, (Root.UponButtonsUpdate & 0x4) > 0); else if ((Root.UponButtonsUpdate & 0x1) > 0) DrawButtons(false, (Root.UponButtonsUpdate & 0x4) > 0); UpdateFormDisplay(true); Root.UponButtonsUpdate = 0; } else if (Root.UponSubPanelUpdate) { ClearCanvus(); DrawStrokes(); DrawButtons(false); UpdateFormDisplay(true); Root.UponSubPanelUpdate = false; } if (Root.AutoScroll && Root.PointerMode) { int moved = Test(); stackmove += moved; if (stackmove != 0 && Tick % 10 == 1) { MoveStrokes(stackmove); ClearCanvus(); DrawStrokes(); DrawButtons(false); UpdateFormDisplay(true); stackmove = 0; } } } private void FormDisplay_FormClosed(object sender, FormClosedEventArgs e) { DeleteObject(Canvus); //DeleteObject(BlankCanvus); DeleteDC(canvusDc); if (Root.AutoScroll) { DeleteObject(hScreenBitmap); DeleteDC(memscreenDc); } } [DllImport("user32.dll")] static extern IntPtr GetDC(IntPtr hWnd); [DllImport("user32.dll")] static extern bool ReleaseDC(IntPtr hWnd, IntPtr hDC); [DllImport("gdi32.dll", EntryPoint = "DeleteDC")] public static extern bool DeleteDC([In] IntPtr hdc); [DllImport("gdi32.dll", EntryPoint = "CreateCompatibleDC", SetLastError = true)] static extern IntPtr CreateCompatibleDC([In] IntPtr hdc); [DllImport("gdi32.dll", EntryPoint = "SelectObject")] public static extern IntPtr SelectObject([In] IntPtr hdc, [In] IntPtr hgdiobj); [DllImport("gdi32.dll", EntryPoint = "DeleteObject")] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool DeleteObject([In] IntPtr hObject); [DllImport("user32.dll", ExactSpelling = true, SetLastError = true)] static extern bool UpdateLayeredWindow(IntPtr hwnd, IntPtr hdcDst, ref Point pptDst, ref Size psize, IntPtr hdcSrc, ref Point pptSrc, uint crKey, [In] ref BLENDFUNCTION pblend, uint dwFlags); [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, uint dwRop); [DllImport("gdi32.dll")] public static extern bool StretchBlt(IntPtr hdcDest, int nXDest, int nYDest, int nWidth, int nHeight, IntPtr hdcSrc, int nXSrc, int nYSrc, int nWidthSrc, int nHeightSrc, long dwRop); [StructLayout(LayoutKind.Sequential)] public struct BLENDFUNCTION { public byte BlendOp; public byte BlendFlags; public byte SourceConstantAlpha; public byte AlphaFormat; public BLENDFUNCTION(byte op, byte flags, byte alpha, byte format) { BlendOp = op; BlendFlags = flags; SourceConstantAlpha = alpha; AlphaFormat = format; } } const int ULW_ALPHA = 2; const int AC_SRC_OVER = 0x00; const int AC_SRC_ALPHA = 0x01; [DllImport("user32.dll")] static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); [DllImport("user32.dll", SetLastError = true)] static extern UInt32 GetWindowLong(IntPtr hWnd, int nIndex); [DllImport("user32.dll")] static extern int SetWindowLong(IntPtr hWnd, int nIndex, UInt32 dwNewLong); [DllImport("user32.dll")] public extern static bool SetLayeredWindowAttributes(IntPtr hwnd, uint crKey, byte bAlpha, uint dwFlags); [DllImport("gdi32.dll")] static extern int GetBitmapBits(IntPtr hbmp, int cbBuffer, [Out] byte[] lpvBits); [DllImport("gdi32.dll")] static extern uint GetPixel(IntPtr hdc, int nXPos, int nYPos); [DllImport("gdi32.dll")] static extern int GetDeviceCaps(IntPtr hdc, int nIndex); [DllImport("msvcrt.dll", EntryPoint = "memcpy", CallingConvention = CallingConvention.Cdecl, SetLastError = false)] public static extern IntPtr memcpy(IntPtr dest, IntPtr src, int count); } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #if !SILVERLIGHT // File System.Collections.Generic.SortedList_2.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Collections.Generic { public partial class SortedList<TKey, TValue> : IDictionary<TKey, TValue>, ICollection<KeyValuePair<TKey, TValue>>, IEnumerable<KeyValuePair<TKey, TValue>>, System.Collections.IDictionary, System.Collections.ICollection, System.Collections.IEnumerable { #region Methods and constructors public void Add (TKey key, TValue value) { } public void Clear () { } public bool ContainsKey (TKey key) { return default(bool); } public bool ContainsValue (TValue value) { return default(bool); } [Pure] public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator () { Contract.Ensures(Contract.Result<IEnumerator<KeyValuePair<TKey,TValue>>>() != null); return default(IEnumerator<KeyValuePair<TKey, TValue>>); } [Pure] public int IndexOfKey (TKey key) { return default(int); } public int IndexOfValue (TValue value) { return default(int); } public bool Remove (TKey key) { return default(bool); } public void RemoveAt (int index) { } public SortedList () { } public SortedList (int capacity, IComparer<TKey> comparer) { } public SortedList (IDictionary<TKey, TValue> dictionary, IComparer<TKey> comparer) { } public SortedList (IComparer<TKey> comparer) { } public SortedList (IDictionary<TKey, TValue> dictionary) { } public SortedList (int capacity) { } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add (KeyValuePair<TKey, TValue> keyValuePair) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Contains (KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); } void System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.CopyTo (KeyValuePair<TKey, TValue>[] array, int arrayIndex) { } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Remove (KeyValuePair<TKey, TValue> keyValuePair) { return default(bool); } IEnumerator<KeyValuePair<TKey, TValue>> System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>.GetEnumerator () { return default(IEnumerator<KeyValuePair<TKey, TValue>>); } void System.Collections.ICollection.CopyTo (Array array, int arrayIndex) { } void System.Collections.IDictionary.Add (Object key, Object value) { } bool System.Collections.IDictionary.Contains (Object key) { return default(bool); } System.Collections.IDictionaryEnumerator System.Collections.IDictionary.GetEnumerator () { return default(System.Collections.IDictionaryEnumerator); } void System.Collections.IDictionary.Remove (Object key) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () { return default(System.Collections.IEnumerator); } public void TrimExcess () { } public bool TryGetValue (TKey key, out TValue value) { value = default(TValue); return default(bool); } #endregion #region Properties and indexers public int Capacity { get { return default(int); } set { } } public IComparer<TKey> Comparer { get { return default(IComparer<TKey>); } } public int Count { get { return default(int); } } public TValue this [TKey key] { get { return default(TValue); } set { } } public IList<TKey> Keys { get { return default(IList<TKey>); } } bool System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.IsReadOnly { get { return default(bool); } } ICollection<TKey> System.Collections.Generic.IDictionary<TKey,TValue>.Keys { get { return default(ICollection<TKey>); } } ICollection<TValue> System.Collections.Generic.IDictionary<TKey,TValue>.Values { get { return default(ICollection<TValue>); } } bool System.Collections.ICollection.IsSynchronized { get { return default(bool); } } Object System.Collections.ICollection.SyncRoot { get { return default(Object); } } bool System.Collections.IDictionary.IsFixedSize { get { return default(bool); } } bool System.Collections.IDictionary.IsReadOnly { get { return default(bool); } } Object System.Collections.IDictionary.this [Object key] { get { return default(Object); } set { } } System.Collections.ICollection System.Collections.IDictionary.Keys { get { return default(System.Collections.ICollection); } } System.Collections.ICollection System.Collections.IDictionary.Values { get { return default(System.Collections.ICollection); } } public IList<TValue> Values { get { return default(IList<TValue>); } } #endregion } } #endif
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Linq; using System.Xml; using System.Xml.Serialization; using AgenaTrader.API; using AgenaTrader.Custom; using AgenaTrader.Plugins; using AgenaTrader.Helper; /// <summary> /// Version: 1.0.0 /// ------------------------------------------------------------------------- /// Simon Pucher 2018 /// ------------------------------------------------------------------------- /// https://github.com/simonpucher/AgenaTrader/issues/52 /// ------------------------------------------------------------------------- /// ****** Important ****** /// To compile this script without any error you also need access to the utility indicator to use global source code elements. /// You will find this script on GitHub: https://raw.githubusercontent.com/simonpucher/AgenaTrader/master/Utilities/GlobalUtilities_Utility.cs /// ------------------------------------------------------------------------- /// Namespace holds all indicators and is required. Do not change it. /// </summary> namespace AgenaTrader.UserCode { [Description("Choppy Market Index")] public class Choppy_Market_Index_Indicator : UserIndicator { bool shortsignalbb = false; bool longsignalbb = false; private int _bollinger_period = 20; private double _bollinger_stddev = 2; private int _macd_fast = 12; private int _macd_slow = 26; private int _macd_smooth = 9; private Color _color_long_signal = Const.DefaultArrowLongColor; private Color _color_short_signal = Const.DefaultArrowShortColor; protected override void OnInit() { AddOutput(new OutputDescriptor(Color.FromKnownColor(KnownColor.Orange), "Plot_Signal_King_Pinball")); CalculateOnClosedBar = true; } protected override void OnCalculate() { Bollinger bol = Bollinger(this.Bollinger_stddev, this.Bollinger_Period); if (Close[0] < bol.Lower[0]) { longsignalbb = true; } else if (Close[0] > bol.Upper[0]) { shortsignalbb = true; } else { //nothing } MACD macd = MACD(this.MACD_Fast, this.MACD_Slow, this.MACD_Smooth); if (longsignalbb && CrossAbove(macd.Default, macd.Avg, 0)) { AddChartArrowUp(Time[0].ToString()+"long", 0, Low[0], this.ColorLongSignal); MyPlot1.Set(1); longsignalbb = false; } else if (shortsignalbb && CrossBelow(macd.Default, macd.Avg, 0)) { AddChartArrowDown(Time[0].ToString()+"short", 0, High[0], this.ColorShortSignal); MyPlot1.Set(-1); shortsignalbb = false; } else { MyPlot1.Set(0); } } #region Properties [Browsable(false)] [XmlIgnore()] public DataSeries MyPlot1 { get { return Outputs[0]; } } /// <summary> /// </summary> [Description("Bollinger Band period.")] [InputParameter] [DisplayName("BB period")] public int Bollinger_Period { get { return _bollinger_period; } set { _bollinger_period = value; } } /// <summary> /// </summary> [Description("Bollinger Band standard deviation")] [InputParameter] [DisplayName("BB stddev")] public double Bollinger_stddev { get { return _bollinger_stddev; } set { _bollinger_stddev = value; } } /// <summary> /// </summary> [Description("Bollinger Band fast")] [InputParameter] [DisplayName("MACD fast")] public int MACD_Fast { get { return _macd_fast; } set { _macd_fast = value; } } /// <summary> /// </summary> [Description("Bollinger Band slow")] [InputParameter] [DisplayName("MACD slow")] public int MACD_Slow { get { return _macd_slow; } set { _macd_slow = value; } } /// <summary> /// </summary> [Description("Bollinger Band smooth")] [InputParameter] [DisplayName("MACD smooth")] public int MACD_Smooth { get { return _macd_smooth; } set { _macd_smooth = value; } } /// <summary> /// </summary> [Description("Select Color for the long signal.")] [Category("Color")] [DisplayName("Signal Long")] public Color ColorLongSignal { get { return _color_long_signal; } set { _color_long_signal = value; } } // Serialize Color object [Browsable(false)] public string ColorLongSignalSerialize { get { return SerializableColor.ToString(_color_long_signal); } set { _color_long_signal = SerializableColor.FromString(value); } } /// <summary> /// </summary> [Description("Select Color for the long signal.")] [Category("Color")] [DisplayName("Signal Long")] public Color ColorShortSignal { get { return _color_short_signal; } set { _color_short_signal = value; } } // Serialize Color object [Browsable(false)] public string ColorShortSignalSerialize { get { return SerializableColor.ToString(_color_short_signal); } set { _color_short_signal = SerializableColor.FromString(value); } } #endregion } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Xml; using System.Text; using System.Globalization; namespace ESRI.ArcLogistics.Data { /// <summary> /// ConfigDataSerializer class. /// </summary> internal class ConfigDataSerializer { #region constants /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private const string NODE_CAPACITIES = "Capacities"; private const string NODE_CAPACITY = "Capacity"; private const string NODE_ORDERCUSTOMPROP = "CustomOrderProperties"; private const string NODE_PROPERTY = "Property"; private const string ATTR_NAME = "Name"; private const string ATTR_DESCRIPTION = "Description"; private const string ATTR_TYPE = "Type"; private const string ATTR_DISPLAYUNITUS = "DisplayUnitUS"; private const string ATTR_DISPLAYUNITMETRIC = "DisplayUnitMetric"; private const string ATTR_MAXLENGTH = "MaxLength"; private const string ATTR_VERSION = "Version"; private const string ATTR_ORDERPAIRKEY = "OrderPairKey"; private const double ORDER_CUST_PROP_VERSION_NUMBER_1_1 = 1.1; private const double ORDER_CUST_PROP_VERSION_NUMBER_1_2 = 1.2; private const double ORDER_CUST_PROP_VERSION_NUMBER_1_3 = 1.3; private const double ORDER_CUST_PROP_CURRENT_VERSION = ORDER_CUST_PROP_VERSION_NUMBER_1_3; #endregion constants #region public methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Parses CapacitiesInfo. /// </summary> public static CapacitiesInfo ParseCapacitiesInfo(string xml) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); CapacitiesInfo info = null; XmlNode root = xmlDoc.SelectSingleNode(NODE_CAPACITIES); if (root != null) { info = new CapacitiesInfo(); foreach (XmlNode node in root.ChildNodes) { if (node.NodeType != XmlNodeType.Element) continue; // skip comments and other non element nodes if (node.Name.Equals(NODE_CAPACITY, StringComparison.OrdinalIgnoreCase)) { XmlAttributeCollection attributes = node.Attributes; string name = attributes[ATTR_NAME].Value; Unit unitUS = (Unit)Enum.Parse(typeof(Unit), attributes[ATTR_DISPLAYUNITUS].Value); Unit unitMetric = (Unit)Enum.Parse(typeof(Unit), attributes[ATTR_DISPLAYUNITMETRIC].Value); info.Add(new CapacityInfo(name, unitUS, unitMetric)); } else throw new FormatException(); } } else throw new FormatException(); return info; } /// <summary> /// Parses OrderCustomPropertiesInfo. /// </summary> public static OrderCustomPropertiesInfo ParseOrderCustomPropertiesInfo(string xml) { XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(xml); OrderCustomPropertiesInfo info = null; XmlNode root = xmlDoc.SelectSingleNode(NODE_ORDERCUSTOMPROP); if (root != null) { info = new OrderCustomPropertiesInfo(); foreach (XmlNode node in root.ChildNodes) { if (node.NodeType != XmlNodeType.Element) continue; // skip comments and other non element nodes if (node.Name.Equals(NODE_PROPERTY, StringComparison.OrdinalIgnoreCase)) { XmlAttributeCollection attributes = node.Attributes; string name = attributes[ATTR_NAME].Value; string description = null; if (null != attributes[ATTR_DESCRIPTION]) description = attributes[ATTR_DESCRIPTION].Value; int length = int.Parse(attributes[ATTR_MAXLENGTH].Value); OrderCustomPropertyType type = OrderCustomPropertyType.Text; // NOTE: for default used text XmlAttribute typeAttribute = attributes[ATTR_TYPE]; if (null != typeAttribute) type = (OrderCustomPropertyType)Enum.Parse(typeof(OrderCustomPropertyType), typeAttribute.Value); bool orderPairKey = false; // default XmlAttribute orderPairKeyAttribute = attributes[ATTR_ORDERPAIRKEY]; if (null != orderPairKeyAttribute) orderPairKey = bool.Parse(orderPairKeyAttribute.Value); info.Add(new OrderCustomProperty(name, type, length, description, orderPairKey)); } else throw new FormatException(); } } else throw new FormatException(); return info; } /// <summary> /// Serializes CapacitiesInfo object. /// </summary> public static string SerializeCapacitiesInfo(CapacitiesInfo capacitiesInfo) { string xml = null; XmlWriter writer = null; try { StringBuilder sb = new StringBuilder(); writer = XmlWriter.Create(sb); writer.WriteStartElement(NODE_CAPACITIES); for (int index = 0; index < capacitiesInfo.Count; index++) { writer.WriteStartElement(NODE_CAPACITY); writer.WriteAttributeString(ATTR_NAME, capacitiesInfo[index].Name); writer.WriteAttributeString(ATTR_DISPLAYUNITUS, capacitiesInfo[index].DisplayUnitUS.ToString()); writer.WriteAttributeString(ATTR_DISPLAYUNITMETRIC, capacitiesInfo[index].DisplayUnitMetric.ToString()); writer.WriteEndElement(); } writer.WriteEndElement(); writer.Flush(); xml = sb.ToString(); } finally { if (writer != null) writer.Close(); } return xml; } /// <summary> /// Serializes OrderCustomPropertiesInfo object. /// </summary> public static string SerializeOrderCustomPropertiesInfo(OrderCustomPropertiesInfo orderCustomPropertiesInfo) { string xml = null; XmlWriter writer = null; try { StringBuilder sb = new StringBuilder(); writer = XmlWriter.Create(sb); writer.WriteStartElement(NODE_ORDERCUSTOMPROP); writer.WriteAttributeString(ATTR_VERSION, ORDER_CUST_PROP_CURRENT_VERSION.ToString(CultureInfo.GetCultureInfo(CommonHelpers.STORAGE_CULTURE))); for (int index = 0; index < orderCustomPropertiesInfo.Count; index++) { OrderCustomProperty property = orderCustomPropertiesInfo[index]; writer.WriteStartElement(NODE_PROPERTY); writer.WriteAttributeString(ATTR_NAME, property.Name); writer.WriteAttributeString(ATTR_TYPE, property.Type.ToString()); writer.WriteAttributeString(ATTR_MAXLENGTH, property.Length.ToString()); writer.WriteAttributeString(ATTR_DESCRIPTION, property.Description); writer.WriteAttributeString(ATTR_ORDERPAIRKEY, property.OrderPairKey.ToString()); writer.WriteEndElement(); } writer.WriteEndElement(); writer.Flush(); xml = sb.ToString(); } finally { if (writer != null) writer.Close(); } return xml; } #endregion public methods } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: JsonTextWriter.cs 640 2009-06-01 17:22:02Z azizatif $")] namespace Elmah { #region Imports using System; using System.Globalization; using System.IO; using System.Xml; #endregion /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only /// way of generating streams or files containing JSON Text according /// to the grammar rules laid out in /// <a href="http://www.ietf.org/rfc/rfc4627.txt">RFC 4627</a>. /// </summary> /// <remarks> /// This class supports ELMAH and is not intended to be used directly /// from your code. It may be modified or removed in the future without /// notice. It has public accessibility for testing purposes. If you /// need a general-purpose JSON Text encoder, consult /// <a href="http://www.json.org/">JSON.org</a> for implementations /// or use classes available from the Microsoft .NET Framework. /// </remarks> public sealed class JsonTextWriter { private readonly TextWriter _writer; private readonly int[] _counters; private readonly char[] _terminators; private int _depth; private string _memberName; public JsonTextWriter(TextWriter writer) { Debug.Assert(writer != null); _writer = writer; const int levels = 10 + /* root */ 1; _counters = new int[levels]; _terminators = new char[levels]; } public int Depth { get { return _depth; } } private int ItemCount { get { return _counters[Depth]; } set { _counters[Depth] = value; } } private char Terminator { get { return _terminators[Depth]; } set { _terminators[Depth] = value; } } public JsonTextWriter Object() { return StartStructured("{", "}"); } public JsonTextWriter EndObject() { return Pop(); } public JsonTextWriter Array() { return StartStructured("[", "]"); } public JsonTextWriter EndArray() { return Pop(); } public JsonTextWriter Pop() { return EndStructured(); } public JsonTextWriter Member(string name) { if (name == null) throw new ArgumentNullException("name"); if (name.Length == 0) throw new ArgumentException(null, "name"); if (_memberName != null) throw new InvalidOperationException("Missing member value."); _memberName = name; return this; } private JsonTextWriter Write(string text) { return WriteImpl(text, /* raw */ false); } private JsonTextWriter WriteEnquoted(string text) { return WriteImpl(text, /* raw */ true); } private JsonTextWriter WriteImpl(string text, bool raw) { Debug.Assert(raw || (text != null && text.Length > 0)); if (Depth == 0 && (text.Length > 1 || (text[0] != '{' && text[0] != '['))) throw new InvalidOperationException(); TextWriter writer = _writer; if (ItemCount > 0) writer.Write(','); string name = _memberName; _memberName = null; if (name != null) { writer.Write(' '); Enquote(name, writer); writer.Write(':'); } if (Depth > 0) writer.Write(' '); if (raw) Enquote(text, writer); else writer.Write(text); ItemCount = ItemCount + 1; return this; } public JsonTextWriter Number(int value) { return Write(value.ToString(CultureInfo.InvariantCulture)); } public JsonTextWriter String(string str) { return str == null ? Null() : WriteEnquoted(str); } public JsonTextWriter Null() { return Write("null"); } public JsonTextWriter Boolean(bool value) { return Write(value ? "true" : "false"); } private static readonly DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); public JsonTextWriter Number(DateTime time) { double seconds = time.ToUniversalTime().Subtract(_epoch).TotalSeconds; return Write(seconds.ToString(CultureInfo.InvariantCulture)); } public JsonTextWriter String(DateTime time) { return String(XmlConvert.ToString(time, XmlDateTimeSerializationMode.Utc)); } private JsonTextWriter StartStructured(string start, string end) { if (Depth + 1 == _counters.Length) throw new Exception(); Write(start); _depth++; Terminator = end[0]; return this; } private JsonTextWriter EndStructured() { if (Depth - 1 < 0) throw new Exception(); _writer.Write(' '); _writer.Write(Terminator); ItemCount = 0; _depth--; return this; } private static void Enquote(string s, TextWriter writer) { Debug.Assert(writer != null); int length = (s ?? string.Empty).Length; writer.Write('"'); char last; char ch = '\0'; for (int index = 0; index < length; index++) { last = ch; ch = s[index]; switch (ch) { case '\\': case '"': { writer.Write('\\'); writer.Write(ch); break; } case '/': { if (last == '<') writer.Write('\\'); writer.Write(ch); break; } case '\b': writer.Write("\\b"); break; case '\t': writer.Write("\\t"); break; case '\n': writer.Write("\\n"); break; case '\f': writer.Write("\\f"); break; case '\r': writer.Write("\\r"); break; default: { if (ch < ' ') { writer.Write("\\u"); writer.Write(((int)ch).ToString("x4", CultureInfo.InvariantCulture)); } else { writer.Write(ch); } break; } } } writer.Write('"'); } } }
// 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.CodeAnalysis; using System.Diagnostics.Contracts; using System.Globalization; using System.Linq.Expressions; using Microsoft.Internal; namespace System.ComponentModel.Composition.Primitives { /// <summary> /// Represents an import required by a <see cref="ComposablePart"/> object. /// </summary> public class ImportDefinition { internal static readonly string EmptyContractName = string.Empty; private readonly Expression<Func<ExportDefinition, bool>> _constraint; private readonly ImportCardinality _cardinality = ImportCardinality.ExactlyOne; private readonly string _contractName = EmptyContractName; private readonly bool _isRecomposable; private readonly bool _isPrerequisite = true; private Func<ExportDefinition, bool> _compiledConstraint; private readonly IDictionary<string, object> _metadata = MetadataServices.EmptyMetadata; /// <summary> /// Initializes a new instance of the <see cref="ImportDefinition"/> class. /// </summary> /// <remarks> /// <note type="inheritinfo"> /// Derived types calling this constructor must override the <see cref="Constraint"/> /// property, and optionally, the <see cref="Cardinality"/>, <see cref="IsPrerequisite"/> /// and <see cref="IsRecomposable"/> /// properties. /// </note> /// </remarks> protected ImportDefinition() { } /// <summary> /// Initializes a new instance of the <see cref="ImportDefinition"/> class /// with the specified constraint, cardinality, value indicating if the import /// definition is recomposable and a value indicating if the import definition /// is a prerequisite. /// </summary> /// <param name="constraint"> /// A <see cref="Expression{TDelegate}"/> containing a <see cref="Func{T, TResult}"/> /// that defines the conditions that must be matched for the <see cref="ImportDefinition"/> /// to be satisfied by an <see cref="Export"/>. /// </param> /// <param name="contractName"> /// The contract name of the export that this import is interested in. The contract name /// property is used as guidance and not automatically enforced in the constraint. If /// the contract name is a required in the constraint then it should be added to the constraint /// by the caller of this constructor. /// </param> /// <param name="cardinality"> /// One of the <see cref="ImportCardinality"/> values indicating the /// cardinality of the <see cref="Export"/> objects required by the /// <see cref="ImportDefinition"/>. /// </param> /// <param name="isRecomposable"> /// <see langword="true"/> if the <see cref="ImportDefinition"/> can be satisfied /// multiple times throughout the lifetime of a <see cref="ComposablePart"/>, otherwise, /// <see langword="false"/>. /// </param> /// <param name="isPrerequisite"> /// <see langword="true"/> if the <see cref="ImportDefinition"/> is required to be /// satisfied before a <see cref="ComposablePart"/> can start producing exported /// objects; otherwise, <see langword="false"/>. /// </param> /// <exception cref="ArgumentNullException"> /// <paramref name="constraint"/> is <see langword="null"/>. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="cardinality"/> is not one of the <see cref="ImportCardinality"/> /// values. /// </exception> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public ImportDefinition(Expression<Func<ExportDefinition, bool>> constraint, string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite) : this(contractName, cardinality, isRecomposable, isPrerequisite, MetadataServices.EmptyMetadata) { Requires.NotNull(constraint, nameof(constraint)); _constraint = constraint; } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public ImportDefinition(Expression<Func<ExportDefinition, bool>> constraint, string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary<string, object> metadata) : this(contractName, cardinality, isRecomposable, isPrerequisite, metadata) { Requires.NotNull(constraint, nameof(constraint)); _constraint = constraint; } internal ImportDefinition(string contractName, ImportCardinality cardinality, bool isRecomposable, bool isPrerequisite, IDictionary<string, object> metadata) { if ( (cardinality != ImportCardinality.ExactlyOne) && (cardinality != ImportCardinality.ZeroOrMore) && (cardinality != ImportCardinality.ZeroOrOne) ) { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_InvalidEnum, nameof(cardinality), cardinality, typeof(ImportCardinality).Name), nameof(cardinality)); } _contractName = contractName ?? EmptyContractName; _cardinality = cardinality; _isRecomposable = isRecomposable; _isPrerequisite = isPrerequisite; //Metadata on imports was added in 4.5, prior to that it was ignored. if (metadata != null) { _metadata = metadata; } } /// <summary> /// Gets the contract name of the export required by the import definition. /// </summary> /// <value> /// A <see cref="String"/> containing the contract name of the <see cref="Export"/> /// required by the <see cref="ContractBasedImportDefinition"/>. This property should /// return <see cref="String.Empty"/> for imports that do not require a specific /// contract name. /// </value> public virtual string ContractName { get { Contract.Ensures(Contract.Result<string>() != null); return _contractName; } } /// <summary> /// Gets the metadata of the import definition. /// </summary> /// <value> /// An <see cref="IDictionary{TKey, TValue}"/> containing the metadata of the /// <see cref="ExportDefinition"/>. The default is an empty, read-only /// <see cref="IDictionary{TKey, TValue}"/>. /// </value> /// <remarks> /// <para> /// <note type="inheritinfo"> /// Overriders of this property should return a read-only /// <see cref="IDictionary{TKey, TValue}"/> object with a case-sensitive, /// non-linguistic comparer, such as <see cref="StringComparer.Ordinal"/>, /// and should never return <see langword="null"/>. /// If the <see cref="ImportDefinition"/> does not contain metadata /// return an empty <see cref="IDictionary{TKey, TValue}"/> instead. /// </note> /// </para> /// </remarks> public virtual IDictionary<string, object> Metadata { get { Contract.Ensures(Contract.Result<IDictionary<string, object>>() != null); return _metadata; } } /// <summary> /// Gets the cardinality of the exports required by the import definition. /// </summary> /// <value> /// One of the <see cref="ImportCardinality"/> values indicating the /// cardinality of the <see cref="Export"/> objects required by the /// <see cref="ImportDefinition"/>. The default is /// <see cref="ImportCardinality.ExactlyOne"/> /// </value> public virtual ImportCardinality Cardinality { get { return _cardinality; } } /// <summary> /// Gets an expression that defines conditions that must be matched for the import /// described by the import definition to be satisfied. /// </summary> /// <returns> /// A <see cref="Expression{TDelegate}"/> containing a <see cref="Func{T, TResult}"/> /// that defines the conditions that must be matched for the /// <see cref="ImportDefinition"/> to be satisfied by an <see cref="Export"/>. /// </returns> /// <exception cref="NotImplementedException"> /// The property was not overridden by a derived class. /// </exception> /// <remarks> /// <note type="inheritinfo"> /// Overriders of this property should never return <see langword="null"/>. /// </note> /// </remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures")] public virtual Expression<Func<ExportDefinition, bool>> Constraint { get { Contract.Ensures(Contract.Result<Expression<Func<ExportDefinition, bool>>>() != null); if (_constraint != null) { return _constraint; } throw ExceptionBuilder.CreateNotOverriddenByDerived("Constraint"); } } /// <summary> /// Gets a value indicating whether the import definition is required to be /// satisfied before a part can start producing exported values. /// </summary> /// <value> /// <see langword="true"/> if the <see cref="ImportDefinition"/> is required to be /// satisfied before a <see cref="ComposablePart"/> can start producing exported /// objects; otherwise, <see langword="false"/>. The default is <see langword="true"/>. /// </value> public virtual bool IsPrerequisite { get { return _isPrerequisite; } } /// <summary> /// Gets a value indicating whether the import definition can be satisfied multiple times. /// </summary> /// <value> /// <see langword="true"/> if the <see cref="ImportDefinition"/> can be satisfied /// multiple times throughout the lifetime of a <see cref="ComposablePart"/>, otherwise, /// <see langword="false"/>. The default is <see langword="false"/>. /// </value> public virtual bool IsRecomposable { get { return _isRecomposable; } } /// <summary> /// Executes of the constraint provided by the <see cref="Constraint"/> property /// against a given <see cref="ExportDefinition"/> to determine if this /// <see cref="ImportDefinition"/> can be satisfied by the given <see cref="Export"/>. /// </summary> /// <param name="exportDefinition"> /// A definition for a <see cref="Export"/> used to determine if it satisfies the /// requirements for this <see cref="ImportDefinition"/>. /// </param> /// <returns> /// <see langword="True"/> if the <see cref="Export"/> satisfies the requirements for /// this <see cref="ImportDefinition"/>, otherwise returns <see langword="False"/>. /// </returns> /// <remarks> /// <note type="inheritinfo"> /// Overrides of this method can provide a more optimized execution of the /// <see cref="Constraint"/> property but the result should remain consistent. /// </note> /// </remarks> /// <exception cref="ArgumentNullException"> /// <paramref name="exportDefinition"/> is <see langword="null"/>. /// </exception> public virtual bool IsConstraintSatisfiedBy(ExportDefinition exportDefinition) { Requires.NotNull(exportDefinition, nameof(exportDefinition)); if (_compiledConstraint == null) { _compiledConstraint = Constraint.Compile(); } return _compiledConstraint.Invoke(exportDefinition); } /// <summary> /// Returns a string representation of the import definition. /// </summary> /// <returns> /// A <see cref="String"/> containing the value of the <see cref="Constraint"/> property. /// </returns> public override string ToString() { return Constraint.Body.ToString(); } } }
// // System.Security.Cryptography MD5CryptoServiceProvider Class implementation // // Authors: // Matthew S. Ford (Matthew.S.Ford@Rose-Hulman.Edu) // Sebastien Pouliot (spouliot@motus.com) // // Copyright 2001 by Matthew S. Ford. // // Comment: Adapted to the Project from Mono CVS as Sebastien Pouliot suggested to enable // support of Npgsql MD5 authentication in platforms which don't have support for MD5 algorithm. // using System; namespace Revenj.DatabasePersistence.Postgres.Npgsql { /// <summary> /// C# implementation of the MD5 cryptographic hash function. /// </summary> #if USE_VERSION_1_0 internal class MD5CryptoServiceProvider : MD5 { #else internal sealed class MD5CryptoServiceProvider : MD5 { #endif private const int BLOCK_SIZE_BYTES = 64; private const int HASH_SIZE_BYTES = 16; private const int HASH_SIZE_BITS = 128; private readonly uint[] _H; private uint count; private readonly byte[] _ProcessingBuffer; // Used to start data when passed less than a block worth. private int _ProcessingBufferCount; // Counts how much data we have stored that still needs processed. /// <summary> /// Creates a new MD5CryptoServiceProvider. /// </summary> public MD5CryptoServiceProvider() { _H = new uint[4]; HashSizeValue = HASH_SIZE_BITS; _ProcessingBuffer = new byte[BLOCK_SIZE_BYTES]; Initialize(); } ~MD5CryptoServiceProvider() { Dispose(false); } protected override void Dispose(bool disposing) { // nothing to do (managed implementation) } /// <summary> /// Drives the hashing function. /// </summary> /// <param name="rgb">Byte array containing the data to hash.</param> /// <param name="start">Where in the input buffer to start.</param> /// <param name="size">Size in bytes of the data in the buffer to hash.</param> protected override void HashCore(byte[] rgb, int start, int size) { int i; State = 1; if (_ProcessingBufferCount != 0) { if (size < (BLOCK_SIZE_BYTES - _ProcessingBufferCount)) { Buffer.BlockCopy(rgb, start, _ProcessingBuffer, _ProcessingBufferCount, size); _ProcessingBufferCount += size; return; } else { i = (BLOCK_SIZE_BYTES - _ProcessingBufferCount); Buffer.BlockCopy(rgb, start, _ProcessingBuffer, _ProcessingBufferCount, i); ProcessBlock(_ProcessingBuffer, 0); _ProcessingBufferCount = 0; start += i; size -= i; } } for (i = 0; i < size - size % BLOCK_SIZE_BYTES; i += BLOCK_SIZE_BYTES) { ProcessBlock(rgb, start + i); } if (size % BLOCK_SIZE_BYTES != 0) { Buffer.BlockCopy(rgb, size - size % BLOCK_SIZE_BYTES + start, _ProcessingBuffer, 0, size % BLOCK_SIZE_BYTES); _ProcessingBufferCount = size % BLOCK_SIZE_BYTES; } } /// <summary> /// This finalizes the hash. Takes the data from the chaining variables and returns it. /// </summary> protected override byte[] HashFinal() { byte[] hash = new byte[16]; int i, j; ProcessFinalBlock(_ProcessingBuffer, 0, _ProcessingBufferCount); for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { hash[i * 4 + j] = (byte)(_H[i] >> j * 8); } } return hash; } /// <summary> /// Resets the class after use. Called automatically after hashing is done. /// </summary> public override void Initialize() { count = 0; _ProcessingBufferCount = 0; _H[0] = 0x67452301; _H[1] = 0xefcdab89; _H[2] = 0x98badcfe; _H[3] = 0x10325476; } /// <summary> /// This is the meat of the hash function. It is what processes each block one at a time. /// </summary> /// <param name="inputBuffer">Byte array to process data from.</param> /// <param name="inputOffset">Where in the byte array to start processing.</param> private void ProcessBlock(byte[] inputBuffer, int inputOffset) { uint[] buff = new uint[16]; uint a, b, c, d; int i; count += BLOCK_SIZE_BYTES; for (i = 0; i < 16; i++) { buff[i] = (inputBuffer[inputOffset + 4 * i]) | (((uint)(inputBuffer[inputOffset + 4 * i + 1])) << 8) | (((uint)(inputBuffer[inputOffset + 4 * i + 2])) << 16) | (((uint)(inputBuffer[inputOffset + 4 * i + 3])) << 24); } a = _H[0]; b = _H[1]; c = _H[2]; d = _H[3]; // This function was unrolled because it seems to be doubling our performance with current compiler/VM. // Possibly roll up if this changes. // ---- Round 1 -------- a += (((c ^ d) & b) ^ d) + (uint)Constants.C0 + buff[0]; a = (a << 7) | (a >> 25); a += b; d += (((b ^ c) & a) ^ c) + (uint)Constants.C1 + buff[1]; d = (d << 12) | (d >> 20); d += a; c += (((a ^ b) & d) ^ b) + (uint)Constants.C2 + buff[2]; c = (c << 17) | (c >> 15); c += d; b += (((d ^ a) & c) ^ a) + (uint)Constants.C3 + buff[3]; b = (b << 22) | (b >> 10); b += c; a += (((c ^ d) & b) ^ d) + (uint)Constants.C4 + buff[4]; a = (a << 7) | (a >> 25); a += b; d += (((b ^ c) & a) ^ c) + (uint)Constants.C5 + buff[5]; d = (d << 12) | (d >> 20); d += a; c += (((a ^ b) & d) ^ b) + (uint)Constants.C6 + buff[6]; c = (c << 17) | (c >> 15); c += d; b += (((d ^ a) & c) ^ a) + (uint)Constants.C7 + buff[7]; b = (b << 22) | (b >> 10); b += c; a += (((c ^ d) & b) ^ d) + (uint)Constants.C8 + buff[8]; a = (a << 7) | (a >> 25); a += b; d += (((b ^ c) & a) ^ c) + (uint)Constants.C9 + buff[9]; d = (d << 12) | (d >> 20); d += a; c += (((a ^ b) & d) ^ b) + (uint)Constants.C10 + buff[10]; c = (c << 17) | (c >> 15); c += d; b += (((d ^ a) & c) ^ a) + (uint)Constants.C11 + buff[11]; b = (b << 22) | (b >> 10); b += c; a += (((c ^ d) & b) ^ d) + (uint)Constants.C12 + buff[12]; a = (a << 7) | (a >> 25); a += b; d += (((b ^ c) & a) ^ c) + (uint)Constants.C13 + buff[13]; d = (d << 12) | (d >> 20); d += a; c += (((a ^ b) & d) ^ b) + (uint)Constants.C14 + buff[14]; c = (c << 17) | (c >> 15); c += d; b += (((d ^ a) & c) ^ a) + (uint)Constants.C15 + buff[15]; b = (b << 22) | (b >> 10); b += c; // ---- Round 2 -------- a += (((b ^ c) & d) ^ c) + (uint)Constants.C16 + buff[1]; a = (a << 5) | (a >> 27); a += b; d += (((a ^ b) & c) ^ b) + (uint)Constants.C17 + buff[6]; d = (d << 9) | (d >> 23); d += a; c += (((d ^ a) & b) ^ a) + (uint)Constants.C18 + buff[11]; c = (c << 14) | (c >> 18); c += d; b += (((c ^ d) & a) ^ d) + (uint)Constants.C19 + buff[0]; b = (b << 20) | (b >> 12); b += c; a += (((b ^ c) & d) ^ c) + (uint)Constants.C20 + buff[5]; a = (a << 5) | (a >> 27); a += b; d += (((a ^ b) & c) ^ b) + (uint)Constants.C21 + buff[10]; d = (d << 9) | (d >> 23); d += a; c += (((d ^ a) & b) ^ a) + (uint)Constants.C22 + buff[15]; c = (c << 14) | (c >> 18); c += d; b += (((c ^ d) & a) ^ d) + (uint)Constants.C23 + buff[4]; b = (b << 20) | (b >> 12); b += c; a += (((b ^ c) & d) ^ c) + (uint)Constants.C24 + buff[9]; a = (a << 5) | (a >> 27); a += b; d += (((a ^ b) & c) ^ b) + (uint)Constants.C25 + buff[14]; d = (d << 9) | (d >> 23); d += a; c += (((d ^ a) & b) ^ a) + (uint)Constants.C26 + buff[3]; c = (c << 14) | (c >> 18); c += d; b += (((c ^ d) & a) ^ d) + (uint)Constants.C27 + buff[8]; b = (b << 20) | (b >> 12); b += c; a += (((b ^ c) & d) ^ c) + (uint)Constants.C28 + buff[13]; a = (a << 5) | (a >> 27); a += b; d += (((a ^ b) & c) ^ b) + (uint)Constants.C29 + buff[2]; d = (d << 9) | (d >> 23); d += a; c += (((d ^ a) & b) ^ a) + (uint)Constants.C30 + buff[7]; c = (c << 14) | (c >> 18); c += d; b += (((c ^ d) & a) ^ d) + (uint)Constants.C31 + buff[12]; b = (b << 20) | (b >> 12); b += c; // ---- Round 3 -------- a += (b ^ c ^ d) + (uint)Constants.C32 + buff[5]; a = (a << 4) | (a >> 28); a += b; d += (a ^ b ^ c) + (uint)Constants.C33 + buff[8]; d = (d << 11) | (d >> 21); d += a; c += (d ^ a ^ b) + (uint)Constants.C34 + buff[11]; c = (c << 16) | (c >> 16); c += d; b += (c ^ d ^ a) + (uint)Constants.C35 + buff[14]; b = (b << 23) | (b >> 9); b += c; a += (b ^ c ^ d) + (uint)Constants.C36 + buff[1]; a = (a << 4) | (a >> 28); a += b; d += (a ^ b ^ c) + (uint)Constants.C37 + buff[4]; d = (d << 11) | (d >> 21); d += a; c += (d ^ a ^ b) + (uint)Constants.C38 + buff[7]; c = (c << 16) | (c >> 16); c += d; b += (c ^ d ^ a) + (uint)Constants.C39 + buff[10]; b = (b << 23) | (b >> 9); b += c; a += (b ^ c ^ d) + (uint)Constants.C40 + buff[13]; a = (a << 4) | (a >> 28); a += b; d += (a ^ b ^ c) + (uint)Constants.C41 + buff[0]; d = (d << 11) | (d >> 21); d += a; c += (d ^ a ^ b) + (uint)Constants.C42 + buff[3]; c = (c << 16) | (c >> 16); c += d; b += (c ^ d ^ a) + (uint)Constants.C43 + buff[6]; b = (b << 23) | (b >> 9); b += c; a += (b ^ c ^ d) + (uint)Constants.C44 + buff[9]; a = (a << 4) | (a >> 28); a += b; d += (a ^ b ^ c) + (uint)Constants.C45 + buff[12]; d = (d << 11) | (d >> 21); d += a; c += (d ^ a ^ b) + (uint)Constants.C46 + buff[15]; c = (c << 16) | (c >> 16); c += d; b += (c ^ d ^ a) + (uint)Constants.C47 + buff[2]; b = (b << 23) | (b >> 9); b += c; // ---- Round 4 -------- a += (((~d) | b) ^ c) + (uint)Constants.C48 + buff[0]; a = (a << 6) | (a >> 26); a += b; d += (((~c) | a) ^ b) + (uint)Constants.C49 + buff[7]; d = (d << 10) | (d >> 22); d += a; c += (((~b) | d) ^ a) + (uint)Constants.C50 + buff[14]; c = (c << 15) | (c >> 17); c += d; b += (((~a) | c) ^ d) + (uint)Constants.C51 + buff[5]; b = (b << 21) | (b >> 11); b += c; a += (((~d) | b) ^ c) + (uint)Constants.C52 + buff[12]; a = (a << 6) | (a >> 26); a += b; d += (((~c) | a) ^ b) + (uint)Constants.C53 + buff[3]; d = (d << 10) | (d >> 22); d += a; c += (((~b) | d) ^ a) + (uint)Constants.C54 + buff[10]; c = (c << 15) | (c >> 17); c += d; b += (((~a) | c) ^ d) + (uint)Constants.C55 + buff[1]; b = (b << 21) | (b >> 11); b += c; a += (((~d) | b) ^ c) + (uint)Constants.C56 + buff[8]; a = (a << 6) | (a >> 26); a += b; d += (((~c) | a) ^ b) + (uint)Constants.C57 + buff[15]; d = (d << 10) | (d >> 22); d += a; c += (((~b) | d) ^ a) + (uint)Constants.C58 + buff[6]; c = (c << 15) | (c >> 17); c += d; b += (((~a) | c) ^ d) + (uint)Constants.C59 + buff[13]; b = (b << 21) | (b >> 11); b += c; a += (((~d) | b) ^ c) + (uint)Constants.C60 + buff[4]; a = (a << 6) | (a >> 26); a += b; d += (((~c) | a) ^ b) + (uint)Constants.C61 + buff[11]; d = (d << 10) | (d >> 22); d += a; c += (((~b) | d) ^ a) + (uint)Constants.C62 + buff[2]; c = (c << 15) | (c >> 17); c += d; b += (((~a) | c) ^ d) + (uint)Constants.C63 + buff[9]; b = (b << 21) | (b >> 11); b += c; _H[0] += a; _H[1] += b; _H[2] += c; _H[3] += d; } /// <summary> /// Pads and then processes the final block. /// </summary> /// <param name="inputBuffer">Buffer to grab data from.</param> /// <param name="inputOffset">Position in buffer in bytes to get data from.</param> /// <param name="inputCount">How much data in bytes in the buffer to use.</param> private void ProcessFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { byte[] fooBuffer; int paddingSize; int i; uint size; paddingSize = (int)(56 - (inputCount + count) % BLOCK_SIZE_BYTES); if (paddingSize < 1) { paddingSize += BLOCK_SIZE_BYTES; } fooBuffer = new byte[inputCount + paddingSize + 8]; for (i = 0; i < inputCount; i++) { fooBuffer[i] = inputBuffer[i + inputOffset]; } fooBuffer[inputCount] = 0x80; for (i = inputCount + 1; i < inputCount + paddingSize; i++) { fooBuffer[i] = 0x00; } size = (uint)(count + inputCount); size *= 8; fooBuffer[inputCount + paddingSize] = (byte)((size) >> 0); fooBuffer[inputCount + paddingSize + 1] = (byte)((size) >> 8); fooBuffer[inputCount + paddingSize + 2] = (byte)((size) >> 16); fooBuffer[inputCount + paddingSize + 3] = (byte)((size) >> 24); fooBuffer[inputCount + paddingSize + 4] = 0x00; fooBuffer[inputCount + paddingSize + 5] = 0x00; fooBuffer[inputCount + paddingSize + 6] = 0x00; fooBuffer[inputCount + paddingSize + 7] = 0x00; ProcessBlock(fooBuffer, 0); if (inputCount + paddingSize + 8 == 128) { ProcessBlock(fooBuffer, 64); } } private enum Constants : uint { C0 = 0xd76aa478, C1 = 0xe8c7b756, C2 = 0x242070db, C3 = 0xc1bdceee, C4 = 0xf57c0faf, C5 = 0x4787c62a, C6 = 0xa8304613, C7 = 0xfd469501, C8 = 0x698098d8, C9 = 0x8b44f7af, C10 = 0xffff5bb1, C11 = 0x895cd7be, C12 = 0x6b901122, C13 = 0xfd987193, C14 = 0xa679438e, C15 = 0x49b40821, C16 = 0xf61e2562, C17 = 0xc040b340, C18 = 0x265e5a51, C19 = 0xe9b6c7aa, C20 = 0xd62f105d, C21 = 0x02441453, C22 = 0xd8a1e681, C23 = 0xe7d3fbc8, C24 = 0x21e1cde6, C25 = 0xc33707d6, C26 = 0xf4d50d87, C27 = 0x455a14ed, C28 = 0xa9e3e905, C29 = 0xfcefa3f8, C30 = 0x676f02d9, C31 = 0x8d2a4c8a, C32 = 0xfffa3942, C33 = 0x8771f681, C34 = 0x6d9d6122, C35 = 0xfde5380c, C36 = 0xa4beea44, C37 = 0x4bdecfa9, C38 = 0xf6bb4b60, C39 = 0xbebfbc70, C40 = 0x289b7ec6, C41 = 0xeaa127fa, C42 = 0xd4ef3085, C43 = 0x04881d05, C44 = 0xd9d4d039, C45 = 0xe6db99e5, C46 = 0x1fa27cf8, C47 = 0xc4ac5665, C48 = 0xf4292244, C49 = 0x432aff97, C50 = 0xab9423a7, C51 = 0xfc93a039, C52 = 0x655b59c3, C53 = 0x8f0ccc92, C54 = 0xffeff47d, C55 = 0x85845dd1, C56 = 0x6fa87e4f, C57 = 0xfe2ce6e0, C58 = 0xa3014314, C59 = 0x4e0811a1, C60 = 0xf7537e82, C61 = 0xbd3af235, C62 = 0x2ad7d2bb, C63 = 0xeb86d391 } } }
using Genny; using Humanizer; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using MvcTemplate.Objects; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text.Json; using System.Text.RegularExpressions; using System.Xml.Linq; namespace MvcTemplate.Web.Templates { [GennyModuleDescriptor("Default system module template")] public class Module : GennyModule { [GennyParameter(0, Required = true)] public String? Model { get; set; } [GennyParameter(1, Required = true)] public String? Controller { get; set; } [GennyParameter(2, Required = false)] public String? Area { get; set; } [GennySwitch("force", "f")] public Boolean Force { get; set; } public Module(IServiceProvider services) : base(services) { } public override void Run() { String path = $"{(Area != null ? $"{Area}/" : "")}{Controller}"; Dictionary<String, GennyScaffoldingResult> results = new() { { $"../MvcTemplate.Controllers/{path}/{Controller}.cs", Scaffold("Controllers/Controller") }, { $"../../test/MvcTemplate.Tests/Unit/Controllers/{path}/{Controller}Tests.cs", Scaffold("Tests/ControllerTests") }, { $"../MvcTemplate.Services/{path}/{Model}Service.cs", Scaffold("Services/Service") }, { $"../MvcTemplate.Services/{path}/I{Model}Service.cs", Scaffold("Services/IService") }, { $"../../test/MvcTemplate.Tests/Unit/Services/{path}/{Model}ServiceTests.cs", Scaffold("Tests/ServiceTests") }, { $"../MvcTemplate.Validators/{path}/{Model}Validator.cs", Scaffold("Validators/Validator") }, { $"../MvcTemplate.Validators/{path}/I{Model}Validator.cs", Scaffold("Validators/IValidator") }, { $"../../test/MvcTemplate.Tests/Unit/Validators/{path}/{Model}ValidatorTests.cs", Scaffold("Tests/ValidatorTests") }, { $"../MvcTemplate.Web/Views/{path}/Index.cshtml", Scaffold("Web/Index") }, { $"../MvcTemplate.Web/Views/{path}/Create.cshtml", Scaffold("Web/Create") }, { $"../MvcTemplate.Web/Views/{path}/Details.cshtml", Scaffold("Web/Details") }, { $"../MvcTemplate.Web/Views/{path}/Edit.cshtml", Scaffold("Web/Edit") }, { $"../MvcTemplate.Web/Views/{path}/Delete.cshtml", Scaffold("Web/Delete") }, { $"../MvcTemplate.Web/Resources/Views/{path}/{Model}View.json", Scaffold("Resources/View") } }; if (!File.Exists($"../MvcTemplate.Objects/Models/{path}/{Model}.cs") || !File.Exists($"../MvcTemplate.Objects/Views/{path}/{Model}View.cs")) { results = new Dictionary<String, GennyScaffoldingResult> { { $"../MvcTemplate.Objects/Models/{path}/{Model}.cs", Scaffold("Objects/Model") }, { $"../MvcTemplate.Objects/Views/{path}/{Model}View.cs", Scaffold("Objects/View") } }; } if (results.Any(result => result.Value.Errors.Any())) { Dictionary<String, GennyScaffoldingResult> errors = new(results.Where(x => x.Value.Errors.Any())); Write(errors); Logger.WriteLine(""); Logger.WriteLine("Scaffolding failed! Rolling back...", ConsoleColor.Red); } else { Logger.WriteLine(""); if (Force) Write(results); else TryWrite(results); if (results.Count > 2) { AddArea(); AddSiteMap(); AddPermissions(); AddViewImports(); AddObjectFactory(); AddPermissionTests(); AddTestingContextDrops(); AddResource("Page", "Headers", Model!, Model.Humanize()); AddResource("Page", "Headers", Model.Pluralize(), Model.Pluralize().Humanize()); AddResource("Page", "Titles", $"{Area}/{Controller}/Create", $"{Model.Humanize()} creation"); AddResource("Page", "Titles", $"{Area}/{Controller}/Delete", $"{Model.Humanize()} deletion"); AddResource("Page", "Titles", $"{Area}/{Controller}/Details", $"{Model.Humanize()} details"); AddResource("Page", "Titles", $"{Area}/{Controller}/Index", Model.Pluralize().Humanize()); AddResource("Page", "Titles", $"{Area}/{Controller}/Edit", $"{Model.Humanize()} edit"); if (Area != null) AddResource("Shared", "Areas", Area, Area.Humanize()); AddResource("Shared", "Controllers", $"{Area}/{Controller}", Model.Pluralize().Humanize()); if (Area != null) AddResource("SiteMap", "Titles", $"{Area}//", Area.Humanize()); AddResource("SiteMap", "Titles", $"{Area}/{Controller}/Create", "Create"); AddResource("SiteMap", "Titles", $"{Area}/{Controller}/Delete", "Delete"); AddResource("SiteMap", "Titles", $"{Area}/{Controller}/Details", "Details"); AddResource("SiteMap", "Titles", $"{Area}/{Controller}/Index", Model.Pluralize().Humanize()); AddResource("SiteMap", "Titles", $"{Area}/{Controller}/Edit", "Edit"); Logger.WriteLine(""); Logger.WriteLine("Scaffolded successfully!", ConsoleColor.Green); } else { Logger.WriteLine(""); Logger.WriteLine("Scaffolded successfully! Write in model and view properties and rerun the scaffolding.", ConsoleColor.Green); } } } public override void ShowHelp() { Logger.WriteLine("Parameters:"); Logger.WriteLine(" 0 - Scaffolded model."); Logger.WriteLine(" 1 - Scaffolded controller."); Logger.WriteLine(" 2 - Scaffolded area (optional)."); } private void AddArea() { if (Area == null) return; Logger.Write("../MvcTemplate.Controllers/Area.cs - "); String areas = File.ReadAllText("../MvcTemplate.Controllers/Area.cs"); String newAreas = String.Join(",\n ", Regex.Matches(areas, @" (\w+),?") .Select(match => match.Groups[1].Value) .Append(Area) .Distinct() .OrderBy(name => name)); areas = Regex.Replace(areas, @" {\r?\n( +\w+,?\r?\n)+ }", $" {{\n {newAreas}\n }}"); File.WriteAllText("../MvcTemplate.Controllers/Area.cs", areas); Logger.WriteLine("Succeeded", ConsoleColor.Green); } private void AddSiteMap() { Logger.Write("../MvcTemplate.Web/mvc.sitemap - "); XElement sitemap = XElement.Parse(File.ReadAllText("mvc.sitemap")); Boolean isDefined = sitemap .Descendants("siteMapNode") .Any(node => node.Attribute("action")?.Value == "Index" && node.Parent?.Attribute("area")?.Value == Area && node.Attribute("controller")?.Value == Controller); if (isDefined) { Logger.WriteLine("Already exists, skipping...", ConsoleColor.Yellow); } else { XElement? parent = sitemap .Descendants("siteMapNode") .FirstOrDefault(node => node.Attribute("action") == null && node.Attribute("controller") == null && node.Attribute("area")?.Value == Area); if (parent == null) { if (Area == null) { parent = sitemap.Descendants("siteMapNode").First(); } else { parent = XElement.Parse($@"<siteMapNode menu=""true"" icon=""far fa-folder"" area=""{Area}"" />"); sitemap.Descendants("siteMapNode").First().Add(parent); } } parent.Add(XElement.Parse( $@"<siteMapNode menu=""true"" icon=""far fa-folder"" controller=""{Controller}"" action=""Index""> <siteMapNode icon=""far fa-file"" action=""Create"" /> <siteMapNode icon=""fa fa-info"" action=""Details"" /> <siteMapNode icon=""fa fa-pencil-alt"" action=""Edit"" /> <siteMapNode icon=""fa fa-times"" action=""Delete"" /> </siteMapNode>" )); File.WriteAllText("mvc.sitemap", $"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n{sitemap.ToString().Replace(" ", " ")}\n"); Logger.WriteLine("Succeeded", ConsoleColor.Green); } } private void AddPermissions() { Logger.Write("../MvcTemplate.Data/Migrations/Configuration.cs - "); String permissions = File.ReadAllText("../MvcTemplate.Data/Migrations/Configuration.cs"); String newPermissions = String.Join(",\n", Regex.Matches(permissions, "new Permission {[^}]+}") .Select(match => $" {match.Value}") .Append($@" new Permission {{ Area = ""{Area}"", Controller = ""{Controller}"", Action = ""Create"" }}") .Append($@" new Permission {{ Area = ""{Area}"", Controller = ""{Controller}"", Action = ""Delete"" }}") .Append($@" new Permission {{ Area = ""{Area}"", Controller = ""{Controller}"", Action = ""Details"" }}") .Append($@" new Permission {{ Area = ""{Area}"", Controller = ""{Controller}"", Action = ""Edit"" }}") .Append($@" new Permission {{ Area = ""{Area}"", Controller = ""{Controller}"", Action = ""Index"" }}") .Distinct() .OrderBy(permission => permission)); permissions = Regex.Replace(permissions, @"( +new Permission {[^}]+},?\r?\n+)+", $"{newPermissions}\n"); File.WriteAllText("../MvcTemplate.Data/Migrations/Configuration.cs", permissions); Logger.WriteLine("Succeeded", ConsoleColor.Green); } private void AddViewImports() { Logger.Write("../MvcTemplate.Web/Views/_ViewImports.cshtml - "); String imports = File.ReadAllText("../MvcTemplate.Web/Views/_ViewImports.cshtml"); String newImports = String.Join("\n", Regex.Matches(imports, "@using (.+);") .Select(match => match.Value) .Append(Area == null ? "@using MvcTemplate.Controllers;" : $"@using MvcTemplate.Controllers.{Area};") .Distinct() .OrderBy(definition => definition.TrimEnd(';'))); imports = Regex.Replace(imports, @"(@using (.+);\r?\n)+", $"{newImports}\n"); File.WriteAllText("../MvcTemplate.Web/Views/_ViewImports.cshtml", imports); Logger.WriteLine("Succeeded", ConsoleColor.Green); } private void AddObjectFactory() { Logger.Write("../../test/MvcTemplate.Tests/Helpers/ObjectsFactory.cs - "); ModuleModel model = new(Model!, Controller!, Area); SyntaxNode tree = CSharpSyntaxTree.ParseText(File.ReadAllText("../../test/MvcTemplate.Tests/Helpers/ObjectsFactory.cs")).GetRoot(); if (tree.DescendantNodes().OfType<MethodDeclarationSyntax>().Any(method => method.Identifier.Text == $"Create{Model}")) { Logger.WriteLine("Already exists, skipping...", ConsoleColor.Yellow); } else { String fakeView = FakeObjectCreation(model.View, model.AllViewProperties); String fakeModel = FakeObjectCreation(model.Model, model.ModelProperties); SyntaxNode last = tree.DescendantNodes().OfType<MethodDeclarationSyntax>().Last(); SyntaxNode modelCreation = CSharpSyntaxTree.ParseText($"{fakeModel}{fakeView}\n").GetRoot(); ClassDeclarationSyntax factory = tree.DescendantNodes().OfType<ClassDeclarationSyntax>().First(); tree = tree.ReplaceNode(factory, factory.InsertNodesAfter(last, modelCreation.ChildNodes())); File.WriteAllText("../../test/MvcTemplate.Tests/Helpers/ObjectsFactory.cs", tree.ToString()); Logger.WriteLine("Succeeded", ConsoleColor.Green); } } private void AddPermissionTests() { Logger.Write("../../test/MvcTemplate.Tests/Unit/Data/Migrations/ConfigurationTests.cs - "); String tests = File.ReadAllText("../../test/MvcTemplate.Tests/Unit/Data/Migrations/ConfigurationTests.cs"); String newTests = String.Join("\n", Regex.Matches(tests, @"\[InlineData\(.*, ""\w+"", ""\w+""\)\]") .Select(match => $" {match.Value}") .Append($@" [InlineData(""{Area}"", ""{Controller}"", ""Create"")]") .Append($@" [InlineData(""{Area}"", ""{Controller}"", ""Delete"")]") .Append($@" [InlineData(""{Area}"", ""{Controller}"", ""Details"")]") .Append($@" [InlineData(""{Area}"", ""{Controller}"", ""Edit"")]") .Append($@" [InlineData(""{Area}"", ""{Controller}"", ""Index"")]") .Distinct() .OrderBy(test => test)); tests = Regex.Replace(tests, @"( +\[InlineData\(.*, ""\w+"", ""\w+""\)\]\r?\n)+", $"{newTests}\n"); File.WriteAllText("../../test/MvcTemplate.Tests/Unit/Data/Migrations/ConfigurationTests.cs", tests); Logger.WriteLine("Succeeded", ConsoleColor.Green); } private void AddTestingContextDrops() { Logger.Write("../../test/MvcTemplate.Tests/Helpers/TestingContext.cs - "); String drops = File.ReadAllText("../../test/MvcTemplate.Tests/Helpers/TestingContext.cs"); String newDrops = String.Join("\n", Regex.Matches(drops, @"context.RemoveRange\(context.Set<(.+)>\(\)\);") .Select(match => $" {match.Value}") .Append($" context.RemoveRange(context.Set<{Model}>());") .Distinct() .OrderByDescending(drop => drop.Length) .ThenByDescending(drop => drop)); drops = Regex.Replace(drops, @"( +context.RemoveRange\(context.Set<(.+)>\(\)\);\r?\n)+", $"{newDrops}\n"); File.WriteAllText("../../test/MvcTemplate.Tests/Helpers/TestingContext.cs", drops); Logger.WriteLine("Succeeded", ConsoleColor.Green); } private void AddResource(String resource, String group, String key, String value) { Logger.Write($"../MvcTemplate.Web/Resources/Shared/{resource}.json - "); String page = File.ReadAllText($"Resources/Shared/{resource}.json"); Dictionary<String, SortedDictionary<String, String>> resources = JsonSerializer.Deserialize<Dictionary<String, SortedDictionary<String, String>>>(page)!; if (resources[group].ContainsKey(key)) { Logger.WriteLine("Already exists, skipping...", ConsoleColor.Yellow); } else { resources[group][key] = value; String text = Regex.Replace(JsonSerializer.Serialize(resources, new JsonSerializerOptions { WriteIndented = true }), "(^ +)", "$1$1", RegexOptions.Multiline); File.WriteAllText($"Resources/Shared/{resource}.json", $"{text}\n"); Logger.WriteLine("Succeeded", ConsoleColor.Green); } } private GennyScaffoldingResult Scaffold(String path) { return Scaffolder.Scaffold($"Templates/Module/{path}", new ModuleModel(Model!, Controller!, Area)); } private String FakeObjectCreation(String name, PropertyInfo[] properties) { String creation = $"\n public static {name} Create{name}(Int64 id)\n"; creation += " {\n"; creation += $" return new {name}\n"; creation += " {\n"; creation += String.Join(",\n", properties .Where(property => property.Name != nameof(AModel.CreationDate)) .OrderBy(property => property.Name.Length) .Select(property => { String set = $" {property.Name} = "; if (property.PropertyType == typeof(String)) return $"{set}$\"{property.Name}{{id}}\""; if (typeof(Boolean?).IsAssignableFrom(property.PropertyType)) return $"{set}true"; if (typeof(DateTime?).IsAssignableFrom(property.PropertyType)) return $"{set}DateTime.Now.AddDays(id)"; return $"{set}id"; })) + "\n"; creation += " };\n"; creation += " }"; return creation; } } }
using System; using System.Collections.Generic; using System.Linq; using Shouldly; using Xunit; namespace GraphQL.Tests.Execution { public abstract class InputConversionTestsBase { #region Input Types private class Person { public string Name { get; set; } public int Age { get; set; } } public class MyInput { public int A { get; set; } public string B { get; set; } public List<string> C { get; set; } public int? D { get; set; } public Guid E { get; set; } public List<int?> F { get; set; } public List<List<int?>> G { get; set; } public DateTime H { get; set; } public double I { get; set; } public long J { get; set; } } public class EnumInput { public Numbers A { get; set; } public Numbers2? B { get; set; } } public enum Numbers { One, Two, Three } public enum Numbers2 : long { One, Two, Three } public class Parent2 { public Parent Input { get; set; } } public class Parent { public string A { get; set; } public List<Child> B { get; set; } public string C { get; set; } } public class Child { public string A { get; set; } } #endregion [Fact] public void converts_null() { var inputs = VariablesToInputs(null); inputs.Count.ShouldBe(0); } [Fact] public void converts_small_numbers_to_int() { var json = @"{""a"": 1}"; var inputs = VariablesToInputs(json); inputs["a"].ShouldBe(1); inputs["a"].GetType().ShouldBe(typeof(int)); } [Fact] public void converts_large_numbers_to_long() { var json = @"{""a"": 1000000000000000001}"; var inputs = VariablesToInputs(json); inputs["a"].ShouldBe(1000000000000000001); inputs["a"].GetType().ShouldBe(typeof(long)); } [Fact] public void can_convert_json_to_input_object_and_specific_object() { var json = @"{""a"": 1, ""b"": ""2""}"; var inputs = VariablesToInputs(json); inputs.ShouldNotBeNull(); inputs["a"].ShouldBe(1); inputs["b"].ShouldBe("2"); var myInput = inputs.ToObject<MyInput>(); myInput.ShouldNotBeNull(); myInput.A.ShouldBe(1); myInput.B.ShouldBe("2"); } [Fact] public void can_convert_json_to_array() { var json = @"{""a"": 1, ""b"": ""2"", ""c"": [""foo""]}"; var inputs = VariablesToInputs(json); inputs.ShouldNotBeNull(); inputs["a"].ShouldBe(1); inputs["b"].ShouldBe("2"); inputs["c"].ShouldBeOfType<List<object>>(); var myInput = inputs.ToObject<MyInput>(); myInput.ShouldNotBeNull(); myInput.A.ShouldBe(1); myInput.B.ShouldBe("2"); myInput.C.ShouldNotBeNull(); myInput.C.Count.ShouldBe(1); myInput.C.First().ShouldBe("foo"); } [Fact] public void can_convert_json_to_nullable_array() { var json = @"{""a"": 1, ""b"": ""2"", ""c"": [""foo""], ""f"": [1,null]}"; var inputs = VariablesToInputs(json); inputs.ShouldNotBeNull(); inputs["f"].ShouldBeOfType<List<object>>(); var myInput = inputs.ToObject<MyInput>(); myInput.ShouldNotBeNull(); myInput.F.ShouldNotBeNull(); myInput.F.Count.ShouldBe(2); myInput.F[0].ShouldBe(1); myInput.F[1].ShouldBe(null); } [Fact] public void can_convert_json_to_nested_nullable_array() { var json = @"{""a"": 1, ""b"": ""2"", ""c"": [""foo""], ""g"": [[1,null], [null, 1]]}"; var inputs = VariablesToInputs(json); inputs.ShouldNotBeNull(); inputs["g"].ShouldBeOfType<List<object>>(); var myInput = inputs.ToObject<MyInput>(); myInput.ShouldNotBeNull(); myInput.G.ShouldNotBeNull(); myInput.G.Count.ShouldBe(2); myInput.G[0].Count.ShouldBe(2); myInput.G[0][0].ShouldBe(1); myInput.G[0][1].ShouldBeNull(); myInput.G[1].Count.ShouldBe(2); myInput.G[1][0].ShouldBeNull(); myInput.G[1][1].ShouldBe(1); } [Fact] public void can_convert_json_to_input_object_with_nullable_int() { var json = @"{""a"": 1, ""b"": ""2"", ""d"": ""5""}"; var inputs = VariablesToInputs(json); inputs.ShouldNotBeNull(); var myInput = inputs.ToObject<MyInput>(); myInput.ShouldNotBeNull(); myInput.D.ShouldBe(5); } [Fact] public void can_read_long() { var json = @"{""j"": 89429901947254093 }"; var inputs = VariablesToInputs(json); inputs.ShouldNotBeNull(); var myInput = inputs.ToObject<MyInput>(); myInput.ShouldNotBeNull(); myInput.J.ShouldBe(89429901947254093); } [Fact] public void can_convert_int_to_double() { var json = @"{""i"": 1 }"; var inputs = VariablesToInputs(json); inputs.ShouldNotBeNull(); var myInput = inputs.ToObject<MyInput>(); myInput.ShouldNotBeNull(); myInput.I.ShouldBe(1.0); } [Fact] public void can_convert_json_to_input_object_with_guid() { var json = @"{""a"": 1, ""b"": ""2"", ""e"": ""920a1b6d-f75a-4594-8567-e2c457b29cc0""}"; var inputs = VariablesToInputs(json); inputs.ShouldNotBeNull(); var myInput = inputs.ToObject<MyInput>(); myInput.ShouldNotBeNull(); myInput.E.ShouldBe(new Guid("920a1b6d-f75a-4594-8567-e2c457b29cc0")); } [Fact] public void can_convert_json_to_input_object_with_enum_string() { var json = @"{""a"": ""three""}"; var inputs = VariablesToInputs(json); inputs.ShouldNotBeNull(); var myInput = inputs.ToObject<EnumInput>(); myInput.ShouldNotBeNull(); myInput.A.ShouldBe(Numbers.Three); myInput.B.ShouldBeNull(); } [Fact] public void can_convert_json_to_input_object_with_enum_string_exact() { var json = @"{""a"": ""Two""}"; var inputs = VariablesToInputs(json); inputs.ShouldNotBeNull(); var myInput = inputs.ToObject<EnumInput>(); myInput.ShouldNotBeNull(); myInput.A.ShouldBe(Numbers.Two); } [Fact] public void can_convert_json_to_input_object_with_enum_number() { var json = @"{""a"": ""2""}"; var inputs = VariablesToInputs(json); inputs.ShouldNotBeNull(); var myInput = inputs.ToObject<EnumInput>(); myInput.ShouldNotBeNull(); myInput.A.ShouldBe(Numbers.Three); myInput.B.ShouldBeNull(); } [Fact] public void can_convert_json_to_input_object_with_enum_long_number() { var json = @"{""a"": 2, ""b"": 2}"; var inputs = VariablesToInputs(json); var myInput = inputs.ToObject<EnumInput>(); myInput.ShouldNotBeNull(); myInput.B.Value.ShouldBe(Numbers2.Three); } [Fact] public void can_convert_json_to_input_object_with_child_object_list() { var json = @"{""a"": ""foo"", ""b"":[{""a"": ""bar""}], ""c"": ""baz""}"; var inputs = VariablesToInputs(json); var myInput = inputs.ToObject<Parent>(); myInput.ShouldNotBeNull(); myInput.B.Count.ShouldBe(1); myInput.B[0].A.ShouldBe("bar"); } [Fact] public void can_convert_json_to_input_object_with_child_object() { var json = @"{ ""input"": {""a"": ""foo"", ""b"":[{""a"": ""bar""}], ""c"": ""baz""}}"; var inputs = VariablesToInputs(json); var myInput = inputs.ToObject<Parent2>(); myInput.ShouldNotBeNull(); myInput.Input.B.Count.ShouldBe(1); myInput.Input.B[0].A.ShouldBe("bar"); } [Fact] public void can_convert_utc_date_to_datetime_with_correct_kind() { var json = @"{ ""h"": ""2016-10-21T13:32:15.753Z"" }"; var expected = DateTime.SpecifyKind(DateTime.Parse("2016-10-21T13:32:15.753"), DateTimeKind.Utc); var inputs = VariablesToInputs(json); var myInput = inputs.ToObject<MyInput>(); myInput.ShouldNotBeNull(); myInput.H.ShouldBe(expected); } [Fact] public void can_convert_unspecified_date_to_datetime_with_correct_kind() { var json = @"{ ""h"": ""2016-10-21T13:32:15"" }"; var expected = DateTime.SpecifyKind(DateTime.Parse("2016-10-21T13:32:15"), DateTimeKind.Unspecified); var inputs = VariablesToInputs(json); var myInput = inputs.ToObject<MyInput>(); myInput.ShouldNotBeNull(); myInput.H.ShouldBe(expected); } [Fact] public void can_convert_json_to_input_object_with_custom_converter() { var json = @"{ ""name1"": ""tom"", ""age1"": 10 }"; var inputs = VariablesToInputs(json); // before custom converter var person1 = inputs.ToObject<Person>(); person1.Name.ShouldBeNull(); person1.Age.ShouldBe(0); ValueConverter.Register(v => new Person { Name = (string)v["name1"], Age = (int)v["age1"] }); // after registering custom converter var person2 = inputs.ToObject<Person>(); person2.Name.ShouldBe("tom"); person2.Age.ShouldBe(10); // after unregistering custom converter ValueConverter.Register<Person>(null); var person3 = inputs.ToObject<Person>(); person3.Name.ShouldBeNull(); person3.Age.ShouldBe(0); } protected abstract Inputs VariablesToInputs(string variables); } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using csscript; using CSScripting; using CSScriptLib; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Scripting; using Testing; using Xunit; namespace EvaluatorTests { public class API_CodeDom : API_Roslyn { public API_CodeDom() { base.GetEvaluator = () => CSScript.CodeDomEvaluator; // CSScript.EvaluatorConfig.DebugBuild = true; CodeDomEvaluator.CompileOnServer = true; } [Fact] public void CompileCode_CompileInfo_CodeDom() { var info = new CompileInfo { RootClass = "test" }; var ex = Assert.Throws<CSScriptException>(() => { Assembly asm = new_evaluator.CompileCode(@"using System; public class Script { public int Sum(int a, int b) { return a+b; } }", info); }); Assert.StartsWith("CompileInfo.RootClass property should only be used with Roslyn evaluator", ex.Message); } } public class API_Roslyn { public string GetTempFileName(string seed) => $"{this.GetHashCode()}.{seed}".GetFullPath(); public string GetTempScript(string seed, string content) { var script = GetTempFileName(seed); File.WriteAllText(script, content); return script; } public Func<IEvaluator> GetEvaluator = () => CSScript.RoslynEvaluator; public IEvaluator new_evaluator => GetEvaluator(); /// <summary> /// Compiles the code with imports. /// </summary> /// <returns></returns> [Fact] public void CompileFileWithImports() { var rootDir = Environment.CurrentDirectory; var primaryScript = rootDir.PathJoin($"{nameof(CompileCodeWithImports)}.cs"); var dependencyScript = rootDir.PathJoin($"dep{nameof(CompileCodeWithImports)}.cs"); File.WriteAllText(primaryScript, $@"//css_inc {dependencyScript} using System; public class Script {{ public int Sum(int a, int b) => Calc.Sum(a ,b); }}"); File.WriteAllText(dependencyScript, @"using System; public class Calc { static public int Sum(int a, int b) { return a+b; } }"); // CSScript.EvaluatorConfig.DebugBuild = true; dynamic script = new_evaluator .LoadFile(primaryScript); var result = script.Sum(7, 3); Assert.Equal(10, result); } [Fact] public void CompileCodeWithImports() { var dependencyScript = $"dep{nameof(CompileCodeWithImports)}.cs".GetFullPath(); File.WriteAllText(dependencyScript, @"using System; public class Calc { static public int Sum(int a, int b) { return a+b; } }"); dynamic script = new_evaluator.LoadCode($@"//css_inc {dependencyScript} using System; public class Script {{ public int Sum(int a, int b) => Calc.Sum(a ,b); }}"); var result = script.Sum(7, 3); Assert.Equal(10, result); } [Fact] public void CompileCodeWithRefs() { var tempDir = ".\\dependencies".EnsureDir(); var calcAsm = tempDir.PathJoin("calc.v1.dll").GetFullPath(); if (!calcAsm.FileExists()) // try to avoid unnecessary compilations as xUnint keeps locking the loaded assemblies CSScript.CodeDomEvaluator .CompileAssemblyFromCode(@"using System; public class Calc { static public int Sum(int a, int b) => a + b; }", calcAsm); // NOTE!!! Roslyn evaluator will inject class in the extra root class "css_root" Very // annoying, but even `css_root.Calc.Sum` will not work when referenced in scrips. // Roslyn does some crazy stuff. The assembly produced by Roslyn cannot be easily used. // // So using CodeDom (csc.exe) instead. It does build proper assemblies var code = @"using System; public class Script { public int Sum(int a, int b) => Calc.Sum(a, b); }"; try { new_evaluator.LoadCode(code); Assert.True(false); } catch (Exception e) { Assert.Contains("The name 'Calc' does not exist in the current context", e.Message); } new_evaluator.LoadCode($"//css_ref {calcAsm}" + Environment.NewLine + code); } [Fact] public void LoadCode_detect_error_in_imported_script() { var dependencyScript = $"dep{nameof(LoadCode_detect_error_in_imported_script)}.cs".GetFullPath(); try { File.WriteAllText(dependencyScript, @"using System; public class Calc { static public int Sum(int a, int b) { return a+b } }"); new_evaluator.LoadCode($@"//css_inc {dependencyScript} using System; public class Script {{ public int Sum(int a, int b) => Calc.Sum(a ,b); }}"); Assert.True(false, "Expected compile error was not detected"); } catch (Exception e) { Assert.Contains($"{dependencyScript}(6,73): error CS1002: ; expected", e.Message); } } [Fact] public void LoadFile_detect_error_in_imported_script() { var primaryScript = $"{nameof(LoadFile_detect_error_in_imported_script)}.cs".GetFullPath(); var dependencyScript = $"dep{nameof(LoadFile_detect_error_in_imported_script)}.cs".GetFullPath(); try { File.WriteAllText(primaryScript, $@"//css_inc {dependencyScript} using System; public class Script {{ public int Sum(int a, int b) => Calc.Sum(a ,b); }}"); File.WriteAllText(dependencyScript, @"using System; public class Calc { static public int Sum(int a, int b) { return a+b } }"); new_evaluator.LoadFile(primaryScript); Assert.True(false, "Expected compile error was not detected"); } catch (Exception e) { Assert.Contains($"{dependencyScript}(6,73): error CS1002: ; expected", e.Message); } } [Fact] public void LoadCode_detect_error_in_primary_script() { var dependencyScript = $"dep{nameof(LoadCode_detect_error_in_primary_script)}.cs".GetFullPath(); try { File.WriteAllText(dependencyScript, @"using System; public class Calc { static public int Sum(int a, int b) { return a+b; } }"); new_evaluator.LoadCode($@"//css_inc {dependencyScript} using System; public class Script {{ public int Sum(int a, int b) => Calc.Sum(a ,b) }}"); Assert.True(false, "Expected compile error was not detected"); } catch (Exception e) { Assert.Contains($"(5,89): error CS1002: ; expected", e.Message); } } [Fact] public void LoadCode_detect_error_in_script() { try { new_evaluator.LoadCode($@"using System; public class Script {{ public int Sum(int a, int b) => a = b }}"); Assert.True(false, "Expected compile error was not detected"); } catch (Exception e) { Assert.Contains($"(4,80): error CS1002: ; expected", e.Message); } } [Fact] public void LoadFiule_detect_error_in_script() { var script = $"{nameof(LoadFiule_detect_error_in_script)}.cs".GetFullPath(); try { File.WriteAllText(script, @"using System; public class Script { public int Sum(int a, int b) => a + b }"); new_evaluator.LoadFile(script); Assert.True(false, "Expected compile error was not detected"); } catch (Exception e) { Assert.Contains($"{script}(4,87): error CS1002: ; expected", e.Message); } } [Fact] public void LoadFile_detect_error_in_primary_script() { var primaryScript = $"{nameof(LoadFile_detect_error_in_primary_script)}.cs".GetFullPath(); var dependencyScript = $"dep{nameof(LoadFile_detect_error_in_primary_script)}.cs".GetFullPath(); try { File.WriteAllText(primaryScript, $@"//css_inc {dependencyScript} using System; public class Script {{ public int Sum(int a, int b) => Calc.Sum(a ,b) }}"); File.WriteAllText(dependencyScript, @"using System; public class Calc { static public int Sum(int a, int b) { return a+b; } }"); new_evaluator.LoadFile(primaryScript); Assert.True(false, "Expected compile error was not detected"); } catch (Exception e) { Assert.Contains($"{primaryScript}(5,103): error CS1002: ; expected", e.Message); } } [Fact] public void CompileCode() { Assembly asm = new_evaluator.CompileCode(@"using System; public class Script { public int Sum(int a, int b) { return a+b; } }"); dynamic script = asm.CreateObject("*"); var result = script.Sum(7, 3); Assert.Equal(10, result); } [Fact] public void CompileCode_CompileInfo() { // Note if you give AssemblyFile the name with the extension .dll xUnit runtime will // lock the file simply because it was present in the local dir. So hide the assembly by // dropping the file extension. var asm_file = GetTempFileName(nameof(CompileCode_InmemAsmLocation)); var info = new CompileInfo { AssemblyFile = asm_file }; Assembly asm = new_evaluator.CompileCode(@"using System; public class Script { public int Sum(int a, int b) { return a+b; } }", info); dynamic script = asm.CreateObject("*"); var result = script.Sum(7, 3); Assert.Equal(10, result); Assert.Equal(asm_file, asm.Location()); } [Fact] public void CompileCode_InmemAsmLocation() { if (new_evaluator is RoslynEvaluator) // Roslyn cannot work with C# files (but in memory streams) return; // So asm location does not make sense. var asm_file = GetTempFileName(nameof(CompileCode_InmemAsmLocation)); var info = new CompileInfo { AssemblyFile = asm_file, PreferLoadingFromFile = false }; Assembly asm = new_evaluator.CompileCode(@"using System; public class Script { public int Sum(int a, int b) { return a+b; } }", info); var css_injected_location = asm.Location(); var clr_standard_location = asm.Location; Assert.Equal(asm_file, css_injected_location); Assert.Equal("", clr_standard_location); } [Fact] public void Check_InvalidScript() { var ex = Assert.Throws<CompilerException>(() => { new_evaluator.Check(@"using System; public class Script ??"); }); Assert.Contains("Invalid expression term '??'", ex.Message); } [Fact] public void Check_ValidScript() { new_evaluator.Check(@"using System; public class Script { public int Sum(int a, int b) { return a+b; } }"); // does not throw } [Fact] public void CompileAssemblyFromCode() { string asmFile = new_evaluator.CompileAssemblyFromCode( @"using System; public class Script { public int Sum(int a, int b) { return a+b; } }", "MyScript.asm"); Assert.True(File.Exists(asmFile)); } [Fact] public void CompileAssemblyFromFile() { var script = GetTempScript(nameof(CompileAssemblyFromFile), @"using System; public class Calc { public int Sum(int a, int b) => a+b; }"); string asmFile = new_evaluator.CompileAssemblyFromFile(script, "MyScript.asm"); Assert.True(File.Exists(asmFile)); } [Fact] public void CompileMethod() { dynamic calc = new_evaluator.CompileMethod("int Sum(int a, int b) => a+b;") .CreateObject("*"); var result = calc.Sum(7, 3); Assert.Equal(10, result); } [Fact] public void LoadMethod() { dynamic calc = new_evaluator.LoadMethod("int Sum(int a, int b) => a+b;"); var result = calc.Sum(7, 3); Assert.Equal(10, result); } [Fact] public void LoadMethod_T() { ICalc calc = new_evaluator.LoadMethod<ICalc>("int Sum(int a, int b) => a+b;"); var result = calc.Sum(7, 3); Assert.Equal(10, result); } [Fact] public void CreateDelegate() { var sum = new_evaluator.CreateDelegate(@"int Sum(int a, int b) => a + b;"); int result = (int)sum(7, 3); Assert.Equal(10, result); } [Fact] public void CreateDelegate_T() { var sum = new_evaluator.CreateDelegate<int>(@"int Sum(int a, int b) => a + b;"); int result = sum(7, 3); Assert.Equal(10, result); } [Fact] public void LoadCode() { dynamic script = new_evaluator .LoadCode(@"using System; public class Script { public int Sum(int a, int b) { return a+b; } }"); int result = script.Sum(1, 2); Assert.Equal(3, result); } [Fact] public void LoadCode_T() { ICalc calc = new_evaluator.LoadCode<ICalc>(@"using System; public class Script : Testing.ICalc { public int Sum(int a, int b) { return a+b; } }"); int result = calc.Sum(1, 2); Assert.Equal(3, result); } [Fact] public void LoadFile() { var script = GetTempScript(nameof(LoadFile), @"using System; public class Calc { public int Sum(int a, int b) => a+b; }"); dynamic calc = new_evaluator.LoadFile(script); int result = calc.Sum(1, 2); Assert.Equal(3, result); } [Fact] public void LoadFile_Params() { var script = GetTempScript(nameof(LoadFile), @"using System; public class Calc { public string Name; public Calc(string name) { Name = name; } public int Sum(int a, int b) => a+b; }"); dynamic calc = new_evaluator.LoadFile(script, "test"); int result = calc.Sum(1, 2); Assert.Equal(3, result); Assert.Equal("test", calc.Name); } [Fact] public void LoadFile_T() { var script = GetTempScript(nameof(LoadFile), @"using System; public class Calc : Testing.ICalc { public int Sum(int a, int b) => a+b; }"); ICalc calc = new_evaluator.ReferenceDomainAssemblies() .LoadFile<ICalc>(script); int result = calc.Sum(1, 2); Assert.Equal(3, result); } [Fact] public void CompileCode_with_toplevel_class() { } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic{ /// <summary> /// Strongly-typed collection for the ConVistaAgenda class. /// </summary> [Serializable] public partial class ConVistaAgendaCollection : ReadOnlyList<ConVistaAgenda, ConVistaAgendaCollection> { public ConVistaAgendaCollection() {} } /// <summary> /// This is Read-only wrapper class for the CON_VistaAgendas view. /// </summary> [Serializable] public partial class ConVistaAgenda : ReadOnlyRecord<ConVistaAgenda>, IReadOnlyRecord { #region Default Settings protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema Accessor public static TableSchema.Table Schema { get { if (BaseSchema == null) { SetSQLProps(); } return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("CON_VistaAgendas", TableType.View, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdAgenda = new TableSchema.TableColumn(schema); colvarIdAgenda.ColumnName = "idAgenda"; colvarIdAgenda.DataType = DbType.Int32; colvarIdAgenda.MaxLength = 0; colvarIdAgenda.AutoIncrement = false; colvarIdAgenda.IsNullable = false; colvarIdAgenda.IsPrimaryKey = false; colvarIdAgenda.IsForeignKey = false; colvarIdAgenda.IsReadOnly = false; schema.Columns.Add(colvarIdAgenda); TableSchema.TableColumn colvarIdAgendaEstado = new TableSchema.TableColumn(schema); colvarIdAgendaEstado.ColumnName = "idAgendaEstado"; colvarIdAgendaEstado.DataType = DbType.Int32; colvarIdAgendaEstado.MaxLength = 0; colvarIdAgendaEstado.AutoIncrement = false; colvarIdAgendaEstado.IsNullable = false; colvarIdAgendaEstado.IsPrimaryKey = false; colvarIdAgendaEstado.IsForeignKey = false; colvarIdAgendaEstado.IsReadOnly = false; schema.Columns.Add(colvarIdAgendaEstado); TableSchema.TableColumn colvarIdConsultorio = new TableSchema.TableColumn(schema); colvarIdConsultorio.ColumnName = "idConsultorio"; colvarIdConsultorio.DataType = DbType.Int32; colvarIdConsultorio.MaxLength = 0; colvarIdConsultorio.AutoIncrement = false; colvarIdConsultorio.IsNullable = false; colvarIdConsultorio.IsPrimaryKey = false; colvarIdConsultorio.IsForeignKey = false; colvarIdConsultorio.IsReadOnly = false; schema.Columns.Add(colvarIdConsultorio); TableSchema.TableColumn colvarFecha = new TableSchema.TableColumn(schema); colvarFecha.ColumnName = "fecha"; colvarFecha.DataType = DbType.DateTime; colvarFecha.MaxLength = 0; colvarFecha.AutoIncrement = false; colvarFecha.IsNullable = false; colvarFecha.IsPrimaryKey = false; colvarFecha.IsForeignKey = false; colvarFecha.IsReadOnly = false; schema.Columns.Add(colvarFecha); TableSchema.TableColumn colvarHoraInicio = new TableSchema.TableColumn(schema); colvarHoraInicio.ColumnName = "HoraInicio"; colvarHoraInicio.DataType = DbType.DateTime; colvarHoraInicio.MaxLength = 0; colvarHoraInicio.AutoIncrement = false; colvarHoraInicio.IsNullable = true; colvarHoraInicio.IsPrimaryKey = false; colvarHoraInicio.IsForeignKey = false; colvarHoraInicio.IsReadOnly = false; schema.Columns.Add(colvarHoraInicio); TableSchema.TableColumn colvarHoraFin = new TableSchema.TableColumn(schema); colvarHoraFin.ColumnName = "HoraFin"; colvarHoraFin.DataType = DbType.DateTime; colvarHoraFin.MaxLength = 0; colvarHoraFin.AutoIncrement = false; colvarHoraFin.IsNullable = true; colvarHoraFin.IsPrimaryKey = false; colvarHoraFin.IsForeignKey = false; colvarHoraFin.IsReadOnly = false; schema.Columns.Add(colvarHoraFin); TableSchema.TableColumn colvarIdEfector = new TableSchema.TableColumn(schema); colvarIdEfector.ColumnName = "idEfector"; colvarIdEfector.DataType = DbType.Int32; colvarIdEfector.MaxLength = 0; colvarIdEfector.AutoIncrement = false; colvarIdEfector.IsNullable = false; colvarIdEfector.IsPrimaryKey = false; colvarIdEfector.IsForeignKey = false; colvarIdEfector.IsReadOnly = false; schema.Columns.Add(colvarIdEfector); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("CON_VistaAgendas",schema); } } #endregion #region Query Accessor public static Query CreateQuery() { return new Query(Schema); } #endregion #region .ctors public ConVistaAgenda() { SetSQLProps(); SetDefaults(); MarkNew(); } public ConVistaAgenda(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) { ForceDefaults(); } MarkNew(); } public ConVistaAgenda(object keyID) { SetSQLProps(); LoadByKey(keyID); } public ConVistaAgenda(string columnName, object columnValue) { SetSQLProps(); LoadByParam(columnName,columnValue); } #endregion #region Props [XmlAttribute("IdAgenda")] [Bindable(true)] public int IdAgenda { get { return GetColumnValue<int>("idAgenda"); } set { SetColumnValue("idAgenda", value); } } [XmlAttribute("IdAgendaEstado")] [Bindable(true)] public int IdAgendaEstado { get { return GetColumnValue<int>("idAgendaEstado"); } set { SetColumnValue("idAgendaEstado", value); } } [XmlAttribute("IdConsultorio")] [Bindable(true)] public int IdConsultorio { get { return GetColumnValue<int>("idConsultorio"); } set { SetColumnValue("idConsultorio", value); } } [XmlAttribute("Fecha")] [Bindable(true)] public DateTime Fecha { get { return GetColumnValue<DateTime>("fecha"); } set { SetColumnValue("fecha", value); } } [XmlAttribute("HoraInicio")] [Bindable(true)] public DateTime? HoraInicio { get { return GetColumnValue<DateTime?>("HoraInicio"); } set { SetColumnValue("HoraInicio", value); } } [XmlAttribute("HoraFin")] [Bindable(true)] public DateTime? HoraFin { get { return GetColumnValue<DateTime?>("HoraFin"); } set { SetColumnValue("HoraFin", value); } } [XmlAttribute("IdEfector")] [Bindable(true)] public int IdEfector { get { return GetColumnValue<int>("idEfector"); } set { SetColumnValue("idEfector", value); } } #endregion #region Columns Struct public struct Columns { public static string IdAgenda = @"idAgenda"; public static string IdAgendaEstado = @"idAgendaEstado"; public static string IdConsultorio = @"idConsultorio"; public static string Fecha = @"fecha"; public static string HoraInicio = @"HoraInicio"; public static string HoraFin = @"HoraFin"; public static string IdEfector = @"idEfector"; } #endregion #region IAbstractRecord Members public new CT GetColumnValue<CT>(string columnName) { return base.GetColumnValue<CT>(columnName); } public object GetColumnValue(string columnName) { return base.GetColumnValue<object>(columnName); } #endregion } }
/* 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 *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.IO; using System.Reflection; using System.Data.Linq; using System.Data.Linq.Mapping; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Xml; using System.Xml.Serialization; using Microsoft.Research.Dryad; namespace Microsoft.Research.Dryad.GraphManager { internal class DryadLogger { static public void LogCritical( string message, [CallerFilePath] string file = "(nofile)", [CallerMemberName] string function = "(nofunction)", [CallerLineNumber] int line = -1) { DrLogging.LogCritical(message, file, function, line); } static public void LogWarning( string message, [CallerFilePath] string file = "(nofile)", [CallerMemberName] string function = "(nofunction)", [CallerLineNumber] int line = -1) { DrLogging.LogWarning(message, file, function, line); } static public void LogInformation( string message, [CallerFilePath] string file = "(nofile)", [CallerMemberName] string function = "(nofunction)", [CallerLineNumber] int line = -1) { DrLogging.LogInformation(message, file, function, line); } } internal class DebugHelper { private static List<DrIReporter> reporters = new List<DrIReporter>(); private static bool brokeInDebugger = false; private static bool loggingInitialized = false; private static object syncRoot = new object(); public static Uri AddDfsJobDirectoryFromArgs(string arg) { string jobId = Microsoft.Research.Peloponnese.Yarn.Utils.ApplicationIdFromEnvironment(); string jobDirectoryBase = Microsoft.Research.Peloponnese.Utils.CmdLineDecode(arg.Substring(arg.IndexOf('=') + 1)); string jobDirectorySpecific = jobDirectoryBase.Replace("_JOBID_", jobId); UriBuilder logLocation = new UriBuilder(jobDirectorySpecific); logLocation.Path = logLocation.Path.TrimEnd('/') + "/calypso.log"; DebugHelper.AddReporter(new DrCalypsoReporter(logLocation.Uri.AbsoluteUri)); return new Uri(jobDirectorySpecific); } public static void UploadToDfs(Uri dfsDirectory, string localPath) { DryadLogger.LogInformation("Uploading " + localPath + " to " + dfsDirectory.AbsoluteUri); try { if (dfsDirectory.Scheme == "hdfs") { using (var hdfs = new Microsoft.Research.Peloponnese.Hdfs.HdfsInstance(dfsDirectory)) { string dfsPath = dfsDirectory.AbsolutePath.TrimEnd('/') + "/" + Path.GetFileName(localPath); DryadLogger.LogInformation("Uploading " + localPath + " to " + dfsPath); hdfs.UploadAll(localPath, dfsPath); } } else if (dfsDirectory.Scheme == "azureblob") { string account, key, container, blob; Microsoft.Research.Peloponnese.Azure.Utils.FromAzureUri(dfsDirectory, out account, out key, out container, out blob); var azure = new Microsoft.Research.Peloponnese.Azure.AzureDfsClient(account, key, container); string dfsPath = blob.TrimEnd('/') + "/" + Path.GetFileName(localPath); Uri dfsUri = Microsoft.Research.Peloponnese.Azure.Utils.ToAzureUri(account, container, dfsPath, null, key); DryadLogger.LogInformation("Uploading " + localPath + " to " + dfsUri.AbsoluteUri); azure.PutDfsFile(dfsUri, localPath); } else if (dfsDirectory.Scheme == "file") { string dstPath = Path.Combine(dfsDirectory.AbsolutePath, Path.GetFileName(localPath)); File.Copy(localPath, dstPath); } } catch (Exception e) { DryadLogger.LogWarning("Failed to upload query plan: " + e.ToString()); } } public static void UploadToDfs(Uri dfsDirectory, string dfsName, string payload) { byte[] payloadBytes = System.Text.Encoding.UTF8.GetBytes(payload); DryadLogger.LogInformation("Uploading payload to " + dfsName + " at " + dfsDirectory.AbsoluteUri); try { if (dfsDirectory.Scheme == "hdfs") { using (var hdfs = new Microsoft.Research.Peloponnese.Hdfs.HdfsInstance(dfsDirectory)) { string dfsPath = dfsDirectory.AbsolutePath + dfsName; hdfs.WriteAll(dfsPath, payloadBytes); } } else if (dfsDirectory.Scheme == "azureblob") { string account, key, container, blob; Microsoft.Research.Peloponnese.Azure.Utils.FromAzureUri(dfsDirectory, out account, out key, out container, out blob); var azure = new Microsoft.Research.Peloponnese.Azure.AzureDfsClient(account, key, container); string dfsPath = blob + dfsName; Uri dfsUri = Microsoft.Research.Peloponnese.Azure.Utils.ToAzureUri(account, container, dfsPath, null, key); azure.PutDfsFile(dfsUri, payloadBytes); } else if (dfsDirectory.Scheme == "file") { string dstPath = Path.Combine(dfsDirectory.AbsolutePath, dfsName); File.WriteAllBytes(dstPath, payloadBytes); } } catch (Exception e) { DryadLogger.LogWarning("Failed to upload final output: " + e.ToString()); } } public static void AddReporter(DrIReporter reporter) { reporters.Add(reporter); } public static List<DrIReporter> Reporters() { return reporters; } public static void WaitForDebugger() { if (!brokeInDebugger) { Console.Out.WriteLine("Waiting for debugger..."); while (!Debugger.IsAttached) { Thread.Sleep(1000); } Debugger.Break(); brokeInDebugger = true; } } public static void DebugBreakOnFileExisting(string breakFileName) { if (File.Exists(breakFileName)) { WaitForDebugger(); } } public static void InitializeLogging(DateTime startTime) { if (!loggingInitialized) { lock (syncRoot) { if (!loggingInitialized) { // Initialize Graph Manager's internal logging string logDir = Environment.GetEnvironmentVariable("LOG_DIRS"); if (logDir == null) { DrLogging.Initialize("graphmanager", false); } else { // deal with comma-separated list logDir = logDir.Split(',').First().Trim(); DrLogging.Initialize(Path.Combine(logDir, "graphmanager"), false); } string logLevel = Environment.GetEnvironmentVariable("DRYAD_LOGGING_LEVEL"); if (logLevel == null) { DrLogging.SetLoggingLevel(DrLogTypeManaged.Debug); } else { if (logLevel == "OFF") { DrLogging.SetLoggingLevel(DrLogTypeManaged.Off); } else if (logLevel == "CRITICAL") { DrLogging.SetLoggingLevel(DrLogTypeManaged.Assert); } else if (logLevel == "ERROR") { DrLogging.SetLoggingLevel(DrLogTypeManaged.Error); } else if (logLevel == "WARN") { DrLogging.SetLoggingLevel(DrLogTypeManaged.Warning); } else if (logLevel == "INFO") { DrLogging.SetLoggingLevel(DrLogTypeManaged.Info); } else { DrLogging.SetLoggingLevel(DrLogTypeManaged.Debug); } } // Report start time to Artemis - must come after // DrLogging is initialized so stdout is redirected foreach (DrIReporter reporter in reporters) { reporter.ReportStart((ulong)startTime.ToFileTime()); } loggingInitialized = true; } } } } public static void StopLogging(int retCode, string errorString, DateTime startTime, Uri dfsDirectory) { if (loggingInitialized) { lock (syncRoot) { if (loggingInitialized) { // Report stop time to Artemis foreach (DrIReporter reporter in reporters) { reporter.ReportStop(unchecked((uint)retCode), errorString, (ulong)startTime.ToFileTime()); } if (dfsDirectory != null && errorString != null) { UploadToDfs(dfsDirectory, "error.txt", errorString); } // Shutdown Graph Manager's internal logging DrLogging.ShutDown(unchecked((uint)retCode)); loggingInitialized = false; } } } } } public class LinqToDryadJM { internal void FinalizeExecution(Query query, DrGraph graph) { SortedDictionary<int, Vertex> queryPlan = query.queryPlan; foreach (KeyValuePair<int, Vertex> kvp in query.queryPlan) { /* used to do CSStream expiration time stuff here */ } } internal bool ConsumeSingleArgument(string arg, ref string[] args) { List<string> temp = new List<string>(); bool found = false; for (int index=0; index<args.Length; index++) { if (!found && (arg == args[index])) { found = true; } else { temp.Add(args[index]); } } args = temp.ToArray(); return found; } // // Main Dryad LINQ execution stuff // public int ExecLinqToDryad(Uri dfsDirectory, string[] args, out string errorString) { // // must be at least two arguments (program name and query XML file name) // if (args.Length < 2) { errorString = "Must provide at least query XML file name and VertexHost executable."; DryadLogger.LogCritical(errorString); return -1; } // // break if --break is included in arguments (and eliminate it, as it is not known downstream) // if (ConsumeSingleArgument("--break", ref args)) { DebugHelper.WaitForDebugger(); } // this is where we ensure the right type of scheduler is registered Microsoft.Research.Dryad.LocalScheduler.Registration.Ensure(); // // parse the XML input, producing a DryadLINQ Query // Query query = new Query(); QueryPlanParser parser = new QueryPlanParser(); if (!parser.ParseQueryXml(args[1], query)) { errorString = "Invalid query plan"; DryadLogger.LogCritical(errorString); return -1; } // // upload the query plan to the job DFS directory for the benefit of debug tools // if (dfsDirectory != null) { DebugHelper.UploadToDfs(dfsDirectory, args[1]); } // // build internal app arguments // List<string> internalArgs = new List<string>(); // // add the XmlExecHost args to the internal app arguments // foreach (string xmlExecHostArg in query.xmlExecHostArgs) { if (xmlExecHostArg == "--break") { DebugHelper.WaitForDebugger(); } else { internalArgs.Add(xmlExecHostArg); } } // // combine internal arguments with any additional arguments received on the command line // don't include argv[0] and argv[1] (program name and query XML file name) // int internalArgc = (int)internalArgs.Count; int externalArgc = args.Length - 2; // don't include argv[0] and argv[1] int combinedArgc = internalArgc + externalArgc; string[] combinedArgv = new string[combinedArgc]; string msg = ""; // internal arguments first for (int i=0; i<internalArgc; i++) { combinedArgv[i] = internalArgs[i]; msg += String.Format("{0} ", combinedArgv[i]); } // then external arguments for (int i = 0; i<externalArgc; i++) { combinedArgv[i+internalArgc] = args[i+2]; // don't include argv[0] and argv[1] msg += String.Format("{0} ", combinedArgv[i+internalArgc]); } DryadLogger.LogInformation(String.Format("Arguments: {0}", msg)); string jobClass = "DryadLINQ"; string exeName = args[0]; // create app and run it // DrGraphParameters p = DrDefaultParameters.Make(exeName, jobClass, query.enableSpeculativeDuplication); foreach (DrIReporter reporter in DebugHelper.Reporters()) { p.m_reporters.Add(reporter); } p.m_intermediateCompressionMode = query.intermediateDataCompression; DrGraphExecutor graphExecutor = new DrGraphExecutor(); DrGraph graph = graphExecutor.Initialize(p); if (graph == null) { errorString = "Failed to initialize Graph Executor"; DryadLogger.LogCritical(errorString); return -1; } DryadLINQApp app = new DryadLINQApp(graph); // Initialize with arguments app.SetXmlFileName(args[1]); if (!app.ParseCommandLineFlags(combinedArgv)) { errorString = "Bad command-line options"; DryadLogger.LogCritical(errorString); return -1; } // Build graph from query plan GraphBuilder builder = new GraphBuilder(); builder.BuildGraphFromQuery(app, query); // Run the app DryadLogger.LogInformation("Running the app"); graphExecutor.Run(); DrError exitStatus = graphExecutor.Join(); DryadLogger.LogInformation("Finished running the app"); if (exitStatus == null || exitStatus.m_code == 0) { FinalizeExecution(query, graph); DryadLogger.LogInformation("Application completed successfully."); errorString = null; return 0; } else { DryadLogger.LogCritical(String.Format("Application failed with error code 0x{0:X8}.\n", exitStatus.m_code)); errorString = exitStatus.ToFullTextNative(); return exitStatus.m_code; } } public int Run(Uri dfsDirectory, string[] args, out string errorString) { return ExecLinqToDryad(dfsDirectory, args, out errorString); } } }
/* | Version 10.1.84 | Copyright 2013 Esri | | Licensed under the Apache License, Version 2.0 (the "License"); | you may not use this file except in compliance with the License. | You may obtain a copy of the License at | | http://www.apache.org/licenses/LICENSE-2.0 | | Unless required by applicable law or agreed to in writing, software | distributed under the License is distributed on an "AS IS" BASIS, | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | See the License for the specific language governing permissions and | limitations under the License. */ using System; using System.Diagnostics; using System.Configuration; using System.Collections.Specialized; using System.Collections; using System.IO; using System.Xml; namespace ESRI.ArcLogistics.App { /// <summary> /// Custom settings provider. /// </summary> internal class AlSettingsProvider : SettingsProvider { #region SettingsProvider overrides /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public override string ApplicationName { get { return "ArcLogistics"; } set { } } public override void Initialize(string name, NameValueCollection col) { base.Initialize(this.ApplicationName, col); } public override void SetPropertyValues(SettingsContext context, SettingsPropertyValueCollection propvals) { lock (_locker) { // iterate through the settings to be stored foreach (SettingsPropertyValue propval in propvals) { if (propval.IsDirty) { // set only user-scoped settings if (_IsUserScoped(propval.Property)) _SetValue(propval); } } _Save(); } } public override SettingsPropertyValueCollection GetPropertyValues(SettingsContext context, SettingsPropertyCollection props) { lock (_locker) { // create new collection of values SettingsPropertyValueCollection values = new SettingsPropertyValueCollection(); // iterate through the settings to be retrieved foreach (SettingsProperty prop in props) { SettingsPropertyValue value = new SettingsPropertyValue(prop); value.SerializedValue = _GetValue(prop); value.IsDirty = false; values.Add(value); } return values; } } #endregion SettingsProvider overrides #region private methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private void _SetValue(SettingsPropertyValue propval) { try { _store.SetValue(propval); } catch (Exception e) { // MSDN: If the provider cannot fulfill the request, it should ignore it silently. Logger.Error(e); } } private object _GetValue(SettingsProperty prop) { object value = null; try { value = _store.GetValue(prop); } catch (Exception e) { // MSDN: If the provider cannot fulfill the request, it should ignore it silently. Logger.Error(e); } return value; } private void _Save() { try { _store.Save(); } catch (Exception e) { // MSDN: If the provider cannot fulfill the request, it should ignore it silently. Logger.Error(e); } } private static bool _IsUserScoped(SettingsProperty prop) { foreach (DictionaryEntry entry in prop.Attributes) { Attribute attr = (Attribute)entry.Value; if (attr.GetType() == typeof(UserScopedSettingAttribute)) return true; } return false; } #endregion private methods #region private fields /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private SettingsStore _store = new SettingsStore(); private object _locker = new object(); // mt #endregion private fields #region private classes /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// /// <summary> /// Settings storage. /// </summary> internal class SettingsStore { #region constants /////////////////////////////////////////////////////////////////////////////////////////// private const string CONF_FILE_NAME = "user.config"; private const string NODE_ROOT = "configuration"; private const string NODE_USER_SETTINGS = "userSettings"; private const string NODE_SETTINGS = "ESRI.ArcLogistics.App.Properties.Settings"; private const string NODE_SETTING = "setting"; private const string NODE_VALUE = "value"; private const string ATTR_NAME = "name"; private const string ATTR_SERIALIZE = "serializeAs"; private static readonly string XPATH_SETTINGS = NODE_ROOT + '/' + NODE_USER_SETTINGS + '/' + NODE_SETTINGS; private static readonly string XPATH_SETTING_BY_NAME = "descendant::" + NODE_ROOT + '/' + NODE_USER_SETTINGS + '/' + NODE_SETTINGS + '/' + NODE_SETTING + "[@name='{0}']"; #endregion constants #region Constructor /// <summary> /// Constructor. /// </summary> /// <exception cref="T:ESRI.ArcLogistics.SettingsException"> Settings file is invalid. /// In property "Source" there is path to invalid settings file.</exception> public SettingsStore() { _Init(); } #endregion #region Public Static Properties /// <summary> /// Path to user.config file. /// </summary> public static string PathToConfig { get { return Path.Combine(DataFolder.Path, CONF_FILE_NAME); } } #endregion #region public methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// public object GetValue(SettingsProperty prop) { Debug.Assert(prop != null); object value = null; string xmlValue = _FindValue(prop.Name); if (xmlValue != null) { // get stored value value = _GetSerializedValue(prop, xmlValue); } else { // get default value value = prop.DefaultValue; } return value; } public void SetValue(SettingsPropertyValue propval) { Debug.Assert(propval != null); bool addSetting = false; XmlNode settingNode = _FindSettingNode(propval.Name); if (settingNode == null) { settingNode = _CreateSettingNode(propval); addSetting = true; } XmlNode valueNode = settingNode.SelectSingleNode( NODE_VALUE); if (valueNode == null) { valueNode = _Document.CreateNode(XmlNodeType.Element, NODE_VALUE, ""); settingNode.AppendChild(valueNode); } valueNode.InnerXml = _Serialize(propval); _FixValueNode(valueNode); if (addSetting) _AddSettingNode(settingNode); _isDirty = true; } public void Save() { if (_isDirty) { _Document.Save(_docPath); _isDirty = false; } } #endregion public methods #region private methods /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private XmlDocument _Document { get { if (_doc == null) _Init(); return _doc; } } private XmlNode _FindSettingNode(string settingName) { return _Document.SelectSingleNode( String.Format(XPATH_SETTING_BY_NAME, settingName)); } private XmlNode _CreateSettingNode(SettingsPropertyValue propval) { XmlNode node = _Document.CreateNode(XmlNodeType.Element, NODE_SETTING, ""); XmlAttribute attrName = _Document.CreateAttribute(ATTR_NAME); attrName.Value = propval.Name; node.Attributes.Append(attrName); XmlAttribute attrSerialize = _Document.CreateAttribute(ATTR_SERIALIZE); attrSerialize.Value = propval.Property.SerializeAs.ToString(); node.Attributes.Append(attrSerialize); return node; } private void _AddSettingNode(XmlNode node) { XmlNode settingsNode = _Document.SelectSingleNode(XPATH_SETTINGS); if (settingsNode == null) throw new ConfigurationErrorsException(); // wrong config file scheme settingsNode.AppendChild(node); } private string _FindValue(string settingName) { string value = null; XmlNode settingsNode = _FindSettingNode(settingName); if (settingsNode != null) { XmlNode valueNode = settingsNode.SelectSingleNode(NODE_VALUE); if (valueNode != null) value = valueNode.InnerXml; } return value; } /// <summary> /// Initialize user config. /// </summary> /// <exception cref="T:ESRI.ArcLogistics.SettingsException"> Settings file is invalid. /// In property "Source" there is path to invalid settings file.</exception> private void _Init() { _doc = _LoadDoc(PathToConfig); _docPath = PathToConfig; } private string _Serialize(SettingsPropertyValue propval) { Debug.Assert(propval != null); string value = propval.SerializedValue as string; if (value == null) value = String.Empty; if (propval.Property.SerializeAs == SettingsSerializeAs.String) { value = _escaper.Escape(value); } else if (propval.Property.SerializeAs == SettingsSerializeAs.Binary) { byte[] buf = propval.SerializedValue as byte[]; if (buf != null) value = Convert.ToBase64String(buf); } return value; } private string _GetSerializedValue(SettingsProperty prop, string xmlValue) { Debug.Assert(prop != null); Debug.Assert(xmlValue != null); string value = xmlValue; if (prop.SerializeAs == SettingsSerializeAs.String) value = _escaper.Unescape(xmlValue); return value; } /// <summary> /// Load user settings from file. /// </summary> /// <param name="configPath">Path to settings file.</param> /// <exception cref="T:ESRI.ArcLogistics.SettingsException"> Settings file is invalid. /// In property "Source" there is path to invalid settings file.</exception> private static XmlDocument _LoadDoc(string path) { XmlDocument doc = new XmlDocument(); if (File.Exists(path)) { // Try to load file. try { doc.Load(path); } catch (XmlException ex) { // If XML corrupted - wrap exception and save path to file. SettingsException settingsException = new SettingsException(ex.Message, ex); settingsException.Source = path; throw settingsException; } } else { _InitDocStructure(doc); doc.Save(path); } return doc; } private static void _InitDocStructure(XmlDocument doc) { XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", ""); doc.AppendChild(dec); XmlNode rootNode = doc.CreateNode(XmlNodeType.Element, NODE_ROOT, ""); doc.AppendChild(rootNode); XmlNode setTypeNode = doc.CreateNode(XmlNodeType.Element, NODE_USER_SETTINGS, ""); rootNode.AppendChild(setTypeNode); XmlNode settingsNode = doc.CreateNode(XmlNodeType.Element, NODE_SETTINGS, ""); setTypeNode.AppendChild(settingsNode); } private static void _FixValueNode(XmlNode valueNode) { // remove declaration node if exists XmlNode nodeToRemove = null; foreach (XmlNode child in valueNode.ChildNodes) { if (child.NodeType == XmlNodeType.XmlDeclaration) { nodeToRemove = child; break; } } if (nodeToRemove != null) valueNode.RemoveChild(nodeToRemove); } #endregion private methods #region private fields /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// private XmlDocument _doc; private string _docPath; private XmlEscaper _escaper = new XmlEscaper(); private bool _isDirty = false; #endregion private fields /// <summary> /// XmlEscaper class. /// </summary> private class XmlEscaper { public XmlEscaper() { doc = new XmlDocument(); temp = doc.CreateElement("temp"); } public string Escape(string xmlString) { if (String.IsNullOrEmpty(xmlString)) return xmlString; temp.InnerText = xmlString; return temp.InnerXml; } public string Unescape(string escapedString) { if (String.IsNullOrEmpty(escapedString)) return escapedString; temp.InnerXml = escapedString; return temp.InnerText; } private XmlDocument doc; private XmlElement temp; } } #endregion private classes } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace Sample.WebApi.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
// Original source: http://servicestack.googlecode.com/svn/trunk/Common/ServiceStack.Redis/ServiceStack.Redis/Support/OrderedDictionary.cs using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Threading; namespace BitCoinSharp.Collections { /// <summary> /// Represents a generic collection of key/value pairs that are ordered independently of the key and value. /// </summary> /// <typeparam name="TKey">The type of the keys in the dictionary</typeparam> /// <typeparam name="TValue">The type of the values in the dictionary</typeparam> internal class OrderedDictionary<TKey, TValue> : IOrderedDictionary, IDictionary<TKey, TValue> { private const int _defaultInitialCapacity = 0; private static readonly string _keyTypeName = typeof (TKey).FullName; private static readonly string _valueTypeName = typeof (TValue).FullName; private static readonly bool _valueTypeIsReferenceType = !typeof (ValueType).IsAssignableFrom(typeof (TValue)); private Dictionary<TKey, TValue> _dictionary; private List<KeyValuePair<TKey, TValue>> _list; private readonly IEqualityComparer<TKey> _comparer; private object _syncRoot; private readonly int _initialCapacity; /// <summary> /// Initializes a new instance of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> class. /// </summary> public OrderedDictionary() : this(_defaultInitialCapacity, null) { } /// <summary> /// Initializes a new instance of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> class using the specified initial capacity. /// </summary> /// <param name="capacity">The initial number of elements that the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> can contain.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="capacity"/> is less than 0</exception> public OrderedDictionary(int capacity) : this(capacity, null) { } /// <summary> /// Initializes a new instance of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> class using the specified comparer. /// </summary> /// <param name="comparer">The <see cref="IEqualityComparer{TKey}">IEqualityComparer&lt;TKey&gt;</see> to use when comparing keys, or <null/> to use the default <see cref="EqualityComparer{TKey}">EqualityComparer&lt;TKey&gt;</see> for the type of the key.</param> public OrderedDictionary(IEqualityComparer<TKey> comparer) : this(_defaultInitialCapacity, comparer) { } /// <summary> /// Initializes a new instance of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> class using the specified initial capacity and comparer. /// </summary> /// <param name="capacity">The initial number of elements that the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection can contain.</param> /// <param name="comparer">The <see cref="IEqualityComparer{TKey}">IEqualityComparer&lt;TKey&gt;</see> to use when comparing keys, or <null/> to use the default <see cref="EqualityComparer{TKey}">EqualityComparer&lt;TKey&gt;</see> for the type of the key.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="capacity"/> is less than 0</exception> public OrderedDictionary(int capacity, IEqualityComparer<TKey> comparer) { if (0 > capacity) throw new ArgumentOutOfRangeException("capacity", "'capacity' must be non-negative"); _initialCapacity = capacity; _comparer = comparer; } /// <summary> /// Converts the object passed as a key to the key type of the dictionary /// </summary> /// <param name="keyObject">The key object to check</param> /// <returns>The key object, cast as the key type of the dictionary</returns> /// <exception cref="ArgumentNullException"><paramref name="keyObject"/> is <null/>.</exception> /// <exception cref="ArgumentException">The key type of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> is not in the inheritance hierarchy of <paramref name="keyObject"/>.</exception> private static TKey ConvertToKeyType(object keyObject) { if (keyObject == null) { throw new ArgumentNullException("keyObject"); } if (!(keyObject is TKey)) { throw new ArgumentException("'key' must be of type " + _keyTypeName, "keyObject"); } return (TKey) keyObject; } /// <summary> /// Converts the object passed as a value to the value type of the dictionary /// </summary> /// <param name="value">The object to convert to the value type of the dictionary</param> /// <returns>The value object, converted to the value type of the dictionary</returns> /// <exception cref="ArgumentNullException"><paramref name="value"/> is <null/>, and the value type of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> is a value type.</exception> /// <exception cref="ArgumentException">The value type of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> is not in the inheritance hierarchy of <paramref name="value"/>.</exception> private static TValue ConvertToValueType(object value) { if (value == null) { if (!_valueTypeIsReferenceType) throw new ArgumentNullException("value"); return default(TValue); } if (!(value is TValue)) throw new ArgumentException("'value' must be of type " + _valueTypeName, "value"); return (TValue) value; } /// <summary> /// Gets the dictionary object that stores the keys and values /// </summary> /// <value>The dictionary object that stores the keys and values for the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see></value> /// <remarks>Accessing this property will create the dictionary object if necessary</remarks> private Dictionary<TKey, TValue> Dictionary { get { return _dictionary ?? (_dictionary = new Dictionary<TKey, TValue>(_initialCapacity, _comparer)); } } /// <summary> /// Gets the list object that stores the key/value pairs. /// </summary> /// <value>The list object that stores the key/value pairs for the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see></value> /// <remarks>Accessing this property will create the list object if necessary.</remarks> private List<KeyValuePair<TKey, TValue>> List { get { return _list ?? (_list = new List<KeyValuePair<TKey, TValue>>(_initialCapacity)); } } IDictionaryEnumerator IOrderedDictionary.GetEnumerator() { return Dictionary.GetEnumerator(); } IDictionaryEnumerator IDictionary.GetEnumerator() { return Dictionary.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return List.GetEnumerator(); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return List.GetEnumerator(); } /// <summary> /// Inserts a new entry into the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection with the specified key and value at the specified index. /// </summary> /// <param name="index">The zero-based index at which the element should be inserted.</param> /// <param name="key">The key of the entry to add.</param> /// <param name="value">The value of the entry to add. The value can be <null/> if the type of the values in the dictionary is a reference type.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than 0.<br/> /// -or-<br/> /// <paramref name="index"/> is greater than <see cref="Count"/>.</exception> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/>.</exception> /// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>.</exception> public void Insert(int index, TKey key, TValue value) { if (index > Count || index < 0) throw new ArgumentOutOfRangeException("index"); Dictionary.Add(key, value); List.Insert(index, new KeyValuePair<TKey, TValue>(key, value)); } /// <summary> /// Inserts a new entry into the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection with the specified key and value at the specified index. /// </summary> /// <param name="index">The zero-based index at which the element should be inserted.</param> /// <param name="key">The key of the entry to add.</param> /// <param name="value">The value of the entry to add. The value can be <null/> if the type of the values in the dictionary is a reference type.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than 0.<br/> /// -or-<br/> /// <paramref name="index"/> is greater than <see cref="Count"/>.</exception> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/>.<br/> /// -or-<br/> /// <paramref name="value"/> is <null/>, and the value type of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> is a value type.</exception> /// <exception cref="ArgumentException">The key type of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> is not in the inheritance hierarchy of <paramref name="key"/>.<br/> /// -or-<br/> /// The value type of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> is not in the inheritance hierarchy of <paramref name="value"/>.<br/> /// -or-<br/> /// An element with the same key already exists in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>.</exception> void IOrderedDictionary.Insert(int index, object key, object value) { Insert(index, ConvertToKeyType(key), ConvertToValueType(value)); } /// <summary> /// Removes the entry at the specified index from the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection. /// </summary> /// <param name="index">The zero-based index of the entry to remove.</param> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than 0.<br/> /// -or-<br/> /// index is equal to or greater than <see cref="Count"/>.</exception> public void RemoveAt(int index) { if (index >= Count || index < 0) throw new ArgumentOutOfRangeException("index", "'index' must be non-negative and less than the size of the collection"); var key = List[index].Key; List.RemoveAt(index); Dictionary.Remove(key); } /// <summary> /// Gets or sets the value at the specified index. /// </summary> /// <param name="index">The zero-based index of the value to get or set.</param> /// <value>The value of the item at the specified index.</value> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than 0.<br/> /// -or-<br/> /// index is equal to or greater than <see cref="Count"/>.</exception> public TValue this[int index] { get { return List[index].Value; } set { if (index >= Count || index < 0) throw new ArgumentOutOfRangeException("index", "'index' must be non-negative and less than the size of the collection"); var key = List[index].Key; List[index] = new KeyValuePair<TKey, TValue>(key, value); Dictionary[key] = value; } } /// <summary> /// Gets or sets the value at the specified index. /// </summary> /// <param name="index">The zero-based index of the value to get or set.</param> /// <value>The value of the item at the specified index.</value> /// <exception cref="ArgumentOutOfRangeException"><paramref name="index"/> is less than 0.<br/> /// -or-<br/> /// index is equal to or greater than <see cref="Count"/>.</exception> /// <exception cref="ArgumentNullException"><paramref name="value"/> is a null reference, and the value type of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> is a value type.</exception> /// <exception cref="ArgumentException">The value type of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> is not in the inheritance hierarchy of <paramref name="value"/>.</exception> object IOrderedDictionary.this[int index] { get { return this[index]; } set { this[index] = ConvertToValueType(value); } } /// <summary> /// Adds an entry with the specified key and value into the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection with the lowest available index. /// </summary> /// <param name="key">The key of the entry to add.</param> /// <param name="value">The value of the entry to add. This value can be <null/>.</param> /// <remarks>A key cannot be <null/>, but a value can be. /// <para>You can also use the indexer property to add new elements by setting the value of a key that does not exist in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection; however, if the specified key already exists in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>, setting the indexer property overwrites the old value. In contrast, the <see cref="Add"/> method does not modify existing elements.</para></remarks> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/></exception> /// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see></exception> void IDictionary<TKey, TValue>.Add(TKey key, TValue value) { Add(key, value); } /// <summary> /// Adds an entry with the specified key and value into the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection with the lowest available index. /// </summary> /// <param name="key">The key of the entry to add.</param> /// <param name="value">The value of the entry to add. This value can be <null/>.</param> /// <returns>The index of the newly added entry</returns> /// <remarks>A key cannot be <null/>, but a value can be. /// <para>You can also use the indexer property to add new elements by setting the value of a key that does not exist in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection; however, if the specified key already exists in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>, setting the indexer property overwrites the old value. In contrast, the <see cref="Add"/> method does not modify existing elements.</para></remarks> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/></exception> /// <exception cref="ArgumentException">An element with the same key already exists in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see></exception> public int Add(TKey key, TValue value) { Dictionary.Add(key, value); List.Add(new KeyValuePair<TKey, TValue>(key, value)); return Count - 1; } /// <summary> /// Adds an entry with the specified key and value into the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection with the lowest available index. /// </summary> /// <param name="key">The key of the entry to add.</param> /// <param name="value">The value of the entry to add. This value can be <null/>.</param> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/>.<br/> /// -or-<br/> /// <paramref name="value"/> is <null/>, and the value type of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> is a value type.</exception> /// <exception cref="ArgumentException">The key type of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> is not in the inheritance hierarchy of <paramref name="key"/>.<br/> /// -or-<br/> /// The value type of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> is not in the inheritance hierarchy of <paramref name="value"/>.</exception> void IDictionary.Add(object key, object value) { Add(ConvertToKeyType(key), ConvertToValueType(value)); } /// <summary> /// Removes all elements from the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection. /// </summary> /// <remarks>The capacity is not changed as a result of calling this method.</remarks> public void Clear() { Dictionary.Clear(); List.Clear(); } /// <summary> /// Determines whether the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection contains a specific key. /// </summary> /// <param name="key">The key to locate in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection.</param> /// <returns><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection contains an element with the specified key; otherwise, <see langword="false"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/></exception> public bool ContainsKey(TKey key) { return Dictionary.ContainsKey(key); } /// <summary> /// Determines whether the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection contains a specific key. /// </summary> /// <param name="key">The key to locate in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection.</param> /// <returns><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection contains an element with the specified key; otherwise, <see langword="false"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="key"/> is <null/></exception> /// <exception cref="ArgumentException">The key type of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> is not in the inheritance hierarchy of <paramref name="key"/>.</exception> bool IDictionary.Contains(object key) { return ContainsKey(ConvertToKeyType(key)); } /// <summary> /// Gets a value indicating whether the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> has a fixed size. /// </summary> /// <value><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> has a fixed size; otherwise, <see langword="false"/>. The default is <see langword="false"/>.</value> bool IDictionary.IsFixedSize { get { return false; } } /// <summary> /// Gets a value indicating whether the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection is read-only. /// </summary> /// <value><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> is read-only; otherwise, <see langword="false"/>. The default is <see langword="false"/>.</value> /// <remarks> /// A collection that is read-only does not allow the addition, removal, or modification of elements after the collection is created. /// <para>A collection that is read-only is simply a collection with a wrapper that prevents modification of the collection; therefore, if changes are made to the underlying collection, the read-only collection reflects those changes.</para> /// </remarks> public bool IsReadOnly { get { return false; } } /// <summary> /// Gets an <see cref="ICollection"/> object containing the keys in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>. /// </summary> /// <value>An <see cref="ICollection"/> object containing the keys in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>.</value> /// <remarks>The returned <see cref="ICollection"/> object is not a static copy; instead, the collection refers back to the keys in the original <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>. Therefore, changes to the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> continue to be reflected in the key collection.</remarks> ICollection IDictionary.Keys { get { return (ICollection) Keys; } } /// <summary> /// Returns the zero-based index of the specified key in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> /// </summary> /// <param name="key">The key to locate in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see></param> /// <returns>The zero-based index of <paramref name="key"/>, if <paramref name="key"/> is found in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>; otherwise, -1</returns> /// <remarks>This method performs a linear search; therefore it has a cost of O(n) at worst.</remarks> public int IndexOfKey(TKey key) { if (Equals(key, default (TKey))) throw new ArgumentNullException("key"); for (var index = 0; index < List.Count; index++) { var entry = List[index]; var next = entry.Key; if (null != _comparer) { if (_comparer.Equals(next, key)) { return index; } } else if (next.Equals(key)) { return index; } } return -1; } /// <summary> /// Removes the entry with the specified key from the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection. /// </summary> /// <param name="key">The key of the entry to remove</param> /// <returns><see langword="true"/> if the key was found and the corresponding element was removed; otherwise, <see langword="false"/></returns> public bool Remove(TKey key) { if (Equals(key, default(TKey))) throw new ArgumentNullException("key"); var index = IndexOfKey(key); if (index >= 0) { if (Dictionary.Remove(key)) { List.RemoveAt(index); return true; } } return false; } /// <summary> /// Removes the entry with the specified key from the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection. /// </summary> /// <param name="key">The key of the entry to remove</param> void IDictionary.Remove(object key) { Remove(ConvertToKeyType(key)); } /// <summary> /// Gets an <see cref="ICollection"/> object containing the values in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection. /// </summary> /// <value>An <see cref="ICollection"/> object containing the values in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection.</value> /// <remarks>The returned <see cref="ICollection"/> object is not a static copy; instead, the <see cref="ICollection"/> refers back to the values in the original <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection. Therefore, changes to the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> continue to be reflected in the <see cref="ICollection"/>.</remarks> ICollection IDictionary.Values { get { return (ICollection) Values; } } /// <summary> /// Gets or sets the value with the specified key. /// </summary> /// <param name="key">The key of the value to get or set.</param> /// <value>The value associated with the specified key. If the specified key is not found, attempting to get it returns <null/>, and attempting to set it creates a new element using the specified key.</value> public TValue this[TKey key] { get { return Dictionary[key]; } set { if (Dictionary.ContainsKey(key)) { Dictionary[key] = value; List[IndexOfKey(key)] = new KeyValuePair<TKey, TValue>(key, value); } else { Add(key, value); } } } /// <summary> /// Gets or sets the value with the specified key. /// </summary> /// <param name="key">The key of the value to get or set.</param> /// <value>The value associated with the specified key. If the specified key is not found, attempting to get it returns <null/>, and attempting to set it creates a new element using the specified key.</value> object IDictionary.this[object key] { get { return this[ConvertToKeyType(key)]; } set { this[ConvertToKeyType(key)] = ConvertToValueType(value); } } /// <summary> /// Copies the elements of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> elements to a one-dimensional Array object at the specified index. /// </summary> /// <param name="array">The one-dimensional <see cref="Array"/> object that is the destination of the <see cref="KeyValuePair{TKey,TValue}"/> objects copied from the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>. The <see cref="Array"/> must have zero-based indexing.</param> /// <param name="index">The zero-based index in <paramref name="array"/> at which copying begins.</param> /// <remarks>The <see cref="ICollection.CopyTo(Array,int)"/> method preserves the order of the elements in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see></remarks> void ICollection.CopyTo(Array array, int index) { ((ICollection) List).CopyTo(array, index); } /// <summary> /// Gets the number of key/values pairs contained in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection. /// </summary> /// <value>The number of key/value pairs contained in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> collection.</value> public int Count { get { return List.Count; } } /// <summary> /// Gets a value indicating whether access to the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> object is synchronized (thread-safe). /// </summary> /// <value>This method always returns false.</value> bool ICollection.IsSynchronized { get { return false; } } /// <summary> /// Gets an object that can be used to synchronize access to the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> object. /// </summary> /// <value>An object that can be used to synchronize access to the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> object.</value> object ICollection.SyncRoot { get { if (_syncRoot == null) { Interlocked.CompareExchange(ref _syncRoot, new object(), null); } return _syncRoot; } } /// <summary> /// Gets an <see cref="System.Collections.Generic.ICollection{TKey}">ICollection&lt;TKey&gt;</see> object containing the keys in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>. /// </summary> /// <value>An <see cref="System.Collections.Generic.ICollection{TKey}">ICollection&lt;TKey&gt;</see> object containing the keys in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>.</value> /// <remarks>The returned <see cref="System.Collections.Generic.ICollection{TKey}">ICollection&lt;TKey&gt;</see> object is not a static copy; instead, the collection refers back to the keys in the original <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>. Therefore, changes to the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> continue to be reflected in the key collection.</remarks> public ICollection<TKey> Keys { get { return Dictionary.Keys; } } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key of the value to get.</param> /// <param name="value">When this method returns, contains the value associated with the specified key, if the key is found; otherwise, the default value for the type of <paramref name="value"/>. This parameter can be passed uninitialized.</param> /// <returns><see langword="true"/> if the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> contains an element with the specified key; otherwise, <see langword="false"/>.</returns> public bool TryGetValue(TKey key, out TValue value) { return Dictionary.TryGetValue(key, out value); } /// <summary> /// Gets an <see cref="ICollection{TValue}">ICollection&lt;TValue&gt;</see> object containing the values in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>. /// </summary> /// <value>An <see cref="ICollection{TValue}">ICollection&lt;TValue&gt;</see> object containing the values in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>.</value> /// <remarks>The returned <see cref="ICollection{TValue}">ICollection&lt;TKey&gt;</see> object is not a static copy; instead, the collection refers back to the values in the original <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>. Therefore, changes to the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> continue to be reflected in the value collection.</remarks> public ICollection<TValue> Values { get { return Dictionary.Values; } } /// <summary> /// Adds the specified value to the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> with the specified key. /// </summary> /// <param name="item">The <see cref="KeyValuePair{TKey,TValue}">KeyValuePair&lt;TKey,TValue&gt;</see> structure representing the key and value to add to the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>.</param> void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } /// <summary> /// Determines whether the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> contains a specific key and value. /// </summary> /// <param name="item">The <see cref="KeyValuePair{TKey,TValue}">KeyValuePair&lt;TKey,TValue&gt;</see> structure to locate in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>.</param> /// <returns><see langword="true"/> if <paramref name="item"/> is found in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>; otherwise, <see langword="false"/>.</returns> bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { return ((ICollection<KeyValuePair<TKey, TValue>>) Dictionary).Contains(item); } /// <summary> /// Copies the elements of the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see> to an array of type <see cref="KeyValuePair{TKey,TValue}"/>, starting at the specified index. /// </summary> /// <param name="array">The one-dimensional array of type <see cref="KeyValuePair{TKey,TValue}">KeyValuePair&lt;TKey,TValue&gt;</see> that is the destination of the <see cref="KeyValuePair{TKey,TValue}">KeyValuePair&lt;TKey,TValue&gt;</see> elements copied from the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>. The array must have zero-based indexing.</param> /// <param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param> void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { ((ICollection<KeyValuePair<TKey, TValue>>) Dictionary).CopyTo(array, arrayIndex); } /// <summary> /// Removes a key and value from the dictionary. /// </summary> /// <param name="item">The <see cref="KeyValuePair{TKey,TValue}">KeyValuePair&lt;TKey,TValue&gt;</see> structure representing the key and value to remove from the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>.</param> /// <returns><see langword="true"/> if the key and value represented by <paramref name="item"/> is successfully found and removed; otherwise, <see langword="false"/>. This method returns <see langword="false"/> if <paramref name="item"/> is not found in the <see cref="OrderedDictionary{TKey,TValue}">OrderedDictionary&lt;TKey,TValue&gt;</see>.</returns> bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { return Remove(item.Key); } } }
/******************************************************************************************** Copyright (c) Microsoft Corporation All rights reserved. Microsoft Public License: This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software. 1. Definitions The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law. A "contribution" is the original software, or any additions or changes to the software. A "contributor" is any person that distributes its contribution under this license. "Licensed patents" are a contributor's patent claims that read directly on its contribution. 2. Grant of Rights (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. 3. Conditions and Limitations (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. ********************************************************************************************/ using System; using System.Diagnostics; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using IServiceProvider = System.IServiceProvider; using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants; namespace Microsoft.VisualStudio.Project { /// <summary> /// Defines an abstract class implementing IVsUpdateSolutionEvents interfaces. /// </summary> public abstract class UpdateSolutionEventsListener : IVsUpdateSolutionEvents3, IVsUpdateSolutionEvents2, IDisposable { #region fields /// <summary> /// The cookie associated to the the events based IVsUpdateSolutionEvents2. /// </summary> private uint solutionEvents2Cookie; /// <summary> /// The cookie associated to the theIVsUpdateSolutionEvents3 events. /// </summary> private uint solutionEvents3Cookie; /// <summary> /// The IVsSolutionBuildManager2 object controlling the update solution events. /// </summary> private IVsSolutionBuildManager2 solutionBuildManager; /// <summary> /// The associated service provider. /// </summary> private IServiceProvider serviceProvider; /// <summary> /// Flag determining if the object has been disposed. /// </summary> private bool isDisposed; /// <summary> /// Defines an object that will be a mutex for this object for synchronizing thread calls. /// </summary> private static volatile object Mutex = new object(); #endregion #region ctors /// <summary> /// Overloaded constructor. /// </summary> /// <param name="serviceProvider">A service provider.</param> protected UpdateSolutionEventsListener(IServiceProvider serviceProvider) { if(serviceProvider == null) { throw new ArgumentNullException("serviceProvider"); } this.serviceProvider = serviceProvider; this.solutionBuildManager = this.serviceProvider.GetService(typeof(SVsSolutionBuildManager)) as IVsSolutionBuildManager2; if(this.solutionBuildManager == null) { throw new InvalidOperationException(); } ErrorHandler.ThrowOnFailure(this.solutionBuildManager.AdviseUpdateSolutionEvents(this, out this.solutionEvents2Cookie)); Debug.Assert(this.solutionBuildManager is IVsSolutionBuildManager3, "The solution build manager object implementing IVsSolutionBuildManager2 does not implement IVsSolutionBuildManager3"); ErrorHandler.ThrowOnFailure(this.SolutionBuildManager3.AdviseUpdateSolutionEvents3(this, out this.solutionEvents3Cookie)); } #endregion #region properties /// <summary> /// The associated service provider. /// </summary> protected IServiceProvider ServiceProvider { get { return this.serviceProvider; } } /// <summary> /// The solution build manager object controlling the solution events. /// </summary> protected IVsSolutionBuildManager2 SolutionBuildManager2 { get { return this.solutionBuildManager; } } /// <summary> /// The solution build manager object controlling the solution events. /// </summary> protected IVsSolutionBuildManager3 SolutionBuildManager3 { get { return (IVsSolutionBuildManager3)this.solutionBuildManager; } } #endregion #region IVsUpdateSolutionEvents3 Members /// <summary> /// Fired after the active solution config is changed (pOldActiveSlnCfg can be NULL). /// </summary> /// <param name="oldActiveSlnCfg">Old configuration.</param> /// <param name="newActiveSlnCfg">New configuration.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int OnAfterActiveSolutionCfgChange(IVsCfg oldActiveSlnCfg, IVsCfg newActiveSlnCfg) { return VSConstants.E_NOTIMPL; } /// <summary> /// Fired before the active solution config is changed (pOldActiveSlnCfg can be NULL /// </summary> /// <param name="oldActiveSlnCfg">Old configuration.</param> /// <param name="newActiveSlnCfg">New configuration.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int OnBeforeActiveSolutionCfgChange(IVsCfg oldActiveSlnCfg, IVsCfg newActiveSlnCfg) { return VSConstants.E_NOTIMPL; } #endregion #region IVsUpdateSolutionEvents2 Members /// <summary> /// Called when the active project configuration for a project in the solution has changed. /// </summary> /// <param name="hierarchy">The project whose configuration has changed.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int OnActiveProjectCfgChange(IVsHierarchy hierarchy) { return VSConstants.E_NOTIMPL; } /// <summary> /// Called right before a project configuration begins to build. /// </summary> /// <param name="hierarchy">The project that is to be build.</param> /// <param name="configProject">A configuration project object.</param> /// <param name="configSolution">A configuration solution object.</param> /// <param name="action">The action taken.</param> /// <param name="cancel">A flag indicating cancel.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> /// <remarks>The values for the action are defined in the enum _SLNUPDACTION env\msenv\core\slnupd2.h</remarks> public int UpdateProjectCfg_Begin(IVsHierarchy hierarchy, IVsCfg configProject, IVsCfg configSolution, uint action, ref int cancel) { return VSConstants.E_NOTIMPL; } /// <summary> /// Called right after a project configuration is finished building. /// </summary> /// <param name="hierarchy">The project that has finished building.</param> /// <param name="configProject">A configuration project object.</param> /// <param name="configSolution">A configuration solution object.</param> /// <param name="action">The action taken.</param> /// <param name="success">Flag indicating success.</param> /// <param name="cancel">Flag indicating cancel.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> /// <remarks>The values for the action are defined in the enum _SLNUPDACTION env\msenv\core\slnupd2.h</remarks> public virtual int UpdateProjectCfg_Done(IVsHierarchy hierarchy, IVsCfg configProject, IVsCfg configSolution, uint action, int success, int cancel) { return VSConstants.E_NOTIMPL; } /// <summary> /// Called before any build actions have begun. This is the last chance to cancel the build before any building begins. /// </summary> /// <param name="cancelUpdate">Flag indicating cancel update.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int UpdateSolution_Begin(ref int cancelUpdate) { return VSConstants.E_NOTIMPL; } /// <summary> /// Called when a build is being cancelled. /// </summary> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int UpdateSolution_Cancel() { return VSConstants.E_NOTIMPL; } /// <summary> /// Called when a build is completed. /// </summary> /// <param name="succeeded">true if no update actions failed.</param> /// <param name="modified">true if any update action succeeded.</param> /// <param name="cancelCommand">true if update actions were canceled.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int UpdateSolution_Done(int fSucceeded, int fModified, int fCancelCommand) { return VSConstants.E_NOTIMPL; } /// <summary> /// Called before the first project configuration is about to be built. /// </summary> /// <param name="cancelUpdate">A flag indicating cancel update.</param> /// <returns>If the method succeeds, it returns S_OK. If it fails, it returns an error code.</returns> public virtual int UpdateSolution_StartUpdate(ref int cancelUpdate) { return VSConstants.E_NOTIMPL; } #endregion #region IDisposable Members /// <summary> /// The IDispose interface Dispose method for disposing the object determinastically. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } #endregion #region methods /// <summary> /// The method that does the cleanup. /// </summary> /// <param name="disposing">true if called from IDispose.Dispose; false if called from Finalizer.</param> protected virtual void Dispose(bool disposing) { // Everybody can go here. if(!this.isDisposed) { // Synchronize calls to the Dispose simultaniously. lock(Mutex) { if(this.solutionEvents2Cookie != (uint)ShellConstants.VSCOOKIE_NIL) { ErrorHandler.ThrowOnFailure(this.solutionBuildManager.UnadviseUpdateSolutionEvents(this.solutionEvents2Cookie)); this.solutionEvents2Cookie = (uint)ShellConstants.VSCOOKIE_NIL; } if(this.solutionEvents3Cookie != (uint)ShellConstants.VSCOOKIE_NIL) { ErrorHandler.ThrowOnFailure(this.SolutionBuildManager3.UnadviseUpdateSolutionEvents3(this.solutionEvents3Cookie)); this.solutionEvents3Cookie = (uint)ShellConstants.VSCOOKIE_NIL; } this.isDisposed = true; } } } #endregion } }
#pragma warning disable 0649 // variable declared but value not assigned //#pragma warning disable 0168 // variable declared but not used. //#pragma warning disable 0219 // variable assigned but not used. //#pragma warning disable 0414 // private field assigned but not used. using UnityEngine; using System.Collections; using System.Collections.Generic; public enum _TurnMode{ FactionAllUnitPerTurn, //each faction take turn to move all units in each round FactionSingleUnitPerTurnSingle, //each faction take turn to move a single unit in each round FactionSingleUnitPerTurnAll, //each faction take turn to move a single unit in each turn, when all unit is moved, the round is completed SingleUnitPerTurn, //all units (regardless of faction) take turn to move according to the stats, when all unit is moves, the round is completed //SingleUnitPerTurnNoRound //not in use SingleUnitRealTime, //all units (regardless of faction) take turn to move according to the stats, faster unit may move more, round is complete when all unit is moved SingleUnitRealTimeNoRound } public enum _MoveOrder{ Free, //unit switching is enabled FixedRandom, //random fix an order and follow the order throughout FixedStatsBased //arrange the order based on unit's stats } public enum _LoadMode{UsePersistantData, UseTemporaryData, UseCurrentData} public enum _CounterAttackRule{None, flexible, Always} public enum _MovementAPCostRule{None, PerMove, PerTile} public enum _AttackAPCostRule{None, PerAttack} //not in used /* [System.Serializable] public class Resource{ public int ID=-1; public string name="resource"; public Texture icon; public int value=100; } */ //not in used public enum _ObjectiveType{ Default, //clear all AI to win FlagGrab, //secure a key item to win Defend, //survive for however many round Escort //get an additional unit from a to b } [RequireComponent (typeof (UnitControl))] [RequireComponent (typeof (DamageTable))] [RequireComponent (typeof (AbilityManagerTB))] [RequireComponent (typeof (AIManager))] public class GameControlTB : MonoBehaviour { public delegate void BattleStartHandler(); public static event BattleStartHandler onBattleStartE; public delegate void BattleEndHandler(int vicFactionID); public static event BattleEndHandler onBattleEndE; public delegate void NextTurnHandler(); public static event NextTurnHandler onNextTurnE; public delegate void NewRoundHandler(int round); public static event NewRoundHandler onNewRoundE; public delegate void GameMessageHandler(string msg); public static event GameMessageHandler onGameMessageE; #if UNITY_IPHONE || UNITY_ANDROID //an event handler to let the ui know weather to show the unit info button, true if there's a unit, else false. //for NGUI free only public delegate void UnitInfoHandler(Tile tile); public static event UnitInfoHandler onUnitInfoE; #endif public _TurnMode turnMode; public _MoveOrder moveOrder; public static bool battleEnded=false; private static bool actionInProgress=false; //for local multiplayer, not fully implemented yet public bool hotseat=false; public List<int> playerFactionID=new List<int>(); public static List<int> playerFactionTurnID=new List<int>(); public List<int> _playerFactionTurnID=new List<int>(); //public int playerFactionID=0; //public static int playerFactionTurnID=-1; public static bool playerFactionExisted=false; public static int turnID=-1; public static int turnIDLoop=0; //to know when all faction has been cycled, this value should never exceed totalFactionInGame public static int totalFactionInGame=2; //a counter indicate the number of round played public static int roundCounter=0; private float newRoundCD=1.0f; public _LoadMode loadMode=_LoadMode.UseCurrentData; public int winPointReward=20; [HideInInspector] public int pointGain=0; public string nextScene=""; public string mainMenu=""; public bool enablePerkMenu=true; public static bool EnablePerkMenu(){ if(instance==null) return false; return instance.enablePerkMenu; } public bool enableUnitPlacement=true; public bool enableCounterAttack; //is counter-attack enabled in the game public bool fullAPOnStart=true; public bool fullAPOnNewRound=false; //restore full ap to all unit at a new round public _MovementAPCostRule movementAPCostRule; // //public int movementAPCost=1; public _AttackAPCostRule attackAPCostRule; //public int attackAPCost=1; public bool enableCover=false; public float coverBonusHalf=0.25f; public float coverBonusFull=0.5f; public float exposedCritBonus=0.3f; public bool enableFogOfWar=false; public bool allowMovementAfterAttack=false; public bool allowAbilityAfterAttack=false; //frequency of actionCam, 0-disabled, 1-always on public float actionCamFrequency=0.5f; private static bool unitSwitchingLocked=false;//to prevent unit switching in factionbasedSingleUnit turnMode after a unit has moved/attacked/used ability public bool allowUnitSwitching=true; //for unit switching in factionbasedSingleUnit turnMode //for external use public _ObjectiveType objectiveType; public static GameControlTB instance; void Awake(){ instance=this; turnID=-1; turnIDLoop=1; AbilityManagerTB.LoadUnitAbility(); roundCounter=0; battleEnded=false; if(playerFactionID.Count==0) playerFactionID.Add(0); } // Use this for initialization void Start () { } void OnEnable(){ UnitTB.onActionCompletedE += OnActionCompleted; UnitTB.onTurnDepletedE += UnitActionDepleted; UnitTB.onUnitDestroyedE+=OnUnitDestroyed; } void OnDisable(){ UnitTB.onActionCompletedE -= OnActionCompleted; UnitTB.onTurnDepletedE -= UnitActionDepleted; UnitTB.onUnitDestroyedE-=OnUnitDestroyed; } void OnUnitDestroyed(UnitTB unit){ if(playerFactionExisted && !hotseat){ if(!playerFactionID.Contains(unit.factionID)){ GainPoint(unit.pointReward); } } } public static void GainPoint(int val){ if(instance==null) return; instance.pointGain+=val; } //function call to set actionInProgress flag to true //when true, all user input are disabled public static bool ActionCommenced(){ LockUnitSwitching(); if(actionInProgress) return false; actionInProgress=true; return true; } //function call to set actionInProgress flag to false //re-enable user input public static void OnActionCompleted(UnitTB unit){ actionInProgress=false; } //note: switching to coroutine will break unitSwitchingLocked IEnumerator _OnActionCompleted(){ yield return new WaitForSeconds(0); actionInProgress=false; } //unit action depleted event handler //called when a unit has used all it's action public void UnitActionDepleted(){ if(instance.turnMode==_TurnMode.FactionAllUnitPerTurn){ //if it's player faction and there are unmoved unit within the faction if(playerFactionTurnID.Contains(turnID) && !UnitControl.AllUnitInFactionMoved(turnID)){ UnitControl.SwitchToNextUnit(); } return; } OnEndTurn(); } //handler when a unit/faction completed it's turn public static void OnEndTurn(){ instance.StartCoroutine(instance._OnEndTurn()); } IEnumerator _OnEndTurn(){ yield return null; if(GetMoveOrder()==_MoveOrder.Free) unitSwitchingLocked=false; if(instance.turnMode==_TurnMode.FactionAllUnitPerTurn){ if(GetMoveOrder()==_MoveOrder.Free){ MoveToNextTurn(); } else{ if(!UnitControl.AllUnitInFactionMoved(turnID)){ UnitControl.OnNextUnit(); } else{ MoveToNextTurn(); } } } else if(instance.turnMode==_TurnMode.FactionSingleUnitPerTurnSingle){ MoveToNextTurn(); } else if(instance.turnMode==_TurnMode.FactionSingleUnitPerTurnAll){ if(UnitControl.AllUnitInAllFactionMoved()){ GridManager.Deselect(); ResetTurnID(); OnNewRound(); } else{ //first check if all the unit has been moved, if yes, switch to next faction NextTurnID(); if(turnID>=totalFactionInGame) turnID=0; int counter=0; while(UnitControl.AllUnitInFactionMoved(turnID)){ NextTurnID(); if(turnID>=totalFactionInGame) turnID=0; //if all the faction has been looped through if((counter+=1)>totalFactionInGame){ Debug.Log("error, no available faction"); //return; yield break; } } //UnitControl.OnNextUnit(); instance.StartCoroutine(instance.OnNextTurn()); } } else if(instance.turnMode==_TurnMode.SingleUnitPerTurn){ instance.StartCoroutine(instance.OnNextTurn()); } else if(instance.turnMode==_TurnMode.SingleUnitRealTime || instance.turnMode==_TurnMode.SingleUnitRealTimeNoRound){ instance.StartCoroutine(instance.OnNextTurn()); } } //a short cut function derives from OnEndTurn() which actually end the current turn public static void MoveToNextTurn(){ GridManager.Deselect(); //probably not needed, NextTurnID(); if(turnIDLoop>totalFactionInGame){ turnIDLoop=1; OnNewRound(); return; } while(!UnitControl.IsFactionStillActive(turnID)){ NextTurnID(); if(turnIDLoop>totalFactionInGame){ turnIDLoop=1; OnNewRound(); return; } } instance.StartCoroutine(instance.OnNextTurn()); } //called by UnitControl to start a new round, fire newRound event public static void OnNewRound(){ if(roundCounter==0) ResetTurnID(); roundCounter+=1; unitSwitchingLocked=false; instance.StartCoroutine(instance._OnNewRound()); } IEnumerator _OnNewRound(){ yield return null; if(battleEnded) yield break; //delay a bit before the game is allowed to progress yield return new WaitForSeconds(newRoundCD*0.25f); actionInProgress=true; if(onGameMessageE!=null) onGameMessageE("Round "+roundCounter); if(onNewRoundE!=null) onNewRoundE(roundCounter); //delay a bit before the game is allowed to progress yield return new WaitForSeconds(newRoundCD*0.85f); actionInProgress=false; StartCoroutine(OnNextTurn()); yield return null; } //called by UnitControl to start switch turn to next faction, fire newTurn event IEnumerator OnNextTurn(){ yield return null; if(onNextTurnE!=null) onNextTurnE(); } //battle ended public static void BattleEnded(int vicFactionID){ battleEnded=true; if(instance.playerFactionID.Contains(vicFactionID)){ //if(vicFactionID==GetPlayerFactionID()){ GainPoint(instance.winPointReward); //if using persistent data, save the point gain in this level if(instance.loadMode==_LoadMode.UsePersistantData){ //instance.pointGain+=instance.winPointReward; GlobalStatsTB.GainPlayerPoint(instance.pointGain); } } if(onBattleEndE!=null) onBattleEndE(vicFactionID); } //reset turnID, called when battle start public static void ResetTurnID(){ //if there's a valid ID, assign to it int factionID=UnitControl.GetPlayerFactionTurnID(); if(factionID>=0) turnID=factionID; else turnID=0; turnIDLoop=1; } //forward to next turnID public static void NextTurnID(){ turnID+=1; turnIDLoop+=1; if(turnID>=totalFactionInGame) turnID=0; } //***************************************************************************************************************************** //player faction ID related function public static bool IsPlayerTurn(){ if(playerFactionExisted){ if(instance.turnMode==_TurnMode.SingleUnitPerTurn){ if(IsPlayerFaction(UnitControl.selectedUnit.factionID)) return true; } else{ if(playerFactionTurnID.Contains(turnID)) return true; } } return false; } public static bool IsHotSeatMode(){ return instance.hotseat; } //for checking if a unit belongs to a player's faction public static bool IsPlayerFaction(int ID){ if(instance.playerFactionID.Contains(ID)) return true; return false; } public static List<int> GetPlayerFactionIDS(){ return instance.playerFactionID; } //get the player factionID that is in current turn public static int GetCurrentPlayerFactionID(){ for(int i=0; i<playerFactionTurnID.Count; i++){ if(playerFactionTurnID[i]==turnID){ return instance.playerFactionID[i]; } } return -1; } //default get playerFactionID function public static int GetPlayerFactionID(){ //if(playerFactionExisted) return instance.playerFactionID[0]; //else return -1; return instance.playerFactionID[0]; } //***************************************************************************************************************************** //UI & input related code // Update is called once per frame void Update () { //for touch input on mobile device #if UNITY_IPHONE || UNITY_ANDROID if(Input.touchCount==1){ Touch touch=Input.touches[0]; //if(touch.phase == TouchPhase.Ended){ if(touch.phase == TouchPhase.Began){ if(!IsCursorOnUI(Input.mousePosition)){ Ray ray = Camera.main.ScreenPointToRay(touch.position); RaycastHit hit; LayerMask mask=1<<LayerManager.GetLayerTile(); if(Physics.Raycast(ray, out hit, Mathf.Infinity, mask)){ Tile tile=hit.collider.gameObject.GetComponent<Tile>(); /**/ //if this is the second tap on the tile if(tile==lastTileTouched){ lastTileTouched=null; tile.OnTouchMouseDown(); } //if the tile is a new one else{ //clear any effect off previously selected tile if(lastTileTouched!=null) lastTileTouched.OnTouchMouseExit(); //if the tile contain friendly unit, select it directly if(tile.unit!=null && tile.unit.factionID==0){ lastTileTouched=tile; tile.OnTouchMouseEnter(); tile.OnTouchMouseDown(); } //a new tile with no friendly unit, just call mouse tnter else{ lastTileTouched=tile; tile.OnTouchMouseEnter(); } } //*/ } else{ if(lastTileTouched!=null){ lastTileTouched.OnTouchMouseExit(); lastTileTouched=null; } } if(onUnitInfoE!=null) onUnitInfoE(lastTileTouched); } } } #else //enable this section and disable OnMouseEnter, OnMouseExit, OnMouseDown, and OnMouseOver in Tile.cs to emulate touch device input scheme on desktop /* if(Input.GetMouseButtonUp(0)){ if(!IsCursorOnUI(Input.mousePosition)){ Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; LayerMask mask=1<<LayerManager.GetLayerTile(); if(Physics.Raycast(ray, out hit, Mathf.Infinity, mask)){ Tile tile=hit.collider.gameObject.GetComponent<Tile>(); //if this is the second tap on the tile if(tile==lastTileTouched){ lastTileTouched.OnTouchMouseExit(); lastTileTouched=null; tile.OnTouchMouseDown(); } //if the tile is a new one else{ //clear any effect off previously selected tile if(lastTileTouched!=null) lastTileTouched.OnTouchMouseExit(); //if the tile contain friendly unit, select it directly if(tile.unit!=null && tile.unit.factionID==0){ lastTileTouched=tile; tile.OnTouchMouseEnter(); tile.OnTouchMouseDown(); } //a new tile with no friendly unit, just call mouse tnter else{ lastTileTouched=tile; tile.OnTouchMouseEnter(); } } } else{ if(lastTileTouched!=null){ lastTileTouched.OnTouchMouseExit(); lastTileTouched=null; } } if(onUnitInfoE!=null) onUnitInfoE(lastTileTouched); } } */ #endif } //this variable is assigned by UITB.cs in runtime public Camera uiCam; //check if any of the mouse click, touch input has landed on UI element public static bool IsCursorOnUI(Vector3 point){ if( instance.uiCam != null ){ // pos is the Vector3 representing the screen position of the input Ray inputRay = instance.uiCam.ScreenPointToRay( point ); RaycastHit hit; LayerMask mask=1<<LayerManager.GetLayerUI(); if( Physics.Raycast( inputRay, out hit, Mathf.Infinity, mask ) ){ // UI was hit return true; } } return false; } public static bool IsObjectOnUI(Vector3 pos){ Camera mainCam=Camera.main; if( instance.uiCam != null && mainCam != null){ // pos is the Vector3 representing the screen position of the input Ray inputRay = instance.uiCam.ScreenPointToRay( mainCam.WorldToScreenPoint(pos) ); RaycastHit hit; LayerMask mask=1<<LayerManager.GetLayerUI(); if( Physics.Raycast( inputRay, out hit, Mathf.Infinity, mask ) ){ // UI was hit return true; } } return false; } public static void SetUICam(Camera cam){ instance.uiCam=cam; } //for touch input on mobile device private Tile lastTileTouched; public static Tile GetLastTileTouched(){ return instance.lastTileTouched; } //***************************************************************************************************************************** //utility function //function called to indicate the unit placement is completed, so the battle can started //called from UITB public static void UnitPlacementCompleted(){ if(onBattleStartE!=null) onBattleStartE(); } //event for UI to display a game event related message public static void DisplayMessage(string msg){ if(onGameMessageE!=null) onGameMessageE(msg); } //scene flow related function public static void LoadNextScene(){ Time.timeScale=1; //make sure the timeScale is reset, in case the function is called when the level is paused; if(instance.nextScene!="") Application.LoadLevel(instance.nextScene); } public static void LoadMainMenu(){ Time.timeScale=1; //make sure the timeScale is reset, in case the function is called when the level is paused; if(instance.mainMenu!="") Application.LoadLevel(instance.mainMenu); } public static bool TogglePause(){ if(Time.timeScale>=1) Time.timeScale=0; else Time.timeScale=1; return Time.timeScale == 0 ? true : false; } public static bool IsPaused(){ return Time.timeScale == 0 ? true : false; } //***************************************************************************************************************************** //public function to get various flag/assignment about rules, mode public static _TurnMode GetTurnMode(){ return instance.turnMode; } public static _MoveOrder GetMoveOrder(){ return instance.moveOrder; } public static bool EnableUnitPlacement(){ return instance.enableUnitPlacement; } public static bool EnableCover(){ return instance.enableCover; } public static float GetCoverHalf(){ return instance.coverBonusHalf; } public static float GetCoverFull(){ return instance.coverBonusFull; } public static float GetExposedCritBonus(){ return instance.exposedCritBonus; } public static bool EnableFogOfWar(){ return instance.enableFogOfWar; } public static bool IsCounterAttackEnabled(){ return instance.enableCounterAttack; } public static bool FullAPOnStart(){ return instance.fullAPOnStart; } public static bool FullAPOnNewRound(){ return instance.fullAPOnNewRound; } public static _MovementAPCostRule MovementAPCostRule(){ return instance.movementAPCostRule; } public static _AttackAPCostRule AttackAPCostRule(){ return instance.attackAPCostRule; } public static bool AllowMovementAfterAttack(){ return instance.allowMovementAfterAttack; } public static bool AllowAbilityAfterAttack(){ return instance.allowAbilityAfterAttack; } public static _LoadMode LoadMode(){ return instance.loadMode; } public static bool AllowUnitSwitching(){ //return instance.allowUnitSwitching && !instance.unitSwitchingLocked; return !unitSwitchingLocked; } public static void LockUnitSwitching(){ //obsolete? if(instance.turnMode==_TurnMode.FactionSingleUnitPerTurnAll || instance.turnMode==_TurnMode.FactionSingleUnitPerTurnSingle) unitSwitchingLocked=true; } public static float GetActionCamFrequency(){ return instance.actionCamFrequency; } public static bool IsActionInProgress(){ return actionInProgress || CameraControl.ActionCamInAction(); } //check if the game is currently in unit placement phase (game not started yet) public static bool IsUnitPlacementState(){ if(turnID<0) return true; return false; } //for debug, draw a box on screen when actionInProgress flag is true /* void OnGUI(){ if(actionInProgress){ GUI.Box(new Rect(100, 100, Screen.width-200, Screen.height-200), ""); } GUI.Label(new Rect(50, 50, 300, 100), "RoundCounter: "+roundCounter); GUI.Label(new Rect(50, 75, 300, 100), "TurnID: "+turnID+" loop:"+turnIDLoop); GUI.Label(new Rect(50, 100, 300, 100), "switching locked: "+unitSwitchingLocked); //GUI.Label(new Rect(50, 125, 300, 100), "unit: "+UnitControl.selectedUnit+" "+UnitControl.selectedUnit.factionID); } */ }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // (C) 2002 Ville Palo // (C) 2003 Martin Willemoes Hansen // Copyright (C) 2004 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 Xunit; using System.Xml; using System.Data.SqlTypes; using System.Globalization; namespace System.Data.Tests.SqlTypes { public class SqlDateTimeTest { private long[] _myTicks = { 631501920000000000L, // 25 Feb 2002 - 00:00:00 631502475130080000L, // 25 Feb 2002 - 15:25:13,8 631502115130080000L, // 25 Feb 2002 - 05:25:13,8 631502115000000000L, // 25 Feb 2002 - 05:25:00 631502115130000000L, // 25 Feb 2002 - 05:25:13 631502079130000000L, // 25 Feb 2002 - 04:25:13 629197085770000000L // 06 Nov 1994 - 08:49:37 }; private SqlDateTime _test1; private SqlDateTime _test2; private SqlDateTime _test3; public SqlDateTimeTest() { CultureInfo.CurrentCulture = new CultureInfo("en-US"); _test1 = new SqlDateTime(2002, 10, 19, 9, 40, 0); _test2 = new SqlDateTime(2003, 11, 20, 10, 50, 1); _test3 = new SqlDateTime(2003, 11, 20, 10, 50, 1); } // Test constructor [Fact] public void Create() { // SqlDateTime (DateTime) SqlDateTime CTest = new SqlDateTime( new DateTime(2002, 5, 19, 3, 34, 0)); Assert.Equal(2002, CTest.Value.Year); // SqlDateTime (int, int) CTest = new SqlDateTime(0, 0); // SqlDateTime (int, int, int) Assert.Equal(1900, CTest.Value.Year); Assert.Equal(1, CTest.Value.Month); Assert.Equal(1, CTest.Value.Day); Assert.Equal(0, CTest.Value.Hour); // SqlDateTime (int, int, int, int, int, int) CTest = new SqlDateTime(5000, 12, 31); Assert.Equal(5000, CTest.Value.Year); Assert.Equal(12, CTest.Value.Month); Assert.Equal(31, CTest.Value.Day); // SqlDateTime (int, int, int, int, int, int, double) CTest = new SqlDateTime(1978, 5, 19, 3, 34, 0); Assert.Equal(1978, CTest.Value.Year); Assert.Equal(5, CTest.Value.Month); Assert.Equal(19, CTest.Value.Day); Assert.Equal(3, CTest.Value.Hour); Assert.Equal(34, CTest.Value.Minute); Assert.Equal(0, CTest.Value.Second); try { CTest = new SqlDateTime(10000, 12, 31); Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(SqlTypeException), e.GetType()); } // SqlDateTime (int, int, int, int, int, int, int) CTest = new SqlDateTime(1978, 5, 19, 3, 34, 0, 12); Assert.Equal(1978, CTest.Value.Year); Assert.Equal(5, CTest.Value.Month); Assert.Equal(19, CTest.Value.Day); Assert.Equal(3, CTest.Value.Hour); Assert.Equal(34, CTest.Value.Minute); Assert.Equal(0, CTest.Value.Second); Assert.Equal(0, CTest.Value.Millisecond); } // Test public fields [Fact] public void PublicFields() { // MaxValue Assert.Equal(9999, SqlDateTime.MaxValue.Value.Year); Assert.Equal(12, SqlDateTime.MaxValue.Value.Month); Assert.Equal(31, SqlDateTime.MaxValue.Value.Day); Assert.Equal(23, SqlDateTime.MaxValue.Value.Hour); Assert.Equal(59, SqlDateTime.MaxValue.Value.Minute); Assert.Equal(59, SqlDateTime.MaxValue.Value.Second); // MinValue Assert.Equal(1753, SqlDateTime.MinValue.Value.Year); Assert.Equal(1, SqlDateTime.MinValue.Value.Month); Assert.Equal(1, SqlDateTime.MinValue.Value.Day); Assert.Equal(0, SqlDateTime.MinValue.Value.Hour); Assert.Equal(0, SqlDateTime.MinValue.Value.Minute); Assert.Equal(0, SqlDateTime.MinValue.Value.Second); // Null Assert.True(SqlDateTime.Null.IsNull); // SQLTicksPerHour Assert.Equal(1080000, SqlDateTime.SQLTicksPerHour); // SQLTicksPerMinute Assert.Equal(18000, SqlDateTime.SQLTicksPerMinute); // SQLTicksPerSecond Assert.Equal(300, SqlDateTime.SQLTicksPerSecond); } // Test properties [Fact] public void Properties() { // DayTicks Assert.Equal(37546, _test1.DayTicks); try { int test = SqlDateTime.Null.DayTicks; Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(SqlNullValueException), e.GetType()); } // IsNull Assert.True(SqlDateTime.Null.IsNull); Assert.True(!_test2.IsNull); // TimeTicks Assert.Equal(10440000, _test1.TimeTicks); try { int test = SqlDateTime.Null.TimeTicks; Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(SqlNullValueException), e.GetType()); } // Value Assert.Equal(2003, _test2.Value.Year); Assert.Equal(2002, _test1.Value.Year); } // PUBLIC METHODS [Fact] public void CompareTo() { SqlString TestString = new SqlString("This is a test"); Assert.True(_test1.CompareTo(_test3) < 0); Assert.True(_test2.CompareTo(_test1) > 0); Assert.True(_test2.CompareTo(_test3) == 0); Assert.True(_test1.CompareTo(SqlDateTime.Null) > 0); try { _test1.CompareTo(TestString); Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(ArgumentException), e.GetType()); } } [Fact] public void EqualsMethods() { Assert.True(!_test1.Equals(_test2)); Assert.True(!_test2.Equals(new SqlString("TEST"))); Assert.True(_test2.Equals(_test3)); // Static Equals()-method Assert.True(SqlDateTime.Equals(_test2, _test3).Value); Assert.True(!SqlDateTime.Equals(_test1, _test2).Value); } [Fact] public void GetHashCodeTest() { // FIXME: Better way to test HashCode Assert.Equal(_test1.GetHashCode(), _test1.GetHashCode()); Assert.True(_test2.GetHashCode() != _test1.GetHashCode()); } [Fact] public void GetTypeTest() { Assert.Equal("System.Data.SqlTypes.SqlDateTime", _test1.GetType().ToString()); Assert.Equal("System.DateTime", _test1.Value.GetType().ToString()); } [Fact] public void Greaters() { // GreateThan () Assert.True(!SqlDateTime.GreaterThan(_test1, _test2).Value); Assert.True(SqlDateTime.GreaterThan(_test2, _test1).Value); Assert.True(!SqlDateTime.GreaterThan(_test2, _test3).Value); // GreaterTharOrEqual () Assert.True(!SqlDateTime.GreaterThanOrEqual(_test1, _test2).Value); Assert.True(SqlDateTime.GreaterThanOrEqual(_test2, _test1).Value); Assert.True(SqlDateTime.GreaterThanOrEqual(_test2, _test3).Value); } [Fact] public void Lessers() { // LessThan() Assert.True(!SqlDateTime.LessThan(_test2, _test3).Value); Assert.True(!SqlDateTime.LessThan(_test2, _test1).Value); Assert.True(SqlDateTime.LessThan(_test1, _test3).Value); // LessThanOrEqual () Assert.True(SqlDateTime.LessThanOrEqual(_test1, _test2).Value); Assert.True(!SqlDateTime.LessThanOrEqual(_test2, _test1).Value); Assert.True(SqlDateTime.LessThanOrEqual(_test3, _test2).Value); Assert.True(SqlDateTime.LessThanOrEqual(_test1, SqlDateTime.Null).IsNull); } [Fact] public void NotEquals() { Assert.True(SqlDateTime.NotEquals(_test1, _test2).Value); Assert.True(SqlDateTime.NotEquals(_test3, _test1).Value); Assert.True(!SqlDateTime.NotEquals(_test2, _test3).Value); Assert.True(SqlDateTime.NotEquals(SqlDateTime.Null, _test2).IsNull); } [Fact] public void Parse() { try { SqlDateTime.Parse(null); Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(ArgumentNullException), e.GetType()); } try { SqlDateTime.Parse("not-a-number"); Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(FormatException), e.GetType()); } SqlDateTime t1 = SqlDateTime.Parse("02/25/2002"); Assert.Equal(_myTicks[0], t1.Value.Ticks); try { t1 = SqlDateTime.Parse("2002-02-25"); } catch (Exception e) { Assert.False(true); } // Thanks for Martin Baulig for these (DateTimeTest.cs) Assert.Equal(_myTicks[0], t1.Value.Ticks); t1 = SqlDateTime.Parse("Monday, 25 February 2002"); Assert.Equal(_myTicks[0], t1.Value.Ticks); t1 = SqlDateTime.Parse("Monday, 25 February 2002 05:25"); Assert.Equal(_myTicks[3], t1.Value.Ticks); t1 = SqlDateTime.Parse("Monday, 25 February 2002 05:25:13"); Assert.Equal(_myTicks[4], t1.Value.Ticks); t1 = SqlDateTime.Parse("02/25/2002 05:25"); Assert.Equal(_myTicks[3], t1.Value.Ticks); t1 = SqlDateTime.Parse("02/25/2002 05:25:13"); Assert.Equal(_myTicks[4], t1.Value.Ticks); t1 = SqlDateTime.Parse("2002-02-25 04:25:13Z"); t1 = t1.Value.ToUniversalTime(); Assert.Equal(2002, t1.Value.Year); Assert.Equal(02, t1.Value.Month); Assert.Equal(25, t1.Value.Day); Assert.Equal(04, t1.Value.Hour); Assert.Equal(25, t1.Value.Minute); Assert.Equal(13, t1.Value.Second); SqlDateTime t2 = new SqlDateTime(DateTime.Today.Year, 2, 25); t1 = SqlDateTime.Parse("February 25"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(DateTime.Today.Year, 2, 8); t1 = SqlDateTime.Parse("February 08"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t1 = SqlDateTime.Parse("Mon, 25 Feb 2002 04:25:13 GMT"); t1 = t1.Value.ToUniversalTime(); Assert.Equal(2002, t1.Value.Year); Assert.Equal(02, t1.Value.Month); Assert.Equal(25, t1.Value.Day); Assert.Equal(04, t1.Value.Hour); Assert.Equal(25, t1.Value.Minute); Assert.Equal(13, t1.Value.Second); t1 = SqlDateTime.Parse("2002-02-25T05:25:13"); Assert.Equal(_myTicks[4], t1.Value.Ticks); t2 = DateTime.Today + new TimeSpan(5, 25, 0); t1 = SqlDateTime.Parse("05:25"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = DateTime.Today + new TimeSpan(5, 25, 13); t1 = SqlDateTime.Parse("05:25:13"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(2002, 2, 1); t1 = SqlDateTime.Parse("2002 February"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(2002, 2, 1); t1 = SqlDateTime.Parse("2002 February"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(DateTime.Today.Year, 2, 8); t1 = SqlDateTime.Parse("February 8"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); } // OPERATORS [Fact] public void ArithmeticOperators() { TimeSpan TestSpan = new TimeSpan(20, 1, 20, 20); SqlDateTime ResultDateTime; // "+"-operator ResultDateTime = _test1 + TestSpan; Assert.Equal(2002, ResultDateTime.Value.Year); Assert.Equal(8, ResultDateTime.Value.Day); Assert.Equal(11, ResultDateTime.Value.Hour); Assert.Equal(0, ResultDateTime.Value.Minute); Assert.Equal(20, ResultDateTime.Value.Second); Assert.True((SqlDateTime.Null + TestSpan).IsNull); try { ResultDateTime = SqlDateTime.MaxValue + TestSpan; Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(ArgumentOutOfRangeException), e.GetType()); } // "-"-operator ResultDateTime = _test1 - TestSpan; Assert.Equal(2002, ResultDateTime.Value.Year); Assert.Equal(29, ResultDateTime.Value.Day); Assert.Equal(8, ResultDateTime.Value.Hour); Assert.Equal(19, ResultDateTime.Value.Minute); Assert.Equal(40, ResultDateTime.Value.Second); Assert.True((SqlDateTime.Null - TestSpan).IsNull); try { ResultDateTime = SqlDateTime.MinValue - TestSpan; Assert.False(true); } catch (Exception e) { Assert.Equal(typeof(SqlTypeException), e.GetType()); } } [Fact] public void ThanOrEqualOperators() { // == -operator Assert.True((_test2 == _test3).Value); Assert.True(!(_test1 == _test2).Value); Assert.True((_test1 == SqlDateTime.Null).IsNull); // != -operator Assert.True(!(_test2 != _test3).Value); Assert.True((_test1 != _test3).Value); Assert.True((_test1 != SqlDateTime.Null).IsNull); // > -operator Assert.True((_test2 > _test1).Value); Assert.True(!(_test3 > _test2).Value); Assert.True((_test1 > SqlDateTime.Null).IsNull); // >= -operator Assert.True(!(_test1 >= _test3).Value); Assert.True((_test3 >= _test1).Value); Assert.True((_test2 >= _test3).Value); Assert.True((_test1 >= SqlDateTime.Null).IsNull); // < -operator Assert.True(!(_test2 < _test1).Value); Assert.True((_test1 < _test3).Value); Assert.True(!(_test2 < _test3).Value); Assert.True((_test1 < SqlDateTime.Null).IsNull); // <= -operator Assert.True((_test1 <= _test3).Value); Assert.True(!(_test3 <= _test1).Value); Assert.True((_test2 <= _test3).Value); Assert.True((_test1 <= SqlDateTime.Null).IsNull); } [Fact] public void SqlDateTimeToDateTime() { Assert.Equal(2002, ((DateTime)_test1).Year); Assert.Equal(2003, ((DateTime)_test2).Year); Assert.Equal(10, ((DateTime)_test1).Month); Assert.Equal(19, ((DateTime)_test1).Day); Assert.Equal(9, ((DateTime)_test1).Hour); Assert.Equal(40, ((DateTime)_test1).Minute); Assert.Equal(0, ((DateTime)_test1).Second); } [Fact] public void SqlStringToSqlDateTime() { SqlString TestString = new SqlString("02/25/2002"); SqlDateTime t1 = (SqlDateTime)TestString; Assert.Equal(_myTicks[0], t1.Value.Ticks); // Thanks for Martin Baulig for these (DateTimeTest.cs) Assert.Equal(_myTicks[0], t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("Monday, 25 February 2002"); Assert.Equal(_myTicks[0], t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("Monday, 25 February 2002 05:25"); Assert.Equal(_myTicks[3], t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("Monday, 25 February 2002 05:25:13"); Assert.Equal(_myTicks[4], t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("02/25/2002 05:25"); Assert.Equal(_myTicks[3], t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("02/25/2002 05:25:13"); Assert.Equal(_myTicks[4], t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("2002-02-25 04:25:13Z"); t1 = t1.Value.ToUniversalTime(); Assert.Equal(2002, t1.Value.Year); Assert.Equal(02, t1.Value.Month); Assert.Equal(25, t1.Value.Day); Assert.Equal(04, t1.Value.Hour); Assert.Equal(25, t1.Value.Minute); Assert.Equal(13, t1.Value.Second); SqlDateTime t2 = new SqlDateTime(DateTime.Today.Year, 2, 25); t1 = (SqlDateTime)new SqlString("February 25"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(DateTime.Today.Year, 2, 8); t1 = (SqlDateTime)new SqlString("February 08"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t1 = (SqlDateTime)new SqlString("Mon, 25 Feb 2002 04:25:13 GMT"); t1 = t1.Value.ToUniversalTime(); Assert.Equal(2002, t1.Value.Year); Assert.Equal(02, t1.Value.Month); Assert.Equal(25, t1.Value.Day); Assert.Equal(04, t1.Value.Hour); Assert.Equal(25, t1.Value.Minute); Assert.Equal(13, t1.Value.Second); t1 = (SqlDateTime)new SqlString("2002-02-25T05:25:13"); Assert.Equal(_myTicks[4], t1.Value.Ticks); t2 = DateTime.Today + new TimeSpan(5, 25, 0); t1 = (SqlDateTime)new SqlString("05:25"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = DateTime.Today + new TimeSpan(5, 25, 13); t1 = (SqlDateTime)new SqlString("05:25:13"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(2002, 2, 1); t1 = (SqlDateTime)new SqlString("2002 February"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(2002, 2, 1); t1 = (SqlDateTime)new SqlString("2002 February"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); t2 = new SqlDateTime(DateTime.Today.Year, 2, 8); t1 = (SqlDateTime)new SqlString("February 8"); Assert.Equal(t2.Value.Ticks, t1.Value.Ticks); } [Fact] public void DateTimeToSqlDateTime() { DateTime DateTimeTest = new DateTime(2002, 10, 19, 11, 53, 4); SqlDateTime Result = DateTimeTest; Assert.Equal(2002, Result.Value.Year); Assert.Equal(10, Result.Value.Month); Assert.Equal(19, Result.Value.Day); Assert.Equal(11, Result.Value.Hour); Assert.Equal(53, Result.Value.Minute); Assert.Equal(4, Result.Value.Second); } [Fact] public void TicksRoundTrip() { SqlDateTime d1 = new SqlDateTime(2007, 05, 04, 18, 02, 40, 398.25); SqlDateTime d2 = new SqlDateTime(d1.DayTicks, d1.TimeTicks); Assert.Equal(39204, d1.DayTicks); Assert.Equal(19488119, d1.TimeTicks); Assert.Equal(633138985603970000, d1.Value.Ticks); Assert.Equal(d1.DayTicks, d2.DayTicks); Assert.Equal(d1.TimeTicks, d2.TimeTicks); Assert.Equal(d1.Value.Ticks, d2.Value.Ticks); Assert.Equal(d1, d2); } [Fact] public void EffingBilisecond() { SqlDateTime d1 = new SqlDateTime(2007, 05, 04, 18, 02, 40, 398252); Assert.Equal(39204, d1.DayTicks); Assert.Equal(19488119, d1.TimeTicks); Assert.Equal(633138985603970000, d1.Value.Ticks); } [Fact] public void GetXsdTypeTest() { XmlQualifiedName qualifiedName = SqlDateTime.GetXsdType(null); Assert.Equal("dateTime", qualifiedName.Name); } } }
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Xml; using System.Data; using System.Collections; namespace fyiReporting.Data { /// <summary> /// LogCommand allows specifying the command for the web log. /// </summary> public class GedcomCommand : IDbCommand { GedcomConnection _lc; // connection we're running under string _cmd; // command to execute // parsed constituents of the command string _Url; // url of the file DataParameterCollection _Parameters = new DataParameterCollection(); public GedcomCommand(GedcomConnection conn) { _lc = conn; } internal string Url { get { // Check to see if "Url" or "@Url" is a parameter IDbDataParameter dp= _Parameters["Url"] as IDbDataParameter; if (dp == null) dp= _Parameters["@Url"] as IDbDataParameter; // Then check to see if the Url value is a parameter? if (dp == null) dp = _Parameters[_Url] as IDbDataParameter; if (dp != null) return dp.Value != null? dp.Value.ToString(): _Url; // don't pass null; pass existing value return _Url; // the value must be a constant } set {_Url = value;} } #region IDbCommand Members public void Cancel() { throw new NotImplementedException("Cancel not implemented"); } public void Prepare() { return; // Prepare is a noop } public System.Data.CommandType CommandType { get { throw new NotImplementedException("CommandType not implemented"); } set { throw new NotImplementedException("CommandType not implemented"); } } public IDataReader ExecuteReader(System.Data.CommandBehavior behavior) { if (!(behavior == CommandBehavior.SingleResult || behavior == CommandBehavior.SchemaOnly)) throw new ArgumentException("ExecuteReader supports SingleResult and SchemaOnly only."); return new GedcomDataReader(behavior, _lc, this); } IDataReader System.Data.IDbCommand.ExecuteReader() { return ExecuteReader(System.Data.CommandBehavior.SingleResult); } public object ExecuteScalar() { throw new NotImplementedException("ExecuteScalar not implemented"); } public int ExecuteNonQuery() { throw new NotImplementedException("ExecuteNonQuery not implemented"); } public int CommandTimeout { get { return 0; } set { throw new NotImplementedException("CommandTimeout not implemented"); } } public IDbDataParameter CreateParameter() { return new GedcomDataParameter(); } public IDbConnection Connection { get { return this._lc; } set { throw new NotImplementedException("Setting Connection not implemented"); } } public System.Data.UpdateRowSource UpdatedRowSource { get { throw new NotImplementedException("UpdatedRowSource not implemented"); } set { throw new NotImplementedException("UpdatedRowSource not implemented"); } } public string CommandText { get { return this._cmd; } set { // Parse the command string for keyword value pairs separated by ';' string[] args = value.Split(';'); string url=null; foreach(string arg in args) { string[] param = arg.Trim().Split('='); if (param == null || param.Length != 2) continue; string key = param[0].Trim().ToLower(); string val = param[1]; switch (key) { case "url": case "file": url = val; break; default: throw new ArgumentException(string.Format("{0} is an unknown parameter key", param[0])); } } // User must specify both the url and the RowsXPath if (url == null) throw new ArgumentException("CommandText requires a 'Url=' parameter."); _cmd = value; _Url = url; } } public IDataParameterCollection Parameters { get { return _Parameters; } } public IDbTransaction Transaction { get { throw new NotImplementedException("Transaction not implemented"); } set { throw new NotImplementedException("Transaction not implemented"); } } #endregion #region IDisposable Members public void Dispose() { // nothing to dispose of } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace LZ4Sharp { /// <summary> /// Class for decompressing an LZ4 compressed byte array. /// </summary> public unsafe class LZ4Decompressor32 : ILZ4Decompressor { const int STEPSIZE = 4; static byte[] DeBruijnBytePos = new byte[32] { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; //************************************** // Macros //************************************** readonly sbyte[] m_DecArray = new sbyte[8] { 0, 3, 2, 3, 0, 0, 0, 0 }; // Note : The decoding functions LZ4_uncompress() and LZ4_uncompress_unknownOutputSize() // are safe against "buffer overflow" attack type // since they will *never* write outside of the provided output buffer : // they both check this condition *before* writing anything. // A corrupted packet however can make them *read* within the first 64K before the output buffer. /// <summary> /// Decompress. /// </summary> /// <param name="source">compressed array</param> /// <param name="dest">This must be the exact length of the decompressed item</param> public void DecompressKnownSize(byte[] compressed, byte[] decompressed) { int len = DecompressKnownSize(compressed, decompressed, decompressed.Length); Debug.Assert(len == decompressed.Length); } public int DecompressKnownSize(byte[] compressed, byte[] decompressedBuffer, int decompressedSize) { fixed (byte* src = compressed) fixed (byte* dst = decompressedBuffer) return DecompressKnownSize(src, dst, decompressedSize); } public int DecompressKnownSize(byte* compressed, byte* decompressedBuffer, int decompressedSize) { fixed (sbyte* dec = m_DecArray) { // Local Variables byte* ip = (byte*)compressed; byte* r; byte* op = (byte*)decompressedBuffer; byte* oend = op + decompressedSize; byte* cpy; byte token; int len, length; // Main Loop while (true) { // get runLength token = *ip++; if ((length = (token >> LZ4Util.ML_BITS)) == LZ4Util.RUN_MASK) { for (; (len = *ip++) == 255; length += 255) { } length += len; } cpy = op + length; if (cpy > oend - LZ4Util.COPYLENGTH) { if (cpy > oend) goto _output_error; LZ4Util.CopyMemory(op, ip, length); ip += length; break; } do { *(uint*)op = *(uint*)ip; op += 4; ip += 4; ; *(uint*)op = *(uint*)ip; op += 4; ip += 4; ; } while (op < cpy); ; ip -= (op - cpy); op = cpy; // get offset { r = (cpy) - *(ushort*)ip; }; ip += 2; if (r < decompressedBuffer) goto _output_error; // get matchLength if ((length = (int)(token & LZ4Util.ML_MASK)) == LZ4Util.ML_MASK) { for (; *ip == 255; length += 255) { ip++; } length += *ip++; } // copy repeated sequence if (op - r < STEPSIZE) { const int dec2 = 0; *op++ = *r++; *op++ = *r++; *op++ = *r++; *op++ = *r++; r -= dec[op - r]; *(uint*)op = *(uint*)r; op += STEPSIZE - 4; r -= dec2; } else { *(uint*)op = *(uint*)r; op += 4; r += 4; ; } cpy = op + length - (STEPSIZE - 4); if (cpy > oend - LZ4Util.COPYLENGTH) { if (cpy > oend) goto _output_error; do { *(uint*)op = *(uint*)r; op += 4; r += 4; ; *(uint*)op = *(uint*)r; op += 4; r += 4; ; } while (op < (oend - LZ4Util.COPYLENGTH)); ; while (op < cpy) *op++ = *r++; op = cpy; if (op == oend) break; continue; } do { *(uint*)op = *(uint*)r; op += 4; r += 4; ; *(uint*)op = *(uint*)r; op += 4; r += 4; ; } while (op < cpy); ; op = cpy; // correction } // end of decoding return (int)(((byte*)ip) - compressed); // write overflow error detected _output_error: return (int)(-(((byte*)ip) - compressed)); } } public byte[] Decompress(byte[] compressed) { int length = compressed.Length; int len; byte[] dest; const int Multiplier = 4; // Just a number. Determines how fast length should increase. do { length *= Multiplier; dest = new byte[length]; len = Decompress(compressed, dest, compressed.Length); } while (len < 0 || dest.Length < len); byte[] d = new byte[len]; Buffer.BlockCopy(dest, 0, d, 0, d.Length); return d; } public int Decompress(byte[] compressed, byte[] decompressedBuffer) { return Decompress(compressed, decompressedBuffer, compressed.Length); } public int Decompress(byte[] compressedBuffer, byte[] decompressedBuffer, int compressedSize) { fixed (byte* src = compressedBuffer) fixed (byte* dst = decompressedBuffer) return Decompress(src, dst, compressedSize, decompressedBuffer.Length); } public int Decompress(byte[] compressedBuffer, int compressedPosition, byte[] decompressedBuffer, int decompressedPosition, int compressedSize) { fixed (byte* src = &compressedBuffer[compressedPosition]) fixed (byte* dst = &decompressedBuffer[decompressedPosition]) return Decompress(src, dst, compressedSize, decompressedBuffer.Length); } public int Decompress( byte* compressedBuffer, byte* decompressedBuffer, int compressedSize, int maxDecompressedSize) { fixed (sbyte* dec = m_DecArray) { // Local Variables byte* ip = (byte*)compressedBuffer; byte* iend = ip + compressedSize; byte* r; byte* op = (byte*)decompressedBuffer; byte* oend = op + maxDecompressedSize; byte* cpy; byte token; int len, length; // Main Loop while (ip < iend) { // get runLength token = *ip++; if ((length = (token >> LZ4Util.ML_BITS)) == LZ4Util.RUN_MASK) { int s = 255; while ((ip < iend) && (s == 255)) { s = *ip++; length += s; } } // copy literals cpy = op + length; if ((cpy > oend - LZ4Util.COPYLENGTH) || (ip + length > iend - LZ4Util.COPYLENGTH)) { if (cpy > oend) goto _output_error; // Error : request to write beyond destination buffer if (ip + length > iend) goto _output_error; // Error : request to read beyond source buffer LZ4Util.CopyMemory(op, ip, length); op += length; ip += length; if (ip < iend) goto _output_error; // Error : LZ4 format violation break; //Necessarily EOF } do { *(uint*)op = *(uint*)ip; op += 4; ip += 4; ; *(uint*)op = *(uint*)ip; op += 4; ip += 4; ; } while (op < cpy); ; ip -= (op - cpy); op = cpy; // get offset { r = (cpy) - *(ushort*)ip; }; ip += 2; if (r < decompressedBuffer) goto _output_error; // get matchlength if ((length = (int)(token & LZ4Util.ML_MASK)) == LZ4Util.ML_MASK) { while (ip < iend) { int s = *ip++; length += s; if (s == 255) continue; break; } } // copy repeated sequence if (op - r < STEPSIZE) { const int dec2 = 0; *op++ = *r++; *op++ = *r++; *op++ = *r++; *op++ = *r++; r -= dec[op - r]; *(uint*)op = *(uint*)r; op += STEPSIZE - 4; r -= dec2; } else { *(uint*)op = *(uint*)r; op += 4; r += 4; ; } cpy = op + length - (STEPSIZE - 4); if (cpy > oend - LZ4Util.COPYLENGTH) { if (cpy > oend) goto _output_error; do { *(uint*)op = *(uint*)r; op += 4; r += 4; ; *(uint*)op = *(uint*)r; op += 4; r += 4; ; } while (op < (oend - LZ4Util.COPYLENGTH)); ; while (op < cpy) *op++ = *r++; op = cpy; if (op == oend) goto _output_error; // Check EOF (should never happen, since last 5 bytes are supposed to be literals) continue; } do { *(uint*)op = *(uint*)r; op += 4; r += 4; ; *(uint*)op = *(uint*)r; op += 4; r += 4; ; } while (op < cpy); ; op = cpy; // correction } return (int)(((byte*)op) - decompressedBuffer); _output_error: return (int)(-(((byte*)ip) - compressedBuffer)); } } } }
//////////////////////////////////////////////////////////////////////////// // // DateTimeFormatInfoScanner // // Scan a specified DateTimeFormatInfo to search for data used in DateTime.Parse() // // The data includes: // // DateWords: such as "de" used in es-ES (Spanish) LongDatePattern. // Postfix: such as "ta" used in fi-FI after the month name. // // This class is shared among mscorlib.dll and sysglobl.dll. // Use conditional CULTURE_AND_REGIONINFO_BUILDER_ONLY to differentiate between // methods for mscorlib.dll and sysglobl.dll. // //////////////////////////////////////////////////////////////////////////// namespace System.Globalization { using System; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Text; // // from LocaleEx.txt header // //; IFORMATFLAGS //; Parsing/formatting flags. internal enum FORMATFLAGS { None = 0x00000000, UseGenitiveMonth = 0x00000001, UseLeapYearMonth = 0x00000002, UseSpacesInMonthNames = 0x00000004, UseHebrewParsing = 0x00000008, UseSpacesInDayNames = 0x00000010, // Has spaces or non-breaking space in the day names. UseDigitPrefixInTokens = 0x00000020, // Has token starting with numbers. } // // To change in CalendarId you have to do the same change in Calendar.cs // To do: make the definintion shared between these two files. // internal enum CalendarId : ushort { GREGORIAN = 1 , // Gregorian (localized) calendar GREGORIAN_US = 2 , // Gregorian (U.S.) calendar JAPAN = 3 , // Japanese Emperor Era calendar /* SSS_WARNINGS_OFF */ TAIWAN = 4 , // Taiwan Era calendar /* SSS_WARNINGS_ON */ KOREA = 5 , // Korean Tangun Era calendar HIJRI = 6 , // Hijri (Arabic Lunar) calendar THAI = 7 , // Thai calendar HEBREW = 8 , // Hebrew (Lunar) calendar GREGORIAN_ME_FRENCH = 9 , // Gregorian Middle East French calendar GREGORIAN_ARABIC = 10, // Gregorian Arabic calendar GREGORIAN_XLIT_ENGLISH = 11, // Gregorian Transliterated English calendar GREGORIAN_XLIT_FRENCH = 12, // Note that all calendars after this point are MANAGED ONLY for now. JULIAN = 13, JAPANESELUNISOLAR = 14, CHINESELUNISOLAR = 15, SAKA = 16, // reserved to match Office but not implemented in our code LUNAR_ETO_CHN = 17, // reserved to match Office but not implemented in our code LUNAR_ETO_KOR = 18, // reserved to match Office but not implemented in our code LUNAR_ETO_ROKUYOU = 19, // reserved to match Office but not implemented in our code KOREANLUNISOLAR = 20, TAIWANLUNISOLAR = 21, PERSIAN = 22, UMALQURA = 23, LAST_CALENDAR = 23 // Last calendar ID } internal class DateTimeFormatInfoScanner { // Special prefix-like flag char in DateWord array. // Use char in PUA area since we won't be using them in real data. // The char used to tell a read date word or a month postfix. A month postfix // is "ta" in the long date pattern like "d. MMMM'ta 'yyyy" for fi-FI. // In this case, it will be stored as "\xfffeta" in the date word array. internal const char MonthPostfixChar = '\xe000'; // Add ignorable symbol in a DateWord array. // hu-HU has: // shrot date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd // long date pattern: yyyy. MMMM d. // Here, "." is the date separator (derived from short date pattern). However, // "." also appear at the end of long date pattern. In this case, we just // "." as ignorable symbol so that the DateTime.Parse() state machine will not // treat the additional date separator at the end of y,m,d pattern as an error // condition. internal const char IgnorableSymbolChar = '\xe001'; // Known CJK suffix internal const String CJKYearSuff = "\u5e74"; internal const String CJKMonthSuff = "\u6708"; internal const String CJKDaySuff = "\u65e5"; internal const String KoreanYearSuff = "\ub144"; internal const String KoreanMonthSuff = "\uc6d4"; internal const String KoreanDaySuff = "\uc77c"; internal const String KoreanHourSuff = "\uc2dc"; internal const String KoreanMinuteSuff = "\ubd84"; internal const String KoreanSecondSuff = "\ucd08"; internal const String CJKHourSuff = "\u6642"; internal const String ChineseHourSuff = "\u65f6"; internal const String CJKMinuteSuff = "\u5206"; internal const String CJKSecondSuff = "\u79d2"; // The collection fo date words & postfix. internal List<String> m_dateWords = new List<String>(); // Hashtable for the known words. private static volatile Dictionary<String, String> s_knownWords; static Dictionary<String, String> KnownWords { get { if (s_knownWords == null) { Dictionary<String, String> temp = new Dictionary<String, String>(); // Add known words into the hash table. // Skip these special symbols. temp.Add("/", String.Empty); temp.Add("-", String.Empty); temp.Add(".", String.Empty); // Skip known CJK suffixes. temp.Add(CJKYearSuff, String.Empty); temp.Add(CJKMonthSuff, String.Empty); temp.Add(CJKDaySuff, String.Empty); temp.Add(KoreanYearSuff, String.Empty); temp.Add(KoreanMonthSuff, String.Empty); temp.Add(KoreanDaySuff, String.Empty); temp.Add(KoreanHourSuff, String.Empty); temp.Add(KoreanMinuteSuff, String.Empty); temp.Add(KoreanSecondSuff, String.Empty); temp.Add(CJKHourSuff, String.Empty); temp.Add(ChineseHourSuff, String.Empty); temp.Add(CJKMinuteSuff, String.Empty); temp.Add(CJKSecondSuff, String.Empty); s_knownWords = temp; } return (s_knownWords); } } //////////////////////////////////////////////////////////////////////////// // // Parameters: // pattern: The pattern to be scanned. // currentIndex: the current index to start the scan. // // Returns: // Return the index with the first character that is a letter, which will // be the start of a date word. // Note that the index can be pattern.Length if we reach the end of the string. // //////////////////////////////////////////////////////////////////////////// internal static int SkipWhiteSpacesAndNonLetter(String pattern, int currentIndex) { while (currentIndex < pattern.Length) { char ch = pattern[currentIndex]; if (ch == '\\') { // Escaped character. Look ahead one character. currentIndex++; if (currentIndex < pattern.Length) { ch = pattern[currentIndex]; if (ch == '\'') { // Skip the leading single quote. We will // stop at the first letter. continue; } // Fall thru to check if this is a letter. } else { // End of string break; } } if (Char.IsLetter(ch) || ch == '\'' || ch == '.') { break; } // Skip the current char since it is not a letter. currentIndex++; } return (currentIndex); } //////////////////////////////////////////////////////////////////////////// // // A helper to add the found date word or month postfix into ArrayList for date words. // // Parameters: // formatPostfix: What kind of postfix this is. // Possible values: // null: This is a regular date word // "MMMM": month postfix // word: The date word or postfix to be added. // //////////////////////////////////////////////////////////////////////////// internal void AddDateWordOrPostfix(String formatPostfix, String str) { if (str.Length > 0) { // Some cultures use . like an abbreviation if (str.Equals(".")) { AddIgnorableSymbols("."); return; } String words; if (KnownWords.TryGetValue(str, out words) == false) { if (m_dateWords == null) { m_dateWords = new List<String>(); } if (formatPostfix == "MMMM") { // Add the word into the ArrayList as "\xfffe" + real month postfix. String temp = MonthPostfixChar + str; if (!m_dateWords.Contains(temp)) { m_dateWords.Add(temp); } } else { if (!m_dateWords.Contains(str)) { m_dateWords.Add(str); } if (str[str.Length - 1] == '.') { // Old version ignore the trialing dot in the date words. Support this as well. String strWithoutDot = str.Substring(0, str.Length - 1); if (!m_dateWords.Contains(strWithoutDot)) { m_dateWords.Add(strWithoutDot); } } } } } } //////////////////////////////////////////////////////////////////////////// // // Scan the pattern from the specified index and add the date word/postfix // when appropriate. // // Parameters: // pattern: The pattern to be scanned. // index: The starting index to be scanned. // formatPostfix: The kind of postfix to be scanned. // Possible values: // null: This is a regular date word // "MMMM": month postfix // // //////////////////////////////////////////////////////////////////////////// internal int AddDateWords(String pattern, int index, String formatPostfix) { // Skip any whitespaces so we will start from a letter. int newIndex = SkipWhiteSpacesAndNonLetter(pattern, index); if (newIndex != index && formatPostfix != null) { // There are whitespaces. This will not be a postfix. formatPostfix = null; } index = newIndex; // This is the first char added into dateWord. // Skip all non-letter character. We will add the first letter into DateWord. StringBuilder dateWord = new StringBuilder(); // We assume that date words should start with a letter. // Skip anything until we see a letter. while (index < pattern.Length) { char ch = pattern[index]; if (ch == '\'') { // We have seen the end of quote. Add the word if we do not see it before, // and break the while loop. AddDateWordOrPostfix(formatPostfix, dateWord.ToString()); index++; break; } else if (ch == '\\') { // // Escaped character. Look ahead one character // // Skip escaped backslash. index++; if (index < pattern.Length) { dateWord.Append(pattern[index]); index++; } } else if (Char.IsWhiteSpace(ch)) { // Found a whitespace. We have to add the current date word/postfix. AddDateWordOrPostfix(formatPostfix, dateWord.ToString()); if (formatPostfix != null) { // Done with postfix. The rest will be regular date word. formatPostfix = null; } // Reset the dateWord. dateWord.Length = 0; index++; } else { dateWord.Append(ch); index++; } } return (index); } //////////////////////////////////////////////////////////////////////////// // // A simple helper to find the repeat count for a specified char. // //////////////////////////////////////////////////////////////////////////// internal static int ScanRepeatChar(String pattern, char ch, int index, out int count) { count = 1; while (++index < pattern.Length && pattern[index] == ch) { count++; } // Return the updated position. return (index); } //////////////////////////////////////////////////////////////////////////// // // Add the text that is a date separator but is treated like ignroable symbol. // E.g. // hu-HU has: // shrot date pattern: yyyy. MM. dd.;yyyy-MM-dd;yy-MM-dd // long date pattern: yyyy. MMMM d. // Here, "." is the date separator (derived from short date pattern). However, // "." also appear at the end of long date pattern. In this case, we just // "." as ignorable symbol so that the DateTime.Parse() state machine will not // treat the additional date separator at the end of y,m,d pattern as an error // condition. // //////////////////////////////////////////////////////////////////////////// internal void AddIgnorableSymbols(String text) { if (m_dateWords == null) { // Create the date word array. m_dateWords = new List<String>(); } // Add the ingorable symbol into the ArrayList. String temp = IgnorableSymbolChar + text; if (!m_dateWords.Contains(temp)) { m_dateWords.Add(temp); } } // // Flag used to trace the date patterns (yy/yyyyy/M/MM/MMM/MMM/d/dd) that we have seen. // enum FoundDatePattern { None = 0x0000, FoundYearPatternFlag = 0x0001, FoundMonthPatternFlag = 0x0002, FoundDayPatternFlag = 0x0004, FoundYMDPatternFlag = 0x0007, // FoundYearPatternFlag | FoundMonthPatternFlag | FoundDayPatternFlag; } // Check if we have found all of the year/month/day pattern. FoundDatePattern m_ymdFlags = FoundDatePattern.None; //////////////////////////////////////////////////////////////////////////// // // Given a date format pattern, scan for date word or postfix. // // A date word should be always put in a single quoted string. And it will // start from a letter, so whitespace and symbols will be ignored before // the first letter. // // Examples of date word: // 'de' in es-SP: dddd, dd' de 'MMMM' de 'yyyy // "\x0443." in bg-BG: dd.M.yyyy '\x0433.' // // Example of postfix: // month postfix: // "ta" in fi-FI: d. MMMM'ta 'yyyy // Currently, only month postfix is supported. // // Usage: // Always call this with Framework-style pattern, instead of Windows style pattern. // Windows style pattern uses '' for single quote, while .NET uses \' // //////////////////////////////////////////////////////////////////////////// internal void ScanDateWord(String pattern) { // Check if we have found all of the year/month/day pattern. m_ymdFlags = FoundDatePattern.None; int i = 0; while (i < pattern.Length) { char ch = pattern[i]; int chCount; switch (ch) { case '\'': // Find a beginning quote. Search until the end quote. i = AddDateWords(pattern, i+1, null); break; case 'M': i = ScanRepeatChar(pattern, 'M', i, out chCount); if (chCount >= 4) { if (i < pattern.Length && pattern[i] == '\'') { i = AddDateWords(pattern, i+1, "MMMM"); } } m_ymdFlags |= FoundDatePattern.FoundMonthPatternFlag; break; case 'y': i = ScanRepeatChar(pattern, 'y', i, out chCount); m_ymdFlags |= FoundDatePattern.FoundYearPatternFlag; break; case 'd': i = ScanRepeatChar(pattern, 'd', i, out chCount); if (chCount <= 2) { // Only count "d" & "dd". // ddd, dddd are day names. Do not count them. m_ymdFlags |= FoundDatePattern.FoundDayPatternFlag; } break; case '\\': // Found a escaped char not in a quoted string. Skip the current backslash // and its next character. i += 2; break; case '.': if (m_ymdFlags == FoundDatePattern.FoundYMDPatternFlag) { // If we find a dot immediately after the we have seen all of the y, m, d pattern. // treat it as a ignroable symbol. Check for comments in AddIgnorableSymbols for // more details. AddIgnorableSymbols("."); m_ymdFlags = FoundDatePattern.None; } i++; break; default: if (m_ymdFlags == FoundDatePattern.FoundYMDPatternFlag && !Char.IsWhiteSpace(ch)) { // We are not seeing "." after YMD. Clear the flag. m_ymdFlags = FoundDatePattern.None; } // We are not in quote. Skip the current character. i++; break; } } } //////////////////////////////////////////////////////////////////////////// // // Given a DTFI, get all of the date words from date patterns and time patterns. // //////////////////////////////////////////////////////////////////////////// #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif internal String[] GetDateWordsOfDTFI(DateTimeFormatInfo dtfi) { // Enumarate all LongDatePatterns, and get the DateWords and scan for month postfix. String[] datePatterns = dtfi.GetAllDateTimePatterns('D'); int i; // Scan the long date patterns for (i = 0; i < datePatterns.Length; i++) { ScanDateWord(datePatterns[i]); } // Scan the short date patterns datePatterns = dtfi.GetAllDateTimePatterns('d'); for (i = 0; i < datePatterns.Length; i++) { ScanDateWord(datePatterns[i]); } // Scan the YearMonth patterns. datePatterns = dtfi.GetAllDateTimePatterns('y'); for (i = 0; i < datePatterns.Length; i++) { ScanDateWord(datePatterns[i]); } // Scan the month/day pattern ScanDateWord(dtfi.MonthDayPattern); // Scan the long time patterns. datePatterns = dtfi.GetAllDateTimePatterns('T'); for (i = 0; i < datePatterns.Length; i++) { ScanDateWord(datePatterns[i]); } // Scan the short time patterns. datePatterns = dtfi.GetAllDateTimePatterns('t'); for (i = 0; i < datePatterns.Length; i++) { ScanDateWord(datePatterns[i]); } String[] result = null; if (m_dateWords != null && m_dateWords.Count > 0) { result = new String[m_dateWords.Count]; for (i = 0; i < m_dateWords.Count; i++) { result[i] = m_dateWords[i]; } } return (result); } #if ADDITIONAL_DTFI_SCANNER_METHODS //////////////////////////////////////////////////////////////////////////// // // Reset the date word ArrayList // //////////////////////////////////////////////////////////////////////////// internal void Reset() { m_dateWords.RemoveRange(0, m_dateWords.Count); } #endif //////////////////////////////////////////////////////////////////////////// // // Scan the month names to see if genitive month names are used, and return // the format flag. // //////////////////////////////////////////////////////////////////////////// internal static FORMATFLAGS GetFormatFlagGenitiveMonth(String[] monthNames, String[] genitveMonthNames, String[] abbrevMonthNames, String[] genetiveAbbrevMonthNames) { // If we have different names in regular and genitive month names, use genitive month flag. return ((!EqualStringArrays(monthNames, genitveMonthNames) || !EqualStringArrays(abbrevMonthNames, genetiveAbbrevMonthNames)) ? FORMATFLAGS.UseGenitiveMonth: 0); } //////////////////////////////////////////////////////////////////////////// // // Scan the month names to see if spaces are used or start with a digit, and return the format flag // //////////////////////////////////////////////////////////////////////////// internal static FORMATFLAGS GetFormatFlagUseSpaceInMonthNames(String[] monthNames, String[] genitveMonthNames, String[] abbrevMonthNames, String[] genetiveAbbrevMonthNames) { FORMATFLAGS formatFlags = 0; formatFlags |= (ArrayElementsBeginWithDigit(monthNames) || ArrayElementsBeginWithDigit(genitveMonthNames) || ArrayElementsBeginWithDigit(abbrevMonthNames) || ArrayElementsBeginWithDigit(genetiveAbbrevMonthNames) ? FORMATFLAGS.UseDigitPrefixInTokens : 0); formatFlags |= (ArrayElementsHaveSpace(monthNames) || ArrayElementsHaveSpace(genitveMonthNames) || ArrayElementsHaveSpace(abbrevMonthNames) || ArrayElementsHaveSpace(genetiveAbbrevMonthNames) ? FORMATFLAGS.UseSpacesInMonthNames : 0); return (formatFlags); } //////////////////////////////////////////////////////////////////////////// // // Scan the day names and set the correct format flag. // //////////////////////////////////////////////////////////////////////////// internal static FORMATFLAGS GetFormatFlagUseSpaceInDayNames(String[] dayNames, String[] abbrevDayNames) { return ((ArrayElementsHaveSpace(dayNames) || ArrayElementsHaveSpace(abbrevDayNames)) ? FORMATFLAGS.UseSpacesInDayNames : 0); } //////////////////////////////////////////////////////////////////////////// // // Check the calendar to see if it is HebrewCalendar and set the Hebrew format flag if necessary. // //////////////////////////////////////////////////////////////////////////// internal static FORMATFLAGS GetFormatFlagUseHebrewCalendar(int calID) { return (calID == (int)CalendarId.HEBREW ? FORMATFLAGS.UseHebrewParsing | FORMATFLAGS.UseLeapYearMonth : 0); } //----------------------------------------------------------------------------- // EqualStringArrays // compares two string arrays and return true if all elements of the first // array equals to all elmentsof the second array. // otherwise it returns false. //----------------------------------------------------------------------------- private static bool EqualStringArrays(string [] array1, string [] array2) { // Shortcut if they're the same array if (array1 == array2) { return true; } // This is effectively impossible if (array1.Length != array2.Length) { return false; } // Check each string for (int i=0; i<array1.Length; i++) { if (!array1[i].Equals(array2[i])) { return false; } } return true; } //----------------------------------------------------------------------------- // ArrayElementsHaveSpace // It checks all input array elements if any of them has space character // returns true if found space character in one of the array elements. // otherwise returns false. //----------------------------------------------------------------------------- private static bool ArrayElementsHaveSpace(string [] array) { for (int i=0; i<array.Length; i++) { // it is faster to check for space character manually instead of calling IndexOf // so we don't have to go to native code side. for (int j=0; j<array[i].Length; j++) { if ( Char.IsWhiteSpace(array[i][j]) ) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////// // // Check if any element of the array start with a digit. // //////////////////////////////////////////////////////////////////////////// private static bool ArrayElementsBeginWithDigit(string [] array) { for (int i=0; i<array.Length; i++) { // it is faster to check for space character manually instead of calling IndexOf // so we don't have to go to native code side. if (array[i].Length > 0 && array[i][0] >= '0' && array[i][0] <= '9') { int index = 1; while (index < array[i].Length && array[i][index] >= '0' && array[i][index] <= '9') { // Skip other digits. index++; } if (index == array[i].Length) { return (false); } if (index == array[i].Length - 1) { // Skip known CJK month suffix. // CJK uses month name like "1\x6708", since \x6708 is a known month suffix, // we don't need the UseDigitPrefixInTokens since it is slower. switch (array[i][index]) { case '\x6708': // CJKMonthSuff case '\xc6d4': // KoreanMonthSuff return (false); } } if (index == array[i].Length - 4) { // Skip known CJK month suffix. // Starting with Windows 8, the CJK months for some cultures looks like: "1' \x6708'" // instead of just "1\x6708" if(array[i][index] == '\'' && array[i][index + 1] == ' ' && array[i][index + 2] == '\x6708' && array[i][index + 3] == '\'') { return (false); } } return (true); } } return false; } } }
using System; using DynamicRest.Xml; using Machine.Specifications; namespace DynamicRest.UnitTests.Xml { [Subject(typeof(StandardResultBuilder))] public class When_a_response_contains_a_collection { static StandardResultBuilder _resultBuilder; static dynamic _response; Establish context = () => { _resultBuilder = new StandardResultBuilder(RestService.Xml); }; Because the_response_is_created = () => { _response = _resultBuilder.CreateResult(_xml); }; It should_contain_the_media_0_url = () => (_response.item.media[0].url as string).ShouldEqual("http://media0url"); It should_contain_the_media_1_url = () => (_response.item.media[1].url as string).ShouldEqual("http://media1url"); It should_contain_the_image_0_url = () => (_response.item.images.image[0].src as string).ShouldEqual("http://image0url"); It should_contain_the_image_1_url = () => (_response.item.images.image[1].src as string).ShouldEqual("http://image1url"); It should_contain_the_link_using_array_access = () => (_response.item.link[0].Value as string).ShouldEqual("http://www.bbc.co.uk/go/rss/int/news/-/news/world-africa-12673956"); It should_contain_the_attachment_title = () => (_response.item.attachments.attachment[0].title.Value as string).ShouldEqual("this is the title"); It should_contain_the_numbers_of_attachments = () => ((int)_response.item.attachments.Count).ShouldEqual(1); It should_contain_the_pubdate = () => ((DateTime)_response.item.pubDate).ShouldEqual(new DateTime(2011, 3, 8, 11, 21, 16)); It should_work_when_a_refence_is_used_as_an_array = () => { var linkAsArray = _response.item.link; ((string)linkAsArray[0].Value).ShouldEqual("http://www.bbc.co.uk/go/rss/int/news/-/news/world-africa-12673956"); }; static string _xml = @" <news> <item> <title>Gaddafi renews attack on rebels</title> <version>5</version> <description>Forces loyal to Libyan leader Col Muammar Gaddafi launch fresh air strikes on the rebel-held Ras Lanuf, as they try to retake the oil-rich town.</description> <link>http://www.bbc.co.uk/go/rss/int/news/-/news/world-africa-12673956</link> <link>http://www.bbc.co.uk/go/rss/int/news/-/news/world-africa-12673956</link> <guid>http://www.bbc.co.uk/news/world-africa-12673956</guid> <pubDate>Tue, 08 Mar 2011 11:21:16 GMT</pubDate> <media url=""http://media0url""/> <media url=""http://media1url""/> <images> <image src=""http://image0url"" /> <image src=""http://image1url"" /> </images> <attachments> <attachment> <title>this is the title</title> </attachment> </attachments> </item> </news>"; } [Subject(typeof(XmlNode))] public class When_accessing_a_non_existing_element { static StandardResultBuilder _resultBuilder; static dynamic _response; Establish context = () => { _resultBuilder = new StandardResultBuilder(RestService.Xml); _response = _resultBuilder.CreateResult(_xml); }; private Because the_response_is_created = () => _thrownException = Catch.Exception(() => { var junk = _response.item.desc; }); It should_work_when_a_refence_is_used_as_an_array = () => _thrownException.Message.ShouldEqual("No element or attribute named 'desc' found in the response."); static string _xml = @" <news> <item> <title>Gaddafi renews attack on rebels</title> <description>Forces loyal to Libyan leader Col Muammar Gaddafi launch fresh air strikes on the rebel-held Ras Lanuf, as they try to retake the oil-rich town.</description> <link>http://www.bbc.co.uk/go/rss/int/news/-/news/world-africa-12673956</link> <link>http://www.bbc.co.uk/go/rss/int/news/-/news/world-africa-12673956</link> <guid>http://www.bbc.co.uk/news/world-africa-12673956</guid> <pubDate>Tue, 08 Mar 2011 11:21:16 GMT</pubDate> <media url=""http://media0url""/> <media url=""http://media1url""/> <images> <image src=""http://image0url"" /> <image src=""http://image1url"" /> </images> <attachments> <attachment> <title>this is the title</title> </attachment> </attachments> </item> </news>"; private static Exception _thrownException; } namespace When_casting_strings_to_datetimes { [Subject(typeof(XmlString))] public class When_a_string_is_a_valid_date { Establish context = () => The_string = new XmlString("2011-03-08T11:21:16Z"); Because we_parse_as_a_date = () => The_result = (DateTime)The_string; It should_have_the_expected_value = () => The_result.ShouldEqual(new DateTime(2011, 3, 8, 11, 21, 16)); private static XmlString The_string; private static DateTime The_result; } [Subject(typeof(XmlString))] public class When_parsing_fails { Establish context = () => The_string = new XmlString("I am not a valid string"); Because we_parse_as_a_date = () => The_result = Catch.Exception(() => Console.Write((DateTime)The_string)); private It should_have_the_expected_value = () => The_result.ShouldBeAssignableTo<FormatException>(); private static XmlString The_string; private static Exception The_result; } } namespace When_casting_strings_to_integers { [Subject(typeof(XmlString))] public class When_a_string_is_a_valid_int { Establish context = () => The_string = new XmlString("8787645"); Because we_parse_as_an_int = () => The_result = (int)The_string; It should_have_the_expected_value = () => The_result.ShouldEqual(8787645); private static XmlString The_string; private static int The_result; } [Subject(typeof(XmlString))] public class When_a_string_is_an_overflow { Establish context = () => The_string = new XmlString( (((long)int.MaxValue) + 1).ToString()); Because we_parse_as_an_int = () => The_result = Catch.Exception(() => Console.Write((int)The_string)); private It should_have_the_expected_value = () => The_result.ShouldBeAssignableTo<OverflowException>(); private static XmlString The_string; private static Exception The_result; } [Subject(typeof(XmlString))] public class When_parsing_fails { Establish context = () => The_string = new XmlString("I am not a valid string"); Because we_parse_as_an_int= () => The_result = Catch.Exception(() => Console.Write((int)The_string)); private It should_have_the_expected_value = () => The_result.ShouldBeAssignableTo<FormatException>(); private static XmlString The_string; private static Exception The_result; } } namespace When_casting_strings_to_longs { [Subject(typeof(XmlString))] public class When_a_string_is_a_valid_long { Establish context = () => The_string = new XmlString("8787645"); Because we_parse_as_a_long = () => The_result = (long)The_string; It should_have_the_expected_value = () => The_result.ShouldEqual(8787645); private static XmlString The_string; private static long The_result; } [Subject(typeof(XmlString))] public class When_a_string_is_an_overflow { Establish context = () => The_string = new XmlString((long.MaxValue)+"1"); Because we_parse_as_a_long = () => The_result = Catch.Exception(() => Console.Write((long)The_string)); private It should_have_the_expected_value = () => The_result.ShouldBeAssignableTo<OverflowException>(); private static XmlString The_string; private static Exception The_result; } [Subject(typeof(XmlString))] public class When_parsing_fails { Establish context = () => The_string = new XmlString("I am not a valid string"); Because we_parse_as_a_long = () => The_result = Catch.Exception(() => Console.Write((long)The_string)); private It should_have_the_expected_value = () => The_result.ShouldBeAssignableTo<FormatException>(); private static XmlString The_string; private static Exception The_result; } } namespace When_casting_strings_to_bools { public class When_parsing_the_empty_string { Because we_parse_string_empty = () => Result = Catch.Exception(() => Console.Write((bool) new XmlString(string.Empty))); It should_throw_format_exception = () => Result.ShouldBeAssignableTo<FormatException>(); protected static Exception Result { get; set; } } public class When_parsing_the_zero_string { Because we_parse_string_empty = () => Result = (bool) new XmlString("0"); It should_be_false = () => Result.ShouldBeFalse(); protected static bool Result { get; set; } } public class When_parsing_negative_one { Because we_parse_string_empty = () => Result = (bool)new XmlString("-1"); It should_be_false = () => Result.ShouldBeFalse(); protected static bool Result { get; set; } } public class When_parsing_one { Because we_parse_string_empty = () => Result = (bool)new XmlString("1"); It should_be_false = () => Result.ShouldBeTrue(); protected static bool Result { get; set; } } public class When_parsing_true { Because we_parse_string_empty = () => Result = (bool)new XmlString("true"); It should_be_false = () => Result.ShouldBeTrue(); protected static bool Result { get; set; } } public class When_parsing_false { Because we_parse_string_empty = () => Result = (bool)new XmlString("false"); It should_be_false = () => Result.ShouldBeFalse(); protected static bool Result { get; set; } } public class When_parsing_weird_casing { Because we_parse_string_empty = () => Result = (bool)new XmlString("tRUe"); It should_be_false = () => Result.ShouldBeTrue(); protected static bool Result { get; set; } } } }
/* * REST API Documentation for the MOTI School Bus Application * * The School Bus application tracks that inspections are performed in a timely fashion. For each school bus the application tracks information about the bus (including data from ICBC, NSC, etc.), it's past and next inspection dates and results, contacts, and the inspector responsible for next inspecting the bus. * * OpenAPI spec version: v1 * * */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using System.ComponentModel.DataAnnotations.Schema; namespace SchoolBusAPI.Models { /// <summary> /// /// </summary> public partial class ServiceArea : IEquatable<ServiceArea> { /// <summary> /// Default constructor, required by entity framework /// </summary> public ServiceArea() { this.Id = 0; } /// <summary> /// Initializes a new instance of the <see cref="ServiceArea" /> class. /// </summary> /// <param name="Id">Primary Key (required).</param> /// <param name="MinistryServiceAreaID">The Ministry ID for the Service Area.</param> /// <param name="Name">The name of the Service Area.</param> /// <param name="District">The district in which the Service Area is found..</param> /// <param name="StartDate">The effective date of the Service Area - NOT CURRENTLY ENFORCED IN SCHOOL BUS.</param> /// <param name="EndDate">The end date of the Service Area; null if active - NOT CURRENTLY ENFORCED IN SCHOOL BUS.</param> public ServiceArea(int Id, int? MinistryServiceAreaID = null, string Name = null, District District = null, DateTime? StartDate = null, DateTime? EndDate = null) { this.Id = Id; this.MinistryServiceAreaID = MinistryServiceAreaID; this.Name = Name; this.District = District; this.StartDate = StartDate; this.EndDate = EndDate; } /// <summary> /// Primary Key /// </summary> /// <value>Primary Key</value> [MetaDataExtension (Description = "Primary Key")] public int Id { get; set; } /// <summary> /// The Ministry ID for the Service Area /// </summary> /// <value>The Ministry ID for the Service Area</value> [MetaDataExtension (Description = "The Ministry ID for the Service Area")] public int? MinistryServiceAreaID { get; set; } /// <summary> /// The name of the Service Area /// </summary> /// <value>The name of the Service Area</value> [MetaDataExtension (Description = "The name of the Service Area")] public string Name { get; set; } /// <summary> /// The district in which the Service Area is found. /// </summary> /// <value>The district in which the Service Area is found.</value> [MetaDataExtension (Description = "The district in which the Service Area is found.")] public District District { get; set; } /// <summary> /// The effective date of the Service Area - NOT CURRENTLY ENFORCED IN SCHOOL BUS /// </summary> /// <value>The effective date of the Service Area - NOT CURRENTLY ENFORCED IN SCHOOL BUS</value> [MetaDataExtension (Description = "The effective date of the Service Area - NOT CURRENTLY ENFORCED IN SCHOOL BUS")] public DateTime? StartDate { get; set; } /// <summary> /// The end date of the Service Area; null if active - NOT CURRENTLY ENFORCED IN SCHOOL BUS /// </summary> /// <value>The end date of the Service Area; null if active - NOT CURRENTLY ENFORCED IN SCHOOL BUS</value> [MetaDataExtension (Description = "The end date of the Service Area; null if active - NOT CURRENTLY ENFORCED IN SCHOOL BUS")] public DateTime? EndDate { 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 ServiceArea {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" MinistryServiceAreaID: ").Append(MinistryServiceAreaID).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" District: ").Append(District).Append("\n"); sb.Append(" StartDate: ").Append(StartDate).Append("\n"); sb.Append(" EndDate: ").Append(EndDate).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((ServiceArea)obj); } /// <summary> /// Returns true if ServiceArea instances are equal /// </summary> /// <param name="other">Instance of ServiceArea to be compared</param> /// <returns>Boolean</returns> public bool Equals(ServiceArea other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } return ( this.Id == other.Id || this.Id.Equals(other.Id) ) && ( this.MinistryServiceAreaID == other.MinistryServiceAreaID || this.MinistryServiceAreaID != null && this.MinistryServiceAreaID.Equals(other.MinistryServiceAreaID) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.District == other.District || this.District != null && this.District.Equals(other.District) ) && ( this.StartDate == other.StartDate || this.StartDate != null && this.StartDate.Equals(other.StartDate) ) && ( this.EndDate == other.EndDate || this.EndDate != null && this.EndDate.Equals(other.EndDate) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks hash = hash * 59 + this.Id.GetHashCode(); if (this.MinistryServiceAreaID != null) { hash = hash * 59 + this.MinistryServiceAreaID.GetHashCode(); } if (this.Name != null) { hash = hash * 59 + this.Name.GetHashCode(); } if (this.District != null) { hash = hash * 59 + this.District.GetHashCode(); } if (this.StartDate != null) { hash = hash * 59 + this.StartDate.GetHashCode(); } if (this.EndDate != null) { hash = hash * 59 + this.EndDate.GetHashCode(); } return hash; } } #region Operators public static bool operator ==(ServiceArea left, ServiceArea right) { return Equals(left, right); } public static bool operator !=(ServiceArea left, ServiceArea right) { return !Equals(left, right); } #endregion Operators } }
// // Copyright 2012 Hakan Kjellerstrand // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using Google.OrTools.ConstraintSolver; public class EinavPuzzle2 { /** * * A programming puzzle from Einav. * * From * "A programming puzzle from Einav" * http://gcanyon.wordpress.com/2009/10/28/a-programming-puzzle-from-einav/ * """ * My friend Einav gave me this programming puzzle to work on. Given * this array of positive and negative numbers: * 33 30 -10 -6 18 7 -11 -23 6 * ... * -25 4 16 30 33 -23 -4 4 -23 * * You can flip the sign of entire rows and columns, as many of them * as you like. The goal is to make all the rows and columns sum to positive * numbers (or zero), and then to find the solution (there are more than one) * that has the smallest overall sum. So for example, for this array: * 33 30 -10 * -16 19 9 * -17 -12 -14 * You could flip the sign for the bottom row to get this array: * 33 30 -10 * -16 19 9 * 17 12 14 * Now all the rows and columns have positive sums, and the overall total is * 108. * But you could instead flip the second and third columns, and the second * row, to get this array: * 33 -30 10 * 16 19 9 * -17 12 14 * All the rows and columns still total positive, and the overall sum is just * 66. So this solution is better (I don't know if it's the best) * A pure brute force solution would have to try over 30 billion solutions. * I wrote code to solve this in J. I'll post that separately. * """ * * Note: * This is a port of Larent Perrons's Python version of my own einav_puzzle.py. * He removed some of the decision variables and made it more efficient. * Thanks! * * Also see http://www.hakank.org/or-tools/einav_puzzle2.py * */ private static void Solve() { Solver solver = new Solver("EinavPuzzle2"); // // Data // // Small problem // int rows = 3; // int cols = 3; // int[,] data = { // { 33, 30, -10}, // {-16, 19, 9}, // {-17, -12, -14} // }; // Full problem int rows = 27; int cols = 9; int[,] data = { {33,30,10,-6,18,-7,-11,23,-6}, {16,-19,9,-26,-8,-19,-8,-21,-14}, {17,12,-14,31,-30,13,-13,19,16}, {-6,-11,1,17,-12,-4,-7,14,-21}, {18,-31,34,-22,17,-19,20,24,6}, {33,-18,17,-15,31,-5,3,27,-3}, {-18,-20,-18,31,6,4,-2,-12,24}, {27,14,4,-29,-3,5,-29,8,-12}, {-15,-7,-23,23,-9,-8,6,8,-12}, {33,-23,-19,-4,-8,-7,11,-12,31}, {-20,19,-15,-30,11,32,7,14,-5}, {-23,18,-32,-2,-31,-7,8,24,16}, {32,-4,-10,-14,-6,-1,0,23,23}, {25,0,-23,22,12,28,-27,15,4}, {-30,-13,-16,-3,-3,-32,-3,27,-31}, {22,1,26,4,-2,-13,26,17,14}, {-9,-18,3,-20,-27,-32,-11,27,13}, {-17,33,-7,19,-32,13,-31,-2,-24}, {-31,27,-31,-29,15,2,29,-15,33}, {-18,-23,15,28,0,30,-4,12,-32}, {-3,34,27,-25,-18,26,1,34,26}, {-21,-31,-10,-13,-30,-17,-12,-26,31}, {23,-31,-19,21,-17,-10,2,-23,23}, {-3,6,0,-3,-32,0,-10,-25,14}, {-19,9,14,-27,20,15,-5,-27,18}, {11,-6,24,7,-17,26,20,-31,-25}, {-25,4,-16,30,33,23,-4,-4,23} }; IEnumerable<int> ROWS = Enumerable.Range(0, rows); IEnumerable<int> COLS = Enumerable.Range(0, cols); // // Decision variables // IntVar[,] x = solver.MakeIntVarMatrix(rows, cols, -100, 100, "x"); IntVar[] x_flat = x.Flatten(); int[] signs_domain = {-1,1}; // This don't work at the moment... IntVar[] row_signs = solver.MakeIntVarArray(rows, signs_domain, "row_signs"); IntVar[] col_signs = solver.MakeIntVarArray(cols, signs_domain, "col_signs"); // To optimize IntVar total_sum = x_flat.Sum().VarWithName("total_sum"); // // Constraints // foreach(int i in ROWS) { foreach(int j in COLS) { solver.Add(x[i,j] == data[i,j] * row_signs[i] * col_signs[j]); } } // row sums IntVar[] row_sums = (from i in ROWS select (from j in COLS select x[i,j] ).ToArray().Sum().Var()).ToArray(); foreach(int i in ROWS) { row_sums[i].SetMin(0); } // col sums IntVar[] col_sums = (from j in COLS select (from i in ROWS select x[i,j] ).ToArray().Sum().Var()).ToArray(); foreach(int j in COLS) { col_sums[j].SetMin(0); } // // Objective // OptimizeVar obj = total_sum.Minimize(1); // // Search // DecisionBuilder db = solver.MakePhase(col_signs.Concat(row_signs).ToArray(), Solver.CHOOSE_MIN_SIZE_LOWEST_MIN, Solver.ASSIGN_MAX_VALUE); solver.NewSearch(db, obj); while (solver.NextSolution()) { Console.WriteLine("Sum: {0}",total_sum.Value()); Console.Write("row_sums: "); foreach(int i in ROWS) { Console.Write(row_sums[i].Value() + " "); } Console.Write("\nrow_signs: "); foreach(int i in ROWS) { Console.Write(row_signs[i].Value() + " "); } Console.Write("\ncol_sums: "); foreach(int j in COLS) { Console.Write(col_sums[j].Value() + " "); } Console.Write("\ncol_signs: "); foreach(int j in COLS) { Console.Write(col_signs[j].Value() + " "); } Console.WriteLine("\n"); foreach(int i in ROWS) { foreach(int j in COLS) { Console.Write("{0,3} ", x[i,j].Value()); } Console.WriteLine(); } Console.WriteLine(); } Console.WriteLine("\nSolutions: {0}", solver.Solutions()); Console.WriteLine("WallTime: {0}ms", solver.WallTime()); Console.WriteLine("Failures: {0}", solver.Failures()); Console.WriteLine("Branches: {0} ", solver.Branches()); solver.EndSearch(); } public static void Main(String[] args) { Solve(); } }
/* * Copyright 2004 - $Date: 2008-11-15 23:58:07 +0100 (za, 15 nov 2008) $ by PeopleWare n.v.. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #region Using using System; using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Net; #endregion namespace PPWCode.Util.SharePoint.I { /// <summary> /// Wrapper around selected remote Sharepoint /// functionality and added functionality. /// </summary> [ContractClass(typeof(ISharePointClientContract))] public interface ISharePointClient { /// <summary> /// Property that holds the base URL of the SharePoint /// site this instance will work on. /// </summary> string SharePointSiteUrl { get; set; } /// <summary> /// Optional credentials for authentication /// </summary> ICredentials Credentials { get; set; } /// <summary> /// Ensure the folder whose name is given /// with a <paramref name="relativeUrl"/> /// exists. /// </summary> /// <remarks> /// <para>If the folder exists, nothing happens.</para> /// <para>Else, it and all intermediate missing folders, /// are created.</para> /// </remarks> /// <param name="relativeUrl">The URL of a folder in a SharePoint document library, /// relative to <see cref="SharePointSiteUrl"/>.</param> void EnsureFolder(string relativeUrl); SharePointDocument DownloadDocument(string relativeUrl); void UploadDocument(string relativeUrl, SharePointDocument doc); /// <summary> /// Validate existence of specified Uri /// </summary> bool ValidateUri(Uri sharePointUri); /// <summary> /// Open specified uri in default web browser /// MUDO: Move this method to other assembly? /// </summary> void OpenUri(Uri uri); /// <summary> /// Return files found at specified url /// </summary> List<SharePointSearchResult> SearchFiles(string url); void RenameFolder(string baseRelativeUrl, string originalFolderName, string newFolderName); void RenameAllOccurrencesOfFolder(string baseRelativeUrl, string oldFolderName, string newFolderName); /// <summary> /// Create folder with given path. /// <para> /// Depending on the parameter "createFullPath", also create all intermediate missing folders, /// or otherwise, throw an exception if any of the intermediate folders is missing. /// </para> /// </summary> /// <param name="folderPath">path of folder to be created</param> /// <param name="createFullPath">create all intermediate missing folders</param> void CreateFolder(string folderPath, bool createFullPath); /// <summary> /// Delete folder with given path. /// <para> /// Depending on the parameter "deleteChildren", also delete all children if any exist, /// or otherwise, throw an exception if any children exist. /// </para> /// </summary> /// <param name="folderPath">path of folder to be deleted</param> /// <param name="deleteChildren">delete all children of folder if any exist</param> void DeleteFolder(string folderPath, bool deleteChildren); int CountAllOccurencesOfFolderInPath(string baseRelativeUrl, string folderName); bool CheckExistenceOfFolderWithExactPath(string folderPath); } // ReSharper disable InconsistentNaming /// <exclude /> [ContractClassFor(typeof(ISharePointClient))] public abstract class ISharePointClientContract : ISharePointClient { #region ISharePointClient Members public string SharePointSiteUrl { get { return default(string); } set { //NOP; } } public ICredentials Credentials { get { return default(ICredentials); } set { // NOP; } } /// <summary> /// Create all folder in the given folder path, that do not yet exist in SharePoint. /// </summary> /// <param name="relativeUrl">the folder path </param> public void EnsureFolder(string relativeUrl) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(relativeUrl)); Contract.Requires(!relativeUrl.StartsWith(SharePointSiteUrl)); } public SharePointDocument DownloadDocument(string relativeUrl) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(relativeUrl)); Contract.Requires(!relativeUrl.StartsWith(SharePointSiteUrl)); return default(SharePointDocument); } public void UploadDocument(string relativeUrl, SharePointDocument doc) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(relativeUrl != null); Contract.Requires(!relativeUrl.StartsWith(SharePointSiteUrl)); Contract.Requires(doc != null); } public bool ValidateUri(Uri sharePointUri) { Contract.Requires(sharePointUri != null); Contract.Requires(sharePointUri.OriginalString.StartsWith(SharePointSiteUrl)); return default(bool); } public void OpenUri(Uri uri) { Contract.Requires(uri != null); } public List<SharePointSearchResult> SearchFiles(string url) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(url != null); return new List<SharePointSearchResult>(); } /// <summary> /// Rename the folder in the given base path that has the given name. /// </summary> /// <param name="baseRelativeUrl">base folder</param> /// <param name="originalFolderName">folder in base path that has to be renamed</param> /// <param name="newFolderName">new name of the folder</param> public void RenameFolder(string baseRelativeUrl, string originalFolderName, string newFolderName) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(originalFolderName)); Contract.Requires(!string.IsNullOrEmpty(newFolderName)); } /// <summary> /// Rename all folders within the given base path, that have the given name. /// </summary> /// <param name="baseRelativeUrl">base path</param> /// <param name="oldFolderName">folder that has to be renamed</param> /// <param name="newFolderName">new name of the folder</param> public void RenameAllOccurrencesOfFolder(string baseRelativeUrl, string oldFolderName, string newFolderName) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(baseRelativeUrl)); Contract.Requires(!string.IsNullOrEmpty(oldFolderName)); Contract.Requires(!string.IsNullOrEmpty(newFolderName)); } public void CreateFolder(string folderPath, bool createFullPath) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(folderPath)); } public void DeleteFolder(string folderPath, bool deleteChildren ) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(folderPath)); } /// <summary> /// Search and count the occurrences of folders with the given name in the given path. /// </summary> /// <param name="baseRelativeUrl">path to search</param> /// <param name="folderName">name of folder</param> /// <returns>number of occurrences</returns> public int CountAllOccurencesOfFolderInPath(string baseRelativeUrl, string folderName) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(baseRelativeUrl)); Contract.Requires(!string.IsNullOrEmpty(folderName)); return default(int); } /// <summary> /// Check whether the folder with the given path exists in SharePoint. /// </summary> /// <param name="folderPath">folder path</param> /// <returns></returns> public bool CheckExistenceOfFolderWithExactPath(string folderPath) { Contract.Requires(!string.IsNullOrEmpty(SharePointSiteUrl)); Contract.Requires(!string.IsNullOrEmpty(folderPath)); return default(bool); } #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; using System.IO; using System.Collections.Generic; using System.Linq; using System.Xml; using System.Xml.Linq; using System.Xml.XmlDiff; using CoreXml.Test.XLinq; using Xunit; namespace XDocumentTests.Streaming { public class XStreamingElementAPI { private XDocument _xDoc = null; private XDocument _xmlDoc = null; private XmlDiff _diff; private bool _invokeStatus = false; private bool _invokeError = false; private Stream _sourceStream = null; private Stream _targetStream = null; private void GetFreshStream() { _sourceStream = new MemoryStream(); _targetStream = new MemoryStream(); } private void ResetStreamPos() { if (_sourceStream.CanSeek) { _sourceStream.Position = 0; } if (_targetStream.CanSeek) { _targetStream.Position = 0; } } private XmlDiff Diff { get { return _diff ?? (_diff = new XmlDiff()); } } [Fact] public void XNameAsNullConstructor() { Assert.Throws<ArgumentNullException>(() => new XStreamingElement(null)); } [Fact] public void XNameAsEmptyStringConstructor() { AssertExtensions.Throws<ArgumentException>(null, () => new XStreamingElement(string.Empty)); Assert.Throws<XmlException>(() => new XStreamingElement(" ")); } [Fact] public void XNameConstructor() { XStreamingElement streamElement = new XStreamingElement("contact"); Assert.Equal("<contact />", streamElement.ToString()); } [Fact] public void XNameWithNamespaceConstructor() { XNamespace ns = @"http:\\www.contacts.com\"; XElement contact = new XElement(ns + "contact"); XStreamingElement streamElement = new XStreamingElement(ns + "contact"); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XNameAndNullObjectConstructor() { XStreamingElement streamElement = new XStreamingElement("contact", null); Assert.Equal("<contact />", streamElement.ToString()); } [Fact] public void XNameAndXElementObjectConstructor() { XElement contact = new XElement("contact", new XElement("phone", "925-555-0134")); XStreamingElement streamElement = new XStreamingElement("contact", contact.Element("phone")); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XNameAndEmptyStringConstructor() { XElement contact = new XElement("contact", ""); XStreamingElement streamElement = new XStreamingElement("contact", ""); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XDocTypeInXStreamingElement() { XDocumentType node = new XDocumentType( "DOCTYPE", "note", "SYSTEM", "<!ELEMENT note (to,from,heading,body)><!ELEMENT to (#PCDATA)><!ELEMENT from (#PCDATA)><!ELEMENT heading (#PCDATA)><!ELEMENT body (#PCDATA)>"); XStreamingElement streamElement = new XStreamingElement("Root", node); Assert.Throws<InvalidOperationException>(() => streamElement.Save(new MemoryStream())); } [Fact] public void XmlDeclInXStreamingElement() { XDeclaration node = new XDeclaration("1.0", "utf-8", "yes"); XElement element = new XElement("Root", node); XStreamingElement streamElement = new XStreamingElement("Root", node); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XCDataInXStreamingElement() { XCData node = new XCData("CDATA Text '%^$#@!&*()'"); XElement element = new XElement("Root", node); XStreamingElement streamElement = new XStreamingElement("Root", node); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XCommentInXStreamingElement() { XComment node = new XComment("This is a comment"); XElement element = new XElement("Root", node); XStreamingElement streamElement = new XStreamingElement("Root", node); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XDocInXStreamingElement() { InputSpace.Contacts(ref _xDoc, ref _xmlDoc); XStreamingElement streamElement = new XStreamingElement("Root", _xDoc); Assert.Throws<InvalidOperationException>(() => streamElement.Save(new MemoryStream())); } [Fact] public void XNameAndCollectionObjectConstructor() { XElement contact = new XElement( "contacts", new XElement("contact1", "jane"), new XElement("contact2", "john")); List<object> list = new List<object>(); list.Add(contact.Element("contact1")); list.Add(contact.Element("contact2")); XStreamingElement streamElement = new XStreamingElement("contacts", list); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XNameAndObjectArrayConstructor() { XElement contact = new XElement( "contact", new XElement("name", "jane"), new XElement("phone", new XAttribute("type", "home"), "925-555-0134")); XStreamingElement streamElement = new XStreamingElement( "contact", new object[] { contact.Element("name"), contact.Element("phone") }); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void NamePropertyGet() { XStreamingElement streamElement = new XStreamingElement("contact"); Assert.Equal("contact", streamElement.Name); } [Fact] public void NamePropertySet() { XStreamingElement streamElement = new XStreamingElement("ThisWillChangeToContact"); streamElement.Name = "contact"; Assert.Equal("contact", streamElement.Name.ToString()); } [Fact] public void NamePropertySetInvalid() { XStreamingElement streamElement = new XStreamingElement("ThisWillChangeToInValidName"); Assert.Throws<ArgumentNullException>(() => streamElement.Name = null); } [Fact] public void XMLPropertyGet() { XElement contact = new XElement("contact", new XElement("phone", "925-555-0134")); XStreamingElement streamElement = new XStreamingElement("contact", contact.Element("phone")); Assert.Equal(contact.ToString(SaveOptions.None), streamElement.ToString(SaveOptions.None)); } [Fact] public void AddWithNull() { XStreamingElement streamElement = new XStreamingElement("contact"); streamElement.Add(null); Assert.Equal("<contact />", streamElement.ToString()); } [Theory] [InlineData(9255550134)] [InlineData("9255550134")] [InlineData(9255550134.0)] public void AddObject(object content) { XElement contact = new XElement("phone", content); XStreamingElement streamElement = new XStreamingElement("phone"); streamElement.Add(content); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void AddTimeSpanObject() { XElement contact = new XElement("Time", TimeSpan.FromMinutes(12)); XStreamingElement streamElement = new XStreamingElement("Time"); streamElement.Add(TimeSpan.FromMinutes(12)); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void AddAttribute() { XElement contact = new XElement("phone", new XAttribute("type", "home"), "925-555-0134"); XStreamingElement streamElement = new XStreamingElement("phone"); streamElement.Add(contact.Attribute("type")); streamElement.Add("925-555-0134"); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } //An attribute cannot be written after content. [Fact] public void AddAttributeAfterContent() { XElement contact = new XElement("phone", new XAttribute("type", "home"), "925-555-0134"); XStreamingElement streamElement = new XStreamingElement("phone", "925-555-0134"); streamElement.Add(contact.Attribute("type")); using (XmlWriter w = XmlWriter.Create(new MemoryStream(), null)) { Assert.Throws<InvalidOperationException>(() => streamElement.WriteTo(w)); } } [Fact] public void AddIEnumerableOfNulls() { XElement element = new XElement("root", GetNulls()); XStreamingElement streamElement = new XStreamingElement("root"); streamElement.Add(GetNulls()); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } ///<summary> /// This function returns an IEnumeralb of nulls ///</summary> public IEnumerable<XNode> GetNulls() { return Enumerable.Repeat((XNode)null, 1000); } [Fact] public void AddIEnumerableOfXNodes() { XElement x = InputSpace.GetElement(100, 3); XElement element = new XElement("root", x.Nodes()); XStreamingElement streamElement = new XStreamingElement("root"); streamElement.Add(x.Nodes()); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void AddIEnumerableOfMixedNodes() { XElement element = new XElement("root", GetMixedNodes()); XStreamingElement streamElement = new XStreamingElement("root"); streamElement.Add(GetMixedNodes()); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } ///<summary> /// This function returns mixed IEnumerable of XObjects with XAttributes first ///</summary> public IEnumerable<XObject> GetMixedNodes() { InputSpace.Load("Word.xml", ref _xDoc, ref _xmlDoc); foreach (XAttribute x in _xDoc.Root.Attributes()) yield return x; foreach (XNode n in _xDoc.Root.DescendantNodes()) yield return n; } [Fact] public void AddIEnumerableOfXNodesPlusString() { InputSpace.Contacts(ref _xDoc, ref _xmlDoc); XElement element = new XElement("contacts", _xDoc.Root.DescendantNodes(), "This String"); XStreamingElement streamElement = new XStreamingElement("contacts"); streamElement.Add(_xDoc.Root.DescendantNodes(), "This String"); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void AddIEnumerableOfXNodesPlusAttribute() { InputSpace.Contacts(ref _xDoc, ref _xmlDoc); XAttribute xAttrib = new XAttribute("Attribute", "Value"); XElement element = new XElement("contacts", xAttrib, _xDoc.Root.DescendantNodes()); XStreamingElement streamElement = new XStreamingElement("contacts"); streamElement.Add(xAttrib, _xDoc.Root.DescendantNodes()); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void SaveWithNull() { XStreamingElement streamElement = new XStreamingElement("phone", "925-555-0134"); Assert.Throws<ArgumentNullException>(() => streamElement.Save((XmlWriter)null)); } [Fact] public void SaveWithXmlTextWriter() { XElement contact = new XElement( "contacts", new XElement("contact", "jane"), new XElement("contact", "john")); XStreamingElement streamElement = new XStreamingElement("contacts", contact.Elements()); GetFreshStream(); TextWriter w = new StreamWriter(_sourceStream); streamElement.Save(w); w.Flush(); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void SaveTwice() { XElement contact = new XElement( "contacts", new XElement("contact", "jane"), new XElement("contact", "john")); XStreamingElement streamElement = new XStreamingElement("contacts", contact.Elements()); GetFreshStream(); streamElement.Save(_sourceStream); _sourceStream.Position = 0; streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void WriteToWithNull() { XStreamingElement streamElement = new XStreamingElement("phone", "925-555-0134"); Assert.Throws<ArgumentNullException>(() => streamElement.WriteTo((XmlWriter)null)); } [Fact] public void ModifyOriginalElement() { XElement contact = new XElement( "contact", new XElement("name", "jane"), new XElement("phone", new XAttribute("type", "home"), "925-555-0134")); XStreamingElement streamElement = new XStreamingElement("contact", new object[] { contact.Elements() }); foreach (XElement x in contact.Elements()) { x.Remove(); } GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void NestedXStreamingElement() { XElement name = new XElement("name", "jane"); XElement phone = new XElement("phone", new XAttribute("type", "home"), "925-555-0134"); XElement contact = new XElement("contact", name, new XElement("phones", phone)); XStreamingElement streamElement = new XStreamingElement( "contact", name, new XStreamingElement("phones", phone)); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void NestedXStreamingElementPlusIEnumerable() { InputSpace.Contacts(ref _xDoc, ref _xmlDoc); XElement element = new XElement("contacts", new XElement("Element", "Value"), _xDoc.Root.DescendantNodes()); XStreamingElement streamElement = new XStreamingElement("contacts"); streamElement.Add(new XStreamingElement("Element", "Value"), _xDoc.Root.DescendantNodes()); GetFreshStream(); streamElement.Save(_sourceStream); element.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void IEnumerableLazinessTest1() { XElement name = new XElement("name", "jane"); XElement phone = new XElement("phone", new XAttribute("type", "home"), "925-555-0134"); XElement contact = new XElement("contact", name, phone); IEnumerable<XElement> elements = contact.Elements(); name.Remove(); phone.Remove(); XStreamingElement streamElement = new XStreamingElement("contact", new object[] { elements }); GetFreshStream(); streamElement.Save(_sourceStream); contact.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void IEnumerableLazinessTest2() { XElement name = new XElement("name", "jane"); XElement phone = new XElement("phone", new XAttribute("type", "home"), "925-555-0134"); XElement contact = new XElement("contact", name, phone); // During debug this test will not work correctly since ToString() of // streamElement gets called for displaying the value in debugger local window. XStreamingElement streamElement = new XStreamingElement("contact", GetElements(contact)); GetFreshStream(); contact.Save(_targetStream); _invokeStatus = true; streamElement.Save(_sourceStream); Assert.False(_invokeError, "IEnumerable walked before expected"); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } ///<summary> /// This function is used in above variation to make sure that the /// IEnumerable is indeed walked lazily ///</summary> public IEnumerable<XElement> GetElements(XElement element) { if (_invokeStatus == false) { _invokeError = true; } foreach (XElement x in element.Elements()) { yield return x; } } [Fact] public void XStreamingElementInXElement() { XElement element = new XElement("contacts"); XStreamingElement streamElement = new XStreamingElement("contact", "SomeValue"); element.Add(streamElement); XElement x = element.Element("contact"); GetFreshStream(); streamElement.Save(_sourceStream); x.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } [Fact] public void XStreamingElementInXDocument() { _xDoc = new XDocument(); XStreamingElement streamElement = new XStreamingElement("contacts", "SomeValue"); _xDoc.Add(streamElement); GetFreshStream(); streamElement.Save(_sourceStream); _xDoc.Save(_targetStream); ResetStreamPos(); Assert.True(Diff.Compare(_sourceStream, _targetStream)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // DefaultIfEmptyQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Threading; using System.Diagnostics; namespace System.Linq.Parallel { /// <summary> /// This operator just exposes elements directly from the underlying data source, if /// it's not empty, or yields a single default element if the data source is empty. /// There is a minimal amount of synchronization at the beginning, until all partitions /// have registered whether their stream is empty or not. Once the 0th partition knows /// that at least one other partition is non-empty, it may proceed. Otherwise, it is /// the 0th partition which yields the default value. /// </summary> /// <typeparam name="TSource"></typeparam> internal sealed class DefaultIfEmptyQueryOperator<TSource> : UnaryQueryOperator<TSource, TSource> { private readonly TSource _defaultValue; // The default value to use (if empty). //--------------------------------------------------------------------------------------- // Initializes a new reverse operator. // // Arguments: // child - the child whose data we will reverse // internal DefaultIfEmptyQueryOperator(IEnumerable<TSource> child, TSource defaultValue) : base(child) { Debug.Assert(child != null, "child data source cannot be null"); _defaultValue = defaultValue; SetOrdinalIndexState(ExchangeUtilities.Worse(Child.OrdinalIndexState, OrdinalIndexState.Correct)); } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping) { // We just open the child operator. QueryResults<TSource> childQueryResults = Child.Open(settings, preferStriping); return new UnaryQueryOperatorResults(childQueryResults, this, settings, preferStriping); } internal override void WrapPartitionedStream<TKey>( PartitionedStream<TSource, TKey> inputStream, IPartitionedStreamRecipient<TSource> recipient, bool preferStriping, QuerySettings settings) { int partitionCount = inputStream.PartitionCount; // Generate the shared data. Shared<int> sharedEmptyCount = new Shared<int>(0); CountdownEvent sharedLatch = new CountdownEvent(partitionCount - 1); PartitionedStream<TSource, TKey> outputStream = new PartitionedStream<TSource, TKey>(partitionCount, inputStream.KeyComparer, OrdinalIndexState); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new DefaultIfEmptyQueryOperatorEnumerator<TKey>( inputStream[i], _defaultValue, i, partitionCount, sharedEmptyCount, sharedLatch, settings.CancellationState.MergedCancellationToken); } recipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token) { return Child.AsSequentialQuery(token).DefaultIfEmpty(_defaultValue); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for executing the default-if-empty operation. // class DefaultIfEmptyQueryOperatorEnumerator<TKey> : QueryOperatorEnumerator<TSource, TKey> { private QueryOperatorEnumerator<TSource, TKey> _source; // The data source to enumerate. private bool _lookedForEmpty; // Whether this partition has looked for empty yet. private int _partitionIndex; // This enumerator's partition index. private int _partitionCount; // The number of partitions. private TSource _defaultValue; // The default value if the 0th partition is empty. // Data shared among partitions. private Shared<int> _sharedEmptyCount; // The number of empty partitions. private CountdownEvent _sharedLatch; // Shared latch, signaled when partitions process the 1st item. private CancellationToken _cancelToken; // Token used to cancel this operator. //--------------------------------------------------------------------------------------- // Instantiates a new select enumerator. // internal DefaultIfEmptyQueryOperatorEnumerator( QueryOperatorEnumerator<TSource, TKey> source, TSource defaultValue, int partitionIndex, int partitionCount, Shared<int> sharedEmptyCount, CountdownEvent sharedLatch, CancellationToken cancelToken) { Debug.Assert(source != null); Debug.Assert(0 <= partitionIndex && partitionIndex < partitionCount); Debug.Assert(partitionCount > 0); Debug.Assert(sharedEmptyCount != null); Debug.Assert(sharedLatch != null); _source = source; _defaultValue = defaultValue; _partitionIndex = partitionIndex; _partitionCount = partitionCount; _sharedEmptyCount = sharedEmptyCount; _sharedLatch = sharedLatch; _cancelToken = cancelToken; } //--------------------------------------------------------------------------------------- // Straightforward IEnumerator<T> methods. // internal override bool MoveNext(ref TSource currentElement, ref TKey currentKey) { Debug.Assert(_source != null); bool moveNextResult = _source.MoveNext(ref currentElement, ref currentKey); // There is special logic the first time this function is called. if (!_lookedForEmpty) { // Ensure we don't enter this loop again. _lookedForEmpty = true; if (!moveNextResult) { if (_partitionIndex == 0) { // If this is the 0th partition, we must wait for all others. Note: we could // actually do a wait-any here: if at least one other partition finds an element, // there is strictly no need to wait. But this would require extra coordination // which may or may not be worth the trouble. _sharedLatch.Wait(_cancelToken); _sharedLatch.Dispose(); // Now see if there were any other partitions with data. if (_sharedEmptyCount.Value == _partitionCount - 1) { // No data, we will yield the default value. currentElement = _defaultValue; currentKey = default(TKey); return true; } else { // Another partition has data, we are done. return false; } } else { // Not the 0th partition, we will increment the shared empty counter. Interlocked.Increment(ref _sharedEmptyCount.Value); } } // Every partition (but the 0th) will signal the latch the first time. if (_partitionIndex != 0) { _sharedLatch.Signal(); } } return moveNextResult; } protected override void Dispose(bool disposing) { _source.Dispose(); } } } }
// 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.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc.ModelBinding.Binders { public class HeaderModelBinderTests { [Fact] public async Task HeaderBinder_BindsHeaders_ToStringCollection_WithoutInnerModelBinder() { // Arrange var binder = new HeaderModelBinder(NullLoggerFactory.Instance); var type = typeof(string[]); var header = "Accept"; var headerValue = "application/json,text/json"; var bindingContext = CreateContext(type); bindingContext.FieldName = header; bindingContext.HttpContext.Request.Headers.Add(header, new[] { headerValue }); // Act await binder.BindModelAsync(bindingContext); // Assert Assert.True(bindingContext.Result.IsModelSet); Assert.Equal(headerValue.Split(','), bindingContext.Result.Model); } [Fact] public async Task HeaderBinder_BindsHeaders_ToStringType_WithoutInnerModelBinder() { // Arrange var type = typeof(string); var header = "User-Agent"; var headerValue = "UnitTest"; var bindingContext = CreateContext(type); var binder = new HeaderModelBinder(NullLoggerFactory.Instance); bindingContext.FieldName = header; bindingContext.HttpContext.Request.Headers.Add(header, new[] { headerValue }); // Act await binder.BindModelAsync(bindingContext); // Assert Assert.True(bindingContext.Result.IsModelSet); Assert.Equal(headerValue, bindingContext.Result.Model); } [Theory] [InlineData(typeof(IEnumerable<string>))] [InlineData(typeof(ICollection<string>))] [InlineData(typeof(IList<string>))] [InlineData(typeof(List<string>))] [InlineData(typeof(LinkedList<string>))] [InlineData(typeof(StringList))] public async Task HeaderBinder_BindsHeaders_ForCollectionsItCanCreate_WithoutInnerModelBinder( Type destinationType) { // Arrange var header = "Accept"; var headerValue = "application/json,text/json"; var binder = new HeaderModelBinder(NullLoggerFactory.Instance); var bindingContext = CreateContext(destinationType); bindingContext.FieldName = header; bindingContext.HttpContext.Request.Headers.Add(header, new[] { headerValue }); // Act await binder.BindModelAsync(bindingContext); // Assert Assert.True(bindingContext.Result.IsModelSet); Assert.IsAssignableFrom(destinationType, bindingContext.Result.Model); Assert.Equal(headerValue.Split(','), bindingContext.Result.Model as IEnumerable<string>); } [Fact] public async Task HeaderBinder_BindsHeaders_ToStringCollection() { // Arrange var type = typeof(string[]); var headerValue = "application/json,text/json"; var bindingContext = CreateContext(type); var binder = CreateBinder(bindingContext); bindingContext.HttpContext.Request.Headers.Add("Header", new[] { headerValue }); // Act await binder.BindModelAsync(bindingContext); // Assert Assert.True(bindingContext.Result.IsModelSet); Assert.Equal(headerValue.Split(','), bindingContext.Result.Model); } public static TheoryData<string, Type, object> BinderHeaderToSimpleTypesData { get { var guid = new Guid("3916A5B1-5FE4-4E09-9812-5CDC127FA5B1"); return new TheoryData<string, Type, object>() { { "10", typeof(int), 10 }, { "10.50", typeof(double), 10.50 }, { "10.50", typeof(IEnumerable<double>), new List<double>() { 10.50 } }, { "Sedan", typeof(CarType), CarType.Sedan }, { "", typeof(CarType?), null }, { "", typeof(string[]), Array.Empty<string>() }, { null, typeof(string[]), Array.Empty<string>() }, { "", typeof(IEnumerable<string>), new List<string>() }, { null, typeof(IEnumerable<string>), new List<string>() }, { guid.ToString(), typeof(Guid), guid }, { "foo", typeof(string), "foo" }, { "foo, bar", typeof(string), "foo, bar" }, { "foo, bar", typeof(string[]), new[]{ "foo", "bar" } }, { "foo, \"bar\"", typeof(string[]), new[]{ "foo", "bar" } }, { "\"foo,bar\"", typeof(string[]), new[]{ "foo,bar" } } }; } } [Theory] [MemberData(nameof(BinderHeaderToSimpleTypesData))] public async Task HeaderBinder_BindsHeaders_ToSimpleTypes( string headerValue, Type modelType, object expectedModel) { // Arrange var bindingContext = CreateContext(modelType); var binder = CreateBinder(bindingContext); if (headerValue != null) { bindingContext.HttpContext.Request.Headers.Add("Header", headerValue); } // Act await binder.BindModelAsync(bindingContext); // Assert Assert.True(bindingContext.Result.IsModelSet); Assert.Equal(expectedModel, bindingContext.Result.Model); } [Theory] [InlineData(typeof(CarType?))] [InlineData(typeof(int?))] public async Task HeaderBinder_DoesNotSetModel_ForHeaderNotPresentOnRequest(Type modelType) { // Arrange var bindingContext = CreateContext(modelType); var binder = CreateBinder(bindingContext); // Act await binder.BindModelAsync(bindingContext); // Assert Assert.False(bindingContext.Result.IsModelSet); Assert.Null(bindingContext.Result.Model); } [Theory] [InlineData(typeof(string[]))] [InlineData(typeof(IEnumerable<string>))] public async Task HeaderBinder_DoesNotCreateEmptyCollection_ForNonTopLevelObjects(Type modelType) { // Arrange var bindingContext = CreateContext(modelType); bindingContext.IsTopLevelObject = false; var binder = CreateBinder(bindingContext); // No header on the request that the header value provider is looking for // Act await binder.BindModelAsync(bindingContext); // Assert Assert.False(bindingContext.Result.IsModelSet); Assert.Null(bindingContext.Result.Model); } [Theory] [InlineData(typeof(IEnumerable<string>))] [InlineData(typeof(ICollection<string>))] [InlineData(typeof(IList<string>))] [InlineData(typeof(List<string>))] [InlineData(typeof(LinkedList<string>))] [InlineData(typeof(StringList))] public async Task HeaderBinder_BindsHeaders_ForCollectionsItCanCreate(Type destinationType) { // Arrange var headerValue = "application/json,text/json"; var bindingContext = CreateContext(destinationType); var binder = CreateBinder(bindingContext); bindingContext.HttpContext.Request.Headers.Add("Header", new[] { headerValue }); // Act await binder.BindModelAsync(bindingContext); // Assert Assert.True(bindingContext.Result.IsModelSet); Assert.IsAssignableFrom(destinationType, bindingContext.Result.Model); Assert.Equal(headerValue.Split(','), bindingContext.Result.Model as IEnumerable<string>); } [Fact] public async Task HeaderBinder_ReturnsResult_ForReadOnlyDestination() { // Arrange var bindingContext = CreateContext(GetMetadataForReadOnlyArray()); var binder = CreateBinder(bindingContext); bindingContext.HttpContext.Request.Headers.Add("Header", "application/json,text/json"); // Act await binder.BindModelAsync(bindingContext); // Assert Assert.True(bindingContext.Result.IsModelSet); Assert.NotNull(bindingContext.Result.Model); } [Fact] public async Task HeaderBinder_ResetsTheBindingScope_GivingOriginalValueProvider() { // Arrange var expectedValueProvider = Mock.Of<IValueProvider>(); var bindingContext = CreateContext(GetMetadataForType(typeof(string)), expectedValueProvider); var binder = CreateBinder(bindingContext); bindingContext.HttpContext.Request.Headers.Add("Header", "application/json,text/json"); // Act await binder.BindModelAsync(bindingContext); // Assert Assert.True(bindingContext.Result.IsModelSet); Assert.Equal("application/json,text/json", bindingContext.Result.Model); Assert.Same(expectedValueProvider, bindingContext.ValueProvider); } [Fact] public async Task HeaderBinder_UsesValues_OnlyFromHeaderValueProvider() { // Arrange var testValueProvider = new Mock<IValueProvider>(); testValueProvider .Setup(vp => vp.ContainsPrefix(It.IsAny<string>())) .Returns(true); testValueProvider .Setup(vp => vp.GetValue(It.IsAny<string>())) .Returns(new ValueProviderResult(new StringValues("foo,bar"))); var bindingContext = CreateContext(GetMetadataForType(typeof(string)), testValueProvider.Object); var binder = CreateBinder(bindingContext); bindingContext.HttpContext.Request.Headers.Add("Header", "application/json,text/json"); // Act await binder.BindModelAsync(bindingContext); // Assert Assert.True(bindingContext.Result.IsModelSet); Assert.Equal("application/json,text/json", bindingContext.Result.Model); Assert.Same(testValueProvider.Object, bindingContext.ValueProvider); } [Theory] [InlineData(typeof(int), "not-an-integer")] [InlineData(typeof(double), "not-an-double")] [InlineData(typeof(CarType?), "boo")] public async Task HeaderBinder_BindModelAsync_AddsErrorToModelState_OnInvalidInput( Type modelType, string headerValue) { // Arrange var bindingContext = CreateContext(modelType); var binder = CreateBinder(bindingContext); bindingContext.HttpContext.Request.Headers.Add("Header", headerValue); // Act await binder.BindModelAsync(bindingContext); // Assert var entry = bindingContext.ModelState["someprefix.Header"]; Assert.NotNull(entry); var error = Assert.Single(entry.Errors); Assert.Equal($"The value '{headerValue}' is not valid.", error.ErrorMessage); } [Theory] [InlineData(typeof(int[]), "a, b")] [InlineData(typeof(IEnumerable<double>), "a, b")] [InlineData(typeof(ICollection<CarType>), "a, b")] public async Task HeaderBinder_BindModelAsync_AddsErrorToModelState_OnInvalid_CollectionInput( Type modelType, string headerValue) { // Arrange var headerValues = headerValue.Split(',').Select(s => s.Trim()).ToArray(); var bindingContext = CreateContext(modelType); var binder = CreateBinder(bindingContext); bindingContext.HttpContext.Request.Headers.Add("Header", headerValue); // Act await binder.BindModelAsync(bindingContext); // Assert var entry = bindingContext.ModelState["someprefix.Header"]; Assert.NotNull(entry); Assert.Equal(2, entry.Errors.Count); Assert.Equal($"The value '{headerValues[0]}' is not valid.", entry.Errors[0].ErrorMessage); Assert.Equal($"The value '{headerValues[1]}' is not valid.", entry.Errors[1].ErrorMessage); } private static DefaultModelBindingContext CreateContext(Type modelType) { return CreateContext(metadata: GetMetadataForType(modelType), valueProvider: null); } private static DefaultModelBindingContext CreateContext( ModelMetadata metadata, IValueProvider valueProvider = null) { if (valueProvider == null) { valueProvider = Mock.Of<IValueProvider>(); } var options = new MvcOptions(); var setup = new MvcCoreMvcOptionsSetup(new TestHttpRequestStreamReaderFactory()); setup.Configure(options); var services = new ServiceCollection(); services.AddSingleton<ILoggerFactory, NullLoggerFactory>(); services.AddSingleton(Options.Create(options)); var serviceProvider = services.BuildServiceProvider(); var headerName = "Header"; return new DefaultModelBindingContext() { IsTopLevelObject = true, ModelMetadata = metadata, BinderModelName = metadata.BinderModelName, BindingSource = metadata.BindingSource, // HeaderModelBinder must always use the field name when getting the values from header value provider // but add keys into ModelState using the ModelName. This is for back compat reasons. ModelName = $"somePrefix.{headerName}", FieldName = headerName, ValueProvider = valueProvider, ModelState = new ModelStateDictionary(), ActionContext = new ActionContext() { HttpContext = new DefaultHttpContext() { RequestServices = serviceProvider } }, }; } private static IModelBinder CreateBinder(DefaultModelBindingContext bindingContext) { var factory = TestModelBinderFactory.Create(bindingContext.HttpContext.RequestServices); var metadata = bindingContext.ModelMetadata; return factory.CreateBinder(new ModelBinderFactoryContext() { Metadata = metadata, BindingInfo = new BindingInfo() { BinderModelName = metadata.BinderModelName, BinderType = metadata.BinderType, BindingSource = metadata.BindingSource, PropertyFilterProvider = metadata.PropertyFilterProvider, }, }); } private static ModelMetadata GetMetadataForType(Type modelType) { var metadataProvider = new TestModelMetadataProvider(); metadataProvider.ForType(modelType).BindingDetails(d => d.BindingSource = BindingSource.Header); return metadataProvider.GetMetadataForType(modelType); } private static ModelMetadata GetMetadataForReadOnlyArray() { var metadataProvider = new TestModelMetadataProvider(); metadataProvider .ForProperty<ModelWithReadOnlyArray>(nameof(ModelWithReadOnlyArray.ArrayProperty)) .BindingDetails(bd => bd.BindingSource = BindingSource.Header); return metadataProvider.GetMetadataForProperty( typeof(ModelWithReadOnlyArray), nameof(ModelWithReadOnlyArray.ArrayProperty)); } private class ModelWithReadOnlyArray { public string[] ArrayProperty { get; } } private class StringList : List<string> { } private enum CarType { Sedan, Coupe } } }
// // PKCS1.cs - Implements PKCS#1 primitives. // // Author: // Sebastien Pouliot <sebastien@xamarin.com> // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // Copyright 2013 Xamarin Inc. (http://www.xamarin.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.Security.Cryptography; namespace Mono.Security.Cryptography { // References: // a. PKCS#1: RSA Cryptography Standard // http://www.rsasecurity.com/rsalabs/pkcs/pkcs-1/index.html internal sealed class PKCS1 { private PKCS1 () { } private static bool Compare (byte[] array1, byte[] array2) { bool result = (array1.Length == array2.Length); if (result) { for (int i=0; i < array1.Length; i++) if (array1[i] != array2[i]) return false; } return result; } private static byte[] xor (byte[] array1, byte[] array2) { byte[] result = new byte [array1.Length]; for (int i=0; i < result.Length; i++) result[i] = (byte) (array1[i] ^ array2[i]); return result; } private static byte[] emptySHA1 = { 0xda, 0x39, 0xa3, 0xee, 0x5e, 0x6b, 0x4b, 0x0d, 0x32, 0x55, 0xbf, 0xef, 0x95, 0x60, 0x18, 0x90, 0xaf, 0xd8, 0x07, 0x09 }; private static byte[] emptySHA256 = { 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55 }; private static byte[] emptySHA384 = { 0x38, 0xb0, 0x60, 0xa7, 0x51, 0xac, 0x96, 0x38, 0x4c, 0xd9, 0x32, 0x7e, 0xb1, 0xb1, 0xe3, 0x6a, 0x21, 0xfd, 0xb7, 0x11, 0x14, 0xbe, 0x07, 0x43, 0x4c, 0x0c, 0xc7, 0xbf, 0x63, 0xf6, 0xe1, 0xda, 0x27, 0x4e, 0xde, 0xbf, 0xe7, 0x6f, 0x65, 0xfb, 0xd5, 0x1a, 0xd2, 0xf1, 0x48, 0x98, 0xb9, 0x5b }; private static byte[] emptySHA512 = { 0xcf, 0x83, 0xe1, 0x35, 0x7e, 0xef, 0xb8, 0xbd, 0xf1, 0x54, 0x28, 0x50, 0xd6, 0x6d, 0x80, 0x07, 0xd6, 0x20, 0xe4, 0x05, 0x0b, 0x57, 0x15, 0xdc, 0x83, 0xf4, 0xa9, 0x21, 0xd3, 0x6c, 0xe9, 0xce, 0x47, 0xd0, 0xd1, 0x3c, 0x5d, 0x85, 0xf2, 0xb0, 0xff, 0x83, 0x18, 0xd2, 0x87, 0x7e, 0xec, 0x2f, 0x63, 0xb9, 0x31, 0xbd, 0x47, 0x41, 0x7a, 0x81, 0xa5, 0x38, 0x32, 0x7a, 0xf9, 0x27, 0xda, 0x3e }; private static byte[] GetEmptyHash (HashAlgorithm hash) { if (hash is SHA1) return emptySHA1; else if (hash is SHA256) return emptySHA256; else if (hash is SHA384) return emptySHA384; else if (hash is SHA512) return emptySHA512; else return hash.ComputeHash ((byte[])null); } // PKCS #1 v.2.1, Section 4.1 // I2OSP converts a non-negative integer to an octet string of a specified length. public static byte[] I2OSP (int x, int size) { byte[] array = BitConverterLE.GetBytes (x); Array.Reverse (array, 0, array.Length); return I2OSP (array, size); } public static byte[] I2OSP (byte[] x, int size) { byte[] result = new byte [size]; Buffer.BlockCopy (x, 0, result, (result.Length - x.Length), x.Length); return result; } // PKCS #1 v.2.1, Section 4.2 // OS2IP converts an octet string to a nonnegative integer. public static byte[] OS2IP (byte[] x) { int i = 0; while ((x [i++] == 0x00) && (i < x.Length)) { // confuse compiler into reporting a warning with {} } i--; if (i > 0) { byte[] result = new byte [x.Length - i]; Buffer.BlockCopy (x, i, result, 0, result.Length); return result; } else return x; } // PKCS #1 v.2.1, Section 5.1.1 public static byte[] RSAEP (RSA rsa, byte[] m) { // c = m^e mod n return rsa.EncryptValue (m); } // PKCS #1 v.2.1, Section 5.1.2 public static byte[] RSADP (RSA rsa, byte[] c) { // m = c^d mod n // Decrypt value may apply CRT optimizations return rsa.DecryptValue (c); } // PKCS #1 v.2.1, Section 5.2.1 public static byte[] RSASP1 (RSA rsa, byte[] m) { // first form: s = m^d mod n // Decrypt value may apply CRT optimizations return rsa.DecryptValue (m); } // PKCS #1 v.2.1, Section 5.2.2 public static byte[] RSAVP1 (RSA rsa, byte[] s) { // m = s^e mod n return rsa.EncryptValue (s); } // PKCS #1 v.2.1, Section 7.1.1 // RSAES-OAEP-ENCRYPT ((n, e), M, L) public static byte[] Encrypt_OAEP (RSA rsa, HashAlgorithm hash, RandomNumberGenerator rng, byte[] M) { int size = rsa.KeySize / 8; int hLen = hash.HashSize / 8; if (M.Length > size - 2 * hLen - 2) throw new CryptographicException ("message too long"); // empty label L SHA1 hash byte[] lHash = GetEmptyHash (hash); int PSLength = (size - M.Length - 2 * hLen - 2); // DB = lHash || PS || 0x01 || M byte[] DB = new byte [lHash.Length + PSLength + 1 + M.Length]; Buffer.BlockCopy (lHash, 0, DB, 0, lHash.Length); DB [(lHash.Length + PSLength)] = 0x01; Buffer.BlockCopy (M, 0, DB, (DB.Length - M.Length), M.Length); byte[] seed = new byte [hLen]; rng.GetBytes (seed); byte[] dbMask = MGF1 (hash, seed, size - hLen - 1); byte[] maskedDB = xor (DB, dbMask); byte[] seedMask = MGF1 (hash, maskedDB, hLen); byte[] maskedSeed = xor (seed, seedMask); // EM = 0x00 || maskedSeed || maskedDB byte[] EM = new byte [maskedSeed.Length + maskedDB.Length + 1]; Buffer.BlockCopy (maskedSeed, 0, EM, 1, maskedSeed.Length); Buffer.BlockCopy (maskedDB, 0, EM, maskedSeed.Length + 1, maskedDB.Length); byte[] m = OS2IP (EM); byte[] c = RSAEP (rsa, m); return I2OSP (c, size); } // PKCS #1 v.2.1, Section 7.1.2 // RSAES-OAEP-DECRYPT (K, C, L) public static byte[] Decrypt_OAEP (RSA rsa, HashAlgorithm hash, byte[] C) { int size = rsa.KeySize / 8; int hLen = hash.HashSize / 8; if ((size < (2 * hLen + 2)) || (C.Length != size)) throw new CryptographicException ("decryption error"); byte[] c = OS2IP (C); byte[] m = RSADP (rsa, c); byte[] EM = I2OSP (m, size); // split EM = Y || maskedSeed || maskedDB byte[] maskedSeed = new byte [hLen]; Buffer.BlockCopy (EM, 1, maskedSeed, 0, maskedSeed.Length); byte[] maskedDB = new byte [size - hLen - 1]; Buffer.BlockCopy (EM, (EM.Length - maskedDB.Length), maskedDB, 0, maskedDB.Length); byte[] seedMask = MGF1 (hash, maskedDB, hLen); byte[] seed = xor (maskedSeed, seedMask); byte[] dbMask = MGF1 (hash, seed, size - hLen - 1); byte[] DB = xor (maskedDB, dbMask); byte[] lHash = GetEmptyHash (hash); // split DB = lHash' || PS || 0x01 || M byte[] dbHash = new byte [lHash.Length]; Buffer.BlockCopy (DB, 0, dbHash, 0, dbHash.Length); bool h = Compare (lHash, dbHash); // find separator 0x01 int nPos = lHash.Length; while (DB[nPos] == 0) nPos++; int Msize = DB.Length - nPos - 1; byte[] M = new byte [Msize]; Buffer.BlockCopy (DB, (nPos + 1), M, 0, Msize); // we could have returned EM[0] sooner but would be helping a timing attack if ((EM[0] != 0) || (!h) || (DB[nPos] != 0x01)) return null; return M; } // PKCS #1 v.2.1, Section 7.2.1 // RSAES-PKCS1-V1_5-ENCRYPT ((n, e), M) public static byte[] Encrypt_v15 (RSA rsa, RandomNumberGenerator rng, byte[] M) { int size = rsa.KeySize / 8; if (M.Length > size - 11) throw new CryptographicException ("message too long"); int PSLength = System.Math.Max (8, (size - M.Length - 3)); byte[] PS = new byte [PSLength]; rng.GetNonZeroBytes (PS); byte[] EM = new byte [size]; EM [1] = 0x02; Buffer.BlockCopy (PS, 0, EM, 2, PSLength); Buffer.BlockCopy (M, 0, EM, (size - M.Length), M.Length); byte[] m = OS2IP (EM); byte[] c = RSAEP (rsa, m); byte[] C = I2OSP (c, size); return C; } // PKCS #1 v.2.1, Section 7.2.2 // RSAES-PKCS1-V1_5-DECRYPT (K, C) public static byte[] Decrypt_v15 (RSA rsa, byte[] C) { int size = rsa.KeySize >> 3; // div by 8 if ((size < 11) || (C.Length > size)) throw new CryptographicException ("decryption error"); byte[] c = OS2IP (C); byte[] m = RSADP (rsa, c); byte[] EM = I2OSP (m, size); if ((EM [0] != 0x00) || (EM [1] != 0x02)) return null; int mPos = 10; // PS is a minimum of 8 bytes + 2 bytes for header while ((EM [mPos] != 0x00) && (mPos < EM.Length)) mPos++; if (EM [mPos] != 0x00) return null; mPos++; byte[] M = new byte [EM.Length - mPos]; Buffer.BlockCopy (EM, mPos, M, 0, M.Length); return M; } // PKCS #1 v.2.1, Section 8.2.1 // RSASSA-PKCS1-V1_5-SIGN (K, M) public static byte[] Sign_v15 (RSA rsa, HashAlgorithm hash, byte[] hashValue) { int size = (rsa.KeySize >> 3); // div 8 byte[] EM = Encode_v15 (hash, hashValue, size); byte[] m = OS2IP (EM); byte[] s = RSASP1 (rsa, m); byte[] S = I2OSP (s, size); return S; } internal static byte[] Sign_v15 (RSA rsa, string hashName, byte[] hashValue) { using (var hash = CreateFromName (hashName)) return Sign_v15 (rsa, hash, hashValue); } // PKCS #1 v.2.1, Section 8.2.2 // RSASSA-PKCS1-V1_5-VERIFY ((n, e), M, S) public static bool Verify_v15 (RSA rsa, HashAlgorithm hash, byte[] hashValue, byte[] signature) { return Verify_v15 (rsa, hash, hashValue, signature, false); } internal static bool Verify_v15 (RSA rsa, string hashName, byte[] hashValue, byte[] signature) { using (var hash = CreateFromName (hashName)) return Verify_v15 (rsa, hash, hashValue, signature, false); } // DO NOT USE WITHOUT A VERY GOOD REASON public static bool Verify_v15 (RSA rsa, HashAlgorithm hash, byte [] hashValue, byte [] signature, bool tryNonStandardEncoding) { int size = (rsa.KeySize >> 3); // div 8 byte[] s = OS2IP (signature); byte[] m = RSAVP1 (rsa, s); byte[] EM2 = I2OSP (m, size); byte[] EM = Encode_v15 (hash, hashValue, size); bool result = Compare (EM, EM2); if (result || !tryNonStandardEncoding) return result; // NOTE: some signatures don't include the hash OID (pretty lame but real) // and compatible with MS implementation. E.g. Verisign Authenticode Timestamps // we're making this "as safe as possible" if ((EM2 [0] != 0x00) || (EM2 [1] != 0x01)) return false; int i; for (i = 2; i < EM2.Length - hashValue.Length - 1; i++) { if (EM2 [i] != 0xFF) return false; } if (EM2 [i++] != 0x00) return false; byte [] decryptedHash = new byte [hashValue.Length]; Buffer.BlockCopy (EM2, i, decryptedHash, 0, decryptedHash.Length); return Compare (decryptedHash, hashValue); } // PKCS #1 v.2.1, Section 9.2 // EMSA-PKCS1-v1_5-Encode public static byte[] Encode_v15 (HashAlgorithm hash, byte[] hashValue, int emLength) { if (hashValue.Length != (hash.HashSize >> 3)) throw new CryptographicException ("bad hash length for " + hash.ToString ()); // DigestInfo ::= SEQUENCE { // digestAlgorithm AlgorithmIdentifier, // digest OCTET STRING // } byte[] t = null; string oid = CryptoConfig.MapNameToOID (hash.ToString ()); if (oid != null) { ASN1 digestAlgorithm = new ASN1 (0x30); digestAlgorithm.Add (new ASN1 (CryptoConfig.EncodeOID (oid))); digestAlgorithm.Add (new ASN1 (0x05)); // NULL ASN1 digest = new ASN1 (0x04, hashValue); ASN1 digestInfo = new ASN1 (0x30); digestInfo.Add (digestAlgorithm); digestInfo.Add (digest); t = digestInfo.GetBytes (); } else { // There are no valid OID, in this case t = hashValue // This is the case of the MD5SHA hash algorithm t = hashValue; } Buffer.BlockCopy (hashValue, 0, t, t.Length - hashValue.Length, hashValue.Length); int PSLength = System.Math.Max (8, emLength - t.Length - 3); // PS = PSLength of 0xff // EM = 0x00 | 0x01 | PS | 0x00 | T byte[] EM = new byte [PSLength + t.Length + 3]; EM [1] = 0x01; for (int i=2; i < PSLength + 2; i++) EM[i] = 0xff; Buffer.BlockCopy (t, 0, EM, PSLength + 3, t.Length); return EM; } // PKCS #1 v.2.1, Section B.2.1 public static byte[] MGF1 (HashAlgorithm hash, byte[] mgfSeed, int maskLen) { // 1. If maskLen > 2^32 hLen, output "mask too long" and stop. // easy - this is impossible by using a int (31bits) as parameter ;-) // BUT with a signed int we do have to check for negative values! if (maskLen < 0) throw new OverflowException(); int mgfSeedLength = mgfSeed.Length; int hLen = (hash.HashSize >> 3); // from bits to bytes int iterations = (maskLen / hLen); if (maskLen % hLen != 0) iterations++; // 2. Let T be the empty octet string. byte[] T = new byte [iterations * hLen]; byte[] toBeHashed = new byte [mgfSeedLength + 4]; int pos = 0; // 3. For counter from 0 to \ceil (maskLen / hLen) - 1, do the following: for (int counter = 0; counter < iterations; counter++) { // a. Convert counter to an octet string C of length 4 octets byte[] C = I2OSP (counter, 4); // b. Concatenate the hash of the seed mgfSeed and C to the octet string T: // T = T || Hash (mgfSeed || C) Buffer.BlockCopy (mgfSeed, 0, toBeHashed, 0, mgfSeedLength); Buffer.BlockCopy (C, 0, toBeHashed, mgfSeedLength, 4); byte[] output = hash.ComputeHash (toBeHashed); Buffer.BlockCopy (output, 0, T, pos, hLen); pos += hLen; } // 4. Output the leading maskLen octets of T as the octet string mask. byte[] mask = new byte [maskLen]; Buffer.BlockCopy (T, 0, mask, 0, maskLen); return mask; } static internal string HashNameFromOid (string oid, bool throwOnError = true) { switch (oid) { case "1.2.840.113549.1.1.2": // MD2 with RSA encryption return "MD2"; case "1.2.840.113549.1.1.3": // MD4 with RSA encryption return "MD4"; case "1.2.840.113549.1.1.4": // MD5 with RSA encryption return "MD5"; case "1.2.840.113549.1.1.5": // SHA-1 with RSA Encryption case "1.3.14.3.2.29": // SHA1 with RSA signature case "1.2.840.10040.4.3": // SHA1-1 with DSA return "SHA1"; case "1.2.840.113549.1.1.11": // SHA-256 with RSA Encryption return "SHA256"; case "1.2.840.113549.1.1.12": // SHA-384 with RSA Encryption return "SHA384"; case "1.2.840.113549.1.1.13": // SHA-512 with RSA Encryption return "SHA512"; case "1.3.36.3.3.1.2": return "RIPEMD160"; default: if (throwOnError) throw new CryptographicException ("Unsupported hash algorithm: " + oid); return null; } } static internal HashAlgorithm CreateFromOid (string oid) { return CreateFromName (HashNameFromOid (oid)); } static internal HashAlgorithm CreateFromName (string name) { #if FULL_AOT_RUNTIME switch (name) { case "MD2": return MD2.Create (); case "MD4": return MD4.Create (); case "MD5": return MD5.Create (); case "SHA1": return SHA1.Create (); case "SHA256": return SHA256.Create (); case "SHA384": return SHA384.Create (); case "SHA512": return SHA512.Create (); case "RIPEMD160": return RIPEMD160.Create (); default: try { return (HashAlgorithm) Activator.CreateInstance (Type.GetType (name)); } catch { throw new CryptographicException ("Unsupported hash algorithm: " + name); } } #else return HashAlgorithm.Create (name); #endif } } }
/* * Copyright 2010-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ElasticBeanstalk.Model { /// <summary> /// Container for the parameters to the DescribeEnvironments operation. /// <para>Returns descriptions for existing environments.</para> /// </summary> /// <seealso cref="Amazon.ElasticBeanstalk.AmazonElasticBeanstalk.DescribeEnvironments"/> public class DescribeEnvironmentsRequest : AmazonWebServiceRequest { private string applicationName; private string versionLabel; private List<string> environmentIds = new List<string>(); private List<string> environmentNames = new List<string>(); private bool? includeDeleted; private DateTime? includedDeletedBackTo; /// <summary> /// If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only those that are associated with this application. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 100</description> /// </item> /// </list> /// </para> /// </summary> public string ApplicationName { get { return this.applicationName; } set { this.applicationName = value; } } /// <summary> /// Sets the ApplicationName property /// </summary> /// <param name="applicationName">The value to set for the ApplicationName property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeEnvironmentsRequest WithApplicationName(string applicationName) { this.applicationName = applicationName; return this; } // Check to see if ApplicationName property is set internal bool IsSetApplicationName() { return this.applicationName != null; } /// <summary> /// If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only those that are associated with this application /// version. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 100</description> /// </item> /// </list> /// </para> /// </summary> public string VersionLabel { get { return this.versionLabel; } set { this.versionLabel = value; } } /// <summary> /// Sets the VersionLabel property /// </summary> /// <param name="versionLabel">The value to set for the VersionLabel property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeEnvironmentsRequest WithVersionLabel(string versionLabel) { this.versionLabel = versionLabel; return this; } // Check to see if VersionLabel property is set internal bool IsSetVersionLabel() { return this.versionLabel != null; } /// <summary> /// If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only those that have the specified IDs. /// /// </summary> public List<string> EnvironmentIds { get { return this.environmentIds; } set { this.environmentIds = value; } } /// <summary> /// Adds elements to the EnvironmentIds collection /// </summary> /// <param name="environmentIds">The values to add to the EnvironmentIds collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeEnvironmentsRequest WithEnvironmentIds(params string[] environmentIds) { foreach (string element in environmentIds) { this.environmentIds.Add(element); } return this; } /// <summary> /// Adds elements to the EnvironmentIds collection /// </summary> /// <param name="environmentIds">The values to add to the EnvironmentIds collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeEnvironmentsRequest WithEnvironmentIds(IEnumerable<string> environmentIds) { foreach (string element in environmentIds) { this.environmentIds.Add(element); } return this; } // Check to see if EnvironmentIds property is set internal bool IsSetEnvironmentIds() { return this.environmentIds.Count > 0; } /// <summary> /// If specified, AWS Elastic Beanstalk restricts the returned descriptions to include only those that have the specified names. /// /// </summary> public List<string> EnvironmentNames { get { return this.environmentNames; } set { this.environmentNames = value; } } /// <summary> /// Adds elements to the EnvironmentNames collection /// </summary> /// <param name="environmentNames">The values to add to the EnvironmentNames collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeEnvironmentsRequest WithEnvironmentNames(params string[] environmentNames) { foreach (string element in environmentNames) { this.environmentNames.Add(element); } return this; } /// <summary> /// Adds elements to the EnvironmentNames collection /// </summary> /// <param name="environmentNames">The values to add to the EnvironmentNames collection </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeEnvironmentsRequest WithEnvironmentNames(IEnumerable<string> environmentNames) { foreach (string element in environmentNames) { this.environmentNames.Add(element); } return this; } // Check to see if EnvironmentNames property is set internal bool IsSetEnvironmentNames() { return this.environmentNames.Count > 0; } /// <summary> /// Indicates whether to include deleted environments: <c>true</c>: Environments that have been deleted after <c>IncludedDeletedBackTo</c> are /// displayed. <c>false</c>: Do not include deleted environments. /// /// </summary> public bool IncludeDeleted { get { return this.includeDeleted ?? default(bool); } set { this.includeDeleted = value; } } /// <summary> /// Sets the IncludeDeleted property /// </summary> /// <param name="includeDeleted">The value to set for the IncludeDeleted property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeEnvironmentsRequest WithIncludeDeleted(bool includeDeleted) { this.includeDeleted = includeDeleted; return this; } // Check to see if IncludeDeleted property is set internal bool IsSetIncludeDeleted() { return this.includeDeleted.HasValue; } /// <summary> /// If specified when <c>IncludeDeleted</c> is set to <c>true</c>, then environments deleted after this date are displayed. /// /// </summary> public DateTime IncludedDeletedBackTo { get { return this.includedDeletedBackTo ?? default(DateTime); } set { this.includedDeletedBackTo = value; } } /// <summary> /// Sets the IncludedDeletedBackTo property /// </summary> /// <param name="includedDeletedBackTo">The value to set for the IncludedDeletedBackTo property </param> /// <returns>this instance</returns> [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")] public DescribeEnvironmentsRequest WithIncludedDeletedBackTo(DateTime includedDeletedBackTo) { this.includedDeletedBackTo = includedDeletedBackTo; return this; } // Check to see if IncludedDeletedBackTo property is set internal bool IsSetIncludedDeletedBackTo() { return this.includedDeletedBackTo.HasValue; } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal abstract partial class CSharpSelectionResult : SelectionResult { public static async Task<CSharpSelectionResult> CreateAsync( OperationStatus status, TextSpan originalSpan, TextSpan finalSpan, OptionSet options, bool selectionInExpression, SemanticDocument document, SyntaxToken firstToken, SyntaxToken lastToken, CancellationToken cancellationToken) { Contract.ThrowIfNull(status); Contract.ThrowIfNull(document); var firstTokenAnnotation = new SyntaxAnnotation(); var lastTokenAnnotation = new SyntaxAnnotation(); var root = await document.Document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newDocument = await SemanticDocument.CreateAsync(document.Document.WithSyntaxRoot(root.AddAnnotations( new[] { Tuple.Create<SyntaxToken, SyntaxAnnotation>(firstToken, firstTokenAnnotation), Tuple.Create<SyntaxToken, SyntaxAnnotation>(lastToken, lastTokenAnnotation) })), cancellationToken).ConfigureAwait(false); if (selectionInExpression) { return new ExpressionResult( status, originalSpan, finalSpan, options, selectionInExpression, newDocument, firstTokenAnnotation, lastTokenAnnotation); } else { return new StatementResult( status, originalSpan, finalSpan, options, selectionInExpression, newDocument, firstTokenAnnotation, lastTokenAnnotation); } } protected CSharpSelectionResult( OperationStatus status, TextSpan originalSpan, TextSpan finalSpan, OptionSet options, bool selectionInExpression, SemanticDocument document, SyntaxAnnotation firstTokenAnnotation, SyntaxAnnotation lastTokenAnnotation) : base(status, originalSpan, finalSpan, options, selectionInExpression, document, firstTokenAnnotation, lastTokenAnnotation) { } protected override bool UnderAsyncAnonymousMethod(SyntaxToken token, SyntaxToken firstToken, SyntaxToken lastToken) { var current = token.Parent; for (; current != null; current = current.Parent) { if (current is MemberDeclarationSyntax || current is SimpleLambdaExpressionSyntax || current is ParenthesizedLambdaExpressionSyntax || current is AnonymousMethodExpressionSyntax) { break; } } if (current == null || current is MemberDeclarationSyntax) { return false; } // make sure the selection contains the lambda return firstToken.SpanStart <= current.GetFirstToken().SpanStart && current.GetLastToken().Span.End <= lastToken.Span.End; } public StatementSyntax GetFirstStatement() { return GetFirstStatement<StatementSyntax>(); } public StatementSyntax GetLastStatement() { return GetLastStatement<StatementSyntax>(); } public StatementSyntax GetFirstStatementUnderContainer() { Contract.ThrowIfTrue(this.SelectionInExpression); var firstToken = this.GetFirstTokenInSelection(); var statement = firstToken.Parent.GetStatementUnderContainer(); Contract.ThrowIfNull(statement); return statement; } public StatementSyntax GetLastStatementUnderContainer() { Contract.ThrowIfTrue(this.SelectionInExpression); var lastToken = this.GetLastTokenInSelection(); var statement = lastToken.Parent.GetStatementUnderContainer(); Contract.ThrowIfNull(statement); var firstStatementUnderContainer = this.GetFirstStatementUnderContainer(); Contract.ThrowIfFalse(statement.Parent == firstStatementUnderContainer.Parent); return statement; } public SyntaxNode GetInnermostStatementContainer() { Contract.ThrowIfFalse(this.SelectionInExpression); var containingScope = this.GetContainingScope(); var statements = containingScope.GetAncestorsOrThis<StatementSyntax>(); StatementSyntax last = null; foreach (var statement in statements) { if (statement.IsStatementContainerNode()) { return statement; } last = statement; } // constructor initializer case var constructorInitializer = this.GetContainingScopeOf<ConstructorInitializerSyntax>(); if (constructorInitializer != null) { return constructorInitializer.Parent; } // field initializer case var field = this.GetContainingScopeOf<FieldDeclarationSyntax>(); if (field != null) { return field.Parent; } Contract.ThrowIfFalse(last.IsParentKind(SyntaxKind.GlobalStatement)); Contract.ThrowIfFalse(last.Parent.IsParentKind(SyntaxKind.CompilationUnit)); return last.Parent.Parent; } public bool ShouldPutUnsafeModifier() { var token = this.GetFirstTokenInSelection(); var ancestors = token.GetAncestors<SyntaxNode>(); // if enclosing type contains unsafe keyword, we don't need to put it again if (ancestors.Where(a => SyntaxFacts.IsTypeDeclaration(a.Kind())) .Cast<MemberDeclarationSyntax>() .Any(m => m.GetModifiers().Any(SyntaxKind.UnsafeKeyword))) { return false; } return token.Parent.IsUnsafeContext(); } public SyntaxKind UnderCheckedExpressionContext() { return UnderCheckedContext<CheckedExpressionSyntax>(); } public SyntaxKind UnderCheckedStatementContext() { return UnderCheckedContext<CheckedStatementSyntax>(); } private SyntaxKind UnderCheckedContext<T>() where T : SyntaxNode { var token = this.GetFirstTokenInSelection(); var contextNode = token.Parent.GetAncestor<T>(); if (contextNode == null) { return SyntaxKind.None; } return contextNode.Kind(); } } }
// // LiveWebGalleryDialog.cs // // Author: // Anton Keks <anton@azib.net> // // Copyright (C) 2009 Novell, Inc. // Copyright (C) 2009 Anton Keks // // 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.Net; using System.Reflection; using FSpot; using FSpot.Core; using Gtk; using Mono.Unix; using Hyena; namespace FSpot.Tools.LiveWebGallery { internal class LiveWebGalleryDialog : FSpot.UI.Dialog.BuilderDialog { [GtkBeans.Builder.Object] Gtk.LinkButton url_button; [GtkBeans.Builder.Object] Gtk.ToggleButton activate_button; [GtkBeans.Builder.Object] Gtk.Button copy_button; [GtkBeans.Builder.Object] Gtk.Label stats_label; [GtkBeans.Builder.Object] Gtk.RadioButton current_view_radio; [GtkBeans.Builder.Object] Gtk.RadioButton tagged_radio; [GtkBeans.Builder.Object] Gtk.RadioButton selected_radio; [GtkBeans.Builder.Object] Gtk.Button tag_button; [GtkBeans.Builder.Object] Gtk.CheckButton limit_checkbox; [GtkBeans.Builder.Object] Gtk.SpinButton limit_spin; [GtkBeans.Builder.Object] Gtk.CheckButton allow_tagging_checkbox; [GtkBeans.Builder.Object] Gtk.Button tag_edit_button; private SimpleWebServer server; private ILiveWebGalleryOptions options; private LiveWebGalleryStats stats; private IPAddress last_ip; private string last_client; public LiveWebGalleryDialog (SimpleWebServer server, ILiveWebGalleryOptions options, LiveWebGalleryStats stats) : base (Assembly.GetExecutingAssembly (), "LiveWebGallery.ui", "live_web_gallery_dialog") { this.server = server; this.options = options; this.stats = stats; Modal = false; activate_button.Active = server.Active; UpdateGalleryURL (); limit_checkbox.Active = options.LimitMaxPhotos; limit_spin.Sensitive = options.LimitMaxPhotos; limit_spin.Value = options.MaxPhotos; UpdateQueryRadios (); HandleQueryTagSelected (options.QueryTag != null ? options.QueryTag : App.Instance.Database.Tags.GetTagById(1)); allow_tagging_checkbox.Active = options.TaggingAllowed; tag_edit_button.Sensitive = options.TaggingAllowed; HandleEditableTagSelected (options.EditableTag != null ? options.EditableTag : App.Instance.Database.Tags.GetTagById(3)); HandleStatsChanged (null, null); activate_button.Toggled += HandleActivated; copy_button.Clicked +=HandleCopyClicked; current_view_radio.Toggled += HandleRadioChanged; tagged_radio.Toggled += HandleRadioChanged; selected_radio.Toggled += HandleRadioChanged; tag_button.Clicked += HandleQueryTagClicked; limit_checkbox.Toggled += HandleLimitToggled; limit_spin.ValueChanged += HandleLimitValueChanged; allow_tagging_checkbox.Toggled += HandleAllowTaggingToggled; tag_edit_button.Clicked += HandleTagForEditClicked; stats.StatsChanged += HandleStatsChanged; } void HandleCopyClicked(object sender, EventArgs e) { Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", true)).Text = url_button.Uri; } void HandleStatsChanged (object sender, EventArgs e) { ThreadAssist.ProxyToMain (() => { if (last_ip == null || !last_ip.Equals (stats.LastIP)) { last_ip = stats.LastIP; try { last_client = Dns.GetHostEntry (last_ip).HostName; } catch (Exception) { last_client = last_ip != null ? last_ip.ToString () : Catalog.GetString ("none"); } } stats_label.Text = string.Format(Catalog.GetString (" Gallery: {0}, Photos: {1}, Last client: {3}"), stats.GalleryViews, stats.PhotoViews, stats.BytesSent / 1024, last_client); }); } void HandleLimitToggled (object sender, EventArgs e) { options.LimitMaxPhotos = limit_checkbox.Active; limit_spin.Sensitive = limit_checkbox.Active; HandleLimitValueChanged (sender, e); } void HandleLimitValueChanged (object sender, EventArgs e) { options.MaxPhotos = limit_spin.ValueAsInt; } void HandleRadioChanged (object o, EventArgs e) { tag_button.Sensitive = tagged_radio.Active; if (tagged_radio.Active) options.QueryType = QueryType.ByTag; else if (current_view_radio.Active) options.QueryType = QueryType.CurrentView; else options.QueryType = QueryType.Selected; } void UpdateQueryRadios () { switch (options.QueryType) { case QueryType.ByTag: tagged_radio.Active = true; break; case QueryType.CurrentView: current_view_radio.Active = true; break; case QueryType.Selected: default: selected_radio.Active = true; break; } HandleRadioChanged (null, null); } void HandleActivated (object o, EventArgs e) { if (activate_button.Active) server.Start (); else server.Stop (); UpdateGalleryURL (); } void UpdateGalleryURL () { url_button.Sensitive = server.Active; copy_button.Sensitive = server.Active; if (server.Active) { url_button.Uri = "http://" + server.HostPort; url_button.Label = url_button.Uri; } else { url_button.Label = Catalog.GetString ("Gallery is inactive"); } } void ShowTagMenuFor (Widget widget, TagMenu.TagSelectedHandler handler) { TagMenu tag_menu = new TagMenu (null, App.Instance.Database.Tags); tag_menu.TagSelected += handler; tag_menu.Populate (); int x, y; GetPosition (out x, out y); x += widget.Allocation.X; y += widget.Allocation.Y; tag_menu.Popup (null, null, delegate (Menu menu, out int x_, out int y_, out bool push_in) {x_ = x; y_ = y; push_in = true;}, 0, 0); } void HandleQueryTagClicked (object sender, EventArgs e) { ShowTagMenuFor (tag_button, HandleQueryTagSelected); } void HandleQueryTagSelected (Tag tag) { options.QueryTag = tag; tag_button.Label = tag.Name; tag_button.Image = tag.Icon != null ? new Gtk.Image (PixbufUtils.ScaleDown (tag.Icon, 16, 16)) : null; } void HandleAllowTaggingToggled (object sender, EventArgs e) { tag_edit_button.Sensitive = allow_tagging_checkbox.Active; options.TaggingAllowed = allow_tagging_checkbox.Active; } void HandleTagForEditClicked (object sender, EventArgs e) { ShowTagMenuFor (tag_edit_button, HandleEditableTagSelected); } void HandleEditableTagSelected (Tag tag) { options.EditableTag = tag; tag_edit_button.Label = tag.Name; tag_edit_button.Image = tag.Icon != null ? new Gtk.Image (PixbufUtils.ScaleDown (tag.Icon, 16, 16)) : null; } } }
// 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.ComponentModel; using System.Diagnostics; using System.Linq; namespace Microsoft.PythonTools.Project { /// <summary> /// Provides a view model for the InstallPythonPackage class. /// </summary> sealed class InstallPythonPackageView : INotifyPropertyChanged { private string _name; private string _installUsing; private bool _installUsingPip, _installUsingEasyInstall, _installUsingConda; private bool _installElevated; private bool _isValid; private readonly bool _isInsecure; private bool _supportsConda; private readonly IServiceProvider _serviceProvider; /// <summary> /// Create a InstallPythonPackageView with default values. /// </summary> public InstallPythonPackageView(IServiceProvider serviceProvider, bool isInsecure, bool supportConda) { _serviceProvider = serviceProvider; _supportsConda = supportConda; InstallUsing = InstallUsingOptions.First(); _isInsecure = isInsecure; PropertyChanged += new PropertyChangedEventHandler(OnPropertyChanged); } /// <summary> /// Gets or sets the name of the Python package to be installed. /// </summary> public string Name { get { return _name; } set { if (_name != value) { _name = value; OnPropertyChanged("Name"); } } } /// <summary> /// Gets whether the download may be insecure. /// </summary> public bool IsInsecure { get { return _isInsecure; } } /// <summary> /// Gets the possible values for InstallUsing. /// </summary> public IEnumerable<string> InstallUsingOptions { get { if (_supportsConda) { yield return "conda"; } yield return "pip"; yield return "easy_install"; } } public bool SupportsConda { get { return _supportsConda; } set { _supportsConda = value; OnPropertyChanged("InstallUsingOptions"); OnPropertyChanged("SupportsConda"); } } /// <summary> /// Gets the current selected tool to install the package with. /// </summary> public string InstallUsing { get { return _installUsing; } set { if (_installUsing != value) { _installUsing = value; OnPropertyChanged("InstallUsing"); InstallUsingPip = _installUsing == "pip"; InstallUsingEasyInstall = _installUsing == "easy_install"; InstallUsingConda = _installUsing == "conda"; if (InstallUsingPip) { InstallElevated = _serviceProvider.GetPythonToolsService().GeneralOptions.ElevatePip; } else if (InstallUsingEasyInstall) { InstallElevated = _serviceProvider.GetPythonToolsService().GeneralOptions.ElevateEasyInstall; } else { InstallElevated = false; IsValid = false; } } } } /// <summary> /// True if InstallUsing is set to pip. /// </summary> public bool InstallUsingPip { get { return _installUsingPip; } private set { if (_installUsingPip != value) { _installUsingPip = value; OnPropertyChanged("InstallUsingPip"); } } } /// <summary> /// True if InstallUsing is set to easy_install. /// </summary> public bool InstallUsingEasyInstall { get { return _installUsingEasyInstall; } private set { if (_installUsingEasyInstall != value) { _installUsingEasyInstall = value; OnPropertyChanged("InstallUsingEasyInstall"); } } } /// <summary> /// True if InstallUsing is set to conda. /// </summary> public bool InstallUsingConda { get { return _installUsingConda; } private set { if (_installUsingConda != value) { _installUsingConda = value; OnPropertyChanged("InstallUsingConda"); } } } /// <summary> /// True if the user wants to elevate to install this package. /// </summary> public bool InstallElevated { get { return _installElevated; } set { if (_installElevated != value) { _installElevated = value; OnPropertyChanged("InstallElevated"); } } } /// <summary> /// Receives our own property change events to update IsValid. /// </summary> void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { Debug.Assert(sender == this); if (e.PropertyName != "IsValid") { IsValid = !String.IsNullOrWhiteSpace(_name); } } /// <summary> /// True if the settings are valid and all paths exist; otherwise, false. /// </summary> public bool IsValid { get { return _isValid; } private set { if (_isValid != value) { _isValid = value; OnPropertyChanged("IsValid"); } } } private void OnPropertyChanged(string propertyName) { var evt = PropertyChanged; if (evt != null) { evt(this, new PropertyChangedEventArgs(propertyName)); } } /// <summary> /// Raised when the value of a property changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; } }
// 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.Buffers.Binary; using System.Text; #nullable enable namespace Ignitor { public static class RenderBatchReader { private const int ReferenceFrameSize = 20; public static RenderBatch Read(ReadOnlySpan<byte> data) { var sections = Sections.Parse(data); var strings = ReadStringTable(data, sections.GetStringTableIndexes(data)); var diffs = ReadUpdatedComponents(data, sections.GetUpdatedComponentIndexes(data), strings); var frames = ReadReferenceFrames(sections.GetReferenceFrameData(data), strings); var disposedComponentIds = ReadDisposedComponentIds(data); var disposedEventHandlerIds = ReadDisposedEventHandlerIds(data); return new RenderBatch(diffs, frames, disposedComponentIds, disposedEventHandlerIds); } private static string[] ReadStringTable(ReadOnlySpan<byte> data, ReadOnlySpan<byte> indexes) { var result = new string[indexes.Length / 4]; for (var i = 0; i < indexes.Length; i += 4) { var index = BinaryPrimitives.ReadInt32LittleEndian(indexes.Slice(i, 4)); // The string table entries are all length-prefixed UTF8 blobs var length = (int)ReadUnsignedLEB128(data, index, out var numLEB128Bytes); var value = Encoding.UTF8.GetString(data.Slice(index + numLEB128Bytes, length)); result[i / 4] = value; } return result; } private static ArrayRange<RenderTreeDiff> ReadUpdatedComponents(ReadOnlySpan<byte> data, ReadOnlySpan<byte> indexes, string[] strings) { var result = new RenderTreeDiff[indexes.Length / 4]; for (var i = 0; i < indexes.Length; i += 4) { var index = BinaryPrimitives.ReadInt32LittleEndian(indexes.Slice(i, 4)); var componentId = BinaryPrimitives.ReadInt32LittleEndian(data.Slice(index, 4)); var editCount = BinaryPrimitives.ReadInt32LittleEndian(data.Slice(index + 4, 4)); var editData = data.Slice(index + 8); var edits = new RenderTreeEdit[editCount]; for (var j = 0; j < editCount; j++) { var type = (RenderTreeEditType)BinaryPrimitives.ReadInt32LittleEndian(editData.Slice(0, 4)); var siblingIndex = BinaryPrimitives.ReadInt32LittleEndian(editData.Slice(4, 4)); // ReferenceFrameIndex and MoveToSiblingIndex share a slot, so this reads // whichever one applies to the edit type var referenceFrameIndex = BinaryPrimitives.ReadInt32LittleEndian(editData.Slice(8, 4)); var removedAttributeName = ReadString(editData.Slice(12, 4), strings); editData = editData.Slice(16); switch (type) { case RenderTreeEditType.UpdateText: edits[j] = RenderTreeEdit.UpdateText(siblingIndex, referenceFrameIndex); break; case RenderTreeEditType.UpdateMarkup: edits[j] = RenderTreeEdit.UpdateMarkup(siblingIndex, referenceFrameIndex); break; case RenderTreeEditType.SetAttribute: edits[j] = RenderTreeEdit.SetAttribute(siblingIndex, referenceFrameIndex); break; case RenderTreeEditType.RemoveAttribute: edits[j] = RenderTreeEdit.RemoveAttribute(siblingIndex, removedAttributeName!); break; case RenderTreeEditType.PrependFrame: edits[j] = RenderTreeEdit.PrependFrame(siblingIndex, referenceFrameIndex); break; case RenderTreeEditType.RemoveFrame: edits[j] = RenderTreeEdit.RemoveFrame(siblingIndex); break; case RenderTreeEditType.StepIn: edits[j] = RenderTreeEdit.StepIn(siblingIndex); break; case RenderTreeEditType.StepOut: edits[j] = RenderTreeEdit.StepOut(); break; case RenderTreeEditType.PermutationListEntry: edits[j] = RenderTreeEdit.PermutationListEntry(siblingIndex, referenceFrameIndex); break; case RenderTreeEditType.PermutationListEnd: edits[j] = RenderTreeEdit.PermutationListEnd(); break; default: throw new InvalidOperationException("Unknown edit type:" + type); } } result[i / 4] = new RenderTreeDiff(componentId, ToArrayBuilderSegment(edits)); } return new ArrayRange<RenderTreeDiff>(result, result.Length); } private static ArrayBuilderSegment<T> ToArrayBuilderSegment<T>(T[] entries) { var builder = new ArrayBuilder<T>(); builder.Append(entries, 0, entries.Length); return builder.ToSegment(0, entries.Length); } private static ArrayRange<RenderTreeFrame> ReadReferenceFrames(ReadOnlySpan<byte> data, string[] strings) { var result = new RenderTreeFrame[data.Length / ReferenceFrameSize]; for (var i = 0; i < data.Length; i += ReferenceFrameSize) { var frameData = data.Slice(i, ReferenceFrameSize); var type = (RenderTreeFrameType)BinaryPrimitives.ReadInt32LittleEndian(frameData.Slice(0, 4)); // We want each frame to take up the same number of bytes, so that the // recipient can index into the array directly instead of having to // walk through it. // Since we can fit every frame type into 16 bytes, use that as the // common size. For smaller frames, we add padding to expand it to // 16 bytes. switch (type) { case RenderTreeFrameType.Attribute: var attributeName = ReadString(frameData.Slice(4, 4), strings); var attributeValue = ReadString(frameData.Slice(8, 4), strings); var attributeEventHandlerId = BinaryPrimitives.ReadUInt64LittleEndian(frameData.Slice(12, 8)); result[i / ReferenceFrameSize] = RenderTreeFrame.Attribute(0, attributeName, attributeValue).WithAttributeEventHandlerId(attributeEventHandlerId); break; case RenderTreeFrameType.Component: var componentSubtreeLength = BinaryPrimitives.ReadInt32LittleEndian(frameData.Slice(4, 4)); var componentId = BinaryPrimitives.ReadInt32LittleEndian(frameData.Slice(8, 4)); // Nowhere to put this without creating a ComponentState result[i / ReferenceFrameSize] = RenderTreeFrame.ChildComponent(0, componentType: null) .WithComponentSubtreeLength(componentSubtreeLength) .WithComponent(new ComponentState(componentId)); break; case RenderTreeFrameType.ComponentReferenceCapture: // Client doesn't process these, skip. result[i / ReferenceFrameSize] = RenderTreeFrame.ComponentReferenceCapture(0, null, 0); break; case RenderTreeFrameType.Element: var elementSubtreeLength = BinaryPrimitives.ReadInt32LittleEndian(frameData.Slice(4, 4)); var elementName = ReadString(frameData.Slice(8, 4), strings); result[i / ReferenceFrameSize] = RenderTreeFrame.Element(0, elementName).WithElementSubtreeLength(elementSubtreeLength); break; case RenderTreeFrameType.ElementReferenceCapture: var referenceCaptureId = ReadString(frameData.Slice(4, 4), strings); result[i / ReferenceFrameSize] = RenderTreeFrame.ElementReferenceCapture(0, null) .WithElementReferenceCaptureId(referenceCaptureId); break; case RenderTreeFrameType.Region: var regionSubtreeLength = BinaryPrimitives.ReadInt32LittleEndian(frameData.Slice(4, 4)); result[i / ReferenceFrameSize] = RenderTreeFrame.Region(0).WithRegionSubtreeLength(regionSubtreeLength); break; case RenderTreeFrameType.Text: var text = ReadString(frameData.Slice(4, 4), strings); result[i / ReferenceFrameSize] = RenderTreeFrame.Text(0, text); break; case RenderTreeFrameType.Markup: var markup = ReadString(frameData.Slice(4, 4), strings); result[i / ReferenceFrameSize] = RenderTreeFrame.Markup(0, markup); break; default: throw new ArgumentException($"Unsupported frame type: {type}"); } } return new ArrayRange<RenderTreeFrame>(result, result.Length); } private static ArrayRange<int> ReadDisposedComponentIds(ReadOnlySpan<byte> data) { return new ArrayRange<int>(Array.Empty<int>(), 0); } private static ArrayRange<ulong> ReadDisposedEventHandlerIds(ReadOnlySpan<byte> data) { return new ArrayRange<ulong>(Array.Empty<ulong>(), 0); } private static string? ReadString(ReadOnlySpan<byte> data, string[] strings) { var index = BinaryPrimitives.ReadInt32LittleEndian(data.Slice(0, 4)); return index >= 0 ? strings[index] : null; } private static uint ReadUnsignedLEB128(ReadOnlySpan<byte> data, int startOffset, out int numBytesRead) { var result = (uint)0; var shift = 0; var currentByte = (byte)128; numBytesRead = 0; for (var count = 0; count < 4 && currentByte >= 128; count++) { currentByte = data[startOffset + count]; result += (uint)(currentByte & 0x7f) << shift; shift += 7; numBytesRead++; } return result; } private readonly struct Sections { public static Sections Parse(ReadOnlySpan<byte> data) { return new Sections( BinaryPrimitives.ReadInt32LittleEndian(data.Slice(data.Length - 20, 4)), BinaryPrimitives.ReadInt32LittleEndian(data.Slice(data.Length - 16, 4)), BinaryPrimitives.ReadInt32LittleEndian(data.Slice(data.Length - 12, 4)), BinaryPrimitives.ReadInt32LittleEndian(data.Slice(data.Length - 8, 4)), BinaryPrimitives.ReadInt32LittleEndian(data.Slice(data.Length - 4, 4))); } private readonly int _updatedComponents; private readonly int _referenceFrames; private readonly int _disposedComponentIds; private readonly int _disposedEventHandlerIds; private readonly int _strings; public Sections(int updatedComponents, int referenceFrames, int disposedComponentIds, int disposedEventHandlerIds, int strings) { _updatedComponents = updatedComponents; _referenceFrames = referenceFrames; _disposedComponentIds = disposedComponentIds; _disposedEventHandlerIds = disposedEventHandlerIds; _strings = strings; } public ReadOnlySpan<byte> GetUpdatedComponentIndexes(ReadOnlySpan<byte> data) { // This is count-prefixed contiguous array of of integers. var count = BinaryPrimitives.ReadInt32LittleEndian(data.Slice(_updatedComponents, 4)); return data.Slice(_updatedComponents + 4, count * 4); } public ReadOnlySpan<byte> GetReferenceFrameData(ReadOnlySpan<byte> data) { // This is a count-prefixed contiguous array of RenderTreeFrame. var count = BinaryPrimitives.ReadInt32LittleEndian(data.Slice(_referenceFrames, 4)); return data.Slice(_referenceFrames + 4, count * ReferenceFrameSize); } public ReadOnlySpan<byte> GetStringTableIndexes(ReadOnlySpan<byte> data) { // This is a contiguous array of integers delimited by the end of the data section. return data.Slice(_strings, data.Length - 20 - _strings); } } } } #nullable restore
/* * JpegWriter.cs - Implementation of the "DotGNU.Images.JpegWriter" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software, you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY, without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program, if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace DotGNU.Images { using System; using System.IO; using System.Runtime.InteropServices; using OpenSystem.Platform; internal unsafe sealed class JpegWriter { // Save a JPEG image to the specified stream. public static void Save(Stream stream, Image image) { // Determine if we actually have the JPEG library. if(!JpegLib.JpegLibraryPresent()) { throw new FormatException("libjpeg is not available"); } // Create the compression object. JpegLib.jpeg_compress_struct cinfo; cinfo = new JpegLib.jpeg_compress_struct(); cinfo.err = JpegLib.CreateErrorHandler(); JpegLib.jpeg_create_compress(ref cinfo); // Initialize the destination manager. JpegLib.StreamToDestinationManager(ref cinfo, stream); // Get the frame to be written. Frame frame = image.GetFrame(0); // Set the JPEG compression parameters. cinfo.image_width = (UInt)(frame.Width); cinfo.image_height = (UInt)(frame.Height); cinfo.input_components = (Int)3; cinfo.in_color_space = JpegLib.J_COLOR_SPACE.JCS_RGB; JpegLib.jpeg_set_defaults(ref cinfo); // Start the compression process. JpegLib.jpeg_start_compress(ref cinfo, (Int)1); // Write the scanlines to the image. int posn, width, offset, stride; width = frame.Width; stride = frame.Stride; byte[] data = frame.Data; PixelFormat format = frame.PixelFormat; IntPtr buf = Marshal.AllocHGlobal(width * 3); byte *pbuf = (byte *)buf; while(((int)(cinfo.next_scanline)) < ((int)(cinfo.image_height))) { // Convert the source scanline into the JCS_RGB format. offset = ((int)(cinfo.next_scanline)) * stride; switch(format) { case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppArgb1555: { Rgb555(data, offset, width, pbuf); } break; case PixelFormat.Format16bppRgb565: { Rgb565(data, offset, width, pbuf); } break; case PixelFormat.Format24bppRgb: { Rgb24bpp(data, offset, width, pbuf); } break; case PixelFormat.Format32bppRgb: case PixelFormat.Format32bppArgb: case PixelFormat.Format32bppPArgb: { Rgb32bpp(data, offset, width, pbuf); } break; case PixelFormat.Format1bppIndexed: { Rgb1bpp(data, offset, width, pbuf, frame.Palette); } break; case PixelFormat.Format4bppIndexed: { Rgb4bpp(data, offset, width, pbuf, frame.Palette); } break; case PixelFormat.Format8bppIndexed: { Rgb8bpp(data, offset, width, pbuf, frame.Palette); } break; case PixelFormat.Format16bppGrayScale: { GrayScale16bpp(data, offset, width, pbuf); } break; case PixelFormat.Format48bppRgb: { Rgb48bpp(data, offset, width, pbuf); } break; case PixelFormat.Format64bppPArgb: case PixelFormat.Format64bppArgb: { Rgb64bpp(data, offset, width, pbuf); } break; } // Write the scanline to the buffer. JpegLib.jpeg_write_scanlines (ref cinfo, ref buf, (UInt)1); } Marshal.FreeHGlobal(buf); // Finish the compression process. JpegLib.jpeg_finish_compress(ref cinfo); // Clean everything up. JpegLib.FreeDestinationManager(ref cinfo); JpegLib.jpeg_destroy_compress(ref cinfo); JpegLib.FreeErrorHandler(cinfo.err); } // Convert 15-bit RGB data into the JPEG scanline format. private static void Rgb555(byte[] data, int offset, int width, byte *buf) { int posn = 0; int value; while(width > 0) { value = data[offset] | (data[offset + 1] << 8); buf[posn] = (byte)(((value >> 7) & 0xF8) | ((value >> 12) & 0x07)); buf[posn + 1] = (byte)(((value >> 2) & 0xF8) | ((value >> 7) & 0x07)); buf[posn + 2] = (byte)(((value << 3) & 0xF8) | ((value >> 2) & 0x07)); offset += 2; posn += 3; --width; } } // Convert 16-bit RGB data into the JPEG scanline format. private static void Rgb565(byte[] data, int offset, int width, byte *buf) { int posn = 0; int value; while(width > 0) { value = data[offset] | (data[offset + 1] << 8); buf[posn] = (byte)(((value >> 8) & 0xF8) | ((value >> 13) & 0x07)); buf[posn + 1] = (byte)(((value >> 3) & 0xFC) | ((value >> 9) & 0x03)); buf[posn + 2] = (byte)(((value << 3) & 0xF8) | ((value >> 2) & 0x07)); offset += 2; posn += 3; --width; } } // Convert 24-bit RGB data into the JPEG scanline format. private static void Rgb24bpp(byte[] data, int offset, int width, byte *buf) { int posn = 0; while(width > 0) { buf[posn] = data[offset + 2]; buf[posn + 1] = data[offset + 1]; buf[posn + 2] = data[offset]; offset += 3; posn += 3; --width; } } // Convert 32-bit RGB data into the JPEG scanline format. private static void Rgb32bpp(byte[] data, int offset, int width, byte *buf) { int posn = 0; while(width > 0) { buf[posn] = data[offset + 2]; buf[posn + 1] = data[offset + 1]; buf[posn + 2] = data[offset]; offset += 4; posn += 3; --width; } } // Convert 1-bit indexed data into the JPEG scanline format. private static void Rgb1bpp (byte[] data, int offset, int width, byte *buf, int[] palette) { int posn = 0; int bit = 0x80; int value; while(width > 0) { if((data[offset] & bit) != 0) { value = palette[1]; } else { value = palette[0]; } buf[posn] = (byte)(value >> 16); buf[posn + 1] = (byte)(value >> 8); buf[posn + 2] = (byte)value; bit >>= 1; if(bit == 0) { bit = 0x80; ++offset; } posn += 3; --width; } } // Convert 4-bit indexed data into the JPEG scanline format. private static void Rgb4bpp (byte[] data, int offset, int width, byte *buf, int[] palette) { int posn = 0; int bit = 4; int value; while(width > 0) { value = palette[(data[offset] >> bit) & 0x0F]; buf[posn] = (byte)(value >> 16); buf[posn + 1] = (byte)(value >> 8); buf[posn + 2] = (byte)value; bit -= 4; if(bit < 0) { bit = 4; ++offset; } posn += 3; --width; } } // Convert 8-bit indexed data into the JPEG scanline format. private static void Rgb8bpp (byte[] data, int offset, int width, byte *buf, int[] palette) { int posn = 0; int value; while(width > 0) { value = palette[data[offset]]; buf[posn] = (byte)(value >> 16); buf[posn + 1] = (byte)(value >> 8); buf[posn + 2] = (byte)value; ++offset; posn += 3; --width; } } // Convert 16-bit grayscale data into the JPEG scanline format. private static void GrayScale16bpp (byte[] data, int offset, int width, byte *buf) { int posn = 0; byte value; while(width > 0) { value = data[offset + 1]; buf[posn] = value; buf[posn + 1] = value; buf[posn + 2] = value; offset += 2; posn += 3; --width; } } // Convert 48-bit RGB data into the JPEG scanline format. private static void Rgb48bpp(byte[] data, int offset, int width, byte *buf) { int posn = 0; while(width > 0) { buf[posn] = data[offset + 5]; buf[posn + 1] = data[offset + 3]; buf[posn + 2] = data[offset + 1]; offset += 6; posn += 3; --width; } } // Convert 64-bit RGB data into the JPEG scanline format. private static void Rgb64bpp(byte[] data, int offset, int width, byte *buf) { int posn = 0; while(width > 0) { buf[posn] = data[offset + 5]; buf[posn + 1] = data[offset + 3]; buf[posn + 2] = data[offset + 1]; offset += 8; posn += 3; --width; } } }; // class JpegWriter }; // namespace DotGNU.Images
// 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.Net { internal static partial class HttpKnownHeaderNames { /// <summary> /// Gets a known header name string from a matching char[] array segment, using an ordinal comparison. /// Used to avoid allocating new strings for known header names. /// </summary> public static bool TryGetHeaderName(char[] array, int startIndex, int length, out string name) { CharArrayHelpers.DebugAssertArrayInputs(array, startIndex, length); return TryGetHeaderName( array, startIndex, length, (arr, index) => arr[index], (known, arr, start, len) => CharArrayHelpers.EqualsOrdinal(known, arr, start, len), out name); } /// <summary> /// Gets a known header name string from a matching IntPtr buffer, using an ordinal comparison. /// Used to avoid allocating new strings for known header names. /// </summary> public unsafe static bool TryGetHeaderName(IntPtr buffer, int length, out string name) { Debug.Assert(length >= 0); if (buffer == IntPtr.Zero) { name = null; return false; } // We always pass 0 for the startIndex, as buffer should already point to the start. const int startIndex = 0; return TryGetHeaderName( buffer, startIndex, length, (buf, index) => (char)((byte*)buf)[index], (known, buf, start, len) => EqualsOrdinal(known, buf, len), out name); } private static bool TryGetHeaderName<T>( T key, int startIndex, int length, Func<T, int, char> charAt, Func<string, T, int, int, bool> equals, out string name) { Debug.Assert(key != null); Debug.Assert(startIndex >= 0); Debug.Assert(length >= 0); Debug.Assert(charAt != null); Debug.Assert(equals != null); // When adding a new constant, add it to HttpKnownHeaderNames.cs as well. // The lookup works as follows: first switch on the length of the passed-in key. // // - If there is only one known header of that length and the key matches that // known header, set it as the out param and return true. // // - If there are more than one known headers of that length, switch on a unique char from that // set of same-length known headers. Typically this will be the first char, but some sets of // same-length known headers do not have unique chars in the first position, so a char in a // position further in the strings is used. If the key matches one of the known headers, // set it as the out param and return true. // // - Otherwise, set the out param to null and return false. switch (length) { case 2: return TryMatch(TE, key, startIndex, length, equals, out name); // TE case 3: switch (charAt(key, startIndex)) { case 'A': return TryMatch(Age, key, startIndex, length, equals, out name); // [A]ge case 'P': return TryMatch(P3P, key, startIndex, length, equals, out name); // [P]3P case 'V': return TryMatch(Via, key, startIndex, length, equals, out name); // [V]ia } break; case 4: switch (charAt(key, startIndex)) { case 'D': return TryMatch(Date, key, startIndex, length, equals, out name); // [D]ate case 'E': return TryMatch(ETag, key, startIndex, length, equals, out name); // [E]Tag case 'F': return TryMatch(From, key, startIndex, length, equals, out name); // [F]rom case 'H': return TryMatch(Host, key, startIndex, length, equals, out name); // [H]ost case 'V': return TryMatch(Vary, key, startIndex, length, equals, out name); // [V]ary } break; case 5: switch (charAt(key, startIndex)) { case 'A': return TryMatch(Allow, key, startIndex, length, equals, out name); // [A]llow case 'R': return TryMatch(Range, key, startIndex, length, equals, out name); // [R]ange } break; case 6: switch (charAt(key, startIndex)) { case 'A': return TryMatch(Accept, key, startIndex, length, equals, out name); // [A]ccept case 'C': return TryMatch(Cookie, key, startIndex, length, equals, out name); // [C]ookie case 'E': return TryMatch(Expect, key, startIndex, length, equals, out name); // [E]xpect case 'O': return TryMatch(Origin, key, startIndex, length, equals, out name); // [O]rigin case 'P': return TryMatch(Pragma, key, startIndex, length, equals, out name); // [P]ragma case 'S': return TryMatch(Server, key, startIndex, length, equals, out name); // [S]erver } break; case 7: switch (charAt(key, startIndex)) { case 'C': return TryMatch(Cookie2, key, startIndex, length, equals, out name); // [C]ookie2 case 'E': return TryMatch(Expires, key, startIndex, length, equals, out name); // [E]xpires case 'R': return TryMatch(Referer, key, startIndex, length, equals, out name); // [R]eferer case 'T': return TryMatch(Trailer, key, startIndex, length, equals, out name); // [T]railer case 'U': return TryMatch(Upgrade, key, startIndex, length, equals, out name); // [U]pgrade case 'W': return TryMatch(Warning, key, startIndex, length, equals, out name); // [W]arning } break; case 8: switch (charAt(key, startIndex + 3)) { case 'M': return TryMatch(IfMatch, key, startIndex, length, equals, out name); // If-[M]atch case 'R': return TryMatch(IfRange, key, startIndex, length, equals, out name); // If-[R]ange case 'a': return TryMatch(Location, key, startIndex, length, equals, out name); // Loc[a]tion } break; case 10: switch (charAt(key, startIndex)) { case 'C': return TryMatch(Connection, key, startIndex, length, equals, out name); // [C]onnection case 'K': return TryMatch(KeepAlive, key, startIndex, length, equals, out name); // [K]eep-Alive case 'S': return TryMatch(SetCookie, key, startIndex, length, equals, out name); // [S]et-Cookie case 'U': return TryMatch(UserAgent, key, startIndex, length, equals, out name); // [U]ser-Agent } break; case 11: switch (charAt(key, startIndex)) { case 'C': return TryMatch(ContentMD5, key, startIndex, length, equals, out name); // [C]ontent-MD5 case 'R': return TryMatch(RetryAfter, key, startIndex, length, equals, out name); // [R]etry-After case 'S': return TryMatch(SetCookie2, key, startIndex, length, equals, out name); // [S]et-Cookie2 } break; case 12: switch (charAt(key, startIndex)) { case 'C': return TryMatch(ContentType, key, startIndex, length, equals, out name); // [C]ontent-Type case 'M': return TryMatch(MaxForwards, key, startIndex, length, equals, out name); // [M]ax-Forwards case 'X': return TryMatch(XPoweredBy, key, startIndex, length, equals, out name); // [X]-Powered-By } break; case 13: switch (charAt(key, startIndex + 6)) { case '-': return TryMatch(AcceptRanges, key, startIndex, length, equals, out name); // Accept[-]Ranges case 'i': return TryMatch(Authorization, key, startIndex, length, equals, out name); // Author[i]zation case 'C': return TryMatch(CacheControl, key, startIndex, length, equals, out name); // Cache-[C]ontrol case 't': return TryMatch(ContentRange, key, startIndex, length, equals, out name); // Conten[t]-Range case 'e': return TryMatch(IfNoneMatch, key, startIndex, length, equals, out name); // If-Non[e]-Match case 'o': return TryMatch(LastModified, key, startIndex, length, equals, out name); // Last-M[o]dified } break; case 14: switch (charAt(key, startIndex)) { case 'A': return TryMatch(AcceptCharset, key, startIndex, length, equals, out name); // [A]ccept-Charset case 'C': return TryMatch(ContentLength, key, startIndex, length, equals, out name); // [C]ontent-Length } break; case 15: switch (charAt(key, startIndex + 7)) { case 'E': return TryMatch(AcceptEncoding, key, startIndex, length, equals, out name); // Accept-[E]ncoding case 'L': return TryMatch(AcceptLanguage, key, startIndex, length, equals, out name); // Accept-[L]anguage } break; case 16: switch (charAt(key, startIndex + 11)) { case 'o': return TryMatch(ContentEncoding, key, startIndex, length, equals, out name); // Content-Enc[o]ding case 'g': return TryMatch(ContentLanguage, key, startIndex, length, equals, out name); // Content-Lan[g]uage case 'a': return TryMatch(ContentLocation, key, startIndex, length, equals, out name); // Content-Loc[a]tion case 'c': return TryMatch(ProxyConnection, key, startIndex, length, equals, out name); // Proxy-Conne[c]tion case 'i': return TryMatch(WWWAuthenticate, key, startIndex, length, equals, out name); // WWW-Authent[i]cate case 'r': return TryMatch(XAspNetVersion, key, startIndex, length, equals, out name); // X-AspNet-Ve[r]sion } break; case 17: switch (charAt(key, startIndex)) { case 'I': return TryMatch(IfModifiedSince, key, startIndex, length, equals, out name); // [I]f-Modified-Since case 'S': return TryMatch(SecWebSocketKey, key, startIndex, length, equals, out name); // [S]ec-WebSocket-Key case 'T': return TryMatch(TransferEncoding, key, startIndex, length, equals, out name); // [T]ransfer-Encoding } break; case 18: return TryMatch(ProxyAuthenticate, key, startIndex, length, equals, out name); // Proxy-Authenticate case 19: switch (charAt(key, startIndex)) { case 'C': return TryMatch(ContentDisposition, key, startIndex, length, equals, out name); // [C]ontent-Disposition case 'I': return TryMatch(IfUnmodifiedSince, key, startIndex, length, equals, out name); // [I]f-Unmodified-Since case 'P': return TryMatch(ProxyAuthorization, key, startIndex, length, equals, out name); // [P]roxy-Authorization } break; case 20: return TryMatch(SecWebSocketAccept, key, startIndex, length, equals, out name); // Sec-WebSocket-Accept case 21: return TryMatch(SecWebSocketVersion, key, startIndex, length, equals, out name); // Sec-WebSocket-Version case 22: return TryMatch(SecWebSocketProtocol, key, startIndex, length, equals, out name); // Sec-WebSocket-Protocol case 24: return TryMatch(SecWebSocketExtensions, key, startIndex, length, equals, out name); // Sec-WebSocket-Extensions } name = null; return false; } /// <summary> /// Returns true if <paramref name="known"/> matches the <paramref name="key"/> char[] array segment, /// using an ordinal comparison. /// </summary> private static bool TryMatch<T>(string known, T key, int startIndex, int length, Func<string, T, int, int, bool> equals, out string name) { Debug.Assert(known != null); Debug.Assert(known.Length > 0); Debug.Assert(startIndex >= 0); Debug.Assert(length > 0); Debug.Assert(equals != null); // The lengths should be equal because this method is only called // from within a "switch (length) { ... }". Debug.Assert(known.Length == length); if (equals(known, key, startIndex, length)) { name = known; return true; } name = null; return false; } private unsafe static bool EqualsOrdinal(string left, IntPtr right, int rightLength) { Debug.Assert(left != null); Debug.Assert(right != IntPtr.Zero); Debug.Assert(rightLength > 0); // At this point the lengths have already been determined to be equal. Debug.Assert(left.Length == rightLength); byte* pRight = (byte*)right; for (int i = 0; i < left.Length; i++) { if (left[i] != pRight[i]) { return false; } } return true; } } }
// ***************************************************************************** // // Copyright 2004, Weifen Luo // All rights reserved. The software and associated documentation // supplied hereunder are the proprietary information of Weifen Luo // and are supplied subject to licence terms. // // WinFormsUI Library Version 1.0 // ***************************************************************************** using System; namespace WeifenLuo.WinFormsUI.Win32 { internal enum PeekMessageFlags { PM_NOREMOVE = 0, PM_REMOVE = 1, PM_NOYIELD = 2 } [Flags] internal enum FlagsSetWindowPos : uint { SWP_NOSIZE = 0x0001, SWP_NOMOVE = 0x0002, SWP_NOZORDER = 0x0004, SWP_NOREDRAW = 0x0008, SWP_NOACTIVATE = 0x0010, SWP_FRAMECHANGED = 0x0020, SWP_SHOWWINDOW = 0x0040, SWP_HIDEWINDOW = 0x0080, SWP_NOCOPYBITS = 0x0100, SWP_NOOWNERZORDER = 0x0200, SWP_NOSENDCHANGING = 0x0400, SWP_DRAWFRAME = 0x0020, SWP_NOREPOSITION = 0x0200, SWP_DEFERERASE = 0x2000, SWP_ASYNCWINDOWPOS = 0x4000 } internal enum SetWindowPosZ { HWND_TOP = 0, HWND_BOTTOM = 1, HWND_TOPMOST = -1, HWND_NOTOPMOST = -2 } internal enum ShowWindowStyles : short { SW_HIDE = 0, SW_SHOWNORMAL = 1, SW_NORMAL = 1, SW_SHOWMINIMIZED = 2, SW_SHOWMAXIMIZED = 3, SW_MAXIMIZE = 3, SW_SHOWNOACTIVATE = 4, SW_SHOW = 5, SW_MINIMIZE = 6, SW_SHOWMINNOACTIVE = 7, SW_SHOWNA = 8, SW_RESTORE = 9, SW_SHOWDEFAULT = 10, SW_FORCEMINIMIZE = 11, SW_MAX = 11 } internal enum WindowStyles : uint { WS_OVERLAPPED = 0x00000000, WS_POPUP = 0x80000000, WS_CHILD = 0x40000000, WS_MINIMIZE = 0x20000000, WS_VISIBLE = 0x10000000, WS_DISABLED = 0x08000000, WS_CLIPSIBLINGS = 0x04000000, WS_CLIPCHILDREN = 0x02000000, WS_MAXIMIZE = 0x01000000, WS_CAPTION = 0x00C00000, WS_BORDER = 0x00800000, WS_DLGFRAME = 0x00400000, WS_VSCROLL = 0x00200000, WS_HSCROLL = 0x00100000, WS_SYSMENU = 0x00080000, WS_THICKFRAME = 0x00040000, WS_GROUP = 0x00020000, WS_TABSTOP = 0x00010000, WS_MINIMIZEBOX = 0x00020000, WS_MAXIMIZEBOX = 0x00010000, WS_TILED = 0x00000000, WS_ICONIC = 0x20000000, WS_SIZEBOX = 0x00040000, WS_POPUPWINDOW = 0x80880000, WS_OVERLAPPEDWINDOW = 0x00CF0000, WS_TILEDWINDOW = 0x00CF0000, WS_CHILDWINDOW = 0x40000000 } internal enum WindowExStyles { WS_EX_DLGMODALFRAME = 0x00000001, WS_EX_NOPARENTNOTIFY = 0x00000004, WS_EX_TOPMOST = 0x00000008, WS_EX_ACCEPTFILES = 0x00000010, WS_EX_TRANSPARENT = 0x00000020, WS_EX_MDICHILD = 0x00000040, WS_EX_TOOLWINDOW = 0x00000080, WS_EX_WINDOWEDGE = 0x00000100, WS_EX_CLIENTEDGE = 0x00000200, WS_EX_CONTEXTHELP = 0x00000400, WS_EX_RIGHT = 0x00001000, WS_EX_LEFT = 0x00000000, WS_EX_RTLREADING = 0x00002000, WS_EX_LTRREADING = 0x00000000, WS_EX_LEFTSCROLLBAR = 0x00004000, WS_EX_RIGHTSCROLLBAR = 0x00000000, WS_EX_CONTROLPARENT = 0x00010000, WS_EX_STATICEDGE = 0x00020000, WS_EX_APPWINDOW = 0x00040000, WS_EX_OVERLAPPEDWINDOW = 0x00000300, WS_EX_PALETTEWINDOW = 0x00000188, WS_EX_LAYERED = 0x00080000 } internal enum VirtualKeys { VK_LBUTTON = 0x01, VK_CANCEL = 0x03, VK_BACK = 0x08, VK_TAB = 0x09, VK_CLEAR = 0x0C, VK_RETURN = 0x0D, VK_SHIFT = 0x10, VK_CONTROL = 0x11, VK_MENU = 0x12, VK_CAPITAL = 0x14, VK_ESCAPE = 0x1B, VK_SPACE = 0x20, VK_PRIOR = 0x21, VK_NEXT = 0x22, VK_END = 0x23, VK_HOME = 0x24, VK_LEFT = 0x25, VK_UP = 0x26, VK_RIGHT = 0x27, VK_DOWN = 0x28, VK_SELECT = 0x29, VK_EXECUTE = 0x2B, VK_SNAPSHOT = 0x2C, VK_HELP = 0x2F, VK_0 = 0x30, VK_1 = 0x31, VK_2 = 0x32, VK_3 = 0x33, VK_4 = 0x34, VK_5 = 0x35, VK_6 = 0x36, VK_7 = 0x37, VK_8 = 0x38, VK_9 = 0x39, VK_A = 0x41, VK_B = 0x42, VK_C = 0x43, VK_D = 0x44, VK_E = 0x45, VK_F = 0x46, VK_G = 0x47, VK_H = 0x48, VK_I = 0x49, VK_J = 0x4A, VK_K = 0x4B, VK_L = 0x4C, VK_M = 0x4D, VK_N = 0x4E, VK_O = 0x4F, VK_P = 0x50, VK_Q = 0x51, VK_R = 0x52, VK_S = 0x53, VK_T = 0x54, VK_U = 0x55, VK_V = 0x56, VK_W = 0x57, VK_X = 0x58, VK_Y = 0x59, VK_Z = 0x5A, VK_NUMPAD0 = 0x60, VK_NUMPAD1 = 0x61, VK_NUMPAD2 = 0x62, VK_NUMPAD3 = 0x63, VK_NUMPAD4 = 0x64, VK_NUMPAD5 = 0x65, VK_NUMPAD6 = 0x66, VK_NUMPAD7 = 0x67, VK_NUMPAD8 = 0x68, VK_NUMPAD9 = 0x69, VK_MULTIPLY = 0x6A, VK_ADD = 0x6B, VK_SEPARATOR = 0x6C, VK_SUBTRACT = 0x6D, VK_DECIMAL = 0x6E, VK_DIVIDE = 0x6F, VK_ATTN = 0xF6, VK_CRSEL = 0xF7, VK_EXSEL = 0xF8, VK_EREOF = 0xF9, VK_PLAY = 0xFA, VK_ZOOM = 0xFB, VK_NONAME = 0xFC, VK_PA1 = 0xFD, VK_OEM_CLEAR = 0xFE, VK_LWIN = 0x5B, VK_RWIN = 0x5C, VK_APPS = 0x5D, VK_LSHIFT = 0xA0, VK_RSHIFT = 0xA1, VK_LCONTROL = 0xA2, VK_RCONTROL = 0xA3, VK_LMENU = 0xA4, VK_RMENU = 0xA5 } internal enum Msgs { WM_NULL = 0x0000, WM_CREATE = 0x0001, WM_DESTROY = 0x0002, WM_MOVE = 0x0003, WM_SIZE = 0x0005, WM_ACTIVATE = 0x0006, WM_SETFOCUS = 0x0007, WM_KILLFOCUS = 0x0008, WM_ENABLE = 0x000A, WM_SETREDRAW = 0x000B, WM_SETTEXT = 0x000C, WM_GETTEXT = 0x000D, WM_GETTEXTLENGTH = 0x000E, WM_PAINT = 0x000F, WM_CLOSE = 0x0010, WM_QUERYENDSESSION = 0x0011, WM_QUIT = 0x0012, WM_QUERYOPEN = 0x0013, WM_ERASEBKGND = 0x0014, WM_SYSCOLORCHANGE = 0x0015, WM_ENDSESSION = 0x0016, WM_SHOWWINDOW = 0x0018, WM_WININICHANGE = 0x001A, WM_SETTINGCHANGE = 0x001A, WM_DEVMODECHANGE = 0x001B, WM_ACTIVATEAPP = 0x001C, WM_FONTCHANGE = 0x001D, WM_TIMECHANGE = 0x001E, WM_CANCELMODE = 0x001F, WM_SETCURSOR = 0x0020, WM_MOUSEACTIVATE = 0x0021, WM_CHILDACTIVATE = 0x0022, WM_QUEUESYNC = 0x0023, WM_GETMINMAXINFO = 0x0024, WM_PAINTICON = 0x0026, WM_ICONERASEBKGND = 0x0027, WM_NEXTDLGCTL = 0x0028, WM_SPOOLERSTATUS = 0x002A, WM_DRAWITEM = 0x002B, WM_MEASUREITEM = 0x002C, WM_DELETEITEM = 0x002D, WM_VKEYTOITEM = 0x002E, WM_CHARTOITEM = 0x002F, WM_SETFONT = 0x0030, WM_GETFONT = 0x0031, WM_SETHOTKEY = 0x0032, WM_GETHOTKEY = 0x0033, WM_QUERYDRAGICON = 0x0037, WM_COMPAREITEM = 0x0039, WM_GETOBJECT = 0x003D, WM_COMPACTING = 0x0041, WM_COMMNOTIFY = 0x0044 , WM_WINDOWPOSCHANGING = 0x0046, WM_WINDOWPOSCHANGED = 0x0047, WM_POWER = 0x0048, WM_COPYDATA = 0x004A, WM_CANCELJOURNAL = 0x004B, WM_NOTIFY = 0x004E, WM_INPUTLANGCHANGEREQUEST = 0x0050, WM_INPUTLANGCHANGE = 0x0051, WM_TCARD = 0x0052, WM_HELP = 0x0053, WM_USERCHANGED = 0x0054, WM_NOTIFYFORMAT = 0x0055, WM_CONTEXTMENU = 0x007B, WM_STYLECHANGING = 0x007C, WM_STYLECHANGED = 0x007D, WM_DISPLAYCHANGE = 0x007E, WM_GETICON = 0x007F, WM_SETICON = 0x0080, WM_NCCREATE = 0x0081, WM_NCDESTROY = 0x0082, WM_NCCALCSIZE = 0x0083, WM_NCHITTEST = 0x0084, WM_NCPAINT = 0x0085, WM_NCACTIVATE = 0x0086, WM_GETDLGCODE = 0x0087, WM_SYNCPAINT = 0x0088, WM_NCMOUSEMOVE = 0x00A0, WM_NCLBUTTONDOWN = 0x00A1, WM_NCLBUTTONUP = 0x00A2, WM_NCLBUTTONDBLCLK = 0x00A3, WM_NCRBUTTONDOWN = 0x00A4, WM_NCRBUTTONUP = 0x00A5, WM_NCRBUTTONDBLCLK = 0x00A6, WM_NCMBUTTONDOWN = 0x00A7, WM_NCMBUTTONUP = 0x00A8, WM_NCMBUTTONDBLCLK = 0x00A9, WM_KEYDOWN = 0x0100, WM_KEYUP = 0x0101, WM_CHAR = 0x0102, WM_DEADCHAR = 0x0103, WM_SYSKEYDOWN = 0x0104, WM_SYSKEYUP = 0x0105, WM_SYSCHAR = 0x0106, WM_SYSDEADCHAR = 0x0107, WM_KEYLAST = 0x0108, WM_IME_STARTCOMPOSITION = 0x010D, WM_IME_ENDCOMPOSITION = 0x010E, WM_IME_COMPOSITION = 0x010F, WM_IME_KEYLAST = 0x010F, WM_INITDIALOG = 0x0110, WM_COMMAND = 0x0111, WM_SYSCOMMAND = 0x0112, WM_TIMER = 0x0113, WM_HSCROLL = 0x0114, WM_VSCROLL = 0x0115, WM_INITMENU = 0x0116, WM_INITMENUPOPUP = 0x0117, WM_MENUSELECT = 0x011F, WM_MENUCHAR = 0x0120, WM_ENTERIDLE = 0x0121, WM_MENURBUTTONUP = 0x0122, WM_MENUDRAG = 0x0123, WM_MENUGETOBJECT = 0x0124, WM_UNINITMENUPOPUP = 0x0125, WM_MENUCOMMAND = 0x0126, WM_CTLCOLORMSGBOX = 0x0132, WM_CTLCOLOREDIT = 0x0133, WM_CTLCOLORLISTBOX = 0x0134, WM_CTLCOLORBTN = 0x0135, WM_CTLCOLORDLG = 0x0136, WM_CTLCOLORSCROLLBAR = 0x0137, WM_CTLCOLORSTATIC = 0x0138, WM_MOUSEMOVE = 0x0200, WM_LBUTTONDOWN = 0x0201, WM_LBUTTONUP = 0x0202, WM_LBUTTONDBLCLK = 0x0203, WM_RBUTTONDOWN = 0x0204, WM_RBUTTONUP = 0x0205, WM_RBUTTONDBLCLK = 0x0206, WM_MBUTTONDOWN = 0x0207, WM_MBUTTONUP = 0x0208, WM_MBUTTONDBLCLK = 0x0209, WM_MOUSEWHEEL = 0x020A, WM_PARENTNOTIFY = 0x0210, WM_ENTERMENULOOP = 0x0211, WM_EXITMENULOOP = 0x0212, WM_NEXTMENU = 0x0213, WM_SIZING = 0x0214, WM_CAPTURECHANGED = 0x0215, WM_MOVING = 0x0216, WM_DEVICECHANGE = 0x0219, WM_MDICREATE = 0x0220, WM_MDIDESTROY = 0x0221, WM_MDIACTIVATE = 0x0222, WM_MDIRESTORE = 0x0223, WM_MDINEXT = 0x0224, WM_MDIMAXIMIZE = 0x0225, WM_MDITILE = 0x0226, WM_MDICASCADE = 0x0227, WM_MDIICONARRANGE = 0x0228, WM_MDIGETACTIVE = 0x0229, WM_MDISETMENU = 0x0230, WM_ENTERSIZEMOVE = 0x0231, WM_EXITSIZEMOVE = 0x0232, WM_DROPFILES = 0x0233, WM_MDIREFRESHMENU = 0x0234, WM_IME_SETCONTEXT = 0x0281, WM_IME_NOTIFY = 0x0282, WM_IME_CONTROL = 0x0283, WM_IME_COMPOSITIONFULL = 0x0284, WM_IME_SELECT = 0x0285, WM_IME_CHAR = 0x0286, WM_IME_REQUEST = 0x0288, WM_IME_KEYDOWN = 0x0290, WM_IME_KEYUP = 0x0291, WM_MOUSEHOVER = 0x02A1, WM_MOUSELEAVE = 0x02A3, WM_CUT = 0x0300, WM_COPY = 0x0301, WM_PASTE = 0x0302, WM_CLEAR = 0x0303, WM_UNDO = 0x0304, WM_RENDERFORMAT = 0x0305, WM_RENDERALLFORMATS = 0x0306, WM_DESTROYCLIPBOARD = 0x0307, WM_DRAWCLIPBOARD = 0x0308, WM_PAINTCLIPBOARD = 0x0309, WM_VSCROLLCLIPBOARD = 0x030A, WM_SIZECLIPBOARD = 0x030B, WM_ASKCBFORMATNAME = 0x030C, WM_CHANGECBCHAIN = 0x030D, WM_HSCROLLCLIPBOARD = 0x030E, WM_QUERYNEWPALETTE = 0x030F, WM_PALETTEISCHANGING = 0x0310, WM_PALETTECHANGED = 0x0311, WM_HOTKEY = 0x0312, WM_PRINT = 0x0317, WM_PRINTCLIENT = 0x0318, WM_HANDHELDFIRST = 0x0358, WM_HANDHELDLAST = 0x035F, WM_AFXFIRST = 0x0360, WM_AFXLAST = 0x037F, WM_PENWINFIRST = 0x0380, WM_PENWINLAST = 0x038F, WM_APP = 0x8000, WM_USER = 0x0400 } internal enum Cursors : uint { IDC_ARROW = 32512U, IDC_IBEAM = 32513U, IDC_WAIT = 32514U, IDC_CROSS = 32515U, IDC_UPARROW = 32516U, IDC_SIZE = 32640U, IDC_ICON = 32641U, IDC_SIZENWSE = 32642U, IDC_SIZENESW = 32643U, IDC_SIZEWE = 32644U, IDC_SIZENS = 32645U, IDC_SIZEALL = 32646U, IDC_NO = 32648U, IDC_HAND = 32649U, IDC_APPSTARTING = 32650U, IDC_HELP = 32651U } internal enum TrackerEventFlags : uint { TME_HOVER = 0x00000001, TME_LEAVE = 0x00000002, TME_QUERY = 0x40000000, TME_CANCEL = 0x80000000 } internal enum MouseActivateFlags { MA_ACTIVATE = 1, MA_ACTIVATEANDEAT = 2, MA_NOACTIVATE = 3, MA_NOACTIVATEANDEAT = 4 } internal enum DialogCodes { DLGC_WANTARROWS = 0x0001, DLGC_WANTTAB = 0x0002, DLGC_WANTALLKEYS = 0x0004, DLGC_WANTMESSAGE = 0x0004, DLGC_HASSETSEL = 0x0008, DLGC_DEFPUSHBUTTON = 0x0010, DLGC_UNDEFPUSHBUTTON = 0x0020, DLGC_RADIOBUTTON = 0x0040, DLGC_WANTCHARS = 0x0080, DLGC_STATIC = 0x0100, DLGC_BUTTON = 0x2000 } internal enum UpdateLayeredWindowsFlags { ULW_COLORKEY = 0x00000001, ULW_ALPHA = 0x00000002, ULW_OPAQUE = 0x00000004 } internal enum AlphaFlags : byte { AC_SRC_OVER = 0x00, AC_SRC_ALPHA = 0x01 } internal enum RasterOperations : uint { SRCCOPY = 0x00CC0020, SRCPAINT = 0x00EE0086, SRCAND = 0x008800C6, SRCINVERT = 0x00660046, SRCERASE = 0x00440328, NOTSRCCOPY = 0x00330008, NOTSRCERASE = 0x001100A6, MERGECOPY = 0x00C000CA, MERGEPAINT = 0x00BB0226, PATCOPY = 0x00F00021, PATPAINT = 0x00FB0A09, PATINVERT = 0x005A0049, DSTINVERT = 0x00550009, BLACKNESS = 0x00000042, WHITENESS = 0x00FF0062 } internal enum BrushStyles { BS_SOLID = 0, BS_NULL = 1, BS_HOLLOW = 1, BS_HATCHED = 2, BS_PATTERN = 3, BS_INDEXED = 4, BS_DIBPATTERN = 5, BS_DIBPATTERNPT = 6, BS_PATTERN8X8 = 7, BS_DIBPATTERN8X8 = 8, BS_MONOPATTERN = 9 } internal enum HatchStyles { HS_HORIZONTAL = 0, HS_VERTICAL = 1, HS_FDIAGONAL = 2, HS_BDIAGONAL = 3, HS_CROSS = 4, HS_DIAGCROSS = 5 } internal enum CombineFlags { RGN_AND = 1, RGN_OR = 2, RGN_XOR = 3, RGN_DIFF = 4, RGN_COPY = 5 } internal enum HitTest { HTERROR = -2, HTTRANSPARENT = -1, HTNOWHERE = 0, HTCLIENT = 1, HTCAPTION = 2, HTSYSMENU = 3, HTGROWBOX = 4, HTSIZE = 4, HTMENU = 5, HTHSCROLL = 6, HTVSCROLL = 7, HTMINBUTTON = 8, HTMAXBUTTON = 9, HTLEFT = 10, HTRIGHT = 11, HTTOP = 12, HTTOPLEFT = 13, HTTOPRIGHT = 14, HTBOTTOM = 15, HTBOTTOMLEFT = 16, HTBOTTOMRIGHT = 17, HTBORDER = 18, HTREDUCE = 8, HTZOOM = 9 , HTSIZEFIRST = 10, HTSIZELAST = 17, HTOBJECT = 19, HTCLOSE = 20, HTHELP = 21 } internal enum SystemParametersInfoActions : uint { GetBeep = 1, SetBeep = 2, GetMouse = 3, SetMouse = 4, GetBorder = 5, SetBorder = 6, GetKeyboardSpeed = 10, SetKeyboardSpeed = 11, LangDriver = 12, IconHorizontalSpacing = 13, GetScreenSaveTimeout = 14, SetScreenSaveTimeout = 15, GetScreenSaveActive = 16, SetScreenSaveActive = 17, GetGridGranularity = 18, SetGridGranularity = 19, SetDeskWallPaper = 20, SetDeskPattern = 21, GetKeyboardDelay = 22, SetKeyboardDelay = 23, IconVerticalSpacing = 24, GetIconTitleWrap = 25, SetIconTitleWrap = 26, GetMenuDropAlignment = 27, SetMenuDropAlignment = 28, SetDoubleClkWidth = 29, SetDoubleClkHeight = 30, GetIconTitleLogFont = 31, SetDoubleClickTime = 32, SetMouseButtonSwap = 33, SetIconTitleLogFont = 34, GetFastTaskSwitch = 35, SetFastTaskSwitch = 36, SetDragFullWindows = 37, GetDragFullWindows = 38, GetNonClientMetrics = 41, SetNonClientMetrics = 42, GetMinimizedMetrics = 43, SetMinimizedMetrics = 44, GetIconMetrics = 45, SetIconMetrics = 46, SetWorkArea = 47, GetWorkArea = 48, SetPenWindows = 49, GetFilterKeys = 50, SetFilterKeys = 51, GetToggleKeys = 52, SetToggleKeys = 53, GetMouseKeys = 54, SetMouseKeys = 55, GetShowSounds = 56, SetShowSounds = 57, GetStickyKeys = 58, SetStickyKeys = 59, GetAccessTimeout = 60, SetAccessTimeout = 61, GetSerialKeys = 62, SetSerialKeys = 63, GetSoundsEntry = 64, SetSoundsEntry = 65, GetHighContrast = 66, SetHighContrast = 67, GetKeyboardPref = 68, SetKeyboardPref = 69, GetScreenReader = 70, SetScreenReader = 71, GetAnimation = 72, SetAnimation = 73, GetFontSmoothing = 74, SetFontSmoothing = 75, SetDragWidth = 76, SetDragHeight = 77, SetHandHeld = 78, GetLowPowerTimeout = 79, GetPowerOffTimeout = 80, SetLowPowerTimeout = 81, SetPowerOffTimeout = 82, GetLowPowerActive = 83, GetPowerOffActive = 84, SetLowPowerActive = 85, SetPowerOffActive = 86, SetCursors = 87, SetIcons = 88, GetDefaultInputLang = 89, SetDefaultInputLang = 90, SetLangToggle = 91, GetWindwosExtension = 92, SetMouseTrails = 93, GetMouseTrails = 94, ScreenSaverRunning = 97, GetMouseHoverTime = 0x0066 } [Flags] internal enum FlagsAnimateWindow : uint { AW_HOR_POSITIVE = 0x00000001, AW_HOR_NEGATIVE = 0x00000002, AW_VER_POSITIVE = 0x00000004, AW_VER_NEGATIVE = 0x00000008, AW_CENTER = 0x00000010, AW_HIDE = 0x00010000, AW_ACTIVATE = 0x00020000, AW_SLIDE = 0x00040000, AW_BLEND =0x00080000 } [Flags] internal enum FlagsDCX : uint { DCX_WINDOW = 0x1, DCX_CACHE = 0x2, DCX_NORESETATTRS = 0x4, DCX_CLIPCHILDREN = 0x8, DCX_CLIPSIBLINGS = 0x10, DCX_PARENTCLIP = 0x20, DCX_EXCLUDERGN = 0x40, DCX_INTERSECTRGN = 0x80, DCX_EXCLUDEUPDATE = 0x100, DCX_INTERSECTUPDATE = 0x200, DCX_LOCKWINDOWUPDATE = 0x400, DCX_NORECOMPUTE = 0x100000, DCX_VALIDATE = 0x200000 } }
using System; using System.Collections; using System.Data.SqlClient; using System.Globalization; using System.IO; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Appleseed.Framework; using Appleseed.Framework.Content.Data; using Appleseed.Framework.Data; using Appleseed.Framework.DataTypes; using Appleseed.Framework.Helpers; using Appleseed.Framework.Site.Configuration; using Appleseed.Framework.Web.UI.WebControls; using History=Appleseed.Framework.History; namespace Appleseed.Content.Web.Modules { using System.Collections.Generic; /// <summary> /// by Jose Viladiu /// Moved into Appleseed by Jakob Hansen /// </summary> [History("jminond", "2006/2/23", "Converted to partial class")] public partial class ComponentModule : PortalModuleControl { // protected PlaceHolder ComponentHolder; public ComponentModule() { var group = SettingItemGroup.MODULE_SPECIAL_SETTINGS; // var groupOrderBase = (int)SettingItemGroup.MODULE_SPECIAL_SETTINGS; //HtmlEditorDataType.HtmlEditorSettings(this.BaseSettings, group); var pS = (PortalSettings)HttpContext.Current.Items["PortalSettings"]; var editor = new SettingItem<string, DropDownList>(new HtmlEditorDataType()) { // Order = 1; modified by Hongwei Shen(hongwei.shen@gmail.com) 11/9/2005 Order = (int)group + 1, Group = group, EnglishName = "Editor", Description = "Select the Html Editor for Module" }; var controlWidth = new SettingItem<int, TextBox>(new BaseDataType<int, TextBox>()) { Value = 700, Order = (int)group + 2, Group = group, EnglishName = "Editor Width", Description = "The width of editor control" }; var controlHeight = new SettingItem<int, TextBox>(new BaseDataType<int, TextBox>()) { Value = 400, Order = (int)group + 3, Group = group, EnglishName = "Editor Height", Description = "The height of editor control" }; var showUpload = new SettingItem<bool, CheckBox>(new BaseDataType<bool, CheckBox>()) { Value = true, Order = (int)group + 4, Group = group, EnglishName = "Upload?", Description = "Only used if Editor is ActiveUp HtmlTextBox" }; SettingItem<string, Panel> moduleImageFolder = null; if (pS != null) { if (pS.PortalFullPath != null) { moduleImageFolder = new SettingItem<string, Panel>( new FolderDataType( HttpContext.Current.Server.MapPath(string.Format("{0}/images", pS.PortalFullPath)), "default")) { Value = "default", Order = (int)group + 5, Group = group, EnglishName = "Default Image Folder", Description = "This folder is used for editor in this module to take and upload images" }; } // Set the portal default values if (pS.CustomSettings != null) { if (pS.CustomSettings["SITESETTINGS_DEFAULT_EDITOR"] != null) { editor.Value = pS.CustomSettings["SITESETTINGS_DEFAULT_EDITOR"].ToString(); } if (pS.CustomSettings["SITESETTINGS_EDITOR_WIDTH"] != null) { controlWidth.Value = pS.CustomSettings["SITESETTINGS_EDITOR_WIDTH"].ToInt32(CultureInfo.InvariantCulture); } if (pS.CustomSettings["SITESETTINGS_EDITOR_HEIGHT"] != null) { controlHeight.Value = pS.CustomSettings["SITESETTINGS_EDITOR_HEIGHT"].ToInt32(CultureInfo.InvariantCulture); } if (pS.CustomSettings["SITESETTINGS_EDITOR_HEIGHT"] != null) { controlHeight.Value = pS.CustomSettings["SITESETTINGS_EDITOR_HEIGHT"].ToInt32(CultureInfo.InvariantCulture); } if (pS.CustomSettings["SITESETTINGS_SHOWUPLOAD"] != null) { showUpload.Value = pS.CustomSettings["SITESETTINGS_SHOWUPLOAD"].ToBoolean(CultureInfo.InvariantCulture); } if (pS.CustomSettings["SITESETTINGS_DEFAULT_IMAGE_FOLDER"] != null) { if (moduleImageFolder != null) { moduleImageFolder.Value = pS.CustomSettings["SITESETTINGS_DEFAULT_IMAGE_FOLDER"].ToString(); } } } } this.BaseSettings.Add("Editor", editor); this.BaseSettings.Add("Width", controlWidth); this.BaseSettings.Add("Height", controlHeight); this.BaseSettings.Add("ShowUpload", showUpload); if (moduleImageFolder != null) { this.BaseSettings.Add("MODULE_IMAGE_FOLDER", moduleImageFolder); } } /// <summary> /// The Page_Load event handler on this User Control is /// used to load and execute a user control block. /// The user control to execute is stored in the HtmlText /// database table. This method uses the Appleseed.HtmlTextDB() /// data component to encapsulate all data functionality. /// Is a simple variation from HtmlModule. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> private void Page_Load(object sender, EventArgs e) { // Obtain the selected item from the HtmlText table ComponentModuleDB comp = new ComponentModuleDB(); SqlDataReader dr = comp.GetComponentModule(ModuleID); try { if (dr.Read()) { // Dynamically add the file content into the page string content = (string) dr["Component"]; try { ComponentHolder.Controls.Add(ParseControl(content)); } catch (Exception controlError) { ComponentHolder.Controls.Add (new LiteralControl("<p>Error in control: " + controlError + "<p>" + content)); } } } finally { // Close the datareader dr.Close(); } } /// <summary> /// If the module is searchable you /// must override the property to return true /// </summary> /// <value></value> public override bool Searchable { get { return true; } } /// <summary> /// Searchable module implementation /// </summary> /// <param name="portalID">The portal ID</param> /// <param name="userID">ID of the user is searching</param> /// <param name="searchString">The text to search</param> /// <param name="searchField">The fields where perfoming the search</param> /// <returns> /// The SELECT sql to perform a search on the current module /// </returns> public override string SearchSqlSelect(int portalID, int userID, string searchString, string searchField) { // Parameters: // Table Name: the table that holds the data // Title field: the field that contains the title for result, must be a field in the table // Abstract field: the field that contains the text for result, must be a field in the table // Search field: pass the searchField parameter you recieve. SearchDefinition s = new SearchDefinition("rb_ComponentModule", "Title", "Component", "CreatedByUser", "CreatedDate", searchField); //Add here extra search fields, this way //s.ArrSearchFields.Add("itm.ExtraFieldToSearch"); // Builds and returns the SELECT query return s.SearchSqlSelect(portalID, userID, searchString, false); } /// <summary> /// GUID of module (mandatory) /// </summary> /// <value></value> public override Guid GuidID { get { return new Guid("{2B113F51-FEA3-499A-98E7-7B83C192FDBC}"); } } # region Install / Uninstall Implementation /// <summary> /// Unknown /// </summary> /// <param name="stateSaver"></param> public override void Install(IDictionary stateSaver) { string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "install.sql"); List<string> errors = DBHelper.ExecuteScript(currentScriptName, true); if (errors.Count > 0) { // Call rollback throw new Exception("Error occurred:" + errors[0].ToString()); } } /// <summary> /// Unknown /// </summary> /// <param name="stateSaver"></param> public override void Uninstall(IDictionary stateSaver) { string currentScriptName = Path.Combine(Server.MapPath(TemplateSourceDirectory), "uninstall.sql"); List<string> errors = DBHelper.ExecuteScript(currentScriptName, true); if (errors.Count > 0) { // Call rollback throw new Exception("Error occurred:" + errors[0].ToString()); } } # endregion #region Web Form Designer generated code /// <summary> /// OnInit /// </summary> /// <param name="e"></param> protected override void OnInit(EventArgs e) { this.Load += new EventHandler(this.Page_Load); // Create a new Title the control // ModuleTitle = new DesktopModuleTitle(); // Set here title properties // Add support for the edit page this.EditText = "EDIT"; this.AddUrl = "~/DesktopModules/CommunityModules/ComponentModule/ComponentModuleEdit.aspx"; // Add title ad the very beginning of // the control's controls collection // Controls.AddAt(0, ModuleTitle); // Call base init procedure base.OnInit(e); } #endregion } }
using System; using Ivvy.API.Json; using Newtonsoft.Json; namespace Ivvy.API.Venue { /// <summary> /// An iVvy venue function space. /// </summary> public class FunctionSpace : ISerializable { // Note that the available attributes in the SimpleLayoutType are different depending // on whether the function space has been retrieved via GetVenueDetails or via // GetFunctionSpaceList. public class SimpleLayoutType { [JsonProperty("id", DefaultValueHandling = DefaultValueHandling.Ignore)] public int Id { get; set; } [JsonProperty("layoutName")] public string LayoutName { get; set; } [JsonProperty("type")] public int? Type { get; set; } [JsonProperty("paxMinimum")] public int? PaxMinimum { get; set; } [JsonProperty("paxMaximum")] public int? PaxMaximum { get; set; } } [JsonProperty("id")] public int Id { get; set; } [JsonProperty("venueId")] public int VenueId { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("categoryId")] public int? CategoryId { get; set; } [JsonProperty("imageId")] public int? ImageId { get; set; } [JsonProperty("hasLayouts")] public bool HasLayouts { get; set; } [JsonProperty("minPax")] public int? MinPax { get; set; } [JsonProperty("maxPax")] public int? MaxPax { get; set; } [JsonProperty("maxNumBookings")] public int? MaxNumBookings { get; set; } [JsonProperty("area")] public float? Area { get; set; } [JsonProperty("length")] public float? Length { get; set; } [JsonProperty("width")] public float? Width { get; set; } [JsonProperty("heightMaximum")] public float? HeightMaximum { get; set; } [JsonProperty("heightMinimum")] public float? HeightMinimum { get; set; } [JsonProperty("floorPressureMaximum")] public float? FloorPressureMaximum { get; set; } [JsonProperty("partSpaceIds")] public int[] PartSpaceIds { get; set; } [JsonProperty("includedInReportDashboard")] public bool IncludedInReportDashboard { get; set; } [JsonProperty("threeDScanId")] public string ThreeDScanId { get; set; } [JsonProperty("isViewable")] public bool IsViewable { get; set; } [JsonProperty("marketplaceName")] public string MarketplaceName { get; set; } [JsonProperty("eventTypes")] public int[] EventTypes { get; set; } [JsonProperty("sortOrder")] public int? SortOrder { get; set; } [JsonProperty("marketplaceSortOrder")] public int? MarketplaceSortOrder { get; set; } [JsonProperty("createdDate")] public DateTime CreatedDate { get; set; } [JsonProperty("modifiedDate")] public DateTime ModifiedDate { get; set; } [JsonProperty("layouts")] public SimpleLayoutType[] Layouts { get; set; } } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using java = biz.ritter.javapi; namespace biz.ritter.javapi.text { /** * An implementation of {@link CharacterIterator} for strings. */ public sealed class StringCharacterIterator : CharacterIterator { String stringJ; int start, end, offset; /** * Constructs a new {@code StringCharacterIterator} on the specified string. * The begin and current indices are set to the beginning of the string, the * end index is set to the length of the string. * * @param value * the source string to iterate over. */ public StringCharacterIterator(String value) { stringJ = value; start = offset = 0; end = stringJ.length(); } /** * Constructs a new {@code StringCharacterIterator} on the specified string * with the current index set to the specified value. The begin index is set * to the beginning of the string, the end index is set to the length of the * string. * * @param value * the source string to iterate over. * @param location * the current index. * @throws IllegalArgumentException * if {@code location} is negative or greater than the length * of the source string. */ public StringCharacterIterator(String value, int location) { stringJ = value; start = 0; end = stringJ.length(); if (location < 0 || location > end) { throw new java.lang.IllegalArgumentException(); } offset = location; } /** * Constructs a new {@code StringCharacterIterator} on the specified string * with the begin, end and current index set to the specified values. * * @param value * the source string to iterate over. * @param start * the index of the first character to iterate. * @param end * the index one past the last character to iterate. * @param location * the current index. * @throws IllegalArgumentException * if {@code start &lt; 0}, {@code start &gt; end}, {@code location &lt; * start}, {@code location &gt; end} or if {@code end} is greater * than the length of {@code value}. */ public StringCharacterIterator(String value, int start, int end, int location) { stringJ = value; if (start < 0 || end > stringJ.length() || start > end || location < start || location > end) { throw new java.lang.IllegalArgumentException(); } this.start = start; this.end = end; offset = location; } /** * Returns a new {@code StringCharacterIterator} with the same source * string, begin, end, and current index as this iterator. * * @return a shallow copy of this iterator. * @see java.lang.Cloneable */ public Object clone() { try { return base.MemberwiseClone(); } catch (java.lang.CloneNotSupportedException e) { return null; } } /** * Returns the character at the current index in the source string. * * @return the current character, or {@code CharacterIteratorConstants.DONE} if the current index is * past the end. */ public char current() { if (offset == end) { return CharacterIteratorConstants.DONE; } return stringJ.charAt(offset); } /** * Compares the specified object with this {@code StringCharacterIterator} * and indicates if they are equal. In order to be equal, {@code object} * must be an instance of {@code StringCharacterIterator} that iterates over * the same sequence of characters with the same index. * * @param object * the object to compare with this object. * @return {@code true} if the specified object is equal to this * {@code StringCharacterIterator}; {@code false} otherwise. * @see #hashCode */ public override bool Equals(Object obj) { if (!(obj is StringCharacterIterator)) { return false; } StringCharacterIterator it = (StringCharacterIterator)obj; return stringJ.equals(it.stringJ) && start == it.start && end == it.end && offset == it.offset; } /** * Sets the current position to the begin index and returns the character at * the new position in the source string. * * @return the character at the begin index or {@code CharacterIteratorConstants.DONE} if the begin * index is equal to the end index. */ public char first() { if (start == end) { return CharacterIteratorConstants.DONE; } offset = start; return stringJ.charAt(offset); } /** * Returns the begin index in the source string. * * @return the index of the first character of the iteration. */ public int getBeginIndex() { return start; } /** * Returns the end index in the source string. * * @return the index one past the last character of the iteration. */ public int getEndIndex() { return end; } /** * Returns the current index in the source string. * * @return the current index. */ public int getIndex() { return offset; } public override int GetHashCode() { return stringJ.GetHashCode() + start + end + offset; } /** * Sets the current position to the end index - 1 and returns the character * at the new position. * * @return the character before the end index or {@code CharacterIteratorConstants.DONE} if the begin * index is equal to the end index. */ public char last() { if (start == end) { return CharacterIteratorConstants.DONE; } offset = end - 1; return stringJ.charAt(offset); } /** * Increments the current index and returns the character at the new index. * * @return the character at the next index, or {@code CharacterIteratorConstants.DONE} if the next * index would be past the end. */ public char next() { if (offset >= (end - 1)) { offset = end; return CharacterIteratorConstants.DONE; } return stringJ.charAt(++offset); } /** * Decrements the current index and returns the character at the new index. * * @return the character at the previous index, or {@code CharacterIteratorConstants.DONE} if the * previous index would be past the beginning. */ public char previous() { if (offset == start) { return CharacterIteratorConstants.DONE; } return stringJ.charAt(--offset); } /** * Sets the current index in the source string. * * @param location * the index the current position is set to. * @return the character at the new index, or {@code CharacterIteratorConstants.DONE} if * {@code location} is set to the end index. * @throws IllegalArgumentException * if {@code location} is smaller than the begin index or greater * than the end index. */ public char setIndex(int location) { if (location < start || location > end) { throw new java.lang.IllegalArgumentException(); } offset = location; if (offset == end) { return CharacterIteratorConstants.DONE; } return stringJ.charAt(offset); } /** * Sets the source string to iterate over. The begin and end positions are * set to the start and end of this string. * * @param value * the new source string. */ public void setText(String value) { stringJ = value; start = offset = 0; end = value.length(); } } }
namespace Fixtures.PetstoreV2 { using System; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Models; public static partial class SwaggerPetstoreV2Extensions { /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static Pet AddPet(this ISwaggerPetstoreV2 operations, Pet body) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).AddPetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<Pet> AddPetAsync( this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Pet> result = await operations.AddPetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> public static void UpdatePet(this ISwaggerPetstoreV2 operations, Pet body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='body'> /// Pet object that needs to be added to the store /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task UpdatePetAsync( this ISwaggerPetstoreV2 operations, Pet body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Multiple status values can be provided with comma seperated strings /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> public static IList<Pet> FindPetsByStatus(this ISwaggerPetstoreV2 operations, IList<string> status) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByStatusAsync(status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Multiple status values can be provided with comma seperated strings /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='status'> /// Status values that need to be considered for filter /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByStatusAsync( this ISwaggerPetstoreV2 operations, IList<string> status, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<IList<Pet>> result = await operations.FindPetsByStatusWithHttpMessagesAsync(status, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='tags'> /// Tags to filter by /// </param> public static IList<Pet> FindPetsByTags(this ISwaggerPetstoreV2 operations, IList<string> tags) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).FindPetsByTagsAsync(tags), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, /// tag3 for testing. /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='tags'> /// Tags to filter by /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<IList<Pet>> FindPetsByTagsAsync( this ISwaggerPetstoreV2 operations, IList<string> tags, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<IList<Pet>> result = await operations.FindPetsByTagsWithHttpMessagesAsync(tags, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// Returns a single pet /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='petId'> /// Id of pet to return /// </param> public static Pet GetPetById(this ISwaggerPetstoreV2 operations, long? petId) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetPetByIdAsync(petId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns a single pet /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='petId'> /// Id of pet to return /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<Pet> GetPetByIdAsync( this ISwaggerPetstoreV2 operations, long? petId, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Pet> result = await operations.GetPetByIdWithHttpMessagesAsync(petId, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='name'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> public static void UpdatePetWithForm(this ISwaggerPetstoreV2 operations, long? petId, string name = default(string), string status = default(string)) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdatePetWithFormAsync(petId, name, status), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='petId'> /// Id of pet that needs to be updated /// </param> /// <param name='name'> /// Updated name of the pet /// </param> /// <param name='status'> /// Updated status of the pet /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task UpdatePetWithFormAsync( this ISwaggerPetstoreV2 operations, long? petId, string name = default(string), string status = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdatePetWithFormWithHttpMessagesAsync(petId, name, status, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> public static void DeletePet(this ISwaggerPetstoreV2 operations, long? petId, string apiKey = default(string)) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeletePetAsync(petId, apiKey), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='petId'> /// Pet id to delete /// </param> /// <param name='apiKey'> /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task DeletePetAsync( this ISwaggerPetstoreV2 operations, long? petId, string apiKey = default(string), CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeletePetWithHttpMessagesAsync(petId, apiKey, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Returns a map of status codes to quantities /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static IDictionary<string, int?> GetInventory(this ISwaggerPetstoreV2 operations) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetInventoryAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Returns a map of status codes to quantities /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<IDictionary<string, int?>> GetInventoryAsync( this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<IDictionary<string, int?>> result = await operations.GetInventoryWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> public static Order PlaceOrder(this ISwaggerPetstoreV2 operations, Order body) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).PlaceOrderAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='body'> /// order placed for purchasing the pet /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<Order> PlaceOrderAsync( this ISwaggerPetstoreV2 operations, Order body, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Order> result = await operations.PlaceOrderWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> public static Order GetOrderById(this ISwaggerPetstoreV2 operations, string orderId) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetOrderByIdAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// For valid response try integer IDs with value &lt;= 5 or &gt; 10. Other /// values will generated exceptions /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='orderId'> /// Id of pet that needs to be fetched /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<Order> GetOrderByIdAsync( this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<Order> result = await operations.GetOrderByIdWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> public static void DeleteOrder(this ISwaggerPetstoreV2 operations, string orderId) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteOrderAsync(orderId), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// For valid response try integer IDs with value &lt; 1000. Anything above /// 1000 or nonintegers will generate API errors /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='orderId'> /// Id of the order that needs to be deleted /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task DeleteOrderAsync( this ISwaggerPetstoreV2 operations, string orderId, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteOrderWithHttpMessagesAsync(orderId, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// This can only be done by the logged in user. /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='body'> /// Created user object /// </param> public static void CreateUser(this ISwaggerPetstoreV2 operations, User body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUserAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// This can only be done by the logged in user. /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='body'> /// Created user object /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task CreateUserAsync( this ISwaggerPetstoreV2 operations, User body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUserWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithArrayInput(this ISwaggerPetstoreV2 operations, IList<User> body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithArrayInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task CreateUsersWithArrayInputAsync( this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithArrayInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='body'> /// List of user object /// </param> public static void CreateUsersWithListInput(this ISwaggerPetstoreV2 operations, IList<User> body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).CreateUsersWithListInputAsync(body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='body'> /// List of user object /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task CreateUsersWithListInputAsync( this ISwaggerPetstoreV2 operations, IList<User> body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.CreateUsersWithListInputWithHttpMessagesAsync(body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> public static string LoginUser(this ISwaggerPetstoreV2 operations, string username, string password) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LoginUserAsync(username, password), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='username'> /// The user name for login /// </param> /// <param name='password'> /// The password for login in clear text /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<string> LoginUserAsync( this ISwaggerPetstoreV2 operations, string username, string password, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<string> result = await operations.LoginUserWithHttpMessagesAsync(username, password, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> public static void LogoutUser(this ISwaggerPetstoreV2 operations) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).LogoutUserAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task LogoutUserAsync( this ISwaggerPetstoreV2 operations, CancellationToken cancellationToken = default(CancellationToken)) { await operations.LogoutUserWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> public static User GetUserByName(this ISwaggerPetstoreV2 operations, string username) { return Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).GetUserByNameAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='username'> /// The name that needs to be fetched. Use user1 for testing. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<User> GetUserByNameAsync( this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { HttpOperationResponse<User> result = await operations.GetUserByNameWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false); return result.Body; } /// <summary> /// This can only be done by the logged in user. /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> public static void UpdateUser(this ISwaggerPetstoreV2 operations, string username, User body) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).UpdateUserAsync(username, body), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// This can only be done by the logged in user. /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='username'> /// name that need to be deleted /// </param> /// <param name='body'> /// Updated user object /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task UpdateUserAsync( this ISwaggerPetstoreV2 operations, string username, User body, CancellationToken cancellationToken = default(CancellationToken)) { await operations.UpdateUserWithHttpMessagesAsync(username, body, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// This can only be done by the logged in user. /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> public static void DeleteUser(this ISwaggerPetstoreV2 operations, string username) { Task.Factory.StartNew(s => ((ISwaggerPetstoreV2)s).DeleteUserAsync(username), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// This can only be done by the logged in user. /// </summary> /// <param name='operations'> /// The operations group for this extension method /// </param> /// <param name='username'> /// The name that needs to be deleted /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task DeleteUserAsync( this ISwaggerPetstoreV2 operations, string username, CancellationToken cancellationToken = default(CancellationToken)) { await operations.DeleteUserWithHttpMessagesAsync(username, null, cancellationToken).ConfigureAwait(false); } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Linq; using Examine; using Moq; using NUnit.Framework; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Infrastructure.Examine; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Infrastructure.Examine { [TestFixture] public class UmbracoContentValueSetValidatorTests { [Test] public void Invalid_Category() { var validator = new ContentValueSetValidator( false, true, Mock.Of<IPublicAccessService>(), Mock.Of<IScopeProvider>()); ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); result = validator.Validate(ValueSet.FromObject("777", IndexTypes.Media, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); result = validator.Validate(ValueSet.FromObject("555", "invalid-category", new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); } [Test] public void Must_Have_Path() { var validator = new ContentValueSetValidator( false, true, Mock.Of<IPublicAccessService>(), Mock.Of<IScopeProvider>()); ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); } [Test] public void Parent_Id() { var validator = new ContentValueSetValidator( false, true, Mock.Of<IPublicAccessService>(), Mock.Of<IScopeProvider>(), 555); ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Filtered, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,444" })); Assert.AreEqual(ValueSetValidationResult.Filtered, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555,777" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555,777,999" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); } [Test] public void Inclusion_Field_List() { var validator = new ValueSetValidator( null, null, new[] { "hello", "world" }, null); var valueSet = ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555", world = "your oyster" }); ValueSetValidationResult result = validator.Validate(valueSet); Assert.AreEqual(ValueSetValidationResult.Filtered, result); Assert.IsFalse(valueSet.Values.ContainsKey("path")); Assert.IsTrue(valueSet.Values.ContainsKey("hello")); Assert.IsTrue(valueSet.Values.ContainsKey("world")); } [Test] public void Exclusion_Field_List() { var validator = new ValueSetValidator( null, null, null, new[] { "hello", "world" }); var valueSet = ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555", world = "your oyster" }); ValueSetValidationResult result = validator.Validate(valueSet); Assert.AreEqual(ValueSetValidationResult.Filtered, result); Assert.IsTrue(valueSet.Values.ContainsKey("path")); Assert.IsFalse(valueSet.Values.ContainsKey("hello")); Assert.IsFalse(valueSet.Values.ContainsKey("world")); } [Test] public void Inclusion_Exclusion_Field_List() { var validator = new ValueSetValidator( null, null, new[] { "hello", "world" }, new[] { "world" }); var valueSet = ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555", world = "your oyster" }); ValueSetValidationResult result = validator.Validate(valueSet); Assert.AreEqual(ValueSetValidationResult.Filtered, result); Assert.IsFalse(valueSet.Values.ContainsKey("path")); Assert.IsTrue(valueSet.Values.ContainsKey("hello")); Assert.IsFalse(valueSet.Values.ContainsKey("world")); } [Test] public void Inclusion_Type_List() { var validator = new ContentValueSetValidator( false, true, Mock.Of<IPublicAccessService>(), Mock.Of<IScopeProvider>(), includeItemTypes: new List<string> { "include-content" }); ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, "include-content", new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); } [Test] public void Exclusion_Type_List() { var validator = new ContentValueSetValidator( false, true, Mock.Of<IPublicAccessService>(), Mock.Of<IScopeProvider>(), excludeItemTypes: new List<string> { "exclude-content" }); ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, "exclude-content", new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); } [Test] public void Inclusion_Exclusion_Type_List() { var validator = new ContentValueSetValidator( false, true, Mock.Of<IPublicAccessService>(), Mock.Of<IScopeProvider>(), includeItemTypes: new List<string> { "include-content", "exclude-content" }, excludeItemTypes: new List<string> { "exclude-content" }); ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, "test-content", new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, "exclude-content", new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, "include-content", new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); } [Test] public void Recycle_Bin_Content() { var validator = new ContentValueSetValidator( true, false, Mock.Of<IPublicAccessService>(), Mock.Of<IScopeProvider>()); ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,-20,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,-20,555,777" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(new ValueSet( "555", IndexTypes.Content, new Dictionary<string, object> { ["hello"] = "world", ["path"] = "-1,555", [UmbracoExamineFieldNames.PublishedFieldName] = "y" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); } [Test] public void Recycle_Bin_Media() { var validator = new ContentValueSetValidator( true, false, Mock.Of<IPublicAccessService>(), Mock.Of<IScopeProvider>()); ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Media, new { hello = "world", path = "-1,-21,555" })); Assert.AreEqual(ValueSetValidationResult.Filtered, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Media, new { hello = "world", path = "-1,-21,555,777" })); Assert.AreEqual(ValueSetValidationResult.Filtered, result); result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Media, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); } [Test] public void Published_Only() { var validator = new ContentValueSetValidator( true, true, Mock.Of<IPublicAccessService>(), Mock.Of<IScopeProvider>()); ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(new ValueSet( "555", IndexTypes.Content, new Dictionary<string, object> { ["hello"] = "world", ["path"] = "-1,555", [UmbracoExamineFieldNames.PublishedFieldName] = "n" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(new ValueSet( "555", IndexTypes.Content, new Dictionary<string, object> { ["hello"] = "world", ["path"] = "-1,555", [UmbracoExamineFieldNames.PublishedFieldName] = "y" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); } [Test] public void Published_Only_With_Variants() { var validator = new ContentValueSetValidator(true, true, Mock.Of<IPublicAccessService>(), Mock.Of<IScopeProvider>()); ValueSetValidationResult result = validator.Validate(new ValueSet( "555", IndexTypes.Content, new Dictionary<string, object> { ["hello"] = "world", ["path"] = "-1,555", [UmbracoExamineFieldNames.VariesByCultureFieldName] = "y", [UmbracoExamineFieldNames.PublishedFieldName] = "n" })); Assert.AreEqual(ValueSetValidationResult.Failed, result); result = validator.Validate(new ValueSet( "555", IndexTypes.Content, new Dictionary<string, object> { ["hello"] = "world", ["path"] = "-1,555", [UmbracoExamineFieldNames.VariesByCultureFieldName] = "y", [UmbracoExamineFieldNames.PublishedFieldName] = "y" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); var valueSet = new ValueSet( "555", IndexTypes.Content, new Dictionary<string, object> { ["hello"] = "world", ["path"] = "-1,555", [UmbracoExamineFieldNames.VariesByCultureFieldName] = "y", [$"{UmbracoExamineFieldNames.PublishedFieldName}_en-us"] = "y", ["hello_en-us"] = "world", ["title_en-us"] = "my title", [$"{UmbracoExamineFieldNames.PublishedFieldName}_es-es"] = "n", ["hello_es-ES"] = "world", ["title_es-ES"] = "my title", [UmbracoExamineFieldNames.PublishedFieldName] = "y" }); Assert.AreEqual(10, valueSet.Values.Count()); Assert.IsTrue(valueSet.Values.ContainsKey($"{UmbracoExamineFieldNames.PublishedFieldName}_es-es")); Assert.IsTrue(valueSet.Values.ContainsKey("hello_es-ES")); Assert.IsTrue(valueSet.Values.ContainsKey("title_es-ES")); result = validator.Validate(valueSet); Assert.AreEqual(ValueSetValidationResult.Filtered, result); Assert.AreEqual(7, valueSet.Values.Count()); // filtered to 7 values (removes es-es values) Assert.IsFalse(valueSet.Values.ContainsKey($"{UmbracoExamineFieldNames.PublishedFieldName}_es-es")); Assert.IsFalse(valueSet.Values.ContainsKey("hello_es-ES")); Assert.IsFalse(valueSet.Values.ContainsKey("title_es-ES")); } [Test] public void Non_Protected() { var publicAccessService = new Mock<IPublicAccessService>(); publicAccessService.Setup(x => x.IsProtected("-1,555")) .Returns(Attempt.Succeed(new PublicAccessEntry(Guid.NewGuid(), 555, 444, 333, Enumerable.Empty<PublicAccessRule>()))); publicAccessService.Setup(x => x.IsProtected("-1,777")) .Returns(Attempt.Fail<PublicAccessEntry>()); var validator = new ContentValueSetValidator( false, false, publicAccessService.Object, Mock.Of<IScopeProvider>()); ValueSetValidationResult result = validator.Validate(ValueSet.FromObject("555", IndexTypes.Content, new { hello = "world", path = "-1,555" })); Assert.AreEqual(ValueSetValidationResult.Filtered, result); result = validator.Validate(ValueSet.FromObject("777", IndexTypes.Content, new { hello = "world", path = "-1,777" })); Assert.AreEqual(ValueSetValidationResult.Valid, result); } } }
// 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.Runtime.InteropServices; using System.Collections; using System.Diagnostics; using System.Text; namespace System.DirectoryServices.ActiveDirectory { [Flags] public enum ActiveDirectorySiteOptions { None = 0, AutoTopologyDisabled = 1, TopologyCleanupDisabled = 2, AutoMinimumHopDisabled = 4, StaleServerDetectDisabled = 8, AutoInterSiteTopologyDisabled = 16, GroupMembershipCachingEnabled = 32, ForceKccWindows2003Behavior = 64, UseWindows2000IstgElection = 128, RandomBridgeHeaderServerSelectionDisabled = 256, UseHashingForReplicationSchedule = 512, RedundantServerTopologyEnabled = 1024 } public class ActiveDirectorySite : IDisposable { internal readonly DirectoryContext context = null; private readonly string _name = null; internal readonly DirectoryEntry cachedEntry = null; private DirectoryEntry _ntdsEntry = null; private readonly ActiveDirectorySubnetCollection _subnets = null; private DirectoryServer _topologyGenerator = null; private readonly ReadOnlySiteCollection _adjacentSites = new ReadOnlySiteCollection(); private bool _disposed = false; private readonly DomainCollection _domains = new DomainCollection(null); private readonly ReadOnlyDirectoryServerCollection _servers = new ReadOnlyDirectoryServerCollection(); private readonly ReadOnlySiteLinkCollection _links = new ReadOnlySiteLinkCollection(); private ActiveDirectorySiteOptions _siteOptions = ActiveDirectorySiteOptions.None; private ReadOnlyDirectoryServerCollection _bridgeheadServers = new ReadOnlyDirectoryServerCollection(); private readonly DirectoryServerCollection _SMTPBridgeheadServers = null; private readonly DirectoryServerCollection _RPCBridgeheadServers = null; private byte[] _replicationSchedule = null; internal bool existing = false; private bool _subnetRetrieved = false; private bool _isADAMServer = false; private bool _checkADAM = false; private bool _topologyTouched = false; private bool _adjacentSitesRetrieved = false; private string _siteDN = null; private bool _domainsRetrieved = false; private bool _serversRetrieved = false; private bool _belongLinksRetrieved = false; private bool _bridgeheadServerRetrieved = false; private bool _SMTPBridgeRetrieved = false; private bool _RPCBridgeRetrieved = false; private static int s_ERROR_NO_SITENAME = 1919; public static ActiveDirectorySite FindByName(DirectoryContext context, string siteName) { // find an existing site ValidateArgument(context, siteName); // work with copy of the context context = new DirectoryContext(context); // bind to the rootdse to get the configurationnamingcontext DirectoryEntry de; string sitedn; try { de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); sitedn = "CN=Sites," + (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); de = DirectoryEntryManager.GetDirectoryEntry(context, sitedn); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name)); } try { ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=site)(objectCategory=site)(name=" + Utils.GetEscapedFilterValue(siteName) + "))", new string[] { "distinguishedName" }, SearchScope.OneLevel, false, /* don't need paged search */ false /* don't need to cache result */); SearchResult srchResult = adSearcher.FindOne(); if (srchResult == null) { // no such site object throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySite), siteName); } // it is an existing site object ActiveDirectorySite site = new ActiveDirectorySite(context, siteName, true); return site; } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { // object is not found since we cannot even find the container in which to search throw new ActiveDirectoryObjectNotFoundException(SR.DSNotFound, typeof(ActiveDirectorySite), siteName); } else { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } finally { de.Dispose(); } } public ActiveDirectorySite(DirectoryContext context, string siteName) { ValidateArgument(context, siteName); // work with copy of the context context = new DirectoryContext(context); this.context = context; _name = siteName; // bind to the rootdse to get the configurationnamingcontext DirectoryEntry de = null; try { de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); _siteDN = "CN=Sites," + config; // bind to the site container de = DirectoryEntryManager.GetDirectoryEntry(context, _siteDN); string rdn = "cn=" + _name; rdn = Utils.GetEscapedPath(rdn); cachedEntry = de.Children.Add(rdn, "site"); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } catch (ActiveDirectoryObjectNotFoundException) { // this is the case where the context is a config set and we could not find an ADAM instance in that config set throw new ActiveDirectoryOperationException(SR.Format(SR.ADAMInstanceNotFoundInConfigSet , context.Name)); } finally { if (de != null) de.Dispose(); } _subnets = new ActiveDirectorySubnetCollection(context, "CN=" + siteName + "," + _siteDN); string transportDN = "CN=IP,CN=Inter-Site Transports," + _siteDN; _RPCBridgeheadServers = new DirectoryServerCollection(context, "CN=" + siteName + "," + _siteDN, transportDN); transportDN = "CN=SMTP,CN=Inter-Site Transports," + _siteDN; _SMTPBridgeheadServers = new DirectoryServerCollection(context, "CN=" + siteName + "," + _siteDN, transportDN); } internal ActiveDirectorySite(DirectoryContext context, string siteName, bool existing) { Debug.Assert(existing == true); this.context = context; _name = siteName; this.existing = existing; DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); _siteDN = "CN=Sites," + (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); cachedEntry = DirectoryEntryManager.GetDirectoryEntry(context, "CN=" + siteName + "," + _siteDN); _subnets = new ActiveDirectorySubnetCollection(context, "CN=" + siteName + "," + _siteDN); string transportDN = "CN=IP,CN=Inter-Site Transports," + _siteDN; _RPCBridgeheadServers = new DirectoryServerCollection(context, (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName), transportDN); transportDN = "CN=SMTP,CN=Inter-Site Transports," + _siteDN; _SMTPBridgeheadServers = new DirectoryServerCollection(context, (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName), transportDN); } public static ActiveDirectorySite GetComputerSite() { // make sure that this is the platform that we support new DirectoryContext(DirectoryContextType.Forest); IntPtr ptr = (IntPtr)0; int result = UnsafeNativeMethods.DsGetSiteName(null, ref ptr); if (result != 0) { // computer is not in a site if (result == s_ERROR_NO_SITENAME) throw new ActiveDirectoryObjectNotFoundException(SR.NoCurrentSite, typeof(ActiveDirectorySite), null); else throw ExceptionHelper.GetExceptionFromErrorCode(result); } else { try { string siteName = Marshal.PtrToStringUni(ptr); Debug.Assert(siteName != null); // find the forest this machine belongs to string forestName = Locator.GetDomainControllerInfo(null, null, null, (long)PrivateLocatorFlags.DirectoryServicesRequired).DnsForestName; DirectoryContext currentContext = Utils.GetNewDirectoryContext(forestName, DirectoryContextType.Forest, null); // existing site ActiveDirectorySite site = ActiveDirectorySite.FindByName(currentContext, siteName); return site; } finally { if (ptr != (IntPtr)0) Marshal.FreeHGlobal(ptr); } } } public string Name { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); return _name; } } public DomainCollection Domains { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { if (!_domainsRetrieved) { // clear it first to be safe in case GetDomains fail in the middle and leave partial results there _domains.Clear(); GetDomains(); _domainsRetrieved = true; } } return _domains; } } public ActiveDirectorySubnetCollection Subnets { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { // if asked the first time, we need to properly construct the subnets collection if (!_subnetRetrieved) { _subnets.initialized = false; _subnets.Clear(); GetSubnets(); _subnetRetrieved = true; } } _subnets.initialized = true; return _subnets; } } public ReadOnlyDirectoryServerCollection Servers { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { if (!_serversRetrieved) { _servers.Clear(); GetServers(); _serversRetrieved = true; } } return _servers; } } public ReadOnlySiteCollection AdjacentSites { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { if (!_adjacentSitesRetrieved) { _adjacentSites.Clear(); GetAdjacentSites(); _adjacentSitesRetrieved = true; } } return _adjacentSites; } } public ReadOnlySiteLinkCollection SiteLinks { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { if (!_belongLinksRetrieved) { _links.Clear(); GetLinks(); _belongLinksRetrieved = true; } } return _links; } } public DirectoryServer InterSiteTopologyGenerator { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { // have not load topology generator information from the directory and user has not set it yet if (_topologyGenerator == null && !_topologyTouched) { bool ISTGExist; try { ISTGExist = NTDSSiteEntry.Properties.Contains("interSiteTopologyGenerator"); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (ISTGExist) { string serverDN = (string)PropertyManager.GetPropertyValue(context, NTDSSiteEntry, PropertyManager.InterSiteTopologyGenerator); string hostname = null; DirectoryEntry tmp = DirectoryEntryManager.GetDirectoryEntry(context, serverDN); try { hostname = (string)PropertyManager.GetPropertyValue(context, tmp.Parent, PropertyManager.DnsHostName); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { // indicates a demoted server return null; } } if (IsADAM) { int port = (int)PropertyManager.GetPropertyValue(context, tmp, PropertyManager.MsDSPortLDAP); string fullHostName = hostname; if (port != 389) { fullHostName = hostname + ":" + port; } _topologyGenerator = new AdamInstance(Utils.GetNewDirectoryContext(fullHostName, DirectoryContextType.DirectoryServer, context), fullHostName); } else { _topologyGenerator = new DomainController(Utils.GetNewDirectoryContext(hostname, DirectoryContextType.DirectoryServer, context), hostname); } } } } return _topologyGenerator; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (value == null) throw new ArgumentNullException(nameof(value)); if (existing) { // for existing site, nTDSSiteSettings needs to exist DirectoryEntry tmp = NTDSSiteEntry; } _topologyTouched = true; _topologyGenerator = value; } } public ActiveDirectorySiteOptions Options { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { try { if (NTDSSiteEntry.Properties.Contains("options")) { return (ActiveDirectorySiteOptions)NTDSSiteEntry.Properties["options"][0]; } else return ActiveDirectorySiteOptions.None; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } else return _siteOptions; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { try { NTDSSiteEntry.Properties["options"].Value = value; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } else _siteOptions = value; } } public string Location { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { if (cachedEntry.Properties.Contains("location")) { return (string)cachedEntry.Properties["location"][0]; } else return null; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { if (value == null) { if (cachedEntry.Properties.Contains("location")) cachedEntry.Properties["location"].Clear(); } else { cachedEntry.Properties["location"].Value = value; } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public ReadOnlyDirectoryServerCollection BridgeheadServers { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (!_bridgeheadServerRetrieved) { _bridgeheadServers = GetBridgeheadServers(); _bridgeheadServerRetrieved = true; } return _bridgeheadServers; } } public DirectoryServerCollection PreferredSmtpBridgeheadServers { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { if (!_SMTPBridgeRetrieved) { _SMTPBridgeheadServers.initialized = false; _SMTPBridgeheadServers.Clear(); GetPreferredBridgeheadServers(ActiveDirectoryTransportType.Smtp); _SMTPBridgeRetrieved = true; } } _SMTPBridgeheadServers.initialized = true; return _SMTPBridgeheadServers; } } public DirectoryServerCollection PreferredRpcBridgeheadServers { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { if (!_RPCBridgeRetrieved) { _RPCBridgeheadServers.initialized = false; _RPCBridgeheadServers.Clear(); GetPreferredBridgeheadServers(ActiveDirectoryTransportType.Rpc); _RPCBridgeRetrieved = true; } } _RPCBridgeheadServers.initialized = true; return _RPCBridgeheadServers; } } public ActiveDirectorySchedule IntraSiteReplicationSchedule { get { if (_disposed) throw new ObjectDisposedException(GetType().Name); ActiveDirectorySchedule schedule = null; if (existing) { // if exists in the cache, return it, otherwise null is returned try { if (NTDSSiteEntry.Properties.Contains("schedule")) { byte[] tmpSchedule = (byte[])NTDSSiteEntry.Properties["schedule"][0]; Debug.Assert(tmpSchedule != null && tmpSchedule.Length == 188); schedule = new ActiveDirectorySchedule(); schedule.SetUnmanagedSchedule(tmpSchedule); } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } else { if (_replicationSchedule != null) { // newly created site, get the schedule if already has been set by the user schedule = new ActiveDirectorySchedule(); schedule.SetUnmanagedSchedule(_replicationSchedule); } } return schedule; } set { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (existing) { try { if (value == null) { // clear it out if existing before if (NTDSSiteEntry.Properties.Contains("schedule")) NTDSSiteEntry.Properties["schedule"].Clear(); } else // replace with the new value NTDSSiteEntry.Properties["schedule"].Value = value.GetUnmanagedSchedule(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } else { // clear out the schedule if (value == null) _replicationSchedule = null; else { // replace with the new value _replicationSchedule = value.GetUnmanagedSchedule(); } } } } private bool IsADAM { get { if (!_checkADAM) { DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); PropertyValueCollection values = null; try { values = de.Properties["supportedCapabilities"]; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (values.Contains(SupportedCapability.ADAMOid)) _isADAMServer = true; } return _isADAMServer; } } private DirectoryEntry NTDSSiteEntry { get { if (_ntdsEntry == null) { DirectoryEntry tmp = DirectoryEntryManager.GetDirectoryEntry(context, "CN=NTDS Site Settings," + (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)); try { tmp.RefreshCache(); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { string message = SR.Format(SR.NTDSSiteSetting , _name); throw new ActiveDirectoryOperationException(message, e, 0x2030); } throw ExceptionHelper.GetExceptionFromCOMException(context, e); } _ntdsEntry = tmp; } return _ntdsEntry; } } public void Save() { if (_disposed) throw new ObjectDisposedException(GetType().Name); try { // commit changes cachedEntry.CommitChanges(); foreach (DictionaryEntry e in _subnets.changeList) { try { ((DirectoryEntry)e.Value).CommitChanges(); } catch (COMException exception) { // there is a bug in ADSI that when targeting ADAM, permissive modify control is not used. if (exception.ErrorCode != unchecked((int)0x8007200A)) throw ExceptionHelper.GetExceptionFromCOMException(exception); } } // reset status variables _subnets.changeList.Clear(); _subnetRetrieved = false; // need to throw better exception for ADAM since its SMTP transport is not available foreach (DictionaryEntry e in _SMTPBridgeheadServers.changeList) { try { ((DirectoryEntry)e.Value).CommitChanges(); } catch (COMException exception) { // SMTP transport is not supported on ADAM if (IsADAM && (exception.ErrorCode == unchecked((int)0x8007202F))) throw new NotSupportedException(SR.NotSupportTransportSMTP); // there is a bug in ADSI that when targeting ADAM, permissive modify control is not used. if (exception.ErrorCode != unchecked((int)0x8007200A)) throw ExceptionHelper.GetExceptionFromCOMException(exception); } } _SMTPBridgeheadServers.changeList.Clear(); _SMTPBridgeRetrieved = false; foreach (DictionaryEntry e in _RPCBridgeheadServers.changeList) { try { ((DirectoryEntry)e.Value).CommitChanges(); } catch (COMException exception) { // there is a bug in ADSI that when targeting ADAM, permissive modify control is not used. if (exception.ErrorCode != unchecked((int)0x8007200A)) throw ExceptionHelper.GetExceptionFromCOMException(exception); } } _RPCBridgeheadServers.changeList.Clear(); _RPCBridgeRetrieved = false; if (existing) { // topology generator is changed if (_topologyTouched) { try { DirectoryServer server = InterSiteTopologyGenerator; string ntdsaName = (server is DomainController) ? ((DomainController)server).NtdsaObjectName : ((AdamInstance)server).NtdsaObjectName; NTDSSiteEntry.Properties["interSiteTopologyGenerator"].Value = ntdsaName; } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } NTDSSiteEntry.CommitChanges(); _topologyTouched = false; } else { try { // create nTDSSiteSettings object DirectoryEntry tmpEntry = cachedEntry.Children.Add("CN=NTDS Site Settings", "nTDSSiteSettings"); //set properties on the Site NTDS settings object DirectoryServer replica = InterSiteTopologyGenerator; if (replica != null) { string ntdsaName = (replica is DomainController) ? ((DomainController)replica).NtdsaObjectName : ((AdamInstance)replica).NtdsaObjectName; tmpEntry.Properties["interSiteTopologyGenerator"].Value = ntdsaName; } tmpEntry.Properties["options"].Value = _siteOptions; if (_replicationSchedule != null) { tmpEntry.Properties["schedule"].Value = _replicationSchedule; } tmpEntry.CommitChanges(); // cached the entry _ntdsEntry = tmpEntry; // create servers contain object tmpEntry = cachedEntry.Children.Add("CN=Servers", "serversContainer"); tmpEntry.CommitChanges(); if (!IsADAM) { // create the licensingSiteSettings object tmpEntry = cachedEntry.Children.Add("CN=Licensing Site Settings", "licensingSiteSettings"); tmpEntry.CommitChanges(); } } finally { // entry is created on the backend store successfully existing = true; } } } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } public void Delete() { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (!existing) { throw new InvalidOperationException(SR.CannotDelete); } else { try { cachedEntry.DeleteTree(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } } } public override string ToString() { if (_disposed) throw new ObjectDisposedException(GetType().Name); return _name; } private ReadOnlyDirectoryServerCollection GetBridgeheadServers() { NativeComInterfaces.IAdsPathname pathCracker = (NativeComInterfaces.IAdsPathname)new NativeComInterfaces.Pathname(); // need to turn off the escaping for name pathCracker.EscapedMode = NativeComInterfaces.ADS_ESCAPEDMODE_OFF_EX; ReadOnlyDirectoryServerCollection collection = new ReadOnlyDirectoryServerCollection(); if (existing) { Hashtable bridgeHeadTable = new Hashtable(); Hashtable nonBridgHeadTable = new Hashtable(); Hashtable hostNameTable = new Hashtable(); const string ocValue = "CN=Server"; // get destination bridgehead servers // first go to the servers container under the current site and then do a search to get the all server objects. string serverContainer = "CN=Servers," + (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName); DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, serverContainer); try { // go through connection objects and find out its fromServer property. ADSearcher adSearcher = new ADSearcher(de, "(|(objectCategory=server)(objectCategory=NTDSConnection))", new string[] { "fromServer", "distinguishedName", "dNSHostName", "objectCategory" }, SearchScope.Subtree, true, /* need paged search */ true /* need cached result as we need to go back to the first record */); SearchResultCollection conResults = null; try { conResults = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { // find out whether fromServer indicates replicating from a server in another site. foreach (SearchResult r in conResults) { string objectCategoryValue = (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.ObjectCategory); if (Utils.Compare(objectCategoryValue, 0, ocValue.Length, ocValue, 0, ocValue.Length) == 0) { hostNameTable.Add((string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.DistinguishedName), (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.DnsHostName)); } } foreach (SearchResult r in conResults) { string objectCategoryValue = (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.ObjectCategory); if (Utils.Compare(objectCategoryValue, 0, ocValue.Length, ocValue, 0, ocValue.Length) != 0) { string fromServer = (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.FromServer); // escaping manipulation string fromSite = Utils.GetPartialDN(fromServer, 3); pathCracker.Set(fromSite, NativeComInterfaces.ADS_SETTYPE_DN); fromSite = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF); Debug.Assert(fromSite != null && Utils.Compare(fromSite, 0, 3, "CN=", 0, 3) == 0); fromSite = fromSite.Substring(3); string serverObjectName = Utils.GetPartialDN((string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.DistinguishedName), 2); // don't know whether it is a bridgehead server yet. if (!bridgeHeadTable.Contains(serverObjectName)) { string hostName = (string)hostNameTable[serverObjectName]; // add if not yet done if (!nonBridgHeadTable.Contains(serverObjectName)) nonBridgHeadTable.Add(serverObjectName, hostName); // check whether from different site if (Utils.Compare((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.Cn), fromSite) != 0) { // the server is a bridgehead server bridgeHeadTable.Add(serverObjectName, hostName); nonBridgHeadTable.Remove(serverObjectName); } } } } } finally { conResults.Dispose(); } } finally { de.Dispose(); } // get source bridgehead server if (nonBridgHeadTable.Count != 0) { // go to sites container to get all the connecdtion object that replicates from servers in the current sites that have // not been determined whether it is a bridgehead server or not. DirectoryEntry serverEntry = DirectoryEntryManager.GetDirectoryEntry(context, _siteDN); // constructing the filter StringBuilder str = new StringBuilder(100); if (nonBridgHeadTable.Count > 1) str.Append("(|"); foreach (DictionaryEntry val in nonBridgHeadTable) { str.Append("(fromServer="); str.Append("CN=NTDS Settings,"); str.Append(Utils.GetEscapedFilterValue((string)val.Key)); str.Append(")"); } if (nonBridgHeadTable.Count > 1) str.Append(")"); ADSearcher adSearcher = new ADSearcher(serverEntry, "(&(objectClass=nTDSConnection)(objectCategory=NTDSConnection)" + str.ToString() + ")", new string[] { "fromServer", "distinguishedName" }, SearchScope.Subtree); SearchResultCollection conResults = null; try { conResults = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { foreach (SearchResult r in conResults) { string fromServer = (string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.FromServer); string serverObject = fromServer.Substring(17); if (nonBridgHeadTable.Contains(serverObject)) { string otherSite = Utils.GetPartialDN((string)PropertyManager.GetSearchResultPropertyValue(r, PropertyManager.DistinguishedName), 4); // escaping manipulation pathCracker.Set(otherSite, NativeComInterfaces.ADS_SETTYPE_DN); otherSite = pathCracker.Retrieve(NativeComInterfaces.ADS_FORMAT_LEAF); Debug.Assert(otherSite != null && Utils.Compare(otherSite, 0, 3, "CN=", 0, 3) == 0); otherSite = otherSite.Substring(3); // check whether from different sites if (Utils.Compare(otherSite, (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.Cn)) != 0) { string val = (string)nonBridgHeadTable[serverObject]; nonBridgHeadTable.Remove(serverObject); bridgeHeadTable.Add(serverObject, val); } } } } finally { conResults.Dispose(); serverEntry.Dispose(); } } DirectoryEntry ADAMEntry = null; foreach (DictionaryEntry e in bridgeHeadTable) { DirectoryServer replica = null; string host = (string)e.Value; // construct directoryreplica if (IsADAM) { ADAMEntry = DirectoryEntryManager.GetDirectoryEntry(context, "CN=NTDS Settings," + e.Key); int port = (int)PropertyManager.GetPropertyValue(context, ADAMEntry, PropertyManager.MsDSPortLDAP); string fullhost = host; if (port != 389) { fullhost = host + ":" + port; } replica = new AdamInstance(Utils.GetNewDirectoryContext(fullhost, DirectoryContextType.DirectoryServer, context), fullhost); } else { replica = new DomainController(Utils.GetNewDirectoryContext(host, DirectoryContextType.DirectoryServer, context), host); } collection.Add(replica); } } return collection; } public DirectoryEntry GetDirectoryEntry() { if (_disposed) throw new ObjectDisposedException(GetType().Name); if (!existing) { throw new InvalidOperationException(SR.CannotGetObject); } else { return DirectoryEntryManager.GetDirectoryEntryInternal(context, cachedEntry.Path); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { // free other state (managed objects) if (cachedEntry != null) cachedEntry.Dispose(); if (_ntdsEntry != null) _ntdsEntry.Dispose(); } // free your own state (unmanaged objects) _disposed = true; } private static void ValidateArgument(DirectoryContext context, string siteName) { // basic validation first if (context == null) throw new ArgumentNullException(nameof(context)); // if target is not specified, then we determin the target from the logon credential, so if it is a local user context, it should fail if ((context.Name == null) && (!context.isRootDomain())) { throw new ArgumentException(SR.ContextNotAssociatedWithDomain, nameof(context)); } // more validation for the context, if the target is not null, then it should be either forest name or server name if (context.Name != null) { if (!(context.isRootDomain() || context.isServer() || context.isADAMConfigSet())) throw new ArgumentException(SR.NotADOrADAM, nameof(context)); } if (siteName == null) throw new ArgumentNullException(nameof(siteName)); if (siteName.Length == 0) throw new ArgumentException(SR.EmptyStringParameter, nameof(siteName)); } private void GetSubnets() { // performs a search to find out the subnets that belong to this site DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); string subnetContainer = "CN=Subnets,CN=Sites," + config; de = DirectoryEntryManager.GetDirectoryEntry(context, subnetContainer); ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=subnet)(objectCategory=subnet)(siteObject=" + Utils.GetEscapedFilterValue((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)) + "))", new string[] { "cn", "location" }, SearchScope.OneLevel ); SearchResultCollection results = null; try { results = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { string subnetName = null; foreach (SearchResult result in results) { subnetName = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.Cn); ActiveDirectorySubnet subnet = new ActiveDirectorySubnet(context, subnetName, null, true); // set the cached entry subnet.cachedEntry = result.GetDirectoryEntry(); // set the site info subnet.Site = this; _subnets.Add(subnet); } } finally { results.Dispose(); de.Dispose(); } } private void GetAdjacentSites() { DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)de.Properties["configurationNamingContext"][0]; string transportContainer = "CN=Inter-Site Transports,CN=Sites," + config; de = DirectoryEntryManager.GetDirectoryEntry(context, transportContainer); ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=siteLink)(objectCategory=SiteLink)(siteList=" + Utils.GetEscapedFilterValue((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)) + "))", new string[] { "cn", "distinguishedName" }, SearchScope.Subtree); SearchResultCollection results = null; try { results = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { ActiveDirectorySiteLink link = null; foreach (SearchResult result in results) { string dn = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.DistinguishedName); string linkName = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.Cn); string transportName = (string)Utils.GetDNComponents(dn)[1].Value; ActiveDirectoryTransportType transportType; if (string.Equals(transportName, "IP", StringComparison.OrdinalIgnoreCase)) transportType = ActiveDirectoryTransportType.Rpc; else if (string.Equals(transportName, "SMTP", StringComparison.OrdinalIgnoreCase)) transportType = ActiveDirectoryTransportType.Smtp; else { // should not happen string message = SR.Format(SR.UnknownTransport , transportName); throw new ActiveDirectoryOperationException(message); } try { link = new ActiveDirectorySiteLink(context, linkName, transportType, true, result.GetDirectoryEntry()); foreach (ActiveDirectorySite tmpSite in link.Sites) { // don't add itself if (Utils.Compare(tmpSite.Name, Name) == 0) continue; if (!_adjacentSites.Contains(tmpSite)) _adjacentSites.Add(tmpSite); } } finally { link.Dispose(); } } } finally { results.Dispose(); de.Dispose(); } } private void GetLinks() { DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, WellKnownDN.RootDSE); string config = (string)PropertyManager.GetPropertyValue(context, de, PropertyManager.ConfigurationNamingContext); string transportContainer = "CN=Inter-Site Transports,CN=Sites," + config; de = DirectoryEntryManager.GetDirectoryEntry(context, transportContainer); ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=siteLink)(objectCategory=SiteLink)(siteList=" + Utils.GetEscapedFilterValue((string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName)) + "))", new string[] { "cn", "distinguishedName" }, SearchScope.Subtree); SearchResultCollection results = null; try { results = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { foreach (SearchResult result in results) { // construct the sitelinks at the same time DirectoryEntry connectionEntry = result.GetDirectoryEntry(); string cn = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.Cn); string transport = Utils.GetDNComponents((string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.DistinguishedName))[1].Value; ActiveDirectorySiteLink link = null; if (string.Equals(transport, "IP", StringComparison.OrdinalIgnoreCase)) link = new ActiveDirectorySiteLink(context, cn, ActiveDirectoryTransportType.Rpc, true, connectionEntry); else if (string.Equals(transport, "SMTP", StringComparison.OrdinalIgnoreCase)) link = new ActiveDirectorySiteLink(context, cn, ActiveDirectoryTransportType.Smtp, true, connectionEntry); else { // should not happen string message = SR.Format(SR.UnknownTransport , transport); throw new ActiveDirectoryOperationException(message); } _links.Add(link); } } finally { results.Dispose(); de.Dispose(); } } private void GetDomains() { // for ADAM, there is no concept of domain, we just return empty collection which is good enough if (!IsADAM) { string serverName = cachedEntry.Options.GetCurrentServerName(); DomainController dc = DomainController.GetDomainController(Utils.GetNewDirectoryContext(serverName, DirectoryContextType.DirectoryServer, context)); IntPtr handle = dc.Handle; Debug.Assert(handle != (IntPtr)0); IntPtr info = (IntPtr)0; // call DsReplicaSyncAllW IntPtr functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsListDomainsInSiteW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } UnsafeNativeMethods.DsListDomainsInSiteW dsListDomainsInSiteW = (UnsafeNativeMethods.DsListDomainsInSiteW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsListDomainsInSiteW)); int result = dsListDomainsInSiteW(handle, (string)PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName), ref info); if (result != 0) throw ExceptionHelper.GetExceptionFromErrorCode(result, serverName); try { DS_NAME_RESULT names = new DS_NAME_RESULT(); Marshal.PtrToStructure(info, names); int count = names.cItems; IntPtr val = names.rItems; if (count > 0) { Debug.Assert(val != (IntPtr)0); int status = Marshal.ReadInt32(val); IntPtr tmpPtr = (IntPtr)0; for (int i = 0; i < count; i++) { tmpPtr = IntPtr.Add(val, Marshal.SizeOf(typeof(DS_NAME_RESULT_ITEM)) * i); DS_NAME_RESULT_ITEM nameResult = new DS_NAME_RESULT_ITEM(); Marshal.PtrToStructure(tmpPtr, nameResult); if (nameResult.status == DS_NAME_ERROR.DS_NAME_NO_ERROR || nameResult.status == DS_NAME_ERROR.DS_NAME_ERROR_DOMAIN_ONLY) { string domainName = Marshal.PtrToStringUni(nameResult.pName); if (domainName != null && domainName.Length > 0) { string d = Utils.GetDnsNameFromDN(domainName); Domain domain = new Domain(Utils.GetNewDirectoryContext(d, DirectoryContextType.Domain, context), d); _domains.Add(domain); } } } } } finally { // call DsFreeNameResultW functionPtr = UnsafeNativeMethods.GetProcAddress(DirectoryContext.ADHandle, "DsFreeNameResultW"); if (functionPtr == (IntPtr)0) { throw ExceptionHelper.GetExceptionFromErrorCode(Marshal.GetLastWin32Error()); } UnsafeNativeMethods.DsFreeNameResultW dsFreeNameResultW = (UnsafeNativeMethods.DsFreeNameResultW)Marshal.GetDelegateForFunctionPointer(functionPtr, typeof(UnsafeNativeMethods.DsFreeNameResultW)); dsFreeNameResultW(info); } } } private void GetServers() { ADSearcher adSearcher = new ADSearcher(cachedEntry, "(&(objectClass=server)(objectCategory=server))", new string[] { "dNSHostName" }, SearchScope.Subtree); SearchResultCollection results = null; try { results = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { foreach (SearchResult result in results) { string hostName = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.DnsHostName); DirectoryEntry de = result.GetDirectoryEntry(); DirectoryEntry child = null; DirectoryServer replica = null; // make sure that the server is not demoted try { child = de.Children.Find("CN=NTDS Settings", "nTDSDSA"); } catch (COMException e) { if (e.ErrorCode == unchecked((int)0x80072030)) { continue; } else throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (IsADAM) { int port = (int)PropertyManager.GetPropertyValue(context, child, PropertyManager.MsDSPortLDAP); string fullHostName = hostName; if (port != 389) { fullHostName = hostName + ":" + port; } replica = new AdamInstance(Utils.GetNewDirectoryContext(fullHostName, DirectoryContextType.DirectoryServer, context), fullHostName); } else replica = new DomainController(Utils.GetNewDirectoryContext(hostName, DirectoryContextType.DirectoryServer, context), hostName); _servers.Add(replica); } } finally { results.Dispose(); } } private void GetPreferredBridgeheadServers(ActiveDirectoryTransportType transport) { string serverContainerDN = "CN=Servers," + PropertyManager.GetPropertyValue(context, cachedEntry, PropertyManager.DistinguishedName); string transportDN = null; if (transport == ActiveDirectoryTransportType.Smtp) transportDN = "CN=SMTP,CN=Inter-Site Transports," + _siteDN; else transportDN = "CN=IP,CN=Inter-Site Transports," + _siteDN; DirectoryEntry de = DirectoryEntryManager.GetDirectoryEntry(context, serverContainerDN); ADSearcher adSearcher = new ADSearcher(de, "(&(objectClass=server)(objectCategory=Server)(bridgeheadTransportList=" + Utils.GetEscapedFilterValue(transportDN) + "))", new string[] { "dNSHostName", "distinguishedName" }, SearchScope.OneLevel); SearchResultCollection results = null; try { results = adSearcher.FindAll(); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } try { DirectoryEntry ADAMEntry = null; foreach (SearchResult result in results) { string hostName = (string)PropertyManager.GetSearchResultPropertyValue(result, PropertyManager.DnsHostName); DirectoryEntry resultEntry = result.GetDirectoryEntry(); DirectoryServer replica = null; try { ADAMEntry = resultEntry.Children.Find("CN=NTDS Settings", "nTDSDSA"); } catch (COMException e) { throw ExceptionHelper.GetExceptionFromCOMException(context, e); } if (IsADAM) { int port = (int)PropertyManager.GetPropertyValue(context, ADAMEntry, PropertyManager.MsDSPortLDAP); string fullHostName = hostName; if (port != 389) { fullHostName = hostName + ":" + port; } replica = new AdamInstance(Utils.GetNewDirectoryContext(fullHostName, DirectoryContextType.DirectoryServer, context), fullHostName); } else replica = new DomainController(Utils.GetNewDirectoryContext(hostName, DirectoryContextType.DirectoryServer, context), hostName); if (transport == ActiveDirectoryTransportType.Smtp) _SMTPBridgeheadServers.Add(replica); else _RPCBridgeheadServers.Add(replica); } } finally { de.Dispose(); results.Dispose(); } } } }
using System.Text.RegularExpressions; using System.Diagnostics; using System; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Collections; using System.Drawing; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using WeifenLuo.WinFormsUI; using Microsoft.Win32; using WeifenLuo; using System.ComponentModel; namespace SoftLogik.Win { namespace UI { /// <summary> /// Treeview Control that utilizes a Custom Data Source Manager . /// </summary> public partial class SPTreeView { protected override void OnPaint(PaintEventArgs pe) { // Calling the base class OnPaint base.OnPaint(pe); } private bool m_autoBuild = true; public bool AutoBuildTree { get { return this.m_autoBuild; } set { this.m_autoBuild = value; } } #region Data Binding private CurrencyManager m_currencyManager = null; private string m_ValueMember; private string m_DisplayMember; private object m_oDataSource; [Category("Data")]public object DataSource { get { return m_oDataSource; } set { if (value == null) { this.m_currencyManager = null; this.Nodes.Clear(); } else { if (!(value is IList|| m_oDataSource is IListSource)) { throw (new System.Exception("Invalid DataSource")); } else { if (value is IListSource) { IListSource myListSource = (IListSource) value; if (myListSource.ContainsListCollection == true) { throw (new System.Exception("Invalid DataSource")); } } this.m_oDataSource = value; this.m_currencyManager = (CurrencyManager) (this.BindingContext[value]); if (this.AutoBuildTree) { BuildTree(); } } } } } // end of DataSource property [Category("Data")]public string ValueMember { get { return this.m_ValueMember; } set { this.m_ValueMember = value; } } [Category("Data")]public string DisplayMember { get { return this.m_DisplayMember; } set { this.m_DisplayMember = value; } } public object GetValue(int index) { IList innerList = this.m_currencyManager.List; if (innerList != null) { if ((this.ValueMember != "") && (index >= 0 && 0 < innerList.Count)) { PropertyDescriptor pdValueMember; pdValueMember = this.m_currencyManager.GetItemProperties()[this.ValueMember]; return pdValueMember.GetValue(innerList[index]); } } return null; } public object GetDisplay(int index) { IList innerList = this.m_currencyManager.List; if (innerList != null) { if ((this.DisplayMember != "") && (index >= 0 && 0 < innerList.Count)) { PropertyDescriptor pdDisplayMember; pdDisplayMember = this.m_currencyManager.GetItemProperties()[this.ValueMember]; return pdDisplayMember.GetValue(innerList[index]); } } return null; } #endregion #region Building the Tree private ArrayList treeGroups = new ArrayList(); public void BuildTree() { this.Nodes.Clear(); if ((this.m_currencyManager != null) && (this.m_currencyManager.List != null)) { IList innerList = this.m_currencyManager.List; TreeNodeCollection currNode = this.Nodes; int currGroupIndex = 0; int currListIndex = 0; if (this.treeGroups.Count > currGroupIndex) { SPTreeNodeGroup currGroup = (SPTreeNodeGroup) (treeGroups[currGroupIndex]); SPTreeNode myFirstNode = null; PropertyDescriptor pdGroupBy; PropertyDescriptor pdValue; PropertyDescriptor pdDisplay; pdGroupBy = this.m_currencyManager.GetItemProperties()[currGroup.GroupBy]; pdValue = this.m_currencyManager.GetItemProperties()[currGroup.ValueMember]; pdDisplay = this.m_currencyManager.GetItemProperties()[currGroup.DisplayMember]; string currGroupBy = null; if (innerList.Count > currListIndex) { object currObject; while (currListIndex < innerList.Count) { currObject = innerList[currListIndex]; if (pdGroupBy.GetValue(currObject).ToString() != currGroupBy) { currGroupBy = pdGroupBy.GetValue(currObject).ToString(); myFirstNode = new SPTreeNode(currGroup.Name, pdDisplay.GetValue(currObject).ToString(), currObject, pdValue.GetValue(innerList[currListIndex]), currGroup.ImageIndex, currGroup.SelectedImageIndex, currListIndex); currNode.Add((TreeNode) myFirstNode); } else { AddNodes(currGroupIndex, ref currListIndex, myFirstNode.Nodes, currGroup.GroupBy); } } // end while } // end if } else { while (currListIndex < innerList.Count) { AddNodes(currGroupIndex, ref currListIndex, this.Nodes, ""); } } // end else if (this.Nodes.Count > 0) { this.SelectedNode = this.Nodes[0]; } } // end if } private void AddNodes(int currGroupIndex, ref int currentListIndex, TreeNodeCollection currNodes, string prevGroupByField) { IList innerList = this.m_currencyManager.List; System.ComponentModel.PropertyDescriptor pdPrevGroupBy = null; string prevGroupByValue = null; SPTreeNodeGroup currGroup; if (prevGroupByField != "") { pdPrevGroupBy = this.m_currencyManager.GetItemProperties()[prevGroupByField]; } currGroupIndex++; if (treeGroups.Count > currGroupIndex) { currGroup = (SPTreeNodeGroup) (treeGroups[currGroupIndex]); PropertyDescriptor pdGroupBy = null; PropertyDescriptor pdValue = null; PropertyDescriptor pdDisplay = null; pdGroupBy = this.m_currencyManager.GetItemProperties()[currGroup.GroupBy]; pdValue = this.m_currencyManager.GetItemProperties()[currGroup.ValueMember]; pdDisplay = this.m_currencyManager.GetItemProperties()[currGroup.DisplayMember]; string currGroupBy = null; if (innerList.Count > currentListIndex) { if (pdPrevGroupBy != null) { prevGroupByValue = pdPrevGroupBy.GetValue(innerList[currentListIndex]).ToString(); } SPTreeNode myFirstNode = null; object currObject = null; while ((currentListIndex < innerList.Count) && (pdPrevGroupBy != null) && (pdPrevGroupBy.GetValue(innerList[currentListIndex]).ToString() == prevGroupByValue)) { currObject = innerList[currentListIndex]; if (pdGroupBy.GetValue(currObject).ToString() != currGroupBy) { currGroupBy = pdGroupBy.GetValue(currObject).ToString(); myFirstNode = new SPTreeNode(currGroup.Name, pdDisplay.GetValue(currObject).ToString(), currObject, pdValue.GetValue(innerList[currentListIndex]), currGroup.ImageIndex, currGroup.SelectedImageIndex, currentListIndex); currNodes.Add((TreeNode) myFirstNode); } else { AddNodes(currGroupIndex, ref currentListIndex, myFirstNode.Nodes, currGroup.GroupBy); } } } } else { SPTreeNode myNewLeafNode; object currObject = this.m_currencyManager.List[currentListIndex]; if ((this.DisplayMember != null) && (this.ValueMember != null) && (this.DisplayMember != "") && (this.ValueMember != "")) { PropertyDescriptorCollection pdDisplayColl = this.m_currencyManager.GetItemProperties(); PropertyDescriptor pdDisplayloc = pdDisplayColl[this.DisplayMember.ToLowerInvariant()]; PropertyDescriptor pdValueloc = pdDisplayColl[this.ValueMember.ToLowerInvariant()]; if (this.Tag == null) { myNewLeafNode = new SPTreeNode("", pdDisplayloc.GetValue(currObject).ToString(), currObject, pdValueloc.GetValue(currObject), currentListIndex); } else { myNewLeafNode = new SPTreeNode(this.Tag.ToString(), pdDisplayloc.GetValue(currObject).ToString(), currObject, pdValueloc.GetValue(currObject), currentListIndex); } } else { myNewLeafNode = new SPTreeNode("", currentListIndex.ToString(), currObject, currObject, this.ImageIndex, this.SelectedImageIndex, currentListIndex); } currNodes.Add((TreeNode) myNewLeafNode); currentListIndex++; } } #endregion #region Groups public void RemoveGroup(SPTreeNodeGroup group) { if (treeGroups.Contains(group)) { treeGroups.Remove(group); if (this.AutoBuildTree) { BuildTree(); } } } public void RemoveGroup(string groupName) { foreach (SPTreeNodeGroup group in this.treeGroups) { if (group.Name == groupName) { RemoveGroup(group); return; } } } public void RemoveAllGroups() { this.treeGroups.Clear(); if (this.AutoBuildTree) { this.BuildTree(); } } public void AddGroup(SPTreeNodeGroup group) { try { treeGroups.Add(group); if (this.AutoBuildTree) { this.BuildTree(); } } catch (NotSupportedException e) { MessageBox.Show(e.Message); } catch (System.Exception e) { throw (e); } } public void AddGroup(string name, string groupBy, string displayMember, string valueMember, int imageIndex, int selectedImageIndex) { SPTreeNodeGroup myNewGroup = new SPTreeNodeGroup(name, groupBy, displayMember, valueMember, imageIndex, selectedImageIndex); this.AddGroup(myNewGroup); } public SPTreeNodeGroup[] GetGroups() { return ((SPTreeNodeGroup[]) (treeGroups.ToArray(Type.GetType("SPTreeNodeGroup")))); } #endregion public void SetLeafData(string name, string displayMember, string valueMember, int imageIndex, int selectedImageIndex) { this.Tag = name; this.DisplayMember = displayMember; this.ValueMember = valueMember; this.ImageIndex = imageIndex; this.SelectedImageIndex = selectedImageIndex; } public bool IsLeafNode(TreeNode node) { return (node.Nodes.Count == 0); } #region Keeping Everything In Sync public TreeNode FindNodeByValue(object value) { return FindNodeByValue(value, this.Nodes); } public TreeNode FindNodeByValue(object Value, TreeNodeCollection nodesToSearch) { int i = 0; TreeNode currNode; SPTreeNode leafNode; while (i < nodesToSearch.Count) { currNode = nodesToSearch[i]; i++; if (currNode.LastNode == null) { leafNode = (SPTreeNode) currNode; if (leafNode.Value.ToString() == Value.ToString()) { return currNode; } } else { currNode = FindNodeByValue(Value, currNode.Nodes); if (currNode != null) { return currNode; } } } return null; } private TreeNode FindNodeByPosition(int posIndex) { return FindNodeByPosition(posIndex, this.Nodes); } private TreeNode FindNodeByPosition(int posIndex, TreeNodeCollection nodesToSearch) { int i = 0; TreeNode currNode; SPTreeNode leafNode; while (i < nodesToSearch.Count) { currNode = nodesToSearch[i]; i++; if (currNode.Nodes.Count == 0) { leafNode = (SPTreeNode) currNode; if (leafNode.Position == posIndex) { return currNode; } else { currNode = FindNodeByPosition(posIndex, currNode.Nodes); if (currNode != null) { return currNode; } } } } return null; } protected override void OnAfterSelect(TreeViewEventArgs e) { SPTreeNode leafNode = (SPTreeNode) e.Node; if (leafNode != null) { if (this.m_currencyManager.Position != leafNode.Position) { this.m_currencyManager.Position = leafNode.Position; } } base.OnAfterSelect(e); } #endregion } [Description("Specify Grouping for a collection of Tree Nodes in TreeView")]public class SPTreeNodeGroup { private string groupName; private string groupByMember; private string groupByDisplayMember; private string groupByValueMember; private int groupImageIndex; private int groupSelectedImageIndex; public SPTreeNodeGroup(string name, string groupBy, string displayMember, string valueMember, int imageIndex, int selectedImageIndex) { this.ImageIndex = imageIndex; this.Name = name; this.GroupBy = groupBy; this.DisplayMember = displayMember; this.ValueMember = valueMember; this.SelectedImageIndex = selectedImageIndex; } public SPTreeNodeGroup(string name, string groupBy, string displayMember, string valueMember, int imageIndex) : this(name, groupBy, displayMember, valueMember, imageIndex, imageIndex) { } public SPTreeNodeGroup(string name, string groupBy) : this(name, groupBy, groupBy, groupBy, - 1, - 1) { } public int SelectedImageIndex { get { return groupSelectedImageIndex; } set { groupSelectedImageIndex = value; } } public int ImageIndex { get { return groupImageIndex; } set { groupImageIndex = value; } } public string Name { get { return groupName; } set { groupName = value; } } public string GroupBy { get { return groupByMember; } set { groupByMember = value; } } public string DisplayMember { get { return groupByDisplayMember; } set { groupByDisplayMember = value; } } public string ValueMember { get { return groupByValueMember; } set { groupByValueMember = value; } } } [Description("A Node in the TreeView")]public class SPTreeNode : TreeNode { private string m_groupName; private object m_value; private object m_item; private int m_position; public SPTreeNode() { } public SPTreeNode(string GroupName, string text, object item, object value, int imageIndex, int selectedImgIndex, int position) { this.GroupName = GroupName; this.Text = text; this.Item = item; this.Value = value; this.ImageIndex = imageIndex; this.SelectedImageIndex = selectedImgIndex; this.m_position = position; } public SPTreeNode(string groupName, string text, object item, object value, int position) { this.GroupName = groupName; this.Text = text; this.Item = item; this.Value = value; this.m_position = position; } public string GroupName { get { return m_groupName; } set { this.m_groupName = value; } } public object Item { get { return m_item; } set { m_item = value; } } public object Value { get { return m_value; } set { m_value = value; } } public int Position { get { return m_position; } } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis; using Analyzer.Utilities; using Analyzer.Utilities.Extensions; using System.Threading; using Analyzer.Utilities.PooledObjects; namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines { [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public sealed class IdentifiersShouldDifferByMoreThanCaseAnalyzer : DiagnosticAnalyzer { public const string RuleId = "CA1708"; public const string Namespace = "Namespaces"; public const string Type = "Types"; public const string Member = "Members"; public const string Parameter = "Parameters of"; private static readonly LocalizableResourceString s_localizableTitle = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldDifferByMoreThanCaseTitle), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableResourceString s_localizableMessage = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldDifferByMoreThanCaseMessage), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); private static readonly LocalizableResourceString s_localizableDescription = new LocalizableResourceString(nameof(MicrosoftCodeQualityAnalyzersResources.IdentifiersShouldDifferByMoreThanCaseDescription), MicrosoftCodeQualityAnalyzersResources.ResourceManager, typeof(MicrosoftCodeQualityAnalyzersResources)); internal static readonly DiagnosticDescriptor Rule = DiagnosticDescriptorHelper.Create(RuleId, s_localizableTitle, s_localizableMessage, DiagnosticCategory.Naming, RuleLevel.IdeHidden_BulkConfigurable, description: s_localizableDescription, isPortedFxCopRule: true, isDataflowRule: false, isEnabledByDefaultInFxCopAnalyzers: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext analysisContext) { analysisContext.EnableConcurrentExecution(); analysisContext.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); analysisContext.RegisterCompilationAction(AnalyzeCompilation); analysisContext.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType); } private static void AnalyzeCompilation(CompilationAnalysisContext context) { IEnumerable<INamespaceSymbol> globalNamespaces = context.Compilation.GlobalNamespace.GetNamespaceMembers() .Where(item => Equals(item.ContainingAssembly, context.Compilation.Assembly)); IEnumerable<INamedTypeSymbol> globalTypes = context.Compilation.GlobalNamespace.GetTypeMembers().Where(item => Equals(item.ContainingAssembly, context.Compilation.Assembly) && MatchesConfiguredVisibility(item, context.Options, context.Compilation, context.CancellationToken)); CheckTypeNames(globalTypes, context); CheckNamespaceMembers(globalNamespaces, context); } private static void AnalyzeSymbol(SymbolAnalysisContext context) { var namedTypeSymbol = (INamedTypeSymbol)context.Symbol; // Do not descent into non-publicly visible types by default // Note: This is the behavior of FxCop, it might be more correct to descend into internal but not private // types because "InternalsVisibleTo" could be set. But it might be bad for users to start seeing warnings // where they previously did not from FxCop. // Note that end user can now override this default behavior via options. if (!namedTypeSymbol.MatchesConfiguredVisibility(context.Options, Rule, context.Compilation, context.CancellationToken)) { return; } // Get externally visible members in the given type IEnumerable<ISymbol> members = namedTypeSymbol.GetMembers() .Where(item => !item.IsAccessorMethod() && MatchesConfiguredVisibility(item, context.Options, context.Compilation, context.CancellationToken)); if (members.Any()) { // Check parameters names of externally visible members with parameters CheckParameterMembers(members, context.ReportDiagnostic); // Check names of externally visible type members and their members CheckTypeMembers(members, context.ReportDiagnostic); } } private static void CheckNamespaceMembers(IEnumerable<INamespaceSymbol> namespaces, CompilationAnalysisContext context) { HashSet<INamespaceSymbol> excludedNamespaces = new HashSet<INamespaceSymbol>(); foreach (INamespaceSymbol @namespace in namespaces) { // Get all the potentially externally visible types in the namespace IEnumerable<INamedTypeSymbol> typeMembers = @namespace.GetTypeMembers().Where(item => Equals(item.ContainingAssembly, context.Compilation.Assembly) && MatchesConfiguredVisibility(item, context.Options, context.Compilation, context.CancellationToken)); if (typeMembers.Any()) { CheckTypeNames(typeMembers, context); } else { // If the namespace does not contain any externally visible types then exclude it from name check excludedNamespaces.Add(@namespace); } IEnumerable<INamespaceSymbol> namespaceMembers = @namespace.GetNamespaceMembers(); if (namespaceMembers.Any()) { CheckNamespaceMembers(namespaceMembers, context); // If there is a child namespace that has externally visible types, then remove the parent namespace from exclusion list if (namespaceMembers.Any(item => !excludedNamespaces.Contains(item))) { excludedNamespaces.Remove(@namespace); } } } // Before name check, remove all namespaces that don't contain externally visible types in current scope namespaces = namespaces.Where(item => !excludedNamespaces.Contains(item)); CheckNamespaceNames(namespaces, context); } private static void CheckTypeMembers(IEnumerable<ISymbol> members, Action<Diagnostic> addDiagnostic) { // If there is only one member, then return if (!members.Skip(1).Any()) { return; } using var overloadsToSkip = PooledHashSet<ISymbol>.GetInstance(); using var membersByName = PooledDictionary<string, PooledHashSet<ISymbol>>.GetInstance(StringComparer.OrdinalIgnoreCase); foreach (var member in members) { // Ignore constructors, indexers, operators and destructors for name check if (member.IsConstructor() || member.IsDestructor() || member.IsIndexer() || member.IsUserDefinedOperator() || overloadsToSkip.Contains(member)) { continue; } var name = DiagnosticHelpers.GetMemberName(member); if (!membersByName.TryGetValue(name, out var membersWithName)) { membersWithName = PooledHashSet<ISymbol>.GetInstance(); membersByName[name] = membersWithName; } membersWithName.Add(member); if (member is IMethodSymbol method) { foreach (var overload in method.GetOverloads()) { overloadsToSkip.Add(overload); } } } foreach (var (name, membersWithName) in membersByName) { if (membersWithName.Count > 1 && !membersWithName.All(m => m.IsOverride)) { ISymbol symbol = membersWithName.First().ContainingSymbol; addDiagnostic(symbol.CreateDiagnostic(Rule, Member, GetSymbolDisplayString(membersWithName))); } membersWithName.Free(); } } private static void CheckParameterMembers(IEnumerable<ISymbol> members, Action<Diagnostic> addDiagnostic) { foreach (var member in members) { if (IsViolatingMember(member) || IsViolatingDelegate(member)) { addDiagnostic(member.CreateDiagnostic(Rule, Parameter, member.ToDisplayString())); } } return; // Local functions static bool IsViolatingMember(ISymbol member) => member.ContainingType.DelegateInvokeMethod == null && HasViolatingParameters(member); static bool IsViolatingDelegate(ISymbol member) => member is INamedTypeSymbol typeSymbol && typeSymbol.DelegateInvokeMethod != null && HasViolatingParameters(typeSymbol.DelegateInvokeMethod); } #region NameCheck Methods private static bool HasViolatingParameters(ISymbol symbol) { var parameters = symbol.GetParameters(); // We only analyze symbols with more then one parameter. if (parameters.Length <= 1) { return false; } using var uniqueNames = PooledHashSet<string>.GetInstance(StringComparer.OrdinalIgnoreCase); foreach (var parameter in parameters) { if (!uniqueNames.Add(parameter.Name)) { return true; } } return false; } private static void CheckTypeNames(IEnumerable<INamedTypeSymbol> types, CompilationAnalysisContext context) { // If there is only one type, then return if (!types.Skip(1).Any()) { return; } using var typesByName = PooledDictionary<string, PooledHashSet<ISymbol>>.GetInstance(StringComparer.OrdinalIgnoreCase); foreach (var type in types) { var name = DiagnosticHelpers.GetMemberName(type); if (!typesByName.TryGetValue(name, out var typesWithName)) { typesWithName = PooledHashSet<ISymbol>.GetInstance(); typesByName[name] = typesWithName; } typesWithName.Add(type); } foreach (var (_, typesWithName) in typesByName) { if (typesWithName.Count > 1) { context.ReportNoLocationDiagnostic(Rule, Type, GetSymbolDisplayString(typesWithName)); } typesWithName.Free(); } } private static void CheckNamespaceNames(IEnumerable<INamespaceSymbol> namespaces, CompilationAnalysisContext context) { // If there is only one namespace, then return if (!namespaces.Skip(1).Any()) { return; } using var namespacesByName = PooledDictionary<string, PooledHashSet<ISymbol>>.GetInstance(StringComparer.OrdinalIgnoreCase); foreach (var namespaceSym in namespaces) { var name = namespaceSym.ToDisplayString(); if (!namespacesByName.TryGetValue(name, out var namespacesWithName)) { namespacesWithName = PooledHashSet<ISymbol>.GetInstance(); namespacesByName[name] = namespacesWithName; } namespacesWithName.Add(namespaceSym); } foreach (var (_, namespacesWithName) in namespacesByName) { if (namespacesWithName.Count > 1) { context.ReportNoLocationDiagnostic(Rule, Namespace, GetSymbolDisplayString(namespacesWithName)); } namespacesWithName.Free(); } } #endregion #region Helper Methods private static string GetSymbolDisplayString(PooledHashSet<ISymbol> group) { return string.Join(", ", group.Select(s => s.ToDisplayString()).OrderBy(k => k, StringComparer.Ordinal)); } public static bool MatchesConfiguredVisibility(ISymbol symbol, AnalyzerOptions options, Compilation compilation, CancellationToken cancellationToken) { var defaultAllowedVisibilties = SymbolVisibilityGroup.Public | SymbolVisibilityGroup.Internal; var allowedVisibilities = options.GetSymbolVisibilityGroupOption(Rule, symbol, compilation, defaultAllowedVisibilties, cancellationToken); return allowedVisibilities.Contains(symbol.GetResultantVisibility()); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection.Metadata; using System.Runtime.InteropServices.ComTypes; using Microsoft.DiaSymReader; using Roslyn.Utilities; namespace Roslyn.Test.PdbUtilities { public sealed class SymReader : ISymUnmanagedReader, ISymUnmanagedReader2, ISymUnmanagedReader3, IDisposable { /// <summary> /// Mock implementation: instead of a single reader with multiple versions, we'll use an array /// of readers - each with a single version. We do this so that we can implement /// <see cref="ISymUnmanagedReader3.GetSymAttributeByVersion"/> on top of /// <see cref="ISymUnmanagedReader.GetSymAttribute"/>. /// </summary> private readonly ISymUnmanagedReader[] _readerVersions; private readonly ImmutableDictionary<string, byte[]> _constantSignaturesOpt; private bool _isDisposed; public SymReader(byte[] pdbBytes, ImmutableDictionary<string, byte[]> constantSignaturesOpt = null) : this(new[] { new MemoryStream(pdbBytes) }, constantSignaturesOpt) { } public SymReader(Stream pdbStream, ImmutableDictionary<string, byte[]> constantSignaturesOpt = null) : this(new[] { pdbStream }, constantSignaturesOpt) { } public SymReader(Stream[] pdbStreamsByVersion, ImmutableDictionary<string, byte[]> constantSignaturesOpt = null) { _readerVersions = pdbStreamsByVersion.Select( pdbStream => SymUnmanagedReaderTestExtensions.CreateReader(pdbStream, DummyMetadataImport.Instance)).ToArray(); // If ISymUnmanagedReader3 is available, then we shouldn't be passing in multiple byte streams - one should suffice. Debug.Assert(!(UnversionedReader is ISymUnmanagedReader3) || _readerVersions.Length == 1); _constantSignaturesOpt = constantSignaturesOpt; } private ISymUnmanagedReader UnversionedReader => _readerVersions[0]; public int GetDocuments(int cDocs, out int pcDocs, ISymUnmanagedDocument[] pDocs) { return UnversionedReader.GetDocuments(cDocs, out pcDocs, pDocs); } public int GetMethod(int methodToken, out ISymUnmanagedMethod retVal) { // The EE should never be calling ISymUnmanagedReader.GetMethod. In order to account // for EnC updates, it should always be calling GetMethodByVersion instead. throw ExceptionUtilities.Unreachable; } public int GetMethodByVersion(int methodToken, int version, out ISymUnmanagedMethod retVal) { // Versions are 1-based. Debug.Assert(version >= 1); var reader = _readerVersions[version - 1]; version = _readerVersions.Length > 1 ? 1 : version; var hr = reader.GetMethodByVersion(methodToken, version, out retVal); if (retVal != null) { var asyncMethod = retVal as ISymUnmanagedAsyncMethod; retVal = asyncMethod == null ? (ISymUnmanagedMethod)new SymMethod(this, retVal) : new SymAsyncMethod(this, asyncMethod); } return hr; } public int GetSymAttribute(int token, string name, int sizeBuffer, out int lengthBuffer, byte[] buffer) { // The EE should never be calling ISymUnmanagedReader.GetSymAttribute. // In order to account for EnC updates, it should always be calling // ISymUnmanagedReader3.GetSymAttributeByVersion instead. // TODO (DevDiv #1145183): throw ExceptionUtilities.Unreachable; return UnversionedReader.GetSymAttribute(token, name, sizeBuffer, out lengthBuffer, buffer); } public int GetSymAttributeByVersion(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { // Versions are 1-based. Debug.Assert(version >= 1); return _readerVersions[version - 1].GetSymAttribute(methodToken, name, bufferLength, out count, customDebugInformation); } public int GetUserEntryPoint(out int entryPoint) { return UnversionedReader.GetUserEntryPoint(out entryPoint); } void IDisposable.Dispose() { if (!_isDisposed) { for (int i = 0; i < _readerVersions.Length; i++) { int hr = (_readerVersions[i] as ISymUnmanagedDispose).Destroy(); SymUnmanagedReaderExtensions.ThrowExceptionForHR(hr); _readerVersions[i] = null; } _isDisposed = true; } } public int GetDocument(string url, Guid language, Guid languageVendor, Guid documentType, out ISymUnmanagedDocument document) { return UnversionedReader.GetDocument(url, language, languageVendor, documentType, out document); } public int GetVariables(int methodToken, int bufferLength, out int count, ISymUnmanagedVariable[] variables) { return UnversionedReader.GetVariables(methodToken, bufferLength, out count, variables); } public int GetGlobalVariables(int bufferLength, out int count, ISymUnmanagedVariable[] variables) { return UnversionedReader.GetGlobalVariables(bufferLength, out count, variables); } public int GetMethodFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, out ISymUnmanagedMethod method) { return UnversionedReader.GetMethodFromDocumentPosition(document, line, column, out method); } public int GetNamespaces(int bufferLength, out int count, ISymUnmanagedNamespace[] namespaces) { return UnversionedReader.GetNamespaces(bufferLength, out count, namespaces); } public int Initialize(object metadataImporter, string fileName, string searchPath, IStream stream) { return UnversionedReader.Initialize(metadataImporter, fileName, searchPath, stream); } public int UpdateSymbolStore(string fileName, IStream stream) { return UnversionedReader.UpdateSymbolStore(fileName, stream); } public int ReplaceSymbolStore(string fileName, IStream stream) { return UnversionedReader.ReplaceSymbolStore(fileName, stream); } public int GetSymbolStoreFileName(int bufferLength, out int count, char[] name) { return UnversionedReader.GetSymbolStoreFileName(bufferLength, out count, name); } public int GetMethodsFromDocumentPosition(ISymUnmanagedDocument document, int line, int column, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { return UnversionedReader.GetMethodsFromDocumentPosition(document, line, column, bufferLength, out count, methods); } public int GetDocumentVersion(ISymUnmanagedDocument document, out int version, out bool isCurrent) { return UnversionedReader.GetDocumentVersion(document, out version, out isCurrent); } public int GetMethodVersion(ISymUnmanagedMethod method, out int version) { return UnversionedReader.GetMethodVersion(method, out version); } public int GetMethodByVersionPreRemap(int methodToken, int version, out ISymUnmanagedMethod method) { throw new NotImplementedException(); } public int GetSymAttributePreRemap(int methodToken, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } public int GetMethodsInDocument(ISymUnmanagedDocument document, int bufferLength, out int count, ISymUnmanagedMethod[] methods) { throw new NotImplementedException(); } public int GetSymAttributeByVersionPreRemap(int methodToken, int version, string name, int bufferLength, out int count, byte[] customDebugInformation) { throw new NotImplementedException(); } private sealed class SymMethod : ISymUnmanagedMethod { private readonly SymReader _reader; private readonly ISymUnmanagedMethod _method; internal SymMethod(SymReader reader, ISymUnmanagedMethod method) { Debug.Assert(!(method is ISymUnmanagedAsyncMethod), "Use SymAsyncMethod."); _reader = reader; _method = method; } public int GetRootScope(out ISymUnmanagedScope retVal) { _method.GetRootScope(out retVal); if (retVal != null) { retVal = new SymScope(_reader, retVal); } return SymUnmanagedReaderExtensions.S_OK; } public int GetScopeFromOffset(int offset, out ISymUnmanagedScope retVal) { throw new NotImplementedException(); } public int GetSequencePointCount(out int retVal) { return _method.GetSequencePointCount(out retVal); } public int GetToken(out int token) { throw new NotImplementedException(); } public int GetNamespace(out ISymUnmanagedNamespace retVal) { throw new NotImplementedException(); } public int GetOffset(ISymUnmanagedDocument document, int line, int column, out int retVal) { throw new NotImplementedException(); } public int GetParameters(int cParams, out int pcParams, ISymUnmanagedVariable[] parms) { throw new NotImplementedException(); } public int GetRanges(ISymUnmanagedDocument document, int line, int column, int cRanges, out int pcRanges, int[] ranges) { throw new NotImplementedException(); } public int GetSequencePoints( int cPoints, out int pcPoints, int[] offsets, ISymUnmanagedDocument[] documents, int[] lines, int[] columns, int[] endLines, int[] endColumns) { _method.GetSequencePoints(cPoints, out pcPoints, offsets, documents, lines, columns, endLines, endColumns); return SymUnmanagedReaderExtensions.S_OK; } public int GetSourceStartEnd(ISymUnmanagedDocument[] docs, int[] lines, int[] columns, out bool retVal) { throw new NotImplementedException(); } } private sealed class SymAsyncMethod : ISymUnmanagedMethod, ISymUnmanagedAsyncMethod { private readonly SymReader _reader; private readonly ISymUnmanagedAsyncMethod _method; internal SymAsyncMethod(SymReader reader, ISymUnmanagedAsyncMethod method) { _reader = reader; _method = method; } public int GetRootScope(out ISymUnmanagedScope retVal) { ((ISymUnmanagedMethod)_method).GetRootScope(out retVal); if (retVal != null) { retVal = new SymScope(_reader, retVal); } return SymUnmanagedReaderExtensions.S_OK; } public int GetScopeFromOffset(int offset, out ISymUnmanagedScope retVal) { throw new NotImplementedException(); } public int GetSequencePointCount(out int retVal) { return ((ISymUnmanagedMethod)_method).GetSequencePointCount(out retVal); } public int GetToken(out int token) { throw new NotImplementedException(); } public int GetNamespace(out ISymUnmanagedNamespace retVal) { throw new NotImplementedException(); } public int GetOffset(ISymUnmanagedDocument document, int line, int column, out int retVal) { throw new NotImplementedException(); } public int GetParameters(int cParams, out int pcParams, ISymUnmanagedVariable[] parms) { throw new NotImplementedException(); } public int GetRanges(ISymUnmanagedDocument document, int line, int column, int cRanges, out int pcRanges, int[] ranges) { throw new NotImplementedException(); } public int GetSequencePoints( int cPoints, out int pcPoints, int[] offsets, ISymUnmanagedDocument[] documents, int[] lines, int[] columns, int[] endLines, int[] endColumns) { ((ISymUnmanagedMethod)_method).GetSequencePoints(cPoints, out pcPoints, offsets, documents, lines, columns, endLines, endColumns); return SymUnmanagedReaderExtensions.S_OK; } public int GetSourceStartEnd(ISymUnmanagedDocument[] docs, int[] lines, int[] columns, out bool retVal) { throw new NotImplementedException(); } public int IsAsyncMethod(out bool value) { return _method.IsAsyncMethod(out value); } public int GetKickoffMethod(out int kickoffMethodToken) { return _method.GetKickoffMethod(out kickoffMethodToken); } public int HasCatchHandlerILOffset(out bool offset) { return _method.HasCatchHandlerILOffset(out offset); } public int GetCatchHandlerILOffset(out int offset) { return _method.GetCatchHandlerILOffset(out offset); } public int GetAsyncStepInfoCount(out int count) { return _method.GetAsyncStepInfoCount(out count); } public int GetAsyncStepInfo(int bufferLength, out int count, int[] yieldOffsets, int[] breakpointOffset, int[] breakpointMethod) { return _method.GetAsyncStepInfo(bufferLength, out count, yieldOffsets, breakpointOffset, breakpointMethod); } } private sealed class SymScope : ISymUnmanagedScope, ISymUnmanagedScope2 { private readonly SymReader _reader; private readonly ISymUnmanagedScope _scope; internal SymScope(SymReader reader, ISymUnmanagedScope scope) { _reader = reader; _scope = scope; } public int GetChildren(int cChildren, out int pcChildren, ISymUnmanagedScope[] children) { _scope.GetChildren(cChildren, out pcChildren, children); if (children != null) { for (int i = 0; i < pcChildren; i++) { children[i] = new SymScope(_reader, children[i]); } } return SymUnmanagedReaderExtensions.S_OK; } public int GetConstantCount(out int pRetVal) { throw new NotImplementedException(); } public int GetConstants(int cConstants, out int pcConstants, ISymUnmanagedConstant[] constants) { ((ISymUnmanagedScope2)_scope).GetConstants(cConstants, out pcConstants, constants); if (constants != null) { for (int i = 0; i < pcConstants; i++) { var c = constants[i]; var signaturesOpt = _reader._constantSignaturesOpt; byte[] signature = null; if (signaturesOpt != null) { int length; int hresult = c.GetName(0, out length, null); SymUnmanagedReaderExtensions.ThrowExceptionForHR(hresult); var chars = new char[length]; hresult = c.GetName(length, out length, chars); SymUnmanagedReaderExtensions.ThrowExceptionForHR(hresult); var name = new string(chars, 0, length - 1); signaturesOpt.TryGetValue(name, out signature); } constants[i] = new SymConstant(c, signature); } } return SymUnmanagedReaderExtensions.S_OK; } public int GetEndOffset(out int pRetVal) { return _scope.GetEndOffset(out pRetVal); } public int GetLocalCount(out int pRetVal) { return _scope.GetLocalCount(out pRetVal); } public int GetLocals(int cLocals, out int pcLocals, ISymUnmanagedVariable[] locals) { return _scope.GetLocals(cLocals, out pcLocals, locals); } public int GetMethod(out ISymUnmanagedMethod pRetVal) { throw new NotImplementedException(); } public int GetNamespaces(int cNameSpaces, out int pcNameSpaces, ISymUnmanagedNamespace[] namespaces) { return _scope.GetNamespaces(cNameSpaces, out pcNameSpaces, namespaces); } public int GetParent(out ISymUnmanagedScope pRetVal) { throw new NotImplementedException(); } public int GetStartOffset(out int pRetVal) { return _scope.GetStartOffset(out pRetVal); } public void _VtblGap1_9() { throw new NotImplementedException(); } } private sealed class SymConstant : ISymUnmanagedConstant { private readonly ISymUnmanagedConstant _constant; private readonly byte[] _signatureOpt; internal SymConstant(ISymUnmanagedConstant constant, byte[] signatureOpt) { _constant = constant; _signatureOpt = signatureOpt; } public int GetName(int cchName, out int pcchName, char[] name) { return _constant.GetName(cchName, out pcchName, name); } public int GetSignature(int cSig, out int pcSig, byte[] sig) { if (_signatureOpt == null) { pcSig = 1; if (sig != null) { object value; _constant.GetValue(out value); sig[0] = (byte)GetSignatureTypeCode(value); } } else { pcSig = _signatureOpt.Length; if (sig != null) { Array.Copy(_signatureOpt, sig, cSig); } } return SymUnmanagedReaderExtensions.S_OK; } public int GetValue(out object value) { return _constant.GetValue(out value); } private static SignatureTypeCode GetSignatureTypeCode(object value) { if (value == null) { // Note: We never reach here since PdbWriter uses // (int)0 for (object)null. This is just an issue with // this implementation of GetSignature however. return SignatureTypeCode.Object; } var typeCode = Type.GetTypeCode(value.GetType()); switch (typeCode) { case TypeCode.Int32: return SignatureTypeCode.Int32; case TypeCode.String: return SignatureTypeCode.String; case TypeCode.Double: return SignatureTypeCode.Double; default: // Only a few TypeCodes handled currently. throw new NotImplementedException(); } } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; namespace Newtonsoft.Json { /// <summary> /// Serializes and deserializes objects into and from the JSON format. /// The <see cref="JsonSerializer"/> enables you to control how objects are encoded into JSON. /// </summary> public class JsonSerializer { internal TypeNameHandling _typeNameHandling; internal TypeNameAssemblyFormatHandling _typeNameAssemblyFormatHandling; internal PreserveReferencesHandling _preserveReferencesHandling; internal ReferenceLoopHandling _referenceLoopHandling; internal MissingMemberHandling _missingMemberHandling; internal ObjectCreationHandling _objectCreationHandling; internal NullValueHandling _nullValueHandling; internal DefaultValueHandling _defaultValueHandling; internal ConstructorHandling _constructorHandling; internal MetadataPropertyHandling _metadataPropertyHandling; internal JsonConverterCollection _converters; internal IContractResolver _contractResolver; internal ITraceWriter _traceWriter; internal IEqualityComparer _equalityComparer; internal ISerializationBinder _serializationBinder; internal StreamingContext _context; private IReferenceResolver _referenceResolver; private Formatting? _formatting; private DateFormatHandling? _dateFormatHandling; private DateTimeZoneHandling? _dateTimeZoneHandling; private DateParseHandling? _dateParseHandling; private FloatFormatHandling? _floatFormatHandling; private FloatParseHandling? _floatParseHandling; private StringEscapeHandling? _stringEscapeHandling; private GuidHandling? _guidHandling; private CultureInfo _culture; private int? _maxDepth; private bool _maxDepthSet; private bool? _checkAdditionalContent; private string _dateFormatString; private bool _dateFormatStringSet; /// <summary> /// Occurs when the <see cref="JsonSerializer"/> errors during serialization and deserialization. /// </summary> public virtual event EventHandler<ErrorEventArgs> Error; /// <summary> /// Gets or sets the <see cref="IReferenceResolver"/> used by the serializer when resolving references. /// </summary> public virtual IReferenceResolver ReferenceResolver { get { return GetReferenceResolver(); } set { if (value == null) { throw new ArgumentNullException(nameof(value), "Reference resolver cannot be null."); } _referenceResolver = value; } } /// <summary> /// Gets or sets the <see cref="SerializationBinder"/> used by the serializer when resolving type names. /// </summary> [Obsolete("Binder is obsolete. Use SerializationBinder instead.")] public virtual SerializationBinder Binder { get { if (_serializationBinder == null) { return null; } SerializationBinderAdapter adapter = _serializationBinder as SerializationBinderAdapter; if (adapter != null) { return adapter.SerializationBinder; } throw new InvalidOperationException("Cannot get SerializationBinder because an ISerializationBinder was previously set."); } set { if (value == null) { throw new ArgumentNullException(nameof(value), "Serialization binder cannot be null."); } _serializationBinder = new SerializationBinderAdapter(value); } } /// <summary> /// Gets or sets the <see cref="ISerializationBinder"/> used by the serializer when resolving type names. /// </summary> public virtual ISerializationBinder SerializationBinder { get { return _serializationBinder; } set { if (value == null) { throw new ArgumentNullException(nameof(value), "Serialization binder cannot be null."); } _serializationBinder = value; } } /// <summary> /// Gets or sets the <see cref="ITraceWriter"/> used by the serializer when writing trace messages. /// </summary> /// <value>The trace writer.</value> public virtual ITraceWriter TraceWriter { get { return _traceWriter; } set { _traceWriter = value; } } /// <summary> /// Gets or sets the equality comparer used by the serializer when comparing references. /// </summary> /// <value>The equality comparer.</value> public virtual IEqualityComparer EqualityComparer { get { return _equalityComparer; } set { _equalityComparer = value; } } /// <summary> /// Gets or sets how type name writing and reading is handled by the serializer. /// </summary> /// <remarks> /// <see cref="TypeNameHandling"/> should be used with caution when your application deserializes JSON from an external source. /// Incoming types should be validated with a custom <see cref="T:System.Runtime.Serialization.SerializationBinder"/> /// when deserializing with a value other than <c>TypeNameHandling.None</c>. /// </remarks> public virtual TypeNameHandling TypeNameHandling { get { return _typeNameHandling; } set { if (value < TypeNameHandling.None || value > TypeNameHandling.Auto) { throw new ArgumentOutOfRangeException(nameof(value)); } _typeNameHandling = value; } } /// <summary> /// Gets or sets how a type name assembly is written and resolved by the serializer. /// </summary> /// <value>The type name assembly format.</value> [Obsolete("TypeNameAssemblyFormat is obsolete. Use TypeNameAssemblyFormatHandling instead.")] public virtual FormatterAssemblyStyle TypeNameAssemblyFormat { get { return (FormatterAssemblyStyle)_typeNameAssemblyFormatHandling; } set { if (value < FormatterAssemblyStyle.Simple || value > FormatterAssemblyStyle.Full) { throw new ArgumentOutOfRangeException(nameof(value)); } _typeNameAssemblyFormatHandling = (TypeNameAssemblyFormatHandling)value; } } /// <summary> /// Gets or sets how a type name assembly is written and resolved by the serializer. /// </summary> /// <value>The type name assembly format.</value> public virtual TypeNameAssemblyFormatHandling TypeNameAssemblyFormatHandling { get { return _typeNameAssemblyFormatHandling; } set { if (value < TypeNameAssemblyFormatHandling.Simple || value > TypeNameAssemblyFormatHandling.Full) { throw new ArgumentOutOfRangeException(nameof(value)); } _typeNameAssemblyFormatHandling = value; } } /// <summary> /// Gets or sets how object references are preserved by the serializer. /// </summary> public virtual PreserveReferencesHandling PreserveReferencesHandling { get { return _preserveReferencesHandling; } set { if (value < PreserveReferencesHandling.None || value > PreserveReferencesHandling.All) { throw new ArgumentOutOfRangeException(nameof(value)); } _preserveReferencesHandling = value; } } /// <summary> /// Gets or sets how reference loops (e.g. a class referencing itself) is handled. /// </summary> public virtual ReferenceLoopHandling ReferenceLoopHandling { get { return _referenceLoopHandling; } set { if (value < ReferenceLoopHandling.Error || value > ReferenceLoopHandling.Serialize) { throw new ArgumentOutOfRangeException(nameof(value)); } _referenceLoopHandling = value; } } /// <summary> /// Gets or sets how missing members (e.g. JSON contains a property that isn't a member on the object) are handled during deserialization. /// </summary> public virtual MissingMemberHandling MissingMemberHandling { get { return _missingMemberHandling; } set { if (value < MissingMemberHandling.Ignore || value > MissingMemberHandling.Error) { throw new ArgumentOutOfRangeException(nameof(value)); } _missingMemberHandling = value; } } /// <summary> /// Gets or sets how null values are handled during serialization and deserialization. /// </summary> public virtual NullValueHandling NullValueHandling { get { return _nullValueHandling; } set { if (value < NullValueHandling.Include || value > NullValueHandling.Ignore) { throw new ArgumentOutOfRangeException(nameof(value)); } _nullValueHandling = value; } } /// <summary> /// Gets or sets how default values are handled during serialization and deserialization. /// </summary> public virtual DefaultValueHandling DefaultValueHandling { get { return _defaultValueHandling; } set { if (value < DefaultValueHandling.Include || value > DefaultValueHandling.IgnoreAndPopulate) { throw new ArgumentOutOfRangeException(nameof(value)); } _defaultValueHandling = value; } } /// <summary> /// Gets or sets how objects are created during deserialization. /// </summary> /// <value>The object creation handling.</value> public virtual ObjectCreationHandling ObjectCreationHandling { get { return _objectCreationHandling; } set { if (value < ObjectCreationHandling.Auto || value > ObjectCreationHandling.Replace) { throw new ArgumentOutOfRangeException(nameof(value)); } _objectCreationHandling = value; } } /// <summary> /// Gets or sets how constructors are used during deserialization. /// </summary> /// <value>The constructor handling.</value> public virtual ConstructorHandling ConstructorHandling { get { return _constructorHandling; } set { if (value < ConstructorHandling.Default || value > ConstructorHandling.AllowNonPublicDefaultConstructor) { throw new ArgumentOutOfRangeException(nameof(value)); } _constructorHandling = value; } } /// <summary> /// Gets or sets how metadata properties are used during deserialization. /// </summary> /// <value>The metadata properties handling.</value> public virtual MetadataPropertyHandling MetadataPropertyHandling { get { return _metadataPropertyHandling; } set { if (value < MetadataPropertyHandling.Default || value > MetadataPropertyHandling.Ignore) { throw new ArgumentOutOfRangeException(nameof(value)); } _metadataPropertyHandling = value; } } /// <summary> /// Gets a collection <see cref="JsonConverter"/> that will be used during serialization. /// </summary> /// <value>Collection <see cref="JsonConverter"/> that will be used during serialization.</value> public virtual JsonConverterCollection Converters { get { if (_converters == null) { _converters = new JsonConverterCollection(); } return _converters; } } /// <summary> /// Gets or sets the contract resolver used by the serializer when /// serializing .NET objects to JSON and vice versa. /// </summary> public virtual IContractResolver ContractResolver { get { return _contractResolver; } set { _contractResolver = value ?? DefaultContractResolver.Instance; } } /// <summary> /// Gets or sets the <see cref="StreamingContext"/> used by the serializer when invoking serialization callback methods. /// </summary> /// <value>The context.</value> public virtual StreamingContext Context { get { return _context; } set { _context = value; } } /// <summary> /// Indicates how JSON text output is formatted. /// </summary> public virtual Formatting Formatting { get { return _formatting ?? JsonSerializerSettings.DefaultFormatting; } set { _formatting = value; } } /// <summary> /// Gets or sets how dates are written to JSON text. /// </summary> public virtual DateFormatHandling DateFormatHandling { get { return _dateFormatHandling ?? JsonSerializerSettings.DefaultDateFormatHandling; } set { _dateFormatHandling = value; } } /// <summary> /// Gets or sets how <see cref="DateTime"/> time zones are handled during serialization and deserialization. /// </summary> public virtual DateTimeZoneHandling DateTimeZoneHandling { get { return _dateTimeZoneHandling ?? JsonSerializerSettings.DefaultDateTimeZoneHandling; } set { _dateTimeZoneHandling = value; } } /// <summary> /// Gets or sets how date formatted strings, e.g. "\/Date(1198908717056)\/" and "2012-03-21T05:40Z", are parsed when reading JSON. /// </summary> public virtual DateParseHandling DateParseHandling { get { return _dateParseHandling ?? JsonSerializerSettings.DefaultDateParseHandling; } set { _dateParseHandling = value; } } /// <summary> /// Gets or sets how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text. /// </summary> public virtual FloatParseHandling FloatParseHandling { get { return _floatParseHandling ?? JsonSerializerSettings.DefaultFloatParseHandling; } set { _floatParseHandling = value; } } /// <summary> /// Gets or sets how special floating point numbers, e.g. <see cref="F:System.Double.NaN"/>, /// <see cref="F:System.Double.PositiveInfinity"/> and <see cref="F:System.Double.NegativeInfinity"/>, /// are written as JSON text. /// </summary> public virtual FloatFormatHandling FloatFormatHandling { get { return _floatFormatHandling ?? JsonSerializerSettings.DefaultFloatFormatHandling; } set { _floatFormatHandling = value; } } /// <summary> /// Gets or sets how strings are escaped when writing JSON text. /// </summary> public virtual StringEscapeHandling StringEscapeHandling { get { return _stringEscapeHandling ?? JsonSerializerSettings.DefaultStringEscapeHandling; } set { _stringEscapeHandling = value; } } /// <summary> /// Gets or sets how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatted when writing JSON text, /// and the expected date format when reading JSON text. /// </summary> public virtual string DateFormatString { get { return _dateFormatString ?? JsonSerializerSettings.DefaultDateFormatString; } set { _dateFormatString = value; _dateFormatStringSet = true; } } /// <summary> /// Gets or sets the culture used when reading JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public virtual CultureInfo Culture { get { return _culture ?? JsonSerializerSettings.DefaultCulture; } set { _culture = value; } } /// <summary> /// Gets or sets the maximum depth allowed when reading JSON. Reading past this depth will throw a <see cref="JsonReaderException"/>. /// </summary> public virtual int? MaxDepth { get { return _maxDepth; } set { if (value <= 0) { throw new ArgumentException("Value must be positive.", nameof(value)); } _maxDepth = value; _maxDepthSet = true; } } /// <summary> /// Gets a value indicating whether there will be a check for additional JSON content after deserializing an object. /// </summary> /// <value> /// <c>true</c> if there will be a check for additional JSON content after deserializing an object; otherwise, <c>false</c>. /// </value> public virtual bool CheckAdditionalContent { get { return _checkAdditionalContent ?? JsonSerializerSettings.DefaultCheckAdditionalContent; } set { _checkAdditionalContent = value; } } internal bool IsCheckAdditionalContentSet() { return (_checkAdditionalContent != null); } /// <summary> /// Initializes a new instance of the <see cref="JsonSerializer"/> class. /// </summary> public JsonSerializer() { _referenceLoopHandling = JsonSerializerSettings.DefaultReferenceLoopHandling; _missingMemberHandling = JsonSerializerSettings.DefaultMissingMemberHandling; _nullValueHandling = JsonSerializerSettings.DefaultNullValueHandling; _defaultValueHandling = JsonSerializerSettings.DefaultDefaultValueHandling; _objectCreationHandling = JsonSerializerSettings.DefaultObjectCreationHandling; _preserveReferencesHandling = JsonSerializerSettings.DefaultPreserveReferencesHandling; _constructorHandling = JsonSerializerSettings.DefaultConstructorHandling; _typeNameHandling = JsonSerializerSettings.DefaultTypeNameHandling; _metadataPropertyHandling = JsonSerializerSettings.DefaultMetadataPropertyHandling; _context = JsonSerializerSettings.DefaultContext; _serializationBinder = DefaultSerializationBinder.Instance; _guidHandling = JsonSerializerSettings.DefaultGuidHandling; _culture = JsonSerializerSettings.DefaultCulture; _contractResolver = DefaultContractResolver.Instance; } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will not use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </summary> /// <returns> /// A new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will not use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </returns> public static JsonSerializer Create() { return new JsonSerializer(); } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will not use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </summary> /// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param> /// <returns> /// A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will not use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </returns> public static JsonSerializer Create(JsonSerializerSettings settings) { JsonSerializer serializer = Create(); if (settings != null) { ApplySerializerSettings(serializer, settings); } return serializer; } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </summary> /// <returns> /// A new <see cref="JsonSerializer"/> instance. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/>. /// </returns> public static JsonSerializer CreateDefault() { // copy static to local variable to avoid concurrency issues Func<JsonSerializerSettings> defaultSettingsCreator = JsonConvert.DefaultSettings; JsonSerializerSettings defaultSettings = (defaultSettingsCreator != null) ? defaultSettingsCreator() : null; return Create(defaultSettings); } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/> as well as the specified <see cref="JsonSerializerSettings"/>. /// </summary> /// <param name="settings">The settings to be applied to the <see cref="JsonSerializer"/>.</param> /// <returns> /// A new <see cref="JsonSerializer"/> instance using the specified <see cref="JsonSerializerSettings"/>. /// The <see cref="JsonSerializer"/> will use default settings /// from <see cref="JsonConvert.DefaultSettings"/> as well as the specified <see cref="JsonSerializerSettings"/>. /// </returns> public static JsonSerializer CreateDefault(JsonSerializerSettings settings) { JsonSerializer serializer = CreateDefault(); if (settings != null) { ApplySerializerSettings(serializer, settings); } return serializer; } private static void ApplySerializerSettings(JsonSerializer serializer, JsonSerializerSettings settings) { if (!CollectionUtils.IsNullOrEmpty(settings.Converters)) { // insert settings converters at the beginning so they take precedence // if user wants to remove one of the default converters they will have to do it manually for (int i = 0; i < settings.Converters.Count; i++) { serializer.Converters.Insert(i, settings.Converters[i]); } } // serializer specific if (settings._typeNameHandling != null) { serializer.TypeNameHandling = settings.TypeNameHandling; } if (settings._metadataPropertyHandling != null) { serializer.MetadataPropertyHandling = settings.MetadataPropertyHandling; } if (settings._typeNameAssemblyFormatHandling != null) { serializer.TypeNameAssemblyFormatHandling = settings.TypeNameAssemblyFormatHandling; } if (settings._preserveReferencesHandling != null) { serializer.PreserveReferencesHandling = settings.PreserveReferencesHandling; } if (settings._referenceLoopHandling != null) { serializer.ReferenceLoopHandling = settings.ReferenceLoopHandling; } if (settings._missingMemberHandling != null) { serializer.MissingMemberHandling = settings.MissingMemberHandling; } if (settings._objectCreationHandling != null) { serializer.ObjectCreationHandling = settings.ObjectCreationHandling; } if (settings._nullValueHandling != null) { serializer.NullValueHandling = settings.NullValueHandling; } if (settings._defaultValueHandling != null) { serializer.DefaultValueHandling = settings.DefaultValueHandling; } if (settings._constructorHandling != null) { serializer.ConstructorHandling = settings.ConstructorHandling; } if (settings._context != null) { serializer.Context = settings.Context; } if (settings._checkAdditionalContent != null) { serializer._checkAdditionalContent = settings._checkAdditionalContent; } if (settings.Error != null) { serializer.Error += settings.Error; } if (settings.ContractResolver != null) { serializer.ContractResolver = settings.ContractResolver; } if (settings.ReferenceResolverProvider != null) { serializer.ReferenceResolver = settings.ReferenceResolverProvider(); } if (settings.TraceWriter != null) { serializer.TraceWriter = settings.TraceWriter; } if (settings.EqualityComparer != null) { serializer.EqualityComparer = settings.EqualityComparer; } if (settings.SerializationBinder != null) { serializer.SerializationBinder = settings.SerializationBinder; } // reader/writer specific // unset values won't override reader/writer set values if (settings._formatting != null) { serializer._formatting = settings._formatting; } if (settings._dateFormatHandling != null) { serializer._dateFormatHandling = settings._dateFormatHandling; } if (settings._dateTimeZoneHandling != null) { serializer._dateTimeZoneHandling = settings._dateTimeZoneHandling; } if (settings._dateParseHandling != null) { serializer._dateParseHandling = settings._dateParseHandling; } if (settings._dateFormatStringSet) { serializer._dateFormatString = settings._dateFormatString; serializer._dateFormatStringSet = settings._dateFormatStringSet; } if (settings._floatFormatHandling != null) { serializer._floatFormatHandling = settings._floatFormatHandling; } if (settings._floatParseHandling != null) { serializer._floatParseHandling = settings._floatParseHandling; } if (settings._stringEscapeHandling != null) { serializer._stringEscapeHandling = settings._stringEscapeHandling; } if (settings._culture != null) { serializer._culture = settings._culture; } if (settings._maxDepthSet) { serializer._maxDepth = settings._maxDepth; serializer._maxDepthSet = settings._maxDepthSet; } if (settings._guidHandling != null) { serializer._guidHandling = settings._guidHandling; } } /// <summary> /// Populates the JSON values onto the target object. /// </summary> /// <param name="reader">The <see cref="TextReader"/> that contains the JSON structure to reader values from.</param> /// <param name="target">The target object to populate values onto.</param> public void Populate(TextReader reader, object target) { Populate(new JsonTextReader(reader), target); } /// <summary> /// Populates the JSON values onto the target object. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to reader values from.</param> /// <param name="target">The target object to populate values onto.</param> public void Populate(JsonReader reader, object target) { PopulateInternal(reader, target); } internal virtual void PopulateInternal(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); ValidationUtils.ArgumentNotNull(target, nameof(target)); // set serialization options onto reader CultureInfo previousCulture; DateTimeZoneHandling? previousDateTimeZoneHandling; DateParseHandling? previousDateParseHandling; FloatParseHandling? previousFloatParseHandling; GuidHandling? previousGuidHandling; int? previousMaxDepth; string previousDateFormatString; SetupReader(reader, out previousCulture, out previousDateTimeZoneHandling, out previousDateParseHandling, out previousFloatParseHandling, out previousMaxDepth, out previousDateFormatString, out previousGuidHandling); TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonReader(reader) : null; JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); serializerReader.Populate(traceJsonReader ?? reader, target); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); } /// <summary> /// Deserializes the JSON structure contained by the specified <see cref="JsonReader"/>. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> that contains the JSON structure to deserialize.</param> /// <returns>The <see cref="Object"/> being deserialized.</returns> public object Deserialize(JsonReader reader) { return Deserialize(reader, null); } /// <summary> /// Deserializes the JSON structure contained by the specified <see cref="StringReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="TextReader"/> containing the object.</param> /// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param> /// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns> public object Deserialize(TextReader reader, Type objectType) { return Deserialize(new JsonTextReader(reader), objectType); } /// <summary> /// Deserializes the JSON structure contained by the specified <see cref="JsonReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> containing the object.</param> /// <typeparam name="T">The type of the object to deserialize.</typeparam> /// <returns>The instance of <typeparamref name="T"/> being deserialized.</returns> public T Deserialize<T>(JsonReader reader) { return (T)Deserialize(reader, typeof(T)); } /// <summary> /// Deserializes the JSON structure contained by the specified <see cref="JsonReader"/> /// into an instance of the specified type. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> containing the object.</param> /// <param name="objectType">The <see cref="Type"/> of object being deserialized.</param> /// <returns>The instance of <paramref name="objectType"/> being deserialized.</returns> public object Deserialize(JsonReader reader, Type objectType) { return DeserializeInternal(reader, objectType); } internal virtual object DeserializeInternal(JsonReader reader, Type objectType) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); // set serialization options onto reader CultureInfo previousCulture; DateTimeZoneHandling? previousDateTimeZoneHandling; DateParseHandling? previousDateParseHandling; FloatParseHandling? previousFloatParseHandling; GuidHandling? previousGuidHandling; int? previousMaxDepth; string previousDateFormatString; SetupReader(reader, out previousCulture, out previousDateTimeZoneHandling, out previousDateParseHandling, out previousFloatParseHandling, out previousMaxDepth, out previousDateFormatString, out previousGuidHandling); TraceJsonReader traceJsonReader = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonReader(reader) : null; JsonSerializerInternalReader serializerReader = new JsonSerializerInternalReader(this); object value = serializerReader.Deserialize(traceJsonReader ?? reader, objectType, CheckAdditionalContent); if (traceJsonReader != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonReader.GetDeserializedJsonMessage(), null); } ResetReader(reader, previousCulture, previousDateTimeZoneHandling, previousDateParseHandling, previousFloatParseHandling, previousMaxDepth, previousDateFormatString); return value; } private void SetupReader(JsonReader reader, out CultureInfo previousCulture, out DateTimeZoneHandling? previousDateTimeZoneHandling, out DateParseHandling? previousDateParseHandling, out FloatParseHandling? previousFloatParseHandling, out int? previousMaxDepth, out string previousDateFormatString, out GuidHandling? previousGuidHandling) { if (_culture != null && !_culture.Equals(reader.Culture)) { previousCulture = reader.Culture; reader.Culture = _culture; } else { previousCulture = null; } if (_dateTimeZoneHandling != null && reader.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = reader.DateTimeZoneHandling; reader.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } else { previousDateTimeZoneHandling = null; } if (_dateParseHandling != null && reader.DateParseHandling != _dateParseHandling) { previousDateParseHandling = reader.DateParseHandling; reader.DateParseHandling = _dateParseHandling.GetValueOrDefault(); } else { previousDateParseHandling = null; } if (_floatParseHandling != null && reader.FloatParseHandling != _floatParseHandling) { previousFloatParseHandling = reader.FloatParseHandling; reader.FloatParseHandling = _floatParseHandling.GetValueOrDefault(); } else { previousFloatParseHandling = null; } if (_maxDepthSet && reader.MaxDepth != _maxDepth) { previousMaxDepth = reader.MaxDepth; reader.MaxDepth = _maxDepth; } else { previousMaxDepth = null; } if (_dateFormatStringSet && reader.DateFormatString != _dateFormatString) { previousDateFormatString = reader.DateFormatString; reader.DateFormatString = _dateFormatString; } else { previousDateFormatString = null; } if (_guidHandling != null && reader.GuidHandling != _guidHandling) { previousGuidHandling = reader.GuidHandling; reader.GuidHandling = _guidHandling.Value; } else { previousGuidHandling = null; } JsonTextReader textReader = reader as JsonTextReader; if (textReader != null) { DefaultContractResolver resolver = _contractResolver as DefaultContractResolver; if (resolver != null) { textReader.NameTable = resolver.GetState().NameTable; } } } private void ResetReader(JsonReader reader, CultureInfo previousCulture, DateTimeZoneHandling? previousDateTimeZoneHandling, DateParseHandling? previousDateParseHandling, FloatParseHandling? previousFloatParseHandling, int? previousMaxDepth, string previousDateFormatString) { // reset reader back to previous options if (previousCulture != null) { reader.Culture = previousCulture; } if (previousDateTimeZoneHandling != null) { reader.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousDateParseHandling != null) { reader.DateParseHandling = previousDateParseHandling.GetValueOrDefault(); } if (previousFloatParseHandling != null) { reader.FloatParseHandling = previousFloatParseHandling.GetValueOrDefault(); } if (_maxDepthSet) { reader.MaxDepth = previousMaxDepth; } if (_dateFormatStringSet) { reader.DateFormatString = previousDateFormatString; } JsonTextReader textReader = reader as JsonTextReader; if (textReader != null) { textReader.NameTable = null; } } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the JSON structure /// to a <c>Stream</c> using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter">The <see cref="TextWriter"/> used to write the JSON structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> public void Serialize(TextWriter textWriter, object value) { Serialize(new JsonTextWriter(textWriter), value); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the JSON structure /// to a <c>Stream</c> using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the JSON structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> /// <param name="objectType"> /// The type of the value being serialized. /// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match. /// Specifing the type is optional. /// </param> public void Serialize(JsonWriter jsonWriter, object value, Type objectType) { SerializeInternal(jsonWriter, value, objectType); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the JSON structure /// to a <c>Stream</c> using the specified <see cref="TextWriter"/>. /// </summary> /// <param name="textWriter">The <see cref="TextWriter"/> used to write the JSON structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> /// <param name="objectType"> /// The type of the value being serialized. /// This parameter is used when <see cref="TypeNameHandling"/> is Auto to write out the type name if the type of the value does not match. /// Specifing the type is optional. /// </param> public void Serialize(TextWriter textWriter, object value, Type objectType) { Serialize(new JsonTextWriter(textWriter), value, objectType); } /// <summary> /// Serializes the specified <see cref="Object"/> and writes the JSON structure /// to a <c>Stream</c> using the specified <see cref="JsonWriter"/>. /// </summary> /// <param name="jsonWriter">The <see cref="JsonWriter"/> used to write the JSON structure.</param> /// <param name="value">The <see cref="Object"/> to serialize.</param> public void Serialize(JsonWriter jsonWriter, object value) { SerializeInternal(jsonWriter, value, null); } internal virtual void SerializeInternal(JsonWriter jsonWriter, object value, Type objectType) { ValidationUtils.ArgumentNotNull(jsonWriter, nameof(jsonWriter)); // set serialization options onto writer Formatting? previousFormatting = null; if (_formatting != null && jsonWriter.Formatting != _formatting) { previousFormatting = jsonWriter.Formatting; jsonWriter.Formatting = _formatting.GetValueOrDefault(); } DateFormatHandling? previousDateFormatHandling = null; if (_dateFormatHandling != null && jsonWriter.DateFormatHandling != _dateFormatHandling) { previousDateFormatHandling = jsonWriter.DateFormatHandling; jsonWriter.DateFormatHandling = _dateFormatHandling.GetValueOrDefault(); } DateTimeZoneHandling? previousDateTimeZoneHandling = null; if (_dateTimeZoneHandling != null && jsonWriter.DateTimeZoneHandling != _dateTimeZoneHandling) { previousDateTimeZoneHandling = jsonWriter.DateTimeZoneHandling; jsonWriter.DateTimeZoneHandling = _dateTimeZoneHandling.GetValueOrDefault(); } FloatFormatHandling? previousFloatFormatHandling = null; if (_floatFormatHandling != null && jsonWriter.FloatFormatHandling != _floatFormatHandling) { previousFloatFormatHandling = jsonWriter.FloatFormatHandling; jsonWriter.FloatFormatHandling = _floatFormatHandling.GetValueOrDefault(); } StringEscapeHandling? previousStringEscapeHandling = null; if (_stringEscapeHandling != null && jsonWriter.StringEscapeHandling != _stringEscapeHandling) { previousStringEscapeHandling = jsonWriter.StringEscapeHandling; jsonWriter.StringEscapeHandling = _stringEscapeHandling.GetValueOrDefault(); } CultureInfo previousCulture = null; if (_culture != null && !_culture.Equals(jsonWriter.Culture)) { previousCulture = jsonWriter.Culture; jsonWriter.Culture = _culture; } string previousDateFormatString = null; if (_dateFormatStringSet && jsonWriter.DateFormatString != _dateFormatString) { previousDateFormatString = jsonWriter.DateFormatString; jsonWriter.DateFormatString = _dateFormatString; } GuidHandling? previousGuidHandling = null; if (_guidHandling != null && jsonWriter.GuidHandling != _guidHandling) { previousGuidHandling = jsonWriter.GuidHandling; jsonWriter.GuidHandling = _guidHandling.Value; } TraceJsonWriter traceJsonWriter = (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Verbose) ? new TraceJsonWriter(jsonWriter) : null; JsonSerializerInternalWriter serializerWriter = new JsonSerializerInternalWriter(this); serializerWriter.Serialize(traceJsonWriter ?? jsonWriter, value, objectType); if (traceJsonWriter != null) { TraceWriter.Trace(TraceLevel.Verbose, traceJsonWriter.GetSerializedJsonMessage(), null); } // reset writer back to previous options if (previousFormatting != null) { jsonWriter.Formatting = previousFormatting.GetValueOrDefault(); } if (previousDateFormatHandling != null) { jsonWriter.DateFormatHandling = previousDateFormatHandling.GetValueOrDefault(); } if (previousDateTimeZoneHandling != null) { jsonWriter.DateTimeZoneHandling = previousDateTimeZoneHandling.GetValueOrDefault(); } if (previousFloatFormatHandling != null) { jsonWriter.FloatFormatHandling = previousFloatFormatHandling.GetValueOrDefault(); } if (previousStringEscapeHandling != null) { jsonWriter.StringEscapeHandling = previousStringEscapeHandling.GetValueOrDefault(); } if (_dateFormatStringSet) { jsonWriter.DateFormatString = previousDateFormatString; } if (previousCulture != null) { jsonWriter.Culture = previousCulture; } if (previousGuidHandling != null) { jsonWriter.GuidHandling = previousGuidHandling.Value; } } internal IReferenceResolver GetReferenceResolver() { if (_referenceResolver == null) { _referenceResolver = new DefaultReferenceResolver(); } return _referenceResolver; } internal JsonConverter GetMatchingConverter(Type type) { return GetMatchingConverter(_converters, type); } internal static JsonConverter GetMatchingConverter(IList<JsonConverter> converters, Type objectType) { #if DEBUG ValidationUtils.ArgumentNotNull(objectType, nameof(objectType)); #endif if (converters != null) { for (int i = 0; i < converters.Count; i++) { JsonConverter converter = converters[i]; if (converter.CanConvert(objectType)) { return converter; } } } return null; } internal void OnError(ErrorEventArgs e) { EventHandler<ErrorEventArgs> error = Error; if (error != null) { error(this, e); } } } }
// // 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.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure.KeyVault.Internal; namespace Microsoft.Azure.KeyVault.Internal { internal partial class KeyVaultInternalClient : ServiceClient<KeyVaultInternalClient>, IKeyVaultInternalClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private KeyVaultCredential _credentials; /// <summary> /// Gets or sets the credential /// </summary> public KeyVaultCredential Credentials { get { return this._credentials; } set { this._credentials = value; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IKeyOperations _keys; /// <summary> /// Cryptographic and management operations for keys in a vault /// </summary> public virtual IKeyOperations Keys { get { return this._keys; } } private ISecretOperations _secrets; /// <summary> /// Operations for secrets in a vault /// </summary> public virtual ISecretOperations Secrets { get { return this._secrets; } } /// <summary> /// Initializes a new instance of the KeyVaultInternalClient class. /// </summary> public KeyVaultInternalClient() : base() { this._keys = new KeyOperations(this); this._secrets = new SecretOperations(this); this._apiVersion = "2015-02-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the KeyVaultInternalClient class. /// </summary> /// <param name='credentials'> /// Required. Gets or sets the credential /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public KeyVaultInternalClient(KeyVaultCredential credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the KeyVaultInternalClient class. /// </summary> /// <param name='credentials'> /// Required. Gets or sets the credential /// </param> public KeyVaultInternalClient(KeyVaultCredential credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = null; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the KeyVaultInternalClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public KeyVaultInternalClient(HttpClient httpClient) : base(httpClient) { this._keys = new KeyOperations(this); this._secrets = new SecretOperations(this); this._apiVersion = "2015-02-01-preview"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the KeyVaultInternalClient class. /// </summary> /// <param name='credentials'> /// Required. Gets or sets the credential /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public KeyVaultInternalClient(KeyVaultCredential credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the KeyVaultInternalClient class. /// </summary> /// <param name='credentials'> /// Required. Gets or sets the credential /// </param> /// <param name='httpClient'> /// The Http client /// </param> public KeyVaultInternalClient(KeyVaultCredential credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = null; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// KeyVaultInternalClient instance /// </summary> /// <param name='client'> /// Instance of KeyVaultInternalClient to clone to /// </param> protected override void Clone(ServiceClient<KeyVaultInternalClient> client) { base.Clone(client); if (client is KeyVaultInternalClient) { KeyVaultInternalClient clonedClient = ((KeyVaultInternalClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Security.Cryptography; using Microsoft.Win32.SafeHandles; namespace Internal.Cryptography.Pal { internal static class PkcsFormatReader { internal static bool TryReadPkcs7Der(byte[] rawData, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs7Der(rawData, true, out certPal, out ignored); } internal static bool TryReadPkcs7Der(SafeBioHandle bio, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs7Der(bio, true, out certPal, out ignored); } internal static bool TryReadPkcs7Der(byte[] rawData, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs7Der(rawData, false, out ignored, out certPals); } internal static bool TryReadPkcs7Der(SafeBioHandle bio, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs7Der(bio, false, out ignored, out certPals); } private static unsafe bool TryReadPkcs7Der( byte[] rawData, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { SafePkcs7Handle pkcs7 = Interop.libcrypto.OpenSslD2I( (ptr, b, i) => Interop.libcrypto.d2i_PKCS7(ptr, b, i), rawData, checkHandle: false); if (pkcs7.IsInvalid) { certPal = null; certPals = null; return false; } using (pkcs7) { return TryReadPkcs7(pkcs7, single, out certPal, out certPals); } } private static bool TryReadPkcs7Der( SafeBioHandle bio, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { SafePkcs7Handle pkcs7 = Interop.libcrypto.d2i_PKCS7_bio(bio, IntPtr.Zero); if (pkcs7.IsInvalid) { certPal = null; certPals = null; return false; } using (pkcs7) { return TryReadPkcs7(pkcs7, single, out certPal, out certPals); } } internal static bool TryReadPkcs7Pem(byte[] rawData, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs7Pem(rawData, true, out certPal, out ignored); } internal static bool TryReadPkcs7Pem(SafeBioHandle bio, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs7Pem(bio, true, out certPal, out ignored); } internal static bool TryReadPkcs7Pem(byte[] rawData, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs7Pem(rawData, false, out ignored, out certPals); } internal static bool TryReadPkcs7Pem(SafeBioHandle bio, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs7Pem(bio, false, out ignored, out certPals); } private static bool TryReadPkcs7Pem( byte[] rawData, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { using (SafeBioHandle bio = Interop.libcrypto.BIO_new(Interop.libcrypto.BIO_s_mem())) { Interop.Crypto.CheckValidOpenSslHandle(bio); Interop.libcrypto.BIO_write(bio, rawData, rawData.Length); SafePkcs7Handle pkcs7 = Interop.libcrypto.PEM_read_bio_PKCS7(bio, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); if (pkcs7.IsInvalid) { certPal = null; certPals = null; return false; } using (pkcs7) { return TryReadPkcs7(pkcs7, single, out certPal, out certPals); } } } private static bool TryReadPkcs7Pem( SafeBioHandle bio, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { SafePkcs7Handle pkcs7 = Interop.libcrypto.PEM_read_bio_PKCS7(bio, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); if (pkcs7.IsInvalid) { certPal = null; certPals = null; return false; } using (pkcs7) { return TryReadPkcs7(pkcs7, single, out certPal, out certPals); } } private static bool TryReadPkcs7( SafePkcs7Handle pkcs7, bool single, out ICertificatePal certPal, out List<ICertificatePal> certPals) { List<ICertificatePal> readPals = single ? null : new List<ICertificatePal>(); using (SafeSharedX509StackHandle certs = Interop.Crypto.GetPkcs7Certificates(pkcs7)) { int count = Interop.Crypto.GetX509StackFieldCount(certs); if (single) { // In single mode for a PKCS#7 signed or signed-and-enveloped file we're supposed to return // the certificate which signed the PKCS#7 file. // // X509Certificate2Collection::Export(X509ContentType.Pkcs7) claims to be a signed PKCS#7, // but doesn't emit a signature block. So this is hard to test. // // TODO(2910): Figure out how to extract the signing certificate, when it's present. throw new CryptographicException(SR.Cryptography_X509_PKCS7_NoSigner); } for (int i = 0; i < count; i++) { // Use FromHandle to duplicate the handle since it would otherwise be freed when the PKCS7 // is Disposed. IntPtr certHandle = Interop.Crypto.GetX509StackField(certs, i); ICertificatePal pal = CertificatePal.FromHandle(certHandle); readPals.Add(pal); } } certPal = null; certPals = readPals; return true; } internal static bool TryReadPkcs12(byte[] rawData, string password, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs12(rawData, password, true, out certPal, out ignored); } internal static bool TryReadPkcs12(SafeBioHandle bio, string password, out ICertificatePal certPal) { List<ICertificatePal> ignored; return TryReadPkcs12(bio, password, true, out certPal, out ignored); } internal static bool TryReadPkcs12(byte[] rawData, string password, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs12(rawData, password, false, out ignored, out certPals); } internal static bool TryReadPkcs12(SafeBioHandle bio, string password, out List<ICertificatePal> certPals) { ICertificatePal ignored; return TryReadPkcs12(bio, password, false, out ignored, out certPals); } private static bool TryReadPkcs12( byte[] rawData, string password, bool single, out ICertificatePal readPal, out List<ICertificatePal> readCerts) { // DER-PKCS12 OpenSslPkcs12Reader pfx; if (!OpenSslPkcs12Reader.TryRead(rawData, out pfx)) { readPal = null; readCerts = null; return false; } using (pfx) { return TryReadPkcs12(pfx, password, single, out readPal, out readCerts); } } private static bool TryReadPkcs12( SafeBioHandle bio, string password, bool single, out ICertificatePal readPal, out List<ICertificatePal> readCerts) { // DER-PKCS12 OpenSslPkcs12Reader pfx; if (!OpenSslPkcs12Reader.TryRead(bio, out pfx)) { readPal = null; readCerts = null; return false; } using (pfx) { return TryReadPkcs12(pfx, password, single, out readPal, out readCerts); } } private static bool TryReadPkcs12( OpenSslPkcs12Reader pfx, string password, bool single, out ICertificatePal readPal, out List<ICertificatePal> readCerts) { pfx.Decrypt(password); ICertificatePal first = null; List<ICertificatePal> certs = null; if (!single) { certs = new List<ICertificatePal>(); } foreach (OpenSslX509CertificateReader certPal in pfx.ReadCertificates()) { if (single) { // When requesting an X509Certificate2 from a PFX only the first entry is // returned. Other entries should be disposed. if (first == null) { first = certPal; } else { certPal.Dispose(); } } else { certs.Add(certPal); } } readPal = first; readCerts = certs; return true; } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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. // ----------------------------------------------------------------------------- // The following code is a port of XNA StockEffects http://xbox.create.msdn.com/en-US/education/catalog/sample/stock_effects // ----------------------------------------------------------------------------- // Microsoft Public License (Ms-PL) // // This license governs use of the accompanying software. If you use the // software, you accept this license. If you do not accept the license, do not // use the software. // // 1. Definitions // The terms "reproduce," "reproduction," "derivative works," and // "distribution" have the same meaning here as under U.S. copyright law. // A "contribution" is the original software, or any additions or changes to // the software. // A "contributor" is any person that distributes its contribution under this // license. // "Licensed patents" are a contributor's patent claims that read directly on // its contribution. // // 2. Grant of Rights // (A) Copyright Grant- Subject to the terms of this license, including the // license conditions and limitations in section 3, each contributor grants // you a non-exclusive, worldwide, royalty-free copyright license to reproduce // its contribution, prepare derivative works of its contribution, and // distribute its contribution or any derivative works that you create. // (B) Patent Grant- Subject to the terms of this license, including the license // conditions and limitations in section 3, each contributor grants you a // non-exclusive, worldwide, royalty-free license under its licensed patents to // make, have made, use, sell, offer for sale, import, and/or otherwise dispose // of its contribution in the software or derivative works of the contribution // in the software. // // 3. Conditions and Limitations // (A) No Trademark License- This license does not grant you rights to use any // contributors' name, logo, or trademarks. // (B) If you bring a patent claim against any contributor over patents that // you claim are infringed by the software, your patent license from such // contributor to the software ends automatically. // (C) If you distribute any portion of the software, you must retain all // copyright, patent, trademark, and attribution notices that are present in the // software. // (D) If you distribute any portion of the software in source code form, you // may do so only under this license by including a complete copy of this // license with your distribution. If you distribute any portion of the software // in compiled or object code form, you may only do so under a license that // complies with this license. // (E) The software is licensed "as-is." You bear the risk of using it. The // contributors give no express warranties, guarantees or conditions. You may // have additional consumer rights under your local laws which this license // cannot change. To the extent permitted under your local laws, the // contributors exclude the implied warranties of merchantability, fitness for a // particular purpose and non-infringement. //----------------------------------------------------------------------------- // DualTextureEffect.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- namespace SharpDX.Toolkit.Graphics { /// <summary> /// Built-in effect that supports two-layer multitexturing. /// </summary> public partial class DualTextureEffect : Effect, IEffectMatrices, IEffectFog { #region Effect Parameters EffectParameter textureParam; EffectParameter texture2Param; EffectParameter diffuseColorParam; EffectParameter fogColorParam; EffectParameter fogVectorParam; EffectParameter worldViewProjParam; EffectPass shaderPass; #endregion #region Fields bool fogEnabled; bool vertexColorEnabled; Matrix world = Matrix.Identity; Matrix view = Matrix.Identity; Matrix projection = Matrix.Identity; Matrix worldView; Vector3 diffuseColor = Vector3.One; float alpha = 1; float fogStart = 0; float fogEnd = 1; EffectDirtyFlags dirtyFlags = EffectDirtyFlags.All; #endregion #region Public Properties /// <summary> /// Gets or sets the world matrix. /// </summary> public Matrix World { get { return world; } set { world = value; dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the view matrix. /// </summary> public Matrix View { get { return view; } set { view = value; dirtyFlags |= EffectDirtyFlags.WorldViewProj | EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the projection matrix. /// </summary> public Matrix Projection { get { return projection; } set { projection = value; dirtyFlags |= EffectDirtyFlags.WorldViewProj; } } /// <summary> /// Gets or sets the material diffuse color (range 0 to 1). /// </summary> public Vector3 DiffuseColor { get { return diffuseColor; } set { diffuseColor = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the material alpha. /// </summary> public float Alpha { get { return alpha; } set { alpha = value; dirtyFlags |= EffectDirtyFlags.MaterialColor; } } /// <summary> /// Gets or sets the fog enable flag. /// </summary> public bool FogEnabled { get { return fogEnabled; } set { if (fogEnabled != value) { fogEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex | EffectDirtyFlags.FogEnable; } } } /// <summary> /// Gets or sets the fog start distance. /// </summary> public float FogStart { get { return fogStart; } set { fogStart = value; dirtyFlags |= EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the fog end distance. /// </summary> public float FogEnd { get { return fogEnd; } set { fogEnd = value; dirtyFlags |= EffectDirtyFlags.Fog; } } /// <summary> /// Gets or sets the fog color. /// </summary> public Vector3 FogColor { get { return fogColorParam.GetValue<Vector3>(); } set { fogColorParam.SetValue(value); } } /// <summary> /// Gets or sets the current base texture. /// </summary> public Texture2D Texture { get { return textureParam.GetResource<Texture2D>(); } set { textureParam.SetResource(value); } } /// <summary> /// Gets or sets the current overlay texture. /// </summary> public Texture2D Texture2 { get { return texture2Param.GetResource<Texture2D>(); } set { texture2Param.SetResource(value); } } /// <summary> /// Gets or sets whether vertex color is enabled. /// </summary> public bool VertexColorEnabled { get { return vertexColorEnabled; } set { if (vertexColorEnabled != value) { vertexColorEnabled = value; dirtyFlags |= EffectDirtyFlags.ShaderIndex; } } } #endregion #region Methods /// <summary> /// Creates a new DualTextureEffect with default parameter settings. /// </summary> public DualTextureEffect(GraphicsDevice device) : this(device, device.DefaultEffectPool) { } /// <summary> /// Creates a new DualTextureEffect with default parameter settings from a specified <see cref="EffectPool"/>. /// </summary> public DualTextureEffect(GraphicsDevice device, EffectPool pool) : base(device, effectBytecode, pool) { } protected override void Initialize() { textureParam = Parameters["Texture"]; texture2Param = Parameters["Texture2"]; diffuseColorParam = Parameters["DiffuseColor"]; fogColorParam = Parameters["FogColor"]; fogVectorParam = Parameters["FogVector"]; worldViewProjParam = Parameters["WorldViewProj"]; } ///// <summary> ///// Creates a new DualTextureEffect by cloning parameter settings from an existing instance. ///// </summary> //protected DualTextureEffect(DualTextureEffect cloneSource) // : base(cloneSource) //{ // CacheEffectParameters(); // fogEnabled = cloneSource.fogEnabled; // vertexColorEnabled = cloneSource.vertexColorEnabled; // world = cloneSource.world; // view = cloneSource.view; // projection = cloneSource.projection; // diffuseColor = cloneSource.diffuseColor; // alpha = cloneSource.alpha; // fogStart = cloneSource.fogStart; // fogEnd = cloneSource.fogEnd; //} ///// <summary> ///// Creates a clone of the current DualTextureEffect instance. ///// </summary> //public override Effect Clone() //{ // return new DualTextureEffect(this); //} /// <summary> /// Lazily computes derived parameter values immediately before applying the effect. /// </summary> protected internal override EffectPass OnApply(EffectPass pass) { // Recompute the world+view+projection matrix or fog vector? dirtyFlags = EffectHelpers.SetWorldViewProjAndFog(dirtyFlags, ref world, ref view, ref projection, ref worldView, fogEnabled, fogStart, fogEnd, worldViewProjParam, fogVectorParam); // Recompute the diffuse/alpha material color parameter? if ((dirtyFlags & EffectDirtyFlags.MaterialColor) != 0) { diffuseColorParam.SetValue(new Vector4(diffuseColor * alpha, alpha)); dirtyFlags &= ~EffectDirtyFlags.MaterialColor; } // Recompute the shader index? if ((dirtyFlags & EffectDirtyFlags.ShaderIndex) != 0) { int shaderIndex = 0; if (!fogEnabled) shaderIndex += 1; if (vertexColorEnabled) shaderIndex += 2; shaderPass = pass.SubPasses[shaderIndex]; dirtyFlags &= ~EffectDirtyFlags.ShaderIndex; } return base.OnApply(shaderPass); } #endregion } }
// Author: abi // Project: DungeonQuest // Path: C:\code\Xna\DungeonQuest\Graphics // Creation date: 28.03.2007 01:01 // Last modified: 31.07.2007 04:40 #region Using directives using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections; using System.Text; using DungeonQuest.Game; #endregion namespace DungeonQuest.Graphics { /// <summary> /// TangentVertex, extracted from Abi.Graphic engine for NormalMapCompressor. /// More information can be found at: /// http://exdream.dyn.ee/blog/PermaLink.aspx?guid=cd2c85b3-13e6-48cd-953e-f7e3bb79fbc5 /// <para/> /// Tangent vertex format for shader vertex format used all over the place. /// DirectX9 or XNA does not provide this crazy format ^^ It contains: /// Position, Normal vector, texture coords, tangent vector. /// </summary> public struct TangentVertex { #region Variables /// <summary> /// Position /// </summary> public Vector3 pos; /// <summary> /// Texture coordinates /// </summary> public Vector2 uv; /// <summary> /// Normal /// </summary> public Vector3 normal; /// <summary> /// Tangent /// </summary> public Vector3 tangent; /// <summary> /// Stride size, in XNA called SizeInBytes. I'm just conforming with that. /// Btw: How is this supposed to work without using unsafe AND /// without using System.Runtime.InteropServices.Marshal.SizeOf? /// </summary> public static int SizeInBytes { get { // 4 bytes per float: // 3 floats pos, 2 floats uv, 3 floats normal and 3 float tangent. return 4 * (3 + 2 + 3 + 3); } // get } // StrideSize /// <summary> /// U texture coordinate /// </summary> /// <returns>Float</returns> public float U { get { return uv.X; } // get } // U /// <summary> /// V texture coordinate /// </summary> /// <returns>Float</returns> public float V { get { return uv.Y; } // get } // V #endregion #region Constructor /// <summary> /// Create tangent vertex /// </summary> /// <param name="setPos">Set position</param> /// <param name="setU">Set u texture coordinate</param> /// <param name="setV">Set v texture coordinate</param> /// <param name="setNormal">Set normal</param> /// <param name="setTangent">Set tangent</param> public TangentVertex( Vector3 setPos, float setU, float setV, Vector3 setNormal, Vector3 setTangent) { pos = setPos; uv = new Vector2(setU, setV); normal = setNormal; tangent = setTangent; } // TangentVertex(setPos, setU, setV) /// <summary> /// Create tangent vertex /// </summary> /// <param name="setPos">Set position</param> /// <param name="setUv">Set uv texture coordinates</param> /// <param name="setNormal">Set normal</param> /// <param name="setTangent">Set tangent</param> public TangentVertex( Vector3 setPos, Vector2 setUv, Vector3 setNormal, Vector3 setTangent) { pos = setPos; uv = setUv; normal = setNormal; tangent = setTangent; } // TangentVertex(setPos, setUv, setNormal) #endregion #region To string /// <summary> /// To string /// </summary> public override string ToString() { return "TangentVertex(pos=" + pos + ", " + "u=" + uv.X + ", " + "v=" + uv.Y + ", " + "normal=" + normal + ", " + "tangent=" + tangent + ")"; } // ToString() #endregion #region Generate vertex declaration /// <summary> /// Vertex elements for Mesh.Clone /// </summary> public static readonly VertexElement[] VertexElements = GenerateVertexElements(); /// <summary> /// Vertex declaration for vertex buffers. /// </summary> public static VertexDeclaration VertexDeclaration = new VertexDeclaration(BaseGame.Device, VertexElements); /// <summary> /// Generate vertex declaration /// </summary> private static VertexElement[] GenerateVertexElements() { VertexElement[] decl = new VertexElement[] { // Construct new vertex declaration with tangent info // First the normal stuff (we should already have that) new VertexElement(0, 0, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Position, 0), new VertexElement(0, 12, VertexElementFormat.Vector2, VertexElementMethod.Default, VertexElementUsage.TextureCoordinate, 0), new VertexElement(0, 20, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Normal, 0), // And now the tangent new VertexElement(0, 32, VertexElementFormat.Vector3, VertexElementMethod.Default, VertexElementUsage.Tangent, 0), }; return decl; } // GenerateVertexElements() #endregion #region Is declaration tangent vertex declaration /// <summary> /// Returns true if declaration is tangent vertex declaration. /// </summary> public static bool IsTangentVertexDeclaration( VertexElement[] declaration) { return declaration.Length == 4 && declaration[0].VertexElementUsage == VertexElementUsage.Position && declaration[1].VertexElementUsage == VertexElementUsage.TextureCoordinate && declaration[2].VertexElementUsage == VertexElementUsage.Normal && declaration[3].VertexElementUsage == VertexElementUsage.Tangent; } // IsTangentVertexDeclaration(declaration) #endregion #region Nearly equal /// <summary> /// Returns true if two vertices are nearly equal. For example the /// tangent or normal data does not have to match 100%. /// Used to optimize vertex buffers and to generate indices. /// </summary> /// <param name="a">A</param> /// <param name="b">B</param> /// <returns>Bool</returns> public static bool NearlyEquals(TangentVertex a, TangentVertex b) { // Position has to match, else it is just different vertex return a.pos == b.pos && // Ignore blend indices and blend weights, they are the same // anyway, because they are calculated from the bone distances. Math.Abs(a.uv.X - b.uv.X) < 0.0001f && Math.Abs(a.uv.Y - b.uv.Y) < 0.0001f && // Normals and tangents do not have to be very close, we can't see // any difference between small variations here, but by optimizing // similar vertices we can improve the overall rendering performance. (a.normal - b.normal).Length() < 0.1f && (a.tangent - b.tangent).Length() < 0.1f; } // NearlyEqual(a, b) #endregion } // struct TangentVertex } // namespace DungeonQuest.Graphics
/* * @(#)DOMElementImpl.java 1.11 2000/08/16 * */ using System; using DOMException = Comzept.Genesis.Tidy.Dom.DOMException; namespace Comzept.Genesis.Tidy.Xml.Dom { /// <summary> /// DOMElementImpl /// /// (c) 1998-2000 (W3C) MIT, INRIA, Keio University /// See Tidy.java for the copyright notice. /// Derived from <a href="http://www.w3.org/People/Raggett/tidy"> /// HTML Tidy Release 4 Aug 2000</a> /// /// </summary> /// <author> Dave Raggett dsr@w3.org /// </author> /// <author> Andy Quick ac.quick@sympatico.ca (translation to Java) /// </author> /// <version> 1.4, 1999/09/04 DOM Support /// </version> /// <version> 1.5, 1999/10/23 Tidy Release 27 Sep 1999 /// </version> /// <version> 1.6, 1999/11/01 Tidy Release 22 Oct 1999 /// </version> /// <version> 1.7, 1999/12/06 Tidy Release 30 Nov 1999 /// </version> /// <version> 1.8, 2000/01/22 Tidy Release 13 Jan 2000 /// </version> /// <version> 1.9, 2000/06/03 Tidy Release 30 Apr 2000 /// </version> /// <version> 1.10, 2000/07/22 Tidy Release 8 Jul 2000 /// </version> /// <version> 1.11, 2000/08/16 Tidy Release 4 Aug 2000 /// </version> public class DOMElementImpl:DOMNodeImpl, Comzept.Genesis.Tidy.Dom.Element { /// <seealso cref="Comzept.Genesis.Tidy.Dom.NodeType"> /// </seealso> override public short NodeType { get { return Comzept.Genesis.Tidy.Dom.Node_Fields.ELEMENT_NODE; } } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Element.TagName"> /// </seealso> virtual public System.String TagName { get { return base.NodeName; } } protected internal DOMElementImpl(Node adaptee):base(adaptee) { } /* --------------------- DOM ---------------------------- */ /// <seealso cref="Comzept.Genesis.Tidy.Dom.Element.getAttribute"> /// </seealso> public virtual System.String getAttribute(System.String name) { if (this.adaptee == null) return null; AttVal att = this.adaptee.attributes; while (att != null) { if (att.attribute.Equals(name)) break; att = att.next; } if (att != null) return att.value_Renamed; else return ""; } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Element.setAttribute"> /// </seealso> public virtual void setAttribute(System.String name, System.String value_Renamed) { if (this.adaptee == null) return ; AttVal att = this.adaptee.attributes; while (att != null) { if (att.attribute.Equals(name)) break; att = att.next; } if (att != null) { att.value_Renamed = value_Renamed; } else { att = new AttVal(null, null, (int) '"', name, value_Renamed); att.dict = AttributeTable.DefaultAttributeTable.findAttribute(att); if (this.adaptee.attributes == null) { this.adaptee.attributes = att; } else { att.next = this.adaptee.attributes; this.adaptee.attributes = att; } } } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Element.removeAttribute"> /// </seealso> public virtual void removeAttribute(System.String name) { if (this.adaptee == null) return ; AttVal att = this.adaptee.attributes; AttVal pre = null; while (att != null) { if (att.attribute.Equals(name)) break; pre = att; att = att.next; } if (att != null) { if (pre == null) { this.adaptee.attributes = att.next; } else { pre.next = att.next; } } } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Element.getAttributeNode"> /// </seealso> public virtual Comzept.Genesis.Tidy.Dom.Attr getAttributeNode(System.String name) { if (this.adaptee == null) return null; AttVal att = this.adaptee.attributes; while (att != null) { if (att.attribute.Equals(name)) break; att = att.next; } if (att != null) return att.Adapter; else return null; } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Element.setAttributeNode"> /// </seealso> public virtual Comzept.Genesis.Tidy.Dom.Attr setAttributeNode(Comzept.Genesis.Tidy.Dom.Attr newAttr) { if (newAttr == null) return null; if (!(newAttr is DOMAttrImpl)) { throw new DOMExceptionImpl(DOMException.WRONG_DOCUMENT_ERR, "newAttr not instanceof DOMAttrImpl"); } DOMAttrImpl newatt = (DOMAttrImpl) newAttr; System.String name = newatt.avAdaptee.attribute; Comzept.Genesis.Tidy.Dom.Attr result = null; AttVal att = this.adaptee.attributes; while (att != null) { if (att.attribute.Equals(name)) break; att = att.next; } if (att != null) { result = att.Adapter; att.adapter = newAttr; } else { if (this.adaptee.attributes == null) { this.adaptee.attributes = newatt.avAdaptee; } else { newatt.avAdaptee.next = this.adaptee.attributes; this.adaptee.attributes = newatt.avAdaptee; } } return result; } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Element.removeAttributeNode"> /// </seealso> public virtual Comzept.Genesis.Tidy.Dom.Attr removeAttributeNode(Comzept.Genesis.Tidy.Dom.Attr oldAttr) { if (oldAttr == null) return null; Comzept.Genesis.Tidy.Dom.Attr result = null; AttVal att = this.adaptee.attributes; AttVal pre = null; while (att != null) { if (att.Adapter == oldAttr) break; pre = att; att = att.next; } if (att != null) { if (pre == null) { this.adaptee.attributes = att.next; } else { pre.next = att.next; } result = oldAttr; } else { throw new DOMExceptionImpl(DOMException.NOT_FOUND_ERR, "oldAttr not found"); } return result; } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Element.getElementsByTagName"> /// </seealso> public virtual Comzept.Genesis.Tidy.Dom.NodeList getElementsByTagName(System.String name) { return new DOMNodeListByTagNameImpl(this.adaptee, name); } /// <seealso cref="Comzept.Genesis.Tidy.Dom.Element.normalize"> /// </seealso> public override void normalize() { // NOT SUPPORTED } /// <summary> DOM2 - not implemented.</summary> public virtual System.String getAttributeNS(System.String namespaceURI, System.String localName) { return null; } /// <summary> DOM2 - not implemented.</summary> /// <exception cref="Comzept.Genesis.Tidy.Dom.DOMException"> /// </exception> public virtual void setAttributeNS(System.String namespaceURI, System.String qualifiedName, System.String value_Renamed) { } /// <summary> DOM2 - not implemented.</summary> /// <exception cref="Comzept.Genesis.Tidy.Dom.DOMException"> /// </exception> public virtual void removeAttributeNS(System.String namespaceURI, System.String localName) { } /// <summary> DOM2 - not implemented.</summary> public virtual Comzept.Genesis.Tidy.Dom.Attr getAttributeNodeNS(System.String namespaceURI, System.String localName) { return null; } /// <summary> DOM2 - not implemented.</summary> /// <exception cref="Comzept.Genesis.Tidy.Dom.DOMException"> /// </exception> public virtual Comzept.Genesis.Tidy.Dom.Attr setAttributeNodeNS(Comzept.Genesis.Tidy.Dom.Attr newAttr) { return null; } /// <summary> DOM2 - not implemented.</summary> public virtual Comzept.Genesis.Tidy.Dom.NodeList getElementsByTagNameNS(System.String namespaceURI, System.String localName) { return null; } /// <summary> DOM2 - not implemented.</summary> public virtual bool hasAttribute(System.String name) { return false; } /// <summary> DOM2 - not implemented.</summary> public virtual bool hasAttributeNS(System.String namespaceURI, System.String localName) { return false; } } }