context stringlengths 2.52k 185k | gt stringclasses 1
value |
|---|---|
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Amazon.DynamoDBv2;
using Amazon.DynamoDBv2.Model;
using Amazon.DynamoDBv2.DocumentModel;
using System.IO;
using ThirdParty.Json.LitJson;
using System.Xml;
using NUnit.Framework;
using CommonTests.Framework;
using System.Threading.Tasks;
namespace CommonTests.IntegrationTests.DynamoDB
{
public partial class DynamoDBTests : TestBase<AmazonDynamoDBClient>
{
[Test]
[Category("DynamoDB")]
public void TestTableOperations()
{
RunAsSync(async () =>
{
foreach (var conversion in new DynamoDBEntryConversion[] { DynamoDBEntryConversion.V1, DynamoDBEntryConversion.V2 })
{
// Clear tables
CleanupTables();
Table hashTable;
Table hashRangeTable;
// Load tables using provided conversion schema
LoadTables(conversion, out hashTable, out hashRangeTable);
// Test saving and loading empty lists and maps
await TestEmptyCollections(hashTable);
// Test operations on hash-key table
await TestHashTable(hashTable, conversion);
// Test operations on hash-and-range-key table
await TestHashRangeTable(hashRangeTable, conversion);
// Test large batch writes and gets
await TestLargeBatchOperations(hashTable);
// Test expressions for update
await TestExpressionUpdate(hashTable);
// Test expressions for put
await TestExpressionPut(hashTable);
// Test expressions for delete
await TestExpressionsOnDelete(hashTable);
// Test expressions for query
await TestExpressionsOnQuery(hashRangeTable);
// Test expressions for scan
await TestExpressionsOnScan(hashRangeTable);
}
});
}
private async Task TestEmptyCollections(Table hashTable)
{
Document doc = new Document();
doc["Id"] = 1;
doc["EmptyList"] = new DynamoDBList();
doc["EmptyMap"] = new Document();
await hashTable.PutItemAsync(doc);
Document retrieved = await hashTable.GetItemAsync(doc);
DynamoDBEntry mapEntry;
Assert.IsTrue(retrieved.TryGetValue("EmptyMap", out mapEntry));
Assert.IsNotNull(mapEntry);
Assert.IsNotNull(mapEntry.AsDocument());
Assert.AreEqual(0, mapEntry.AsDocument().Count);
DynamoDBEntry listEntry;
Assert.IsTrue(retrieved.TryGetValue("EmptyList", out listEntry));
Assert.IsNotNull(listEntry);
Assert.IsNotNull(listEntry.AsDynamoDBList());
Assert.AreEqual(0, listEntry.AsDynamoDBList().Entries.Count);
}
private async Task TestHashTable(Table hashTable, DynamoDBEntryConversion conversion)
{
// Put an item
Document doc = new Document();
doc["Id"] = 1;
doc["Product"] = "CloudSpotter";
doc["Company"] = "CloudsAreGrate";
doc["IsPublic"] = true;
doc["Price"] = 1200;
doc["Tags"] = new HashSet<string> { "Prod", "1.0" };
doc["Aliases"] = new List<string> { "CS", "Magic" };
doc["Developers"] = new List<Document>
{
new Document(new Dictionary<string,DynamoDBEntry>
{
{ "Name", "Alan" },
{ "Age", 29 }
}),
new Document(new Dictionary<string,DynamoDBEntry>
{
{ "Name", "Franco" },
{ "Age", 32 }
})
};
doc["Garbage"] = "asdf";
Assert.AreEqual("asdf", doc["Garbage"].AsString());
await hashTable.PutItemAsync(doc);
// Get the item by hash key
Document retrieved = await hashTable.GetItemAsync(1);
Assert.IsFalse(AreValuesEqual(doc, retrieved));
var convertedDoc = doc.ForceConversion(conversion);
Assert.IsTrue(AreValuesEqual(convertedDoc, retrieved));
// Get the item by document
retrieved = await hashTable.GetItemAsync(doc);
// Verify retrieved document
Assert.IsTrue(AreValuesEqual(convertedDoc, retrieved, conversion));
var tagsRetrieved = retrieved["Tags"];
Assert.IsTrue(tagsRetrieved is PrimitiveList);
Assert.AreEqual(2, tagsRetrieved.AsPrimitiveList().Entries.Count);
// Test bool storage for different conversions
var isPublicRetrieved = retrieved["IsPublic"];
if (conversion == DynamoDBEntryConversion.V1)
Assert.AreEqual("1", isPublicRetrieved.AsPrimitive().Value as string);
else
Assert.IsTrue(isPublicRetrieved is DynamoDBBool);
// Test HashSet<string> storage for different conversions
var aliasesRetrieved = retrieved["Aliases"];
if (conversion == DynamoDBEntryConversion.V1)
Assert.AreEqual(2, aliasesRetrieved.AsPrimitiveList().Entries.Count);
else
Assert.AreEqual(2, aliasesRetrieved.AsDynamoDBList().Entries.Count);
List<Document> developers = retrieved["Developers"].AsListOfDocument();
Assert.AreEqual(2, developers.Count);
AssertExtensions.ExpectException<InvalidCastException>(() => aliasesRetrieved.AsListOfDocument());
// Update the item
doc["Tags"] = new List<string> { "Prod", "1.0", "2.0" };
doc["Developers"] = new DynamoDBList(new List<DynamoDBEntry>
{
new Document(new Dictionary<string,DynamoDBEntry>
{
{ "Name", "Alan" },
{ "Age", 29 }
})
});
// Delete the Garbage attribute
doc["Garbage"] = null;
Assert.IsNull(doc["Garbage"].AsString());
await hashTable.UpdateItemAsync(doc);
retrieved = await hashTable.GetItemAsync(1);
Assert.IsFalse(AreValuesEqual(doc, retrieved, conversion));
doc.Remove("Garbage");
Assert.IsTrue(AreValuesEqual(doc, retrieved, conversion));
developers = retrieved["Developers"].AsListOfDocument();
Assert.AreEqual(1, developers.Count);
// Create new, circularly-referencing item
Document doc2 = doc.ForceConversion(conversion);
doc2["Id"] = doc2["Id"].AsInt() + 1;
doc2["Price"] = 94;
doc2["Tags"] = null;
doc2["IsPublic"] = false;
doc2["Parent"] = doc2;
await AssertExtensions.ExpectExceptionAsync(hashTable.UpdateItemAsync(doc2));
// Remove circular reference and save new item
doc2.Remove("Parent");
await hashTable.UpdateItemAsync(doc2);
// Scan the hash-key table
var items = await hashTable.Scan(new ScanFilter()).GetRemainingAsync();
Assert.AreEqual(2, items.Count);
// Scan by pages
var search = hashTable.Scan(new ScanOperationConfig { Limit = 1 });
items.Clear();
while (!search.IsDone)
{
var set = await search.GetNextSetAsync();
items.AddRange(set);
}
Assert.AreEqual(2, items.Count);
// Query against GlobalIndex
var queryFilter = new QueryFilter("Company", QueryOperator.Equal, "CloudsAreGrate");
queryFilter.AddCondition("Price", QueryOperator.GreaterThan, 100);
search = hashTable.Query(new QueryOperationConfig
{
IndexName = "GlobalIndex",
Filter = queryFilter
});
items = await search.GetRemainingAsync();
Assert.AreEqual(1, items.Count);
// Scan for specific tag
var scanFilter = new ScanFilter();
scanFilter.AddCondition("Tags", ScanOperator.Contains, "2.0");
search = hashTable.Scan(scanFilter);
items = await search.GetRemainingAsync();
Assert.AreEqual(1, items.Count);
// Delete the item by hash key
await hashTable.DeleteItemAsync(1);
Assert.IsNull(await hashTable.GetItemAsync(1));
// Delete the item by document
await hashTable.DeleteItemAsync(doc2);
Assert.IsNull(await hashTable.GetItemAsync(doc2));
// Scan the hash-key table to confirm it is empty
items = await hashTable.Scan(new ScanFilter()).GetRemainingAsync();
Assert.AreEqual(0, items.Count);
// Batch-put items
var batchWrite = hashTable.CreateBatchWrite();
batchWrite.AddDocumentToPut(doc);
batchWrite.AddDocumentToPut(doc2);
await batchWrite.ExecuteAsync();
// Batch-get items
var batchGet = hashTable.CreateBatchGet();
batchGet.AddKey(1);
batchGet.AddKey(doc2);
await batchGet.ExecuteAsync();
Assert.AreEqual(2, batchGet.Results.Count);
// Batch-delete items
batchWrite = hashTable.CreateBatchWrite();
batchWrite.AddItemToDelete(doc);
batchWrite.AddKeyToDelete(2);
await batchWrite.ExecuteAsync();
// Batch-get non-existent items
batchGet = hashTable.CreateBatchGet();
batchGet.AddKey(1);
batchGet.AddKey(doc2);
await batchGet.ExecuteAsync();
Assert.AreEqual(0, batchGet.Results.Count);
// Scan the hash-key table to confirm it is empty
items = await hashTable.Scan(new ScanFilter()).GetRemainingAsync();
Assert.AreEqual(0, items.Count);
}
private async Task TestHashRangeTable(Table hashRangeTable, DynamoDBEntryConversion conversion)
{
// Put an item
Document doc1 = new Document();
doc1["Name"] = "Alan";
doc1["Age"] = 31;
doc1["Company"] = "Big River";
doc1["Score"] = 120;
doc1["IsTester"] = true;
doc1["Manager"] = "Barbara";
doc1["Aliases"] = new HashSet<string> { "Al", "Steve" };
doc1["PastManagers"] = new List<string> { "Carl", "Karl" };
await hashRangeTable.PutItemAsync(doc1);
// Update a non-existent item creates the item
Document doc2 = new Document();
doc2["Name"] = "Chuck";
doc2["Age"] = 30;
doc2["Company"] = "Big River";
doc2["Score"] = 94;
doc1["IsTester"] = false;
doc2["Manager"] = "Barbara";
doc2["Aliases"] = new HashSet<string> { "Charles" };
await hashRangeTable.UpdateItemAsync(doc2);
// Save more items
Document doc3 = new Document();
doc3["Name"] = "Diane";
doc3["Age"] = 40;
doc3["Company"] = "Madeira";
doc1["IsTester"] = true;
doc3["Score"] = 140;
doc3["Manager"] = "Eva";
await hashRangeTable.UpdateItemAsync(doc3);
var oldDoc3 = doc3.Clone() as Document;
// Changing the range key will force a creation of a new item
doc3["Age"] = 24;
doc3["Score"] = 101;
await hashRangeTable.UpdateItemAsync(doc3);
// Get item
var retrieved = await hashRangeTable.GetItemAsync("Alan", 31);
// Verify retrieved document
Assert.IsTrue(AreValuesEqual(doc1, retrieved, conversion));
var tagsRetrieved = retrieved["Aliases"];
Assert.IsTrue(tagsRetrieved is PrimitiveList);
Assert.AreEqual(2, tagsRetrieved.AsPrimitiveList().Entries.Count);
// Test bool storage for different conversions
var isTesterRetrieved = retrieved["IsTester"];
if (conversion == DynamoDBEntryConversion.V1)
Assert.AreEqual("1", isTesterRetrieved.AsPrimitive().Value as string);
else
Assert.IsTrue(isTesterRetrieved is DynamoDBBool);
// Test HashSet<string> storage for different conversions
var pastManagersRetrieved = retrieved["PastManagers"];
if (conversion == DynamoDBEntryConversion.V1)
Assert.AreEqual(2, pastManagersRetrieved.AsPrimitiveList().Entries.Count);
else
Assert.AreEqual(2, pastManagersRetrieved.AsDynamoDBList().Entries.Count);
// Get item using GetItem overloads that expect a key in different ways
retrieved = await hashRangeTable.GetItemAsync(doc2);
Assert.IsTrue(AreValuesEqual(doc2, retrieved, conversion));
retrieved = await hashRangeTable.GetItemAsync(oldDoc3, new GetItemOperationConfig { ConsistentRead = true });
Assert.IsTrue(AreValuesEqual(oldDoc3, retrieved, conversion));
retrieved = await hashRangeTable.GetItemAsync("Diane", 24, new GetItemOperationConfig { ConsistentRead = true });
Assert.IsTrue(AreValuesEqual(doc3, retrieved, conversion));
// Scan the hash-and-range-key table
var items = await hashRangeTable.Scan(new ScanFilter()).GetRemainingAsync();
Assert.AreEqual(4, items.Count);
// Scan by pages
var search = hashRangeTable.Scan(new ScanOperationConfig { Limit = 1 });
items.Clear();
while(!search.IsDone)
{
var set = await search.GetNextSetAsync();
items.AddRange(set);
}
Assert.AreEqual(4, items.Count);
// Scan in parallel
var segment1 = await hashRangeTable.Scan(new ScanOperationConfig { Segment = 0, TotalSegments = 2 }).GetRemainingAsync();
var segment2 = await hashRangeTable.Scan(new ScanOperationConfig { Segment = 1, TotalSegments = 2 }).GetRemainingAsync();
Assert.AreEqual(4, segment1.Count + segment2.Count);
// Query items
items = await hashRangeTable.Query("Diane", new QueryFilter()).GetRemainingAsync();
Assert.AreEqual(2, items.Count);
var queryConfig = new QueryOperationConfig
{
KeyExpression = new Expression
{
ExpressionAttributeNames = new Dictionary<string, string>
{
{ "#N", "Name" }
},
ExpressionAttributeValues = new Dictionary<string, DynamoDBEntry>
{
{ ":v", "Diane" }
},
ExpressionStatement = "#N = :v"
}
};
items = await hashRangeTable.Query(queryConfig).GetRemainingAsync();
Assert.AreEqual(2, items.Count);
queryConfig = new QueryOperationConfig
{
KeyExpression = new Expression
{
ExpressionAttributeNames = new Dictionary<string, string>
{
{ "#N", "Name" }
},
ExpressionAttributeValues = new Dictionary<string, DynamoDBEntry>
{
{ ":v", "Diane" }
},
ExpressionStatement = "#N = :v"
},
FilterExpression = new Expression
{
ExpressionAttributeNames = new Dictionary<string, string>
{
{ "#S", "Score" }
},
ExpressionAttributeValues = new Dictionary<string, DynamoDBEntry>
{
{ ":v2", 120 }
},
ExpressionStatement = "#S > :v2"
}
};
items = await hashRangeTable.Query(queryConfig).GetRemainingAsync();
Assert.AreEqual(1, items.Count);
queryConfig = new QueryOperationConfig
{
KeyExpression = new Expression
{
ExpressionAttributeNames = new Dictionary<string, string>
{
{ "#N", "Name" },
{ "#A", "Age" }
},
ExpressionAttributeValues = new Dictionary<string, DynamoDBEntry>
{
{ ":v2", 120 }
},
ExpressionStatement = "#N = :v and #A < :v2"
},
FilterExpression = new Expression
{
ExpressionAttributeNames = new Dictionary<string, string>
{
{ "#S", "Score" },
{ "#A", "Age" }
},
ExpressionAttributeValues = new Dictionary<string, DynamoDBEntry>
{
{ ":v", "Diane" },
},
ExpressionStatement = "#S < :v2"
}
};
items = await hashRangeTable.Query(queryConfig).GetRemainingAsync();
Assert.AreEqual(1, items.Count);
// Query local index
items = await hashRangeTable.Query(new QueryOperationConfig
{
IndexName = "LocalIndex",
Filter = new QueryFilter("Name", QueryOperator.Equal, "Diane")
}).GetRemainingAsync();
Assert.AreEqual(2, items.Count);
// Query global index
var queryFilter = new QueryFilter("Company", QueryOperator.Equal, "Big River");
queryFilter.AddCondition("Score", QueryOperator.GreaterThan, 100);
items = await hashRangeTable.Query(new QueryOperationConfig
{
IndexName = "GlobalIndex",
Filter = queryFilter
}).GetRemainingAsync();
Assert.AreEqual(1, items.Count);
// Scan local index
var scanFilter = new ScanFilter();
scanFilter.AddCondition("Name", ScanOperator.Equal, "Diane");
items = await hashRangeTable.Scan(new ScanOperationConfig
{
IndexName = "LocalIndex",
Filter = scanFilter
}).GetRemainingAsync();
Assert.AreEqual(2, items.Count);
// Scan global index
scanFilter = new ScanFilter();
scanFilter.AddCondition("Company", ScanOperator.Equal, "Big River");
scanFilter.AddCondition("Score", ScanOperator.GreaterThan, 100);
items = await hashRangeTable.Query(new QueryOperationConfig
{
IndexName = "GlobalIndex",
Filter = queryFilter
}).GetRemainingAsync();
Assert.AreEqual(1, items.Count);
}
private async Task TestLargeBatchOperations(Table hashTable)
{
int itemCount = 30;
int itemSize = 40 * 1024;
string textData = new string('@', itemSize);
MemoryStream data = new MemoryStream(Encoding.UTF8.GetBytes(textData));
// Write all items
var batchWrite = hashTable.CreateBatchWrite();
for(int i=0;i<itemCount;i++)
{
var doc = new Document();
doc["Id"] = i;
doc["Data"] = data;
batchWrite.AddDocumentToPut(doc);
}
await batchWrite.ExecuteAsync();
UtilityMethods.Sleep(TimeSpan.FromSeconds(1)); // Wait for the eventual consistence of the batch add to catch up.
// Scan table, but retrieve only keys
var ids = await hashTable.Scan(new ScanOperationConfig
{
AttributesToGet = new List<string> { "Id" },
Select = SelectValues.SpecificAttributes
}).GetRemainingAsync();
Assert.AreEqual(itemCount, ids.Count);
// Batch-get all items
var batchGet = hashTable.CreateBatchGet();
foreach (var id in ids)
batchGet.AddKey(id);
await batchGet.ExecuteAsync();
Assert.AreEqual(itemCount, batchGet.Results.Count);
// Batch-delete all items
batchWrite = hashTable.CreateBatchWrite();
foreach (var id in ids)
batchWrite.AddKeyToDelete(id);
await batchWrite.ExecuteAsync();
UtilityMethods.Sleep(TimeSpan.FromSeconds(1)); // Wait for the eventual consistence of the batch add to catch up.
// Scan table to confirm it is empty
var items = await hashTable.Scan(new ScanFilter()).GetRemainingAsync();
Assert.AreEqual(0, items.Count);
}
private async Task TestExpressionsOnDelete(Table hashTable)
{
Document doc1 = new Document();
doc1["Id"] = 13;
doc1["Price"] = 6;
await hashTable.PutItemAsync(doc1);
Expression expression = new Expression();
expression.ExpressionStatement = "Price > :price";
expression.ExpressionAttributeValues[":price"] = 7;
DeleteItemOperationConfig config = new DeleteItemOperationConfig();
config.ConditionalExpression = expression;
//Assert.IsFalse(hashTable.TryDeleteItem(doc1, config));
await AssertExtensions.ExpectExceptionAsync(hashTable.DeleteItemAsync(doc1, config));
expression.ExpressionAttributeValues[":price"] = 4;
//Assert.IsTrue(hashTable.TryDeleteItem(doc1, config));
await hashTable.DeleteItemAsync(doc1, config);
}
private async Task TestExpressionsOnQuery(Table hashRangeTable)
{
Document doc1 = new Document();
doc1["Name"] = "Gunnar";
doc1["Age"] = 77;
doc1["Job"] = "Retired";
await hashRangeTable.PutItemAsync(doc1);
Document doc2 = new Document();
doc2["Name"] = "Gunnar";
doc2["Age"] = 45;
doc2["Job"] = "Electrician";
await hashRangeTable.PutItemAsync(doc2);
Expression expression = new Expression();
expression.ExpressionStatement = "Job = :job";
expression.ExpressionAttributeValues[":job"] = "Retired";
var search = hashRangeTable.Query("Gunnar", expression);
var docs = await search.GetRemainingAsync();
Assert.AreEqual(1, docs.Count);
Assert.AreEqual(77, docs[0]["Age"].AsInt());
search = hashRangeTable.Query(new QueryOperationConfig
{
Filter = new QueryFilter("Name", QueryOperator.Equal, "Gunnar"),
FilterExpression = expression,
AttributesToGet = new List<string> { "Age" },
Select = SelectValues.SpecificAttributes
});
docs = await search.GetRemainingAsync();
Assert.AreEqual(1, docs.Count);
Assert.AreEqual(1, docs[0].Count);
Assert.AreEqual(77, docs[0]["Age"].AsInt());
await hashRangeTable.DeleteItemAsync(doc1);
await hashRangeTable.DeleteItemAsync(doc2);
}
private async Task TestExpressionsOnScan(Table hashRangeTable)
{
await ClearTable(hashRangeTableName);
Document doc1 = new Document();
doc1["Name"] = "Lewis";
doc1["Age"] = 6;
doc1["School"] = "Elementary";
await hashRangeTable.PutItemAsync(doc1);
Document doc2 = new Document();
doc2["Name"] = "Frida";
doc2["Age"] = 3;
doc2["School"] = "Preschool";
await hashRangeTable.PutItemAsync(doc2);
Expression expression = new Expression();
expression.ExpressionStatement = "Age > :age";
expression.ExpressionAttributeValues[":age"] = 5;
var search = hashRangeTable.Scan(expression);
var docs = await search.GetRemainingAsync();
Assert.AreEqual(1, docs.Count);
Assert.AreEqual("Elementary", docs[0]["School"].AsString());
search = hashRangeTable.Scan(new ScanOperationConfig
{
FilterExpression = expression,
Select = SelectValues.SpecificAttributes,
AttributesToGet = new List<string> { "School" }
});
docs = await search.GetRemainingAsync();
Assert.AreEqual(1, docs.Count);
Assert.AreEqual(1, docs[0].Count);
Assert.AreEqual("Elementary", docs[0]["School"].AsString());
await hashRangeTable.DeleteItemAsync(doc1);
await hashRangeTable.DeleteItemAsync(doc2);
}
private async Task TestExpressionPut(Table hashTable)
{
Document doc = new Document();
doc["Id"] = DateTime.Now.Ticks;
doc["name"] = "condition-form";
await hashTable.PutItemAsync(doc);
Expression expression = new Expression
{
ExpressionStatement = "attribute_not_exists(referencecounter) or referencecounter = :cond1",
ExpressionAttributeValues = new Dictionary<string, DynamoDBEntry>
{
{":cond1", 0}
}
};
PutItemOperationConfig config = new PutItemOperationConfig
{
ConditionalExpression = expression
};
doc["update-test"] = 1;
//Assert.IsTrue(hashTable.TryPutItem(doc, config));
await hashTable.PutItemAsync(doc, config);
doc["referencecounter"] = 0;
await hashTable.UpdateItemAsync(doc);
doc["update-test"] = null;
//Assert.IsTrue(hashTable.TryPutItem(doc, config));
await hashTable.PutItemAsync(doc, config);
// Make sure removing attributes works
doc = await hashTable.GetItemAsync(doc);
Assert.IsFalse(doc.Contains("update-test"));
doc["referencecounter"] = 1;
await hashTable.UpdateItemAsync(doc);
doc["update-test"] = 3;
//Assert.IsFalse(hashTable.TryPutItem(doc, config));
await AssertExtensions.ExpectExceptionAsync(hashTable.PutItemAsync(doc, config));
await hashTable.DeleteItemAsync(doc);
}
private async Task TestExpressionUpdate(Table hashTable)
{
Document doc = new Document();
doc["Id"] = DateTime.Now.Ticks;
doc["name"] = "condition-form";
await hashTable.PutItemAsync(doc);
Expression expression = new Expression
{
ExpressionStatement = "attribute_not_exists(referencecounter) or referencecounter = :cond1",
ExpressionAttributeValues = new Dictionary<string, DynamoDBEntry>
{
{":cond1", 0}
}
};
UpdateItemOperationConfig config = new UpdateItemOperationConfig
{
ConditionalExpression = expression
};
doc["update-test"] = 1;
//Assert.IsTrue(hashTable.TryUpdateItem(doc, config));
await hashTable.UpdateItemAsync(doc, config);
doc["referencecounter"] = 0;
await hashTable.UpdateItemAsync(doc);
doc["update-test"] = null;
//Assert.IsTrue(hashTable.TryUpdateItem(doc, config));
await hashTable.UpdateItemAsync(doc, config);
// Make sure removing attributes works
doc = await hashTable.GetItemAsync(doc);
Assert.IsFalse(doc.Contains("update-test"));
doc["referencecounter"] = 1;
await hashTable.UpdateItemAsync(doc);
doc["update-test"] = 3;
//Assert.IsFalse(hashTable.TryUpdateItem(doc, config));
await AssertExtensions.ExpectExceptionAsync(hashTable.UpdateItemAsync(doc, config));
doc = await hashTable.GetItemAsync(doc);
Assert.IsFalse(doc.Contains("update-test"));
await hashTable.DeleteItemAsync(doc);
}
private bool AreValuesEqual(Document docA, Document docB, DynamoDBEntryConversion conversion = null)
{
if (conversion != null)
{
docA = docA.ForceConversion(conversion);
docB = docB.ForceConversion(conversion);
}
if (object.ReferenceEquals(docA, docB))
return true;
return docA.Equals(docB);
}
private void LoadTables(DynamoDBEntryConversion conversion, out Table hashTable, out Table hashRangeTable)
{
TableCache.Clear();
using (var counter = CountServiceResponses(Client))
{
// Load table using TryLoadTable API
hashTable = null;
Assert.IsFalse(Table.TryLoadTable(Client, "FakeHashTableThatShouldNotExist", conversion, out hashTable));
Assert.AreEqual(0, counter.ResponseCount);
Assert.IsTrue(Table.TryLoadTable(Client, hashTableName, conversion, out hashTable));
Assert.AreEqual(1, counter.ResponseCount);
Assert.IsNotNull(hashTable);
Assert.AreEqual(hashTableName, hashTable.TableName);
Assert.AreEqual(3, hashTable.Attributes.Count);
Assert.AreEqual(1, hashTable.GlobalSecondaryIndexes.Count);
Assert.AreEqual(1, hashTable.GlobalSecondaryIndexes["GlobalIndex"].ProvisionedThroughput.ReadCapacityUnits);
Assert.AreEqual(1, hashTable.GlobalSecondaryIndexNames.Count);
Assert.AreEqual(1, hashTable.HashKeys.Count);
Assert.AreEqual(0, hashTable.RangeKeys.Count);
Assert.AreEqual(1, hashTable.Keys.Count);
Assert.AreEqual(0, hashTable.LocalSecondaryIndexes.Count);
Assert.AreEqual(0, hashTable.LocalSecondaryIndexNames.Count);
// Load table using LoadTable API (may throw an exception)
AssertExtensions.ExpectException(() => Table.LoadTable(Client, "FakeHashRangeTableThatShouldNotExist", conversion));
Assert.AreEqual(1, counter.ResponseCount);
hashRangeTable = Table.LoadTable(Client, hashRangeTableName, conversion);
Assert.AreEqual(2, counter.ResponseCount);
Assert.IsNotNull(hashRangeTable);
Assert.AreEqual(hashRangeTableName, hashRangeTable.TableName);
Assert.AreEqual(5, hashRangeTable.Attributes.Count);
Assert.AreEqual(1, hashRangeTable.GlobalSecondaryIndexes.Count);
Assert.AreEqual(1, hashRangeTable.GlobalSecondaryIndexes["GlobalIndex"].ProvisionedThroughput.ReadCapacityUnits);
Assert.AreEqual(1, hashRangeTable.GlobalSecondaryIndexNames.Count);
Assert.AreEqual(1, hashRangeTable.HashKeys.Count);
Assert.AreEqual(1, hashRangeTable.RangeKeys.Count);
Assert.AreEqual(2, hashRangeTable.Keys.Count);
Assert.AreEqual(1, hashRangeTable.LocalSecondaryIndexes.Count);
Assert.AreEqual(2, hashRangeTable.LocalSecondaryIndexes["LocalIndex"].KeySchema.Count);
Assert.AreEqual(1, hashRangeTable.LocalSecondaryIndexNames.Count);
}
}
}
}
| |
//
// ResourceWriter.cs
//
// Author:
// Jb Evain (jbevain@gmail.com)
//
// (C) 2006 Jb Evain
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System.Text;
namespace Mono.Cecil.Binary {
using System.Collections;
class ResourceWriter {
Image m_img;
Section m_rsrc;
MemoryBinaryWriter m_writer;
ArrayList m_dataEntries;
ArrayList m_stringEntries;
long m_pos;
public ResourceWriter (Image img, Section rsrc, MemoryBinaryWriter writer)
{
m_img = img;
m_rsrc = rsrc;
m_writer = writer;
m_dataEntries = new ArrayList ();
m_stringEntries = new ArrayList ();
}
public void Write ()
{
if (m_img.ResourceDirectoryRoot == null)
return;
ComputeOffset (m_img.ResourceDirectoryRoot);
WriteResourceDirectoryTable (m_img.ResourceDirectoryRoot);
}
public void Patch ()
{
foreach (ResourceDataEntry rde in m_dataEntries) {
GotoOffset (rde.Offset);
m_writer.Write ((uint) rde.Data + m_rsrc.VirtualAddress);
RestoreOffset ();
}
}
void ComputeOffset (ResourceDirectoryTable root)
{
int offset = 0;
Queue directoryTables = new Queue ();
directoryTables.Enqueue (root);
while (directoryTables.Count > 0) {
ResourceDirectoryTable rdt = directoryTables.Dequeue () as ResourceDirectoryTable;
rdt.Offset = offset;
offset += 16;
foreach (ResourceDirectoryEntry rde in rdt.Entries) {
rde.Offset = offset;
offset += 8;
if (rde.IdentifiedByName)
m_stringEntries.Add (rde.Name);
if (rde.Child is ResourceDirectoryTable)
directoryTables.Enqueue (rde.Child);
else
m_dataEntries.Add (rde.Child);
}
}
foreach (ResourceDataEntry rde in m_dataEntries) {
rde.Offset = offset;
offset += 16;
}
foreach (ResourceDirectoryString rds in m_stringEntries) {
rds.Offset = offset;
byte [] str = Encoding.Unicode.GetBytes (rds.String);
offset += 2 + str.Length;
offset += 3;
offset &= ~3;
}
foreach (ResourceDataEntry rde in m_dataEntries) {
rde.Data = (uint) offset;
offset += rde.ResourceData.Length;
offset += 3;
offset &= ~3;
}
m_writer.Write (new byte [offset]);
}
void WriteResourceDirectoryTable (ResourceDirectoryTable rdt)
{
GotoOffset (rdt.Offset);
m_writer.Write (rdt.Characteristics);
m_writer.Write (rdt.TimeDateStamp);
m_writer.Write (rdt.MajorVersion);
m_writer.Write (rdt.MinorVersion);
ResourceDirectoryEntry [] namedEntries = GetEntries (rdt, true);
ResourceDirectoryEntry [] idEntries = GetEntries (rdt, false);
m_writer.Write ((ushort) namedEntries.Length);
m_writer.Write ((ushort) idEntries.Length);
foreach (ResourceDirectoryEntry rde in namedEntries)
WriteResourceDirectoryEntry (rde);
foreach (ResourceDirectoryEntry rde in idEntries)
WriteResourceDirectoryEntry (rde);
RestoreOffset ();
}
ResourceDirectoryEntry [] GetEntries (ResourceDirectoryTable rdt, bool identifiedByName)
{
ArrayList entries = new ArrayList ();
foreach (ResourceDirectoryEntry rde in rdt.Entries)
if (rde.IdentifiedByName == identifiedByName)
entries.Add (rde);
return entries.ToArray (typeof (ResourceDirectoryEntry)) as ResourceDirectoryEntry [];
}
void WriteResourceDirectoryEntry (ResourceDirectoryEntry rde)
{
GotoOffset (rde.Offset);
if (rde.IdentifiedByName) {
m_writer.Write ((uint) rde.Name.Offset | 0x80000000);
WriteResourceDirectoryString (rde.Name);
} else
m_writer.Write ((uint) rde.ID);
if (rde.Child is ResourceDirectoryTable) {
m_writer.Write((uint) rde.Child.Offset | 0x80000000);
WriteResourceDirectoryTable (rde.Child as ResourceDirectoryTable);
} else {
m_writer.Write (rde.Child.Offset);
WriteResourceDataEntry (rde.Child as ResourceDataEntry);
}
RestoreOffset ();
}
void WriteResourceDataEntry (ResourceDataEntry rde)
{
GotoOffset (rde.Offset);
m_writer.Write (0);
m_writer.Write ((uint) rde.ResourceData.Length);
m_writer.Write (rde.Codepage);
m_writer.Write (rde.Reserved);
m_writer.BaseStream.Position = rde.Data;
m_writer.Write (rde.ResourceData);
RestoreOffset ();
}
void WriteResourceDirectoryString (ResourceDirectoryString name)
{
GotoOffset (name.Offset);
byte [] str = Encoding.Unicode.GetBytes (name.String);
m_writer.Write ((ushort) str.Length);
m_writer.Write (str);
RestoreOffset ();
}
void GotoOffset (int offset)
{
m_pos = m_writer.BaseStream.Position;
m_writer.BaseStream.Position = offset;
}
void RestoreOffset ()
{
m_writer.BaseStream.Position = m_pos;
}
}
}
| |
using System.Diagnostics;
using Jint.Runtime;
namespace Jint.Native.Number.Dtoa
{
internal sealed class Bignum
{
// 3584 = 128 * 28. We can represent 2^3584 > 10^1000 accurately.
// This bignum can encode much bigger numbers, since it contains an
// exponent.
private const int kMaxSignificantBits = 3584;
private const int kChunkSize = sizeof(uint) * 8;
private const int kDoubleChunkSize = sizeof(ulong) * 8;
// With bigit size of 28 we loose some bits, but a double still fits easily
// into two chunks, and more importantly we can use the Comba multiplication.
private const int kBigitSize = 28;
private const uint kBigitMask = (1 << kBigitSize) - 1;
// Every instance allocates kBigitLength chunks on the stack. Bignums cannot
// grow. There are no checks if the stack-allocated space is sufficient.
private const int kBigitCapacity = kMaxSignificantBits / kBigitSize;
private uint[] bigits_ = new uint[kBigitCapacity];
// The Bignum's value equals value(bigits_) * 2^(exponent_ * kBigitSize).
private int exponent_;
private int used_digits_;
private int BigitLength()
{
return used_digits_ + exponent_;
}
// Precondition: this/other < 16bit.
public uint DivideModuloIntBignum(Bignum other)
{
Debug.Assert(IsClamped());
Debug.Assert(other.IsClamped());
Debug.Assert(other.used_digits_ > 0);
// Easy case: if we have less digits than the divisor than the result is 0.
// Note: this handles the case where this == 0, too.
if (BigitLength() < other.BigitLength()) return 0;
Align(other);
uint result = 0;
// Start by removing multiples of 'other' until both numbers have the same
// number of digits.
while (BigitLength() > other.BigitLength())
{
// This naive approach is extremely inefficient if the this divided other
// might be big. This function is implemented for doubleToString where
// the result should be small (less than 10).
Debug.Assert(other.bigits_[other.used_digits_ - 1] >= (1 << kBigitSize) / 16);
// Remove the multiples of the first digit.
// Example this = 23 and other equals 9. -> Remove 2 multiples.
result += bigits_[used_digits_ - 1];
SubtractTimes(other, bigits_[used_digits_ - 1]);
}
Debug.Assert(BigitLength() == other.BigitLength());
// Both bignums are at the same length now.
// Since other has more than 0 digits we know that the access to
// bigits_[used_digits_ - 1] is safe.
var this_bigit = bigits_[used_digits_ - 1];
var other_bigit = other.bigits_[other.used_digits_ - 1];
if (other.used_digits_ == 1)
{
// Shortcut for easy (and common) case.
uint quotient = this_bigit / other_bigit;
bigits_[used_digits_ - 1] = this_bigit - other_bigit * quotient;
result += quotient;
Clamp();
return result;
}
uint division_estimate = this_bigit / (other_bigit + 1);
result += division_estimate;
SubtractTimes(other, division_estimate);
if (other_bigit * (division_estimate + 1) > this_bigit) return result;
while (LessEqual(other, this))
{
SubtractBignum(other);
result++;
}
return result;
}
void Align(Bignum other)
{
if (exponent_ > other.exponent_)
{
// If "X" represents a "hidden" digit (by the exponent) then we are in the
// following case (a == this, b == other):
// a: aaaaaaXXXX or a: aaaaaXXX
// b: bbbbbbX b: bbbbbbbbXX
// We replace some of the hidden digits (X) of a with 0 digits.
// a: aaaaaa000X or a: aaaaa0XX
int zero_digits = exponent_ - other.exponent_;
EnsureCapacity(used_digits_ + zero_digits);
for (int i = used_digits_ - 1; i >= 0; --i)
{
bigits_[i + zero_digits] = bigits_[i];
}
for (int i = 0; i < zero_digits; ++i)
{
bigits_[i] = 0;
}
used_digits_ += zero_digits;
exponent_ -= zero_digits;
Debug.Assert(used_digits_ >= 0);
Debug.Assert(exponent_ >= 0);
}
}
void EnsureCapacity(int size)
{
if (size > kBigitCapacity)
{
ExceptionHelper.ThrowInvalidOperationException();
}
}
private void Clamp()
{
while (used_digits_ > 0 && bigits_[used_digits_ - 1] == 0) used_digits_--;
if (used_digits_ == 0) exponent_ = 0;
}
private bool IsClamped()
{
return used_digits_ == 0 || bigits_[used_digits_ - 1] != 0;
}
private void Zero()
{
for (var i = 0; i < used_digits_; ++i) bigits_[i] = 0;
used_digits_ = 0;
exponent_ = 0;
}
// Guaranteed to lie in one Bigit.
internal void AssignUInt16(uint value)
{
Debug.Assert(kBigitSize <= 8 * sizeof(uint));
Zero();
if (value == 0) return;
EnsureCapacity(1);
bigits_[0] = value;
used_digits_ = 1;
}
internal void AssignUInt64(ulong value)
{
const int kUInt64Size = 64;
Zero();
if (value == 0) return;
int needed_bigits = kUInt64Size / kBigitSize + 1;
EnsureCapacity(needed_bigits);
for (int i = 0; i < needed_bigits; ++i)
{
bigits_[i] = (uint) (value & kBigitMask);
value = value >> kBigitSize;
}
used_digits_ = needed_bigits;
Clamp();
}
internal void AssignBignum(Bignum other)
{
exponent_ = other.exponent_;
for (int i = 0; i < other.used_digits_; ++i)
{
bigits_[i] = other.bigits_[i];
}
// Clear the excess digits (if there were any).
for (int i = other.used_digits_; i < used_digits_; ++i)
{
bigits_[i] = 0;
}
used_digits_ = other.used_digits_;
}
void SubtractTimes(Bignum other, uint factor)
{
#if DEBUG
var a = new Bignum();
var b = new Bignum();
a.AssignBignum(this);
b.AssignBignum(other);
b.MultiplyByUInt32(factor);
a.SubtractBignum(b);
#endif
Debug.Assert(exponent_ <= other.exponent_);
if (factor < 3)
{
for (int i = 0; i < factor; ++i)
{
SubtractBignum(other);
}
return;
}
uint borrow = 0;
int exponent_diff = other.exponent_ - exponent_;
for (int i = 0; i < other.used_digits_; ++i)
{
ulong product = factor * other.bigits_[i];
ulong remove = borrow + product;
uint difference = bigits_[i + exponent_diff] - (uint) (remove & kBigitMask);
bigits_[i + exponent_diff] = difference & kBigitMask;
borrow = (uint) ((difference >> (kChunkSize - 1)) + (remove >> kBigitSize));
}
for (int i = other.used_digits_ + exponent_diff; i < used_digits_; ++i)
{
if (borrow == 0) return;
uint difference = bigits_[i] - borrow;
bigits_[i] = difference & kBigitMask;
borrow = difference >> (kChunkSize - 1);
}
Clamp();
#if DEBUG
Debug.Assert(Equal(a, this));
#endif
}
void SubtractBignum(Bignum other)
{
Debug.Assert(IsClamped());
Debug.Assert(other.IsClamped());
// We require this to be bigger than other.
Debug.Assert(LessEqual(other, this));
Align(other);
int offset = other.exponent_ - exponent_;
uint borrow = 0;
int i;
for (i = 0; i < other.used_digits_; ++i)
{
Debug.Assert((borrow == 0) || (borrow == 1));
uint difference = bigits_[i + offset] - other.bigits_[i] - borrow;
bigits_[i + offset] = difference & kBigitMask;
borrow = difference >> (kChunkSize - 1);
}
while (borrow != 0)
{
uint difference = bigits_[i + offset] - borrow;
bigits_[i + offset] = difference & kBigitMask;
borrow = difference >> (kChunkSize - 1);
++i;
}
Clamp();
}
internal static bool Equal(Bignum a, Bignum b)
{
return Compare(a, b) == 0;
}
internal static bool LessEqual(Bignum a, Bignum b)
{
return Compare(a, b) <= 0;
}
internal static bool Less(Bignum a, Bignum b)
{
return Compare(a, b) < 0;
}
// Returns a + b == c
static bool PlusEqual(Bignum a, Bignum b, Bignum c)
{
return PlusCompare(a, b, c) == 0;
}
// Returns a + b <= c
static bool PlusLessEqual(Bignum a, Bignum b, Bignum c)
{
return PlusCompare(a, b, c) <= 0;
}
// Returns a + b < c
static bool PlusLess(Bignum a, Bignum b, Bignum c)
{
return PlusCompare(a, b, c) < 0;
}
uint BigitAt(int index)
{
if (index >= BigitLength()) return 0;
if (index < exponent_) return 0;
return bigits_[index - exponent_];
}
static int Compare(Bignum a, Bignum b)
{
Debug.Assert(a.IsClamped());
Debug.Assert(b.IsClamped());
int bigit_length_a = a.BigitLength();
int bigit_length_b = b.BigitLength();
if (bigit_length_a < bigit_length_b) return -1;
if (bigit_length_a > bigit_length_b) return +1;
for (int i = bigit_length_a - 1; i >= System.Math.Min(a.exponent_, b.exponent_); --i)
{
uint bigit_a = a.BigitAt(i);
uint bigit_b = b.BigitAt(i);
if (bigit_a < bigit_b) return -1;
if (bigit_a > bigit_b) return +1;
// Otherwise they are equal up to this digit. Try the next digit.
}
return 0;
}
internal static int PlusCompare(Bignum a, Bignum b, Bignum c)
{
Debug.Assert(a.IsClamped());
Debug.Assert(b.IsClamped());
Debug.Assert(c.IsClamped());
if (a.BigitLength() < b.BigitLength())
{
return PlusCompare(b, a, c);
}
if (a.BigitLength() + 1 < c.BigitLength()) return -1;
if (a.BigitLength() > c.BigitLength()) return +1;
// The exponent encodes 0-bigits. So if there are more 0-digits in 'a' than
// 'b' has digits, then the bigit-length of 'a'+'b' must be equal to the one
// of 'a'.
if (a.exponent_ >= b.BigitLength() && a.BigitLength() < c.BigitLength())
{
return -1;
}
uint borrow = 0;
// Starting at min_exponent all digits are == 0. So no need to compare them.
int min_exponent = System.Math.Min(System.Math.Min(a.exponent_, b.exponent_), c.exponent_);
for (int i = c.BigitLength() - 1; i >= min_exponent; --i)
{
uint chunk_a = a.BigitAt(i);
uint chunk_b = b.BigitAt(i);
uint chunk_c = c.BigitAt(i);
uint sum = chunk_a + chunk_b;
if (sum > chunk_c + borrow)
{
return +1;
}
else
{
borrow = chunk_c + borrow - sum;
if (borrow > 1) return -1;
borrow <<= kBigitSize;
}
}
if (borrow == 0) return 0;
return -1;
}
internal void Times10()
{
MultiplyByUInt32(10);
}
internal void MultiplyByUInt32(uint factor)
{
if (factor == 1) return;
if (factor == 0)
{
Zero();
return;
}
if (used_digits_ == 0) return;
// The product of a bigit with the factor is of size kBigitSize + 32.
// Assert that this number + 1 (for the carry) fits into double chunk.
Debug.Assert(kDoubleChunkSize >= kBigitSize + 32 + 1);
ulong carry = 0;
for (int i = 0; i < used_digits_; ++i)
{
ulong product = ((ulong) factor) * bigits_[i] + carry;
bigits_[i] = (uint) (product & kBigitMask);
carry = (product >> kBigitSize);
}
while (carry != 0)
{
EnsureCapacity(used_digits_ + 1);
bigits_[used_digits_] = (uint) (carry & kBigitMask);
used_digits_++;
carry >>= kBigitSize;
}
}
internal void MultiplyByUInt64(ulong factor)
{
if (factor == 1) return;
if (factor == 0) {
Zero();
return;
}
Debug.Assert(kBigitSize < 32);
ulong carry = 0;
ulong low = factor & 0xFFFFFFFF;
ulong high = factor >> 32;
for (int i = 0; i < used_digits_; ++i) {
ulong product_low = low * bigits_[i];
ulong product_high = high * bigits_[i];
ulong tmp = (carry & kBigitMask) + product_low;
bigits_[i] = (uint) (tmp & kBigitMask);
carry = (carry >> kBigitSize) + (tmp >> kBigitSize) +
(product_high << (32 - kBigitSize));
}
while (carry != 0) {
EnsureCapacity(used_digits_ + 1);
bigits_[used_digits_] = (uint) (carry & kBigitMask);
used_digits_++;
carry >>= kBigitSize;
}
}
internal void ShiftLeft(int shift_amount)
{
if (used_digits_ == 0) return;
exponent_ += shift_amount / kBigitSize;
int local_shift = shift_amount % kBigitSize;
EnsureCapacity(used_digits_ + 1);
BigitsShiftLeft(local_shift);
}
void BigitsShiftLeft(int shift_amount)
{
Debug.Assert(shift_amount < kBigitSize);
Debug.Assert(shift_amount >= 0);
uint carry = 0;
for (int i = 0; i < used_digits_; ++i)
{
uint new_carry = bigits_[i] >> (kBigitSize - shift_amount);
bigits_[i] = ((bigits_[i] << shift_amount) + carry) & kBigitMask;
carry = new_carry;
}
if (carry != 0)
{
bigits_[used_digits_] = carry;
used_digits_++;
}
}
internal void AssignPowerUInt16(uint baseValue, int power_exponent)
{
Debug.Assert(baseValue != 0);
Debug.Assert(power_exponent >= 0);
if (power_exponent == 0)
{
AssignUInt16(1);
return;
}
Zero();
int shifts = 0;
// We expect baseValue to be in range 2-32, and most often to be 10.
// It does not make much sense to implement different algorithms for counting
// the bits.
while ((baseValue & 1) == 0)
{
baseValue >>= 1;
shifts++;
}
int bit_size = 0;
uint tmp_base = baseValue;
while (tmp_base != 0)
{
tmp_base >>= 1;
bit_size++;
}
int final_size = bit_size * power_exponent;
// 1 extra bigit for the shifting, and one for rounded final_size.
EnsureCapacity(final_size / kBigitSize + 2);
// Left to Right exponentiation.
int mask = 1;
while (power_exponent >= mask) mask <<= 1;
// The mask is now pointing to the bit above the most significant 1-bit of
// power_exponent.
// Get rid of first 1-bit;
mask >>= 2;
ulong this_value = baseValue;
bool delayed_multipliciation = false;
const ulong max_32bits = 0xFFFFFFFF;
while (mask != 0 && this_value <= max_32bits)
{
this_value = this_value * this_value;
// Verify that there is enough space in this_value to perform the
// multiplication. The first bit_size bits must be 0.
if ((power_exponent & mask) != 0)
{
ulong base_bits_mask = ~((((ulong) 1) << (64 - bit_size)) - 1);
bool high_bits_zero = (this_value & base_bits_mask) == 0;
if (high_bits_zero)
{
this_value *= baseValue;
}
else
{
delayed_multipliciation = true;
}
}
mask >>= 1;
}
AssignUInt64(this_value);
if (delayed_multipliciation)
{
MultiplyByUInt32(baseValue);
}
// Now do the same thing as a bignum.
while (mask != 0)
{
Square();
if ((power_exponent & mask) != 0)
{
MultiplyByUInt32(baseValue);
}
mask >>= 1;
}
// And finally add the saved shifts.
ShiftLeft(shifts * power_exponent);
}
void Square()
{
Debug.Assert(IsClamped());
int product_length = 2 * used_digits_;
EnsureCapacity(product_length);
// Comba multiplication: compute each column separately.
// Example: r = a2a1a0 * b2b1b0.
// r = 1 * a0b0 +
// 10 * (a1b0 + a0b1) +
// 100 * (a2b0 + a1b1 + a0b2) +
// 1000 * (a2b1 + a1b2) +
// 10000 * a2b2
//
// In the worst case we have to accumulate nb-digits products of digit*digit.
//
// Assert that the additional number of bits in a DoubleChunk are enough to
// sum up used_digits of Bigit*Bigit.
if ((1 << (2 * (kChunkSize - kBigitSize))) <= used_digits_)
{
ExceptionHelper.ThrowNotImplementedException();
}
ulong accumulator = 0;
// First shift the digits so we don't overwrite them.
int copy_offset = used_digits_;
for (int i = 0; i < used_digits_; ++i)
{
bigits_[copy_offset + i] = bigits_[i];
}
// We have two loops to avoid some 'if's in the loop.
for (int i = 0; i < used_digits_; ++i)
{
// Process temporary digit i with power i.
// The sum of the two indices must be equal to i.
int bigit_index1 = i;
int bigit_index2 = 0;
// Sum all of the sub-products.
while (bigit_index1 >= 0)
{
uint chunk1 = bigits_[copy_offset + bigit_index1];
uint chunk2 = bigits_[copy_offset + bigit_index2];
accumulator += (ulong) chunk1 * chunk2;
bigit_index1--;
bigit_index2++;
}
bigits_[i] = (uint) accumulator & kBigitMask;
accumulator >>= kBigitSize;
}
for (int i = used_digits_; i < product_length; ++i)
{
int bigit_index1 = used_digits_ - 1;
int bigit_index2 = i - bigit_index1;
// Invariant: sum of both indices is again equal to i.
// Inner loop runs 0 times on last iteration, emptying accumulator.
while (bigit_index2 < used_digits_)
{
uint chunk1 = bigits_[copy_offset + bigit_index1];
uint chunk2 = bigits_[copy_offset + bigit_index2];
accumulator += (ulong) chunk1 * chunk2;
bigit_index1--;
bigit_index2++;
}
// The overwritten bigits_[i] will never be read in further loop iterations,
// because bigit_index1 and bigit_index2 are always greater
// than i - used_digits_.
bigits_[i] = (uint) accumulator & kBigitMask;
accumulator >>= kBigitSize;
}
// Since the result was guaranteed to lie inside the number the
// accumulator must be 0 now.
Debug.Assert(accumulator == 0);
// Don't forget to update the used_digits and the exponent.
used_digits_ = product_length;
exponent_ *= 2;
Clamp();
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.IO.PortsTests;
using System.Text;
using System.Threading;
using Legacy.Support;
using Xunit;
using Xunit.NetCore.Extensions;
namespace System.IO.Ports.Tests
{
public class Read_char_int_int_Generic : PortsTest
{
//Set bounds fore random timeout values.
//If the min is to low read will not timeout accurately and the testcase will fail
private const int minRandomTimeout = 250;
//If the max is to large then the testcase will take forever to run
private const int maxRandomTimeout = 2000;
//If the percentage difference between the expected timeout and the actual timeout
//found through Stopwatch is greater then 10% then the timeout value was not correctly
//to the read method and the testcase fails.
private const double maxPercentageDifference = .15;
//The number of random bytes to receive for parity testing
private const int numRndBytesPairty = 8;
//The number of characters to read at a time for parity testing
private const int numBytesReadPairty = 2;
//The number of random bytes to receive for BytesToRead testing
private const int numRndBytesToRead = 16;
//When we test Read and do not care about actually reading anything we must still
//create an byte array to pass into the method the following is the size of the
//byte array used in this situation
private const int defaultCharArraySize = 1;
private const int NUM_TRYS = 5;
#region Test Cases
[Fact]
public void ReadWithoutOpen()
{
using (SerialPort com = new SerialPort())
{
Debug.WriteLine("Verifying read method throws exception without a call to Open()");
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterFailedOpen()
{
using (SerialPort com = new SerialPort("BAD_PORT_NAME"))
{
Debug.WriteLine("Verifying read method throws exception with a failed call to Open()");
//Since the PortName is set to a bad port name Open will thrown an exception
//however we don't care what it is since we are verifying a read method
Assert.ThrowsAny<Exception>(() => com.Open());
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[ConditionalFact(nameof(HasOneSerialPort))]
public void ReadAfterClose()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Debug.WriteLine("Verifying read method throws exception after a call to Cloes()");
com.Open();
com.Close();
VerifyReadException(com, typeof(InvalidOperationException));
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void Timeout()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
Debug.WriteLine("Verifying ReadTimeout={0}", com.ReadTimeout);
com.Open();
VerifyTimeout(com);
}
}
[Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // Timing-sensitive
[ConditionalFact(nameof(HasOneSerialPort))]
public void SuccessiveReadTimeoutNoData()
{
using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
com.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
// com.Encoding = new System.Text.UTF7Encoding();
com.Encoding = Encoding.Unicode;
Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and no data", com.ReadTimeout);
com.Open();
Assert.Throws<TimeoutException>(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
VerifyTimeout(com);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void SuccessiveReadTimeoutSomeData()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
{
Random rndGen = new Random(-55);
Thread t = new Thread(WriteToCom1);
com1.ReadTimeout = rndGen.Next(minRandomTimeout, maxRandomTimeout);
com1.Encoding = new UTF8Encoding();
Debug.WriteLine("Verifying ReadTimeout={0} with successive call to read method and some data being received in the first call", com1.ReadTimeout);
com1.Open();
//Call WriteToCom1 asynchronously this will write to com1 some time before the following call
//to a read method times out
t.Start();
try
{
com1.Read(new char[defaultCharArraySize], 0, defaultCharArraySize);
}
catch (TimeoutException)
{
}
//Wait for the thread to finish
while (t.IsAlive)
Thread.Sleep(50);
//Make sure there is no bytes in the buffer so the next call to read will timeout
com1.DiscardInBuffer();
VerifyTimeout(com1);
}
}
private void WriteToCom1()
{
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] xmitBuffer = new byte[1];
int sleepPeriod = rndGen.Next(minRandomTimeout, maxRandomTimeout / 2);
//Sleep some random period with of a maximum duration of half the largest possible timeout value for a read method on COM1
Thread.Sleep(sleepPeriod);
com2.Open();
com2.Write(xmitBuffer, 0, xmitBuffer.Length);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void DefaultParityReplaceByte()
{
VerifyParityReplaceByte(-1, numRndBytesPairty - 2);
}
[ConditionalFact(nameof(HasNullModem))]
public void NoParityReplaceByte()
{
Random rndGen = new Random(-55);
VerifyParityReplaceByte('\0', rndGen.Next(0, numRndBytesPairty - 1));
}
[ConditionalFact(nameof(HasNullModem))]
public void RNDParityReplaceByte()
{
Random rndGen = new Random(-55);
VerifyParityReplaceByte(rndGen.Next(0, 128), 0);
}
[ConditionalFact(nameof(HasNullModem))]
public void ParityErrorOnLastByte()
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(15);
byte[] bytesToWrite = new byte[numRndBytesPairty];
char[] expectedChars = new char[numRndBytesPairty];
char[] actualChars = new char[numRndBytesPairty + 1];
/* 1 Additional character gets added to the input buffer when the parity error occurs on the last byte of a stream
We are verifying that besides this everything gets read in correctly. See NDP Whidbey: 24216 for more info on this */
Debug.WriteLine("Verifying default ParityReplace byte with a parity errro on the last byte");
//Genrate random characters without an parity error
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedChars[i] = (char)randByte;
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] | 0x80);
//Create a parity error on the last byte
expectedChars[expectedChars.Length - 1] = (char)com1.ParityReplace;
// Set the last expected char to be the ParityReplace Byte
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.ReadTimeout = 250;
com1.Open();
com2.Open();
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length + 1);
com1.Read(actualChars, 0, actualChars.Length);
//Compare the chars that were written with the ones we expected to read
for (int i = 0; i < expectedChars.Length; i++)
{
if (expectedChars[i] != actualChars[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)actualChars[i]);
}
}
if (1 < com1.BytesToRead)
{
Debug.WriteLine("ByteRead={0}, {1}", com1.ReadByte(), bytesToWrite[bytesToWrite.Length - 1]);
Fail("ERROR!!!: Expected BytesToRead=0 actual={0}", com1.BytesToRead);
}
bytesToWrite[bytesToWrite.Length - 1] = (byte)(bytesToWrite[bytesToWrite.Length - 1] & 0x7F);
//Clear the parity error on the last byte
expectedChars[expectedChars.Length - 1] = (char)bytesToWrite[bytesToWrite.Length - 1];
VerifyRead(com1, com2, bytesToWrite, expectedChars, expectedChars.Length / 2);
}
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_RND_Buffer_Size()
{
Random rndGen = new Random(-55);
VerifyBytesToRead(rndGen.Next(1, 2 * numRndBytesToRead));
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_1_Buffer_Size()
{
VerifyBytesToRead(1);
}
[ConditionalFact(nameof(HasNullModem))]
public void BytesToRead_Equal_Buffer_Size()
{
Random rndGen = new Random(-55);
VerifyBytesToRead(numRndBytesToRead);
}
#endregion
#region Verification for Test Cases
private void VerifyTimeout(SerialPort com)
{
Stopwatch timer = new Stopwatch();
int expectedTime = com.ReadTimeout;
int actualTime = 0;
double percentageDifference;
//Warm up read method
Assert.Throws<TimeoutException>(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
Thread.CurrentThread.Priority = ThreadPriority.Highest;
for (int i = 0; i < NUM_TRYS; i++)
{
timer.Start();
Assert.Throws<TimeoutException>(() => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
timer.Stop();
actualTime += (int)timer.ElapsedMilliseconds;
timer.Reset();
}
Thread.CurrentThread.Priority = ThreadPriority.Normal;
actualTime /= NUM_TRYS;
percentageDifference = Math.Abs((expectedTime - actualTime) / (double)expectedTime);
//Verify that the percentage difference between the expected and actual timeout is less then maxPercentageDifference
if (maxPercentageDifference < percentageDifference)
{
Fail("ERROR!!!: The read method timed-out in {0} expected {1} percentage difference: {2}", actualTime, expectedTime, percentageDifference);
}
}
private void VerifyReadException(SerialPort com, Type expectedException)
{
Assert.Throws(expectedException, () => com.Read(new char[defaultCharArraySize], 0, defaultCharArraySize));
}
private void VerifyParityReplaceByte(int parityReplace, int parityErrorIndex)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] bytesToWrite = new byte[numRndBytesPairty];
char[] expectedChars = new char[numRndBytesPairty];
byte expectedByte;
//Genrate random characters without an parity error
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 128);
bytesToWrite[i] = randByte;
expectedChars[i] = (char)randByte;
}
if (-1 == parityReplace)
{
//If parityReplace is -1 and we should just use the default value
expectedByte = com1.ParityReplace;
}
else if ('\0' == parityReplace)
{
//If parityReplace is the null charachater and parity replacement should not occur
com1.ParityReplace = (byte)parityReplace;
expectedByte = bytesToWrite[parityErrorIndex];
}
else
{
//Else parityReplace was set to a value and we should expect this value to be returned on a parity error
com1.ParityReplace = (byte)parityReplace;
expectedByte = (byte)parityReplace;
}
//Create an parity error by setting the highest order bit to true
bytesToWrite[parityErrorIndex] = (byte)(bytesToWrite[parityErrorIndex] | 0x80);
expectedChars[parityErrorIndex] = (char)expectedByte;
Debug.WriteLine("Verifying ParityReplace={0} with an ParityError at: {1} ", com1.ParityReplace,
parityErrorIndex);
com1.Parity = Parity.Space;
com1.DataBits = 7;
com1.Open();
com2.Open();
VerifyRead(com1, com2, bytesToWrite, expectedChars, numBytesReadPairty);
}
}
private void VerifyBytesToRead(int numBytesRead)
{
using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName))
using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName))
{
Random rndGen = new Random(-55);
byte[] bytesToWrite = new byte[numRndBytesToRead];
char[] expectedChars;
ASCIIEncoding encoding = new ASCIIEncoding();
//Genrate random characters
for (int i = 0; i < bytesToWrite.Length; i++)
{
byte randByte = (byte)rndGen.Next(0, 256);
bytesToWrite[i] = randByte;
}
expectedChars = encoding.GetChars(bytesToWrite, 0, bytesToWrite.Length);
Debug.WriteLine("Verifying BytesToRead with a buffer of: {0} ", numBytesRead);
com1.Open();
com2.Open();
VerifyRead(com1, com2, bytesToWrite, expectedChars, numBytesRead);
}
}
private void VerifyRead(SerialPort com1, SerialPort com2, byte[] bytesToWrite, char[] expectedChars, int rcvBufferSize)
{
char[] rcvBuffer = new char[rcvBufferSize];
char[] buffer = new char[expectedChars.Length];
int totalBytesRead;
int totalCharsRead;
int bytesToRead;
com2.Write(bytesToWrite, 0, bytesToWrite.Length);
com1.ReadTimeout = 250;
TCSupport.WaitForReadBufferToLoad(com1, bytesToWrite.Length);
totalBytesRead = 0;
totalCharsRead = 0;
bytesToRead = com1.BytesToRead;
while (true)
{
int charsRead;
try
{
charsRead = com1.Read(rcvBuffer, 0, rcvBufferSize);
}
catch (TimeoutException)
{
break;
}
//While their are more characters to be read
int bytesRead = com1.Encoding.GetByteCount(rcvBuffer, 0, charsRead);
if ((bytesToRead > bytesRead && rcvBufferSize != bytesRead) ||
(bytesToRead <= bytesRead && bytesRead != bytesToRead))
{
//If we have not read all of the characters that we should have
Fail("ERROR!!!: Read did not return all of the characters that were in SerialPort buffer");
}
if (expectedChars.Length < totalCharsRead + charsRead)
{
//If we have read in more characters then we expect
Fail("ERROR!!!: We have received more characters then were sent");
}
Array.Copy(rcvBuffer, 0, buffer, totalCharsRead, charsRead);
totalBytesRead += bytesRead;
totalCharsRead += charsRead;
if (bytesToWrite.Length - totalBytesRead != com1.BytesToRead)
{
Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", bytesToWrite.Length - totalBytesRead,
com1.BytesToRead);
}
bytesToRead = com1.BytesToRead;
}
//Compare the chars that were written with the ones we expected to read
for (int i = 0; i < expectedChars.Length; i++)
{
if (expectedChars[i] != buffer[i])
{
Fail("ERROR!!!: Expected to read {0} actual read {1}", (int)expectedChars[i], (int)buffer[i]);
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using ImageResizer;
using Nop.Core;
using Nop.Core.Data;
using Nop.Core.Domain.Catalog;
using Nop.Core.Domain.Media;
using Nop.Services.Configuration;
using Nop.Services.Events;
using Nop.Services.Logging;
using Nop.Services.Seo;
namespace Nop.Services.Media
{
/// <summary>
/// Picture service
/// </summary>
public partial class PictureService : IPictureService
{
#region Const
private const int MULTIPLE_THUMB_DIRECTORIES_LENGTH = 3;
#endregion
#region Fields
private static readonly object s_lock = new object();
private readonly IRepository<Picture> _pictureRepository;
private readonly IRepository<ProductPicture> _productPictureRepository;
private readonly ISettingService _settingService;
private readonly IWebHelper _webHelper;
private readonly ILogger _logger;
private readonly IEventPublisher _eventPublisher;
private readonly MediaSettings _mediaSettings;
#endregion
#region Ctor
/// <summary>
/// Ctor
/// </summary>
/// <param name="pictureRepository">Picture repository</param>
/// <param name="productPictureRepository">Product picture repository</param>
/// <param name="settingService">Setting service</param>
/// <param name="webHelper">Web helper</param>
/// <param name="logger">Logger</param>
/// <param name="eventPublisher">Event publisher</param>
/// <param name="mediaSettings">Media settings</param>
public PictureService(IRepository<Picture> pictureRepository,
IRepository<ProductPicture> productPictureRepository,
ISettingService settingService, IWebHelper webHelper,
ILogger logger, IEventPublisher eventPublisher,
MediaSettings mediaSettings)
{
this._pictureRepository = pictureRepository;
this._productPictureRepository = productPictureRepository;
this._settingService = settingService;
this._webHelper = webHelper;
this._logger = logger;
this._eventPublisher = eventPublisher;
this._mediaSettings = mediaSettings;
}
#endregion
#region Utilities
/// <summary>
/// Calculates picture dimensions whilst maintaining aspect
/// </summary>
/// <param name="originalSize">The original picture size</param>
/// <param name="targetSize">The target picture size (longest side)</param>
/// <param name="resizeType">Resize type</param>
/// <param name="ensureSizePositive">A value indicatingh whether we should ensure that size values are positive</param>
/// <returns></returns>
protected virtual Size CalculateDimensions(Size originalSize, int targetSize,
ResizeType resizeType = ResizeType.LongestSide, bool ensureSizePositive = true)
{
var newSize = new Size();
switch (resizeType)
{
case ResizeType.LongestSide:
if (originalSize.Height > originalSize.Width)
{
// portrait
newSize.Width = (int)(originalSize.Width * (float)(targetSize / (float)originalSize.Height));
newSize.Height = targetSize;
}
else
{
// landscape or square
newSize.Height = (int)(originalSize.Height * (float)(targetSize / (float)originalSize.Width));
newSize.Width = targetSize;
}
break;
case ResizeType.Width:
newSize.Height = (int)(originalSize.Height * (float)(targetSize / (float)originalSize.Width));
newSize.Width = targetSize;
break;
case ResizeType.Height:
newSize.Width = (int)(originalSize.Width * (float)(targetSize / (float)originalSize.Height));
newSize.Height = targetSize;
break;
default:
throw new Exception("Not supported ResizeType");
}
if (ensureSizePositive)
{
if (newSize.Width < 1)
newSize.Width = 1;
if (newSize.Height < 1)
newSize.Height = 1;
}
return newSize;
}
/// <summary>
/// Returns the file extension from mime type.
/// </summary>
/// <param name="mimeType">Mime type</param>
/// <returns>File extension</returns>
protected virtual string GetFileExtensionFromMimeType(string mimeType)
{
if (mimeType == null)
return null;
//also see System.Web.MimeMapping for more mime types
string[] parts = mimeType.Split('/');
string lastPart = parts[parts.Length - 1];
switch (lastPart)
{
case "pjpeg":
lastPart = "jpg";
break;
case "x-png":
lastPart = "png";
break;
case "x-icon":
lastPart = "ico";
break;
}
return lastPart;
}
/// <summary>
/// Loads a picture from file
/// </summary>
/// <param name="pictureId">Picture identifier</param>
/// <param name="mimeType">MIME type</param>
/// <returns>Picture binary</returns>
protected virtual byte[] LoadPictureFromFile(int pictureId, string mimeType)
{
string lastPart = GetFileExtensionFromMimeType(mimeType);
string fileName = string.Format("{0}_0.{1}", pictureId.ToString("0000000"), lastPart);
var filePath = GetPictureLocalPath(fileName);
if (!File.Exists(filePath))
return new byte[0];
return File.ReadAllBytes(filePath);
}
/// <summary>
/// Save picture on file system
/// </summary>
/// <param name="pictureId">Picture identifier</param>
/// <param name="pictureBinary">Picture binary</param>
/// <param name="mimeType">MIME type</param>
protected virtual void SavePictureInFile(int pictureId, byte[] pictureBinary, string mimeType)
{
string lastPart = GetFileExtensionFromMimeType(mimeType);
string fileName = string.Format("{0}_0.{1}", pictureId.ToString("0000000"), lastPart);
File.WriteAllBytes(GetPictureLocalPath(fileName), pictureBinary);
}
/// <summary>
/// Delete a picture on file system
/// </summary>
/// <param name="picture">Picture</param>
protected virtual void DeletePictureOnFileSystem(Picture picture)
{
if (picture == null)
throw new ArgumentNullException("picture");
string lastPart = GetFileExtensionFromMimeType(picture.MimeType);
string fileName = string.Format("{0}_0.{1}", picture.Id.ToString("0000000"), lastPart);
string filePath = GetPictureLocalPath(fileName);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
/// <summary>
/// Delete picture thumbs
/// </summary>
/// <param name="picture">Picture</param>
protected virtual void DeletePictureThumbs(Picture picture)
{
string filter = string.Format("{0}*.*", picture.Id.ToString("0000000"));
var thumbDirectoryPath = _webHelper.MapPath("~/content/images/thumbs");
string[] currentFiles = System.IO.Directory.GetFiles(thumbDirectoryPath, filter, SearchOption.AllDirectories);
foreach (string currentFileName in currentFiles)
{
var thumbFilePath = GetThumbLocalPath(currentFileName);
File.Delete(thumbFilePath);
}
}
/// <summary>
/// Get picture (thumb) local path
/// </summary>
/// <param name="thumbFileName">Filename</param>
/// <returns>Local picture thumb path</returns>
protected virtual string GetThumbLocalPath(string thumbFileName)
{
var thumbsDirectoryPath = _webHelper.MapPath("~/content/images/thumbs");
if (_mediaSettings.MultipleThumbDirectories)
{
//get the first two letters of the file name
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(thumbFileName);
if (fileNameWithoutExtension != null && fileNameWithoutExtension.Length > MULTIPLE_THUMB_DIRECTORIES_LENGTH)
{
var subDirectoryName = fileNameWithoutExtension.Substring(0, MULTIPLE_THUMB_DIRECTORIES_LENGTH);
thumbsDirectoryPath = Path.Combine(thumbsDirectoryPath, subDirectoryName);
if (!System.IO.Directory.Exists(thumbsDirectoryPath))
{
System.IO.Directory.CreateDirectory(thumbsDirectoryPath);
}
}
}
var thumbFilePath = Path.Combine(thumbsDirectoryPath, thumbFileName);
return thumbFilePath;
}
/// <summary>
/// Get picture (thumb) URL
/// </summary>
/// <param name="thumbFileName">Filename</param>
/// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
/// <returns>Local picture thumb path</returns>
protected virtual string GetThumbUrl(string thumbFileName, string storeLocation = null)
{
storeLocation = !String.IsNullOrEmpty(storeLocation)
? storeLocation
: _webHelper.GetStoreLocation();
var url = storeLocation + "content/images/thumbs/";
if (_mediaSettings.MultipleThumbDirectories)
{
//get the first two letters of the file name
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(thumbFileName);
if (fileNameWithoutExtension != null && fileNameWithoutExtension.Length > MULTIPLE_THUMB_DIRECTORIES_LENGTH)
{
var subDirectoryName = fileNameWithoutExtension.Substring(0, MULTIPLE_THUMB_DIRECTORIES_LENGTH);
url = url + subDirectoryName + "/";
}
}
url = url + thumbFileName;
return url;
}
/// <summary>
/// Get picture local path. Used when images stored on file system (not in the database)
/// </summary>
/// <param name="fileName">Filename</param>
/// <returns>Local picture path</returns>
protected virtual string GetPictureLocalPath(string fileName)
{
var imagesDirectoryPath = _webHelper.MapPath("~/content/images/");
var filePath = Path.Combine(imagesDirectoryPath, fileName);
return filePath;
}
/// <summary>
/// Gets the loaded picture binary depending on picture storage settings
/// </summary>
/// <param name="picture">Picture</param>
/// <param name="fromDb">Load from database; otherwise, from file system</param>
/// <returns>Picture binary</returns>
protected virtual byte[] LoadPictureBinary(Picture picture, bool fromDb)
{
if (picture == null)
throw new ArgumentNullException("picture");
byte[] result = null;
if (fromDb)
result = picture.PictureBinary;
else
result = LoadPictureFromFile(picture.Id, picture.MimeType);
return result;
}
#endregion
#region Getting picture local path/URL methods
/// <summary>
/// Gets the loaded picture binary depending on picture storage settings
/// </summary>
/// <param name="picture">Picture</param>
/// <returns>Picture binary</returns>
public virtual byte[] LoadPictureBinary(Picture picture)
{
return LoadPictureBinary(picture, this.StoreInDb);
}
/// <summary>
/// Get picture SEO friendly name
/// </summary>
/// <param name="name">Name</param>
/// <returns>Result</returns>
public virtual string GetPictureSeName(string name)
{
return SeoExtensions.GetSeName(name, true, false);
}
/// <summary>
/// Gets the default picture URL
/// </summary>
/// <param name="targetSize">The target picture size (longest side)</param>
/// <param name="defaultPictureType">Default picture type</param>
/// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
/// <returns>Picture URL</returns>
public virtual string GetDefaultPictureUrl(int targetSize = 0,
PictureType defaultPictureType = PictureType.Entity,
string storeLocation = null)
{
string defaultImageFileName;
switch (defaultPictureType)
{
case PictureType.Entity:
defaultImageFileName = _settingService.GetSettingByKey("Media.DefaultImageName", "default-image.gif");
break;
case PictureType.Avatar:
defaultImageFileName = _settingService.GetSettingByKey("Media.Customer.DefaultAvatarImageName", "default-avatar.jpg");
break;
default:
defaultImageFileName = _settingService.GetSettingByKey("Media.DefaultImageName", "default-image.gif");
break;
}
string filePath = GetPictureLocalPath(defaultImageFileName);
if (!File.Exists(filePath))
{
return "";
}
if (targetSize == 0)
{
string url = (!String.IsNullOrEmpty(storeLocation)
? storeLocation
: _webHelper.GetStoreLocation())
+ "content/images/" + defaultImageFileName;
return url;
}
else
{
string fileExtension = Path.GetExtension(filePath);
string thumbFileName = string.Format("{0}_{1}{2}",
Path.GetFileNameWithoutExtension(filePath),
targetSize,
fileExtension);
var thumbFilePath = GetThumbLocalPath(thumbFileName);
if (!File.Exists(thumbFilePath))
{
using (var b = new Bitmap(filePath))
{
var newSize = CalculateDimensions(b.Size, targetSize);
var destStream = new MemoryStream();
ImageBuilder.Current.Build(b, destStream, new ResizeSettings()
{
Width = newSize.Width,
Height = newSize.Height,
Scale = ScaleMode.Both,
Quality = _mediaSettings.DefaultImageQuality
});
var destBinary = destStream.ToArray();
File.WriteAllBytes(thumbFilePath, destBinary);
}
}
var url = GetThumbUrl(thumbFileName, storeLocation);
return url;
}
}
/// <summary>
/// Get a picture URL
/// </summary>
/// <param name="pictureId">Picture identifier</param>
/// <param name="targetSize">The target picture size (longest side)</param>
/// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
/// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
/// <param name="defaultPictureType">Default picture type</param>
/// <returns>Picture URL</returns>
public virtual string GetPictureUrl(int pictureId,
int targetSize = 0,
bool showDefaultPicture = true,
string storeLocation = null,
PictureType defaultPictureType = PictureType.Entity)
{
var picture = GetPictureById(pictureId);
return GetPictureUrl(picture, targetSize, showDefaultPicture, storeLocation, defaultPictureType);
}
/// <summary>
/// Get a picture URL
/// </summary>
/// <param name="picture">Picture instance</param>
/// <param name="targetSize">The target picture size (longest side)</param>
/// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
/// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
/// <param name="defaultPictureType">Default picture type</param>
/// <returns>Picture URL</returns>
public virtual string GetPictureUrl(Picture picture,
int targetSize = 0,
bool showDefaultPicture = true,
string storeLocation = null,
PictureType defaultPictureType = PictureType.Entity)
{
string url = string.Empty;
byte[] pictureBinary = null;
if (picture != null)
pictureBinary = LoadPictureBinary(picture);
if (picture == null || pictureBinary == null || pictureBinary.Length == 0)
{
if(showDefaultPicture)
{
url = GetDefaultPictureUrl(targetSize, defaultPictureType, storeLocation);
}
return url;
}
string lastPart = GetFileExtensionFromMimeType(picture.MimeType);
string thumbFileName;
if (picture.IsNew)
{
DeletePictureThumbs(picture);
//we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
picture = UpdatePicture(picture.Id,
pictureBinary,
picture.MimeType,
picture.SeoFilename,
false,
false);
}
lock (s_lock)
{
string seoFileName = picture.SeoFilename; // = GetPictureSeName(picture.SeoFilename); //just for sure
if (targetSize == 0)
{
thumbFileName = !String.IsNullOrEmpty(seoFileName) ?
string.Format("{0}_{1}.{2}", picture.Id.ToString("0000000"), seoFileName, lastPart) :
string.Format("{0}.{1}", picture.Id.ToString("0000000"), lastPart);
var thumbFilePath = GetThumbLocalPath(thumbFileName);
if (!File.Exists(thumbFilePath))
{
File.WriteAllBytes(thumbFilePath, pictureBinary);
}
}
else
{
thumbFileName = !String.IsNullOrEmpty(seoFileName) ?
string.Format("{0}_{1}_{2}.{3}", picture.Id.ToString("0000000"), seoFileName, targetSize, lastPart) :
string.Format("{0}_{1}.{2}", picture.Id.ToString("0000000"), targetSize, lastPart);
var thumbFilePath = GetThumbLocalPath(thumbFileName);
if (!File.Exists(thumbFilePath))
{
using (var stream = new MemoryStream(pictureBinary))
{
Bitmap b = null;
try
{
//try-catch to ensure that picture binary is really OK. Otherwise, we can get "Parameter is not valid" exception if binary is corrupted for some reasons
b = new Bitmap(stream);
}
catch (ArgumentException exc)
{
_logger.Error(string.Format("Error generating picture thumb. ID={0}", picture.Id), exc);
}
if (b == null)
{
//bitmap could not be loaded for some reasons
return url;
}
var newSize = CalculateDimensions(b.Size, targetSize);
var destStream = new MemoryStream();
ImageBuilder.Current.Build(b, destStream, new ResizeSettings()
{
Width = newSize.Width,
Height = newSize.Height,
Scale = ScaleMode.Both,
Quality = _mediaSettings.DefaultImageQuality
});
var destBinary = destStream.ToArray();
File.WriteAllBytes(thumbFilePath, destBinary);
b.Dispose();
}
}
}
}
url = GetThumbUrl(thumbFileName, storeLocation);
return url;
}
/// <summary>
/// Get a picture local path
/// </summary>
/// <param name="picture">Picture instance</param>
/// <param name="targetSize">The target picture size (longest side)</param>
/// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
/// <returns></returns>
public virtual string GetThumbLocalPath(Picture picture, int targetSize = 0, bool showDefaultPicture = true)
{
string url = GetPictureUrl(picture, targetSize, showDefaultPicture);
if(String.IsNullOrEmpty(url))
return String.Empty;
else
return GetThumbLocalPath(Path.GetFileName(url));
}
#endregion
#region CRUD methods
/// <summary>
/// Gets a picture
/// </summary>
/// <param name="pictureId">Picture identifier</param>
/// <returns>Picture</returns>
public virtual Picture GetPictureById(int pictureId)
{
if (pictureId == 0)
return null;
return _pictureRepository.GetById(pictureId);
}
/// <summary>
/// Deletes a picture
/// </summary>
/// <param name="picture">Picture</param>
public virtual void DeletePicture(Picture picture)
{
if (picture == null)
throw new ArgumentNullException("picture");
//delete thumbs
DeletePictureThumbs(picture);
//delete from file system
if (!this.StoreInDb)
DeletePictureOnFileSystem(picture);
//delete from database
_pictureRepository.Delete(picture);
//event notification
_eventPublisher.EntityDeleted(picture);
}
/// <summary>
/// Gets a collection of pictures
/// </summary>
/// <param name="pageIndex">Current page</param>
/// <param name="pageSize">Items on each page</param>
/// <returns>Paged list of pictures</returns>
public virtual IPagedList<Picture> GetPictures(int pageIndex, int pageSize)
{
var query = from p in _pictureRepository.Table
orderby p.Id descending
select p;
var pics = new PagedList<Picture>(query, pageIndex, pageSize);
return pics;
}
/// <summary>
/// Gets pictures by product identifier
/// </summary>
/// <param name="productId">Product identifier</param>
/// <param name="recordsToReturn">Number of records to return. 0 if you want to get all items</param>
/// <returns>Pictures</returns>
public virtual IList<Picture> GetPicturesByProductId(int productId, int recordsToReturn = 0)
{
if (productId == 0)
return new List<Picture>();
var query = from p in _pictureRepository.Table
join pp in _productPictureRepository.Table on p.Id equals pp.PictureId
orderby pp.DisplayOrder
where pp.ProductId == productId
select p;
if (recordsToReturn > 0)
query = query.Take(recordsToReturn);
var pics = query.ToList();
return pics;
}
/// <summary>
/// Inserts a picture
/// </summary>
/// <param name="pictureBinary">The picture binary</param>
/// <param name="mimeType">The picture MIME type</param>
/// <param name="seoFilename">The SEO filename</param>
/// <param name="isNew">A value indicating whether the picture is new</param>
/// <param name="validateBinary">A value indicating whether to validated provided picture binary</param>
/// <returns>Picture</returns>
public virtual Picture InsertPicture(byte[] pictureBinary, string mimeType, string seoFilename,
bool isNew, bool validateBinary = true)
{
mimeType = CommonHelper.EnsureNotNull(mimeType);
mimeType = CommonHelper.EnsureMaximumLength(mimeType, 20);
seoFilename = CommonHelper.EnsureMaximumLength(seoFilename, 100);
if (validateBinary)
pictureBinary = ValidatePicture(pictureBinary, mimeType);
var picture = new Picture()
{
PictureBinary = this.StoreInDb ? pictureBinary : new byte[0],
MimeType = mimeType,
SeoFilename = seoFilename,
IsNew = isNew,
};
_pictureRepository.Insert(picture);
if(!this.StoreInDb)
SavePictureInFile(picture.Id, pictureBinary, mimeType);
//event notification
_eventPublisher.EntityInserted(picture);
return picture;
}
/// <summary>
/// Updates the picture
/// </summary>
/// <param name="pictureId">The picture identifier</param>
/// <param name="pictureBinary">The picture binary</param>
/// <param name="mimeType">The picture MIME type</param>
/// <param name="seoFilename">The SEO filename</param>
/// <param name="isNew">A value indicating whether the picture is new</param>
/// <param name="validateBinary">A value indicating whether to validated provided picture binary</param>
/// <returns>Picture</returns>
public virtual Picture UpdatePicture(int pictureId, byte[] pictureBinary, string mimeType,
string seoFilename, bool isNew, bool validateBinary = true)
{
mimeType = CommonHelper.EnsureNotNull(mimeType);
mimeType = CommonHelper.EnsureMaximumLength(mimeType, 20);
seoFilename = CommonHelper.EnsureMaximumLength(seoFilename, 100);
if (validateBinary)
pictureBinary = ValidatePicture(pictureBinary, mimeType);
var picture = GetPictureById(pictureId);
if (picture == null)
return null;
//delete old thumbs if a picture has been changed
if (seoFilename != picture.SeoFilename)
DeletePictureThumbs(picture);
picture.PictureBinary = (this.StoreInDb ? pictureBinary : new byte[0]);
picture.MimeType = mimeType;
picture.SeoFilename = seoFilename;
picture.IsNew = isNew;
_pictureRepository.Update(picture);
if(!this.StoreInDb)
SavePictureInFile(picture.Id, pictureBinary, mimeType);
//event notification
_eventPublisher.EntityUpdated(picture);
return picture;
}
/// <summary>
/// Updates a SEO filename of a picture
/// </summary>
/// <param name="pictureId">The picture identifier</param>
/// <param name="seoFilename">The SEO filename</param>
/// <returns>Picture</returns>
public virtual Picture SetSeoFilename(int pictureId, string seoFilename)
{
var picture = GetPictureById(pictureId);
if (picture == null)
throw new ArgumentException("No picture found with the specified id");
//update if it has been changed
if (seoFilename != picture.SeoFilename)
{
//update picture
picture = UpdatePicture(picture.Id, LoadPictureBinary(picture), picture.MimeType, seoFilename, true, false);
}
return picture;
}
/// <summary>
/// Validates input picture dimensions
/// </summary>
/// <param name="pictureBinary">Picture binary</param>
/// <param name="mimeType">MIME type</param>
/// <returns>Picture binary or throws an exception</returns>
public virtual byte[] ValidatePicture(byte[] pictureBinary, string mimeType)
{
var destStream = new MemoryStream();
ImageBuilder.Current.Build(pictureBinary, destStream, new ResizeSettings()
{
MaxWidth = _mediaSettings.MaximumImageSize,
MaxHeight = _mediaSettings.MaximumImageSize,
Quality = _mediaSettings.DefaultImageQuality
});
return destStream.ToArray();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets a value indicating whether the images should be stored in data base.
/// </summary>
public virtual bool StoreInDb
{
get
{
return _settingService.GetSettingByKey<bool>("Media.Images.StoreInDB", true);
}
set
{
//check whether it's a new value
if (this.StoreInDb != value)
{
//save the new setting value
_settingService.SetSetting<bool>("Media.Images.StoreInDB", value);
//update all picture objects
var pictures = this.GetPictures(0, int.MaxValue);
foreach (var picture in pictures)
{
var pictureBinary = LoadPictureBinary(picture, !value);
//delete from file system
if (value)
DeletePictureOnFileSystem(picture);
//just update a picture (all required logic is in UpdatePicture method)
UpdatePicture(picture.Id,
pictureBinary,
picture.MimeType,
picture.SeoFilename,
true,
false);
//we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown when "moving" pictures
}
}
}
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using NationalInstruments.UI.WindowsForms;
using NationalInstruments.UI;
using RRLab.PhysiologyWorkbench.Data;
namespace RRLab.PhysiologyWorkbench
{
public partial class RecordingViewer : UserControl
{
public event EventHandler RecordingChanged;
private Recording _Recording;
public Recording Recording
{
get { return _Recording; }
set {
//if (Recording != null) Recording.Updated -= new EventHandler(OnRecordingUpdated);
_Recording = value;
if (Recording != null) RecordingBindingSource.DataSource = Recording;
else RecordingBindingSource.DataSource = typeof(Recording);
//if (Recording != null) Recording.Updated += new EventHandler(OnRecordingUpdated);
if (!Disposing)
{
UpdateRecordingView();
if (RecordingChanged != null) RecordingChanged(this, EventArgs.Empty);
}
}
}
public event EventHandler IsLegendVisibleChanged;
private bool _IsLegendVisible = true;
[DefaultValue(true)]
public bool IsLegendVisible
{
get { return _IsLegendVisible; }
set
{
_IsLegendVisible = value;
UpdateViewStyle();
if (IsLegendVisibleChanged != null) IsLegendVisibleChanged(this, EventArgs.Empty);
}
}
public event EventHandler IsTitleVisibleChanged;
private bool _IsTitleVisible = true;
[DefaultValue(true)]
public bool IsTitleVisible
{
get { return _IsTitleVisible; }
set
{
_IsTitleVisible = value;
UpdateViewStyle();
if (IsTitleVisibleChanged != null) IsTitleVisibleChanged(this, EventArgs.Empty);
}
}
public event EventHandler IsSidebarHiddenChanged;
private bool _IsSidebarHidden = false;
[DefaultValue(false)]
public bool IsSidebarHidden {
get {
return _IsSidebarHidden;
}
set {
_IsSidebarHidden = value;
UpdateViewStyle();
if (IsSidebarHiddenChanged != null) IsSidebarHiddenChanged(this, EventArgs.Empty);
}
}
public event EventHandler VoltageAxisScalingChanged;
private AutoAxisMode _VoltageAxisScaling = AutoAxisMode.DynamicRange;
public AutoAxisMode VoltageAxisScaling
{
get { return _VoltageAxisScaling; }
set
{
bool needsUpdate = (_VoltageAxisScaling != value);
_VoltageAxisScaling = value;
if(needsUpdate) UpdateVoltageAxisScaling();
if (VoltageAxisScalingChanged != null) VoltageAxisScalingChanged(this, EventArgs.Empty);
}
}
public event EventHandler CurrentAxisScalingChanged;
private AutoAxisMode _CurrentAxisScaling = AutoAxisMode.DynamicRange;
public AutoAxisMode CurrentAxisScaling
{
get { return _CurrentAxisScaling; }
set
{
bool needsUpdate = (_CurrentAxisScaling != value);
_CurrentAxisScaling = value;
if(needsUpdate) UpdateCurrentAxisScaling();
if (CurrentAxisScalingChanged != null) CurrentAxisScalingChanged(this, EventArgs.Empty);
}
}
public Range VoltageAxisRange
{
get { return VoltageAxis.Range; }
set {
VoltageAxis.Range = value;
}
}
public Range CurrentAxisRange
{
get { return CurrentAxis.Range; }
set
{
CurrentAxis.Range = value;
}
}
public event EventHandler CurrentMinDaqVoltageChanged;
private double _CurrentMinDaqVoltage = -10;
public double CurrentMinDaqVoltage
{
get { return _CurrentMinDaqVoltage; }
set {
_CurrentMinDaqVoltage = value;
if (InvokeRequired)
Invoke(new System.Threading.ThreadStart(delegate()
{
CurrentAxisRange = new Range(CurrentMinDaqVoltage, CurrentAxisRange.Maximum);
}));
if (CurrentMinDaqVoltageChanged != null) CurrentMinDaqVoltageChanged(this, EventArgs.Empty);
}
}
public event EventHandler CurrentMaxDaqVoltageChanged;
private double _CurrentMaxDaqVoltage = 10;
public double CurrentMaxDaqVoltage
{
get { return _CurrentMaxDaqVoltage; }
set {
_CurrentMaxDaqVoltage = value;
if (InvokeRequired)
Invoke(new System.Threading.ThreadStart(delegate()
{
CurrentAxisRange = new Range(CurrentAxisRange.Minimum, CurrentMaxDaqVoltage);
}));
if (CurrentMaxDaqVoltageChanged != null) CurrentMaxDaqVoltageChanged(this, EventArgs.Empty);
}
}
public event EventHandler VoltageMinDaqVoltageChanged;
private double _VoltageMinDaqVoltage = -10;
public double VoltageMinDaqVoltage
{
get { return _VoltageMinDaqVoltage; }
set {
_VoltageMinDaqVoltage = value;
if (InvokeRequired)
Invoke(new System.Threading.ThreadStart(delegate()
{
VoltageAxisRange = new Range(VoltageMinDaqVoltage, VoltageAxisRange.Maximum);
}));
if (VoltageMinDaqVoltageChanged != null) VoltageMinDaqVoltageChanged(this, EventArgs.Empty);
}
}
public event EventHandler VoltageMaxDaqVoltageChanged;
private double _VoltageMaxDaqVoltage = 10;
public double VoltageMaxDaqVoltage
{
get { return _VoltageMaxDaqVoltage; }
set {
_VoltageMaxDaqVoltage = value;
if(InvokeRequired)
Invoke(new System.Threading.ThreadStart(delegate() {
VoltageAxisRange = new Range(VoltageAxisRange.Minimum, VoltageMaxDaqVoltage);
}));
if (VoltageMaxDaqVoltageChanged != null) VoltageMaxDaqVoltageChanged(this, EventArgs.Empty);
}
}
private SortedList<string, ScatterPlot> _Plots = new SortedList<string, ScatterPlot>();
protected IDictionary<string, ScatterPlot> Plots
{
get { return _Plots; }
set { _Plots = new SortedList<string,ScatterPlot>(value); }
}
public RecordingViewer()
{
InitializeComponent();
RecordingViewerBindingSource.DataSource = this;
RegisterEventListeners();
}
protected virtual void RegisterEventListeners()
{
CurrentAxis.RangeChanged += new EventHandler(OnCurrentAxisRangeChanged);
VoltageAxis.RangeChanged += new EventHandler(OnVoltageAxisRangeChanged);
}
protected virtual void UpdateRecordingView()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(UpdateRecordingView));
return;
}
if (Recording == null)
{
Enabled = false;
return;
}
Enabled = true;
Title.Text = Recording.Title;
UpdateAvailableDataListBox();
DetermineDataToShow();
CreatePlots();
UpdateGraph();
UpdateCurrentAxisScaling();
UpdateVoltageAxisScaling();
UpdateAmplifierData();
}
private void OnHideButtonClicked(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnHideButtonClicked), sender, e);
return;
}
IsSidebarHidden = !IsSidebarHidden;
}
private void OnRecordingUpdated(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnRecordingUpdated), sender, e);
return;
}
UpdateRecordingView();
}
protected virtual void UpdateAvailableDataListBox()
{
ChannelsCheckListBox.Items.Clear();
if (Recording == null) return;
foreach (string s in Recording.Data.Keys)
{
ChannelsCheckListBox.Items.Add(s, true);
}
}
protected virtual void DetermineDataToShow()
{
if (Recording != null && Recording.MetaData.ContainsKey("DataToShow"))
{
List<string> dataToShow = new List<string>(Recording.MetaData["DataToShow"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
for (int i = 0; i < ChannelsCheckListBox.Items.Count; i++)
ChannelsCheckListBox.SetItemChecked(i, dataToShow.Contains(ChannelsCheckListBox.Items[i].ToString()));
}
}
protected virtual void UpdateGraph()
{
Graph.Plots.Clear();
List<ScatterPlot> plotsToShow = new List<ScatterPlot>(Plots.Values);
Graph.Plots.AddRange(plotsToShow.ToArray());
}
protected virtual void CreatePlots()
{
CurrentLineColorIndex = 0;
Plots.Clear();
Legend.Items.Clear();
foreach (object o in ChannelsCheckListBox.CheckedItems)
{
string key = o.ToString();
YAxis yaxis = VoltageAxis;
if (ShowOnCurrentAxis(key)) yaxis = CurrentAxis;
ScatterPlot plot = new ScatterPlot(TimeAxis, yaxis);
if (Recording != null)
{
TimeResolvedData points = Recording.Data[key];
plot.PlotXY(Array.ConvertAll<float,double>(points.Time,
new Converter<float,double>(delegate(float input) { return (double) input; }))
,points.Values);
}
plot.LineColor = NextLineColor();
Plots.Add(key, plot);
Legend.Items.Add(new LegendItem(Plots[key], key));
}
}
protected virtual void UpdatePlotsData()
{
foreach (object o in ChannelsCheckListBox.CheckedItems)
{
string key = o.ToString();
Plots[key].ClearData();
if (Recording != null)
{
TimeResolvedData points = Recording.Data[key];
Plots[key].PlotXY(Array.ConvertAll<float,double>(points.Time,new Converter<float,double>(delegate(float target) { return (double) target; })),
points.Values);
}
}
}
protected int CurrentLineColorIndex = 0;
protected Color[] LineColors = new Color[] { Color.Yellow, Color.White, Color.Pink, Color.LawnGreen };
protected virtual Color NextLineColor()
{
if (CurrentLineColorIndex >= LineColors.Length) CurrentLineColorIndex = 0;
return LineColors[CurrentLineColorIndex++];
}
protected virtual bool ShowOnCurrentAxis(string key)
{
if (key == "Current") return true;
else return false;
}
protected virtual void UpdateAmplifierData()
{
// Update the amplifer settings boxes
if (Recording.EquipmentSettings.ContainsKey("AmplifierCapacitanceCorrection"))
this.CapacTextbox.Text = Recording.EquipmentSettings["AmplifierCapacitanceCorrection"];
else
this.CapacTextbox.Text = "";
if (Recording.EquipmentSettings.ContainsKey("AmplifierGain"))
this.GainTextbox.Text = Recording.EquipmentSettings["AmplifierGain"];
else
this.GainTextbox.Text = "";
}
public virtual void Clear()
{
foreach (ScatterPlot p in Plots.Values) p.ClearData();
ChannelsCheckListBox.Items.Clear();
}
protected virtual void OnCurrentAxisRangeChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnCurrentAxisRangeChanged), sender, e);
return;
}
CurrentMinTextBox.Text = CurrentAxis.Range.Minimum.ToString();
CurrentMaxTextBox.Text = CurrentAxis.Range.Maximum.ToString();
}
protected virtual void OnVoltageAxisRangeChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnVoltageAxisRangeChanged), sender, e);
return;
}
VoltageMinTextBox.Text = VoltageAxis.Range.Minimum.ToString();
VoltageMaxTextBox.Text = VoltageAxis.Range.Maximum.ToString();
}
protected virtual void SetCurrentAxisFixed()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(SetCurrentAxisFixed));
return;
}
if (CurrentAxisModeComboBox.SelectedIndex != (int)AutoAxisMode.Fixed) CurrentAxisModeComboBox.SelectedIndex = (int)AutoAxisMode.Fixed;
CurrentMinTextBox.ReadOnly = false;
CurrentMinTextBox.Enabled = true;
CurrentMaxTextBox.ReadOnly = false;
CurrentMaxTextBox.Enabled = true;
if(CurrentAxis.Mode != AxisMode.Fixed) CurrentAxis.Mode = AxisMode.Fixed;
try
{
double minCurrent, maxCurrent;
if (CurrentMinTextBox.Text == "") minCurrent = -1;
else minCurrent = Double.Parse(CurrentMinTextBox.Text);
if (CurrentMaxTextBox.Text == "") maxCurrent = 1;
else maxCurrent = Double.Parse(CurrentMaxTextBox.Text);
CurrentAxis.Range = new Range(minCurrent, maxCurrent);
}
catch (Exception x)
{
;
}
}
protected virtual void SetCurrentAxisData()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(SetCurrentAxisData));
return;
}
if (CurrentAxisModeComboBox.SelectedIndex != (int)AutoAxisMode.Data) CurrentAxisModeComboBox.SelectedIndex = (int)AutoAxisMode.Data;
CurrentMinTextBox.ReadOnly = true;
CurrentMinTextBox.Enabled = false;
CurrentMaxTextBox.ReadOnly = true;
CurrentMaxTextBox.Enabled = false;
if (CurrentAxis.Mode != AxisMode.AutoScaleLoose) CurrentAxis.Mode = AxisMode.AutoScaleLoose;
}
protected virtual void SetCurrentAxisDynamicRange()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(SetCurrentAxisDynamicRange));
return;
}
// If the dynamic range information is not available, use autoscaling
if ((Recording == null) || (Recording.EquipmentSettings.ContainsKey("AmplifierGain")))
{
CurrentAxisScaling = AutoAxisMode.Data;
return;
}
try {
if (CurrentAxisModeComboBox.SelectedIndex != (int)AutoAxisMode.DynamicRange) CurrentAxisModeComboBox.SelectedIndex = (int)AutoAxisMode.DynamicRange;
CurrentMinTextBox.ReadOnly = true;
CurrentMinTextBox.Enabled = false;
CurrentMaxTextBox.ReadOnly = true;
CurrentMaxTextBox.Enabled = false;
if (CurrentAxis.Mode != AxisMode.Fixed) CurrentAxis.Mode = AxisMode.Fixed;
double gain = 1000/Double.Parse(Recording.EquipmentSettings["AmplifierGain"]); // gain is in pA/V
double min = CurrentMinDaqVoltage*gain;
double max = CurrentMaxDaqVoltage*gain;
CurrentAxis.Range = new Range(min, max);
} catch(Exception e) {
CurrentAxisScaling = AutoAxisMode.Data; // If a problem happens, autoscale the data
}
}
protected virtual void SetVoltageAxisFixed()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(SetVoltageAxisFixed));
return;
}
if (VoltageAxisModeComboBox.SelectedIndex != (int)AutoAxisMode.Fixed) VoltageAxisModeComboBox.SelectedIndex = (int)AutoAxisMode.Fixed;
VoltageMinTextBox.ReadOnly = false;
VoltageMinTextBox.Enabled = true;
VoltageMaxTextBox.ReadOnly = false;
VoltageMaxTextBox.Enabled = true;
if (VoltageAxis.Mode != AxisMode.Fixed) VoltageAxis.Mode = AxisMode.Fixed;
try
{
double minVoltage = Double.Parse(VoltageMinTextBox.Text);
double maxVoltage = Double.Parse(VoltageMaxTextBox.Text);
VoltageAxis.Range = new Range(minVoltage, maxVoltage);
}
catch (Exception x)
{
;
}
}
protected virtual void SetVoltageAxisData()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(SetVoltageAxisData));
return;
}
if (VoltageAxisModeComboBox.SelectedIndex != (int)AutoAxisMode.Data) VoltageAxisModeComboBox.SelectedIndex = (int)AutoAxisMode.Data;
VoltageMinTextBox.ReadOnly = true;
VoltageMinTextBox.Enabled = false;
VoltageMaxTextBox.ReadOnly = true;
VoltageMaxTextBox.Enabled = false;
if (VoltageAxis.Mode != AxisMode.AutoScaleLoose) VoltageAxis.Mode = AxisMode.AutoScaleLoose;
}
protected virtual void SetVoltageAxisDynamicRange()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(SetVoltageAxisDynamicRange));
return;
}
if (VoltageAxisModeComboBox.SelectedIndex != (int)AutoAxisMode.DynamicRange) VoltageAxisModeComboBox.SelectedIndex = (int)AutoAxisMode.DynamicRange;
VoltageMinTextBox.ReadOnly = true;
VoltageMinTextBox.Enabled = false;
VoltageMaxTextBox.ReadOnly = true;
VoltageMaxTextBox.Enabled = false;
if (VoltageAxis.Mode != AxisMode.Fixed) VoltageAxis.Mode = AxisMode.Fixed;
VoltageAxis.Range = new Range(VoltageMinDaqVoltage, VoltageMaxDaqVoltage);
}
protected virtual void UpdateViewStyle()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(UpdateViewStyle));
return;
}
Title.Visible = IsTitleVisible;
Legend.Visible = IsLegendVisible;
if (!IsSidebarHidden)
{
HideButton.Text = "Hide >>>";
HideablePanel.Visible = true;
SidebarPanel.MinimumSize = new Size(180, 0);
}
else
{
HideButton.Text = "<<<";
HideablePanel.Visible = false;
SidebarPanel.MinimumSize = new Size(50, 0);
}
}
protected virtual void UpdateCurrentAxisScaling()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(UpdateCurrentAxisScaling));
return;
}
switch (CurrentAxisScaling)
{
case AutoAxisMode.Fixed:
SetCurrentAxisFixed();
break;
case AutoAxisMode.Data:
SetCurrentAxisData();
break;
case AutoAxisMode.DynamicRange:
SetCurrentAxisDynamicRange();
break;
}
}
protected virtual void UpdateVoltageAxisScaling()
{
if (InvokeRequired)
{
Invoke(new System.Threading.ThreadStart(UpdateVoltageAxisScaling));
return;
}
switch (VoltageAxisScaling)
{
case AutoAxisMode.Fixed:
SetVoltageAxisFixed();
break;
case AutoAxisMode.Data:
SetVoltageAxisData();
break;
case AutoAxisMode.DynamicRange:
SetVoltageAxisDynamicRange();
break;
}
}
private void OnCurrentRecordingChanged(object sender, EventArgs e)
{
UpdateRecordingView();
}
private void OnCurrentAxisModeComboBoxSelectionChanged(object sender, EventArgs e)
{
CurrentAxisScaling = (AutoAxisMode)CurrentAxisModeComboBox.SelectedIndex;
}
private void OnVoltageAxisModeComboBoxSelectionChanged(object sender, EventArgs e)
{
VoltageAxisScaling = (AutoAxisMode)VoltageAxisModeComboBox.SelectedIndex;
}
protected virtual void OnCheckedChannelsChanged(object sender, EventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler(OnCheckedChannelsChanged), sender, e);
return;
}
CreatePlots();
UpdateGraph();
// if(Recording != null) Recording.SetMetaData("DataToShow",...);
}
private void OnShowTitleClicked(object sender, EventArgs e)
{
Invoke(new System.Threading.ThreadStart(delegate()
{
this.IsTitleVisible = ShowTitleMenuItem.Checked;
}));
}
private void OnShowLegendClicked(object sender, EventArgs e)
{
Invoke(new System.Threading.ThreadStart(delegate()
{
this.IsLegendVisible = ShowLegendMenuItem.Checked;
}));
}
}
public enum AutoAxisMode { Fixed, Data, DynamicRange };
}
| |
//
// field.cs: All field handlers
//
// Authors: Miguel de Icaza (miguel@gnu.org)
// Martin Baulig (martin@ximian.com)
// Marek Safar (marek.safar@seznam.cz)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
// Copyright 2004-2008 Novell, Inc
//
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
#if STATIC
using MetaType = IKVM.Reflection.Type;
using IKVM.Reflection;
using IKVM.Reflection.Emit;
#else
using MetaType = System.Type;
using System.Reflection;
using System.Reflection.Emit;
#endif
namespace Mono.CSharp
{
public class FieldDeclarator
{
public FieldDeclarator (SimpleMemberName name, Expression initializer)
{
this.Name = name;
this.Initializer = initializer;
}
#region Properties
public SimpleMemberName Name { get; private set; }
public Expression Initializer { get; private set; }
#endregion
}
//
// Abstract class for all fields
//
abstract public class FieldBase : MemberBase
{
protected FieldBuilder FieldBuilder;
protected FieldSpec spec;
public Status status;
protected Expression initializer;
protected List<FieldDeclarator> declarators;
[Flags]
public enum Status : byte {
HAS_OFFSET = 4 // Used by FieldMember.
}
static readonly string[] attribute_targets = new string [] { "field" };
protected FieldBase (DeclSpace parent, FullNamedExpression type, Modifiers mod,
Modifiers allowed_mod, MemberName name, Attributes attrs)
: base (parent, null, type, mod, allowed_mod | Modifiers.ABSTRACT, Modifiers.PRIVATE,
name, attrs)
{
if ((mod & Modifiers.ABSTRACT) != 0)
Report.Error (681, Location, "The modifier 'abstract' is not valid on fields. Try using a property instead");
}
#region Properties
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Field;
}
}
public Expression Initializer {
get {
return initializer;
}
set {
this.initializer = value;
}
}
public FieldSpec Spec {
get {
return spec;
}
}
public override string[] ValidAttributeTargets {
get {
return attribute_targets;
}
}
#endregion
public void AddDeclarator (FieldDeclarator declarator)
{
if (declarators == null)
declarators = new List<FieldDeclarator> (2);
declarators.Add (declarator);
// TODO: This will probably break
Parent.AddMember (this, declarator.Name.Value);
}
public override void ApplyAttributeBuilder (Attribute a, MethodSpec ctor, byte[] cdata, PredefinedAttributes pa)
{
if (a.Type == pa.FieldOffset) {
status |= Status.HAS_OFFSET;
if (!Parent.PartialContainer.HasExplicitLayout) {
Report.Error (636, Location, "The FieldOffset attribute can only be placed on members of types marked with the StructLayout(LayoutKind.Explicit)");
return;
}
if ((ModFlags & Modifiers.STATIC) != 0 || this is Const) {
Report.Error (637, Location, "The FieldOffset attribute is not allowed on static or const fields");
return;
}
}
if (a.Type == pa.FixedBuffer) {
Report.Error (1716, Location, "Do not use 'System.Runtime.CompilerServices.FixedBuffer' attribute. Use the 'fixed' field modifier instead");
return;
}
#if false
if (a.Type == pa.MarshalAs) {
UnmanagedMarshal marshal = a.GetMarshal (this);
if (marshal != null) {
FieldBuilder.SetMarshal (marshal);
}
return;
}
#endif
if ((a.HasSecurityAttribute)) {
a.Error_InvalidSecurityParent ();
return;
}
if (a.Type == pa.Dynamic) {
a.Error_MisusedDynamicAttribute ();
return;
}
FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), cdata);
}
public void SetCustomAttribute (MethodSpec ctor, byte[] data)
{
FieldBuilder.SetCustomAttribute ((ConstructorInfo) ctor.GetMetaInfo (), data);
}
protected override bool CheckBase ()
{
if (!base.CheckBase ())
return false;
MemberSpec candidate;
var conflict_symbol = MemberCache.FindBaseMember (this, out candidate);
if (conflict_symbol == null)
conflict_symbol = candidate;
if (conflict_symbol == null) {
if ((ModFlags & Modifiers.NEW) != 0) {
Report.Warning (109, 4, Location, "The member `{0}' does not hide an inherited member. The new keyword is not required",
GetSignatureForError ());
}
} else {
if ((ModFlags & (Modifiers.NEW | Modifiers.OVERRIDE | Modifiers.BACKING_FIELD)) == 0) {
Report.SymbolRelatedToPreviousError (conflict_symbol);
Report.Warning (108, 2, Location, "`{0}' hides inherited member `{1}'. Use the new keyword if hiding was intended",
GetSignatureForError (), conflict_symbol.GetSignatureForError ());
}
if (conflict_symbol.IsAbstract) {
Report.SymbolRelatedToPreviousError (conflict_symbol);
Report.Error (533, Location, "`{0}' hides inherited abstract member `{1}'",
GetSignatureForError (), conflict_symbol.GetSignatureForError ());
}
}
return true;
}
public virtual Constant ConvertInitializer (ResolveContext rc, Constant expr)
{
return expr.ConvertImplicitly (rc, MemberType);
}
protected override void DoMemberTypeDependentChecks ()
{
base.DoMemberTypeDependentChecks ();
if (MemberType.IsGenericParameter)
return;
if (MemberType.IsStatic)
Error_VariableOfStaticClass (Location, GetSignatureForError (), MemberType, Report);
CheckBase ();
IsTypePermitted ();
}
//
// Represents header string for documentation comment.
//
public override string DocCommentHeader {
get { return "F:"; }
}
public override void Emit ()
{
if (member_type == InternalType.Dynamic) {
Module.PredefinedAttributes.Dynamic.EmitAttribute (FieldBuilder);
} else if (!(Parent is CompilerGeneratedClass) && member_type.HasDynamicElement) {
Module.PredefinedAttributes.Dynamic.EmitAttribute (FieldBuilder, member_type, Location);
}
if ((ModFlags & Modifiers.COMPILER_GENERATED) != 0 && !Parent.IsCompilerGenerated)
Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (FieldBuilder);
if (OptAttributes != null) {
OptAttributes.Emit ();
}
if (((status & Status.HAS_OFFSET) == 0) && (ModFlags & (Modifiers.STATIC | Modifiers.BACKING_FIELD)) == 0 && Parent.PartialContainer.HasExplicitLayout) {
Report.Error (625, Location, "`{0}': Instance field types marked with StructLayout(LayoutKind.Explicit) must have a FieldOffset attribute", GetSignatureForError ());
}
base.Emit ();
}
public static void Error_VariableOfStaticClass (Location loc, string variable_name, TypeSpec static_class, Report Report)
{
Report.SymbolRelatedToPreviousError (static_class);
Report.Error (723, loc, "`{0}': cannot declare variables of static types",
variable_name);
}
protected override bool VerifyClsCompliance ()
{
if (!base.VerifyClsCompliance ())
return false;
if (!MemberType.IsCLSCompliant () || this is FixedField) {
Report.Warning (3003, 1, Location, "Type of `{0}' is not CLS-compliant",
GetSignatureForError ());
}
return true;
}
}
//
// Field specification
//
public class FieldSpec : MemberSpec, IInterfaceMemberSpec
{
FieldInfo metaInfo;
TypeSpec memberType;
public FieldSpec (TypeSpec declaringType, IMemberDefinition definition, TypeSpec memberType, FieldInfo info, Modifiers modifiers)
: base (MemberKind.Field, declaringType, definition, modifiers)
{
this.metaInfo = info;
this.memberType = memberType;
}
#region Properties
public bool IsReadOnly {
get {
return (Modifiers & Modifiers.READONLY) != 0;
}
}
public TypeSpec MemberType {
get {
return memberType;
}
}
#endregion
public FieldInfo GetMetaInfo ()
{
if ((state & StateFlags.PendingMetaInflate) != 0) {
var decl_meta = DeclaringType.GetMetaInfo ();
if (DeclaringType.IsTypeBuilder) {
metaInfo = TypeBuilder.GetField (decl_meta, metaInfo);
} else {
var orig_token = metaInfo.MetadataToken;
metaInfo = decl_meta.GetField (Name, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
if (metaInfo.MetadataToken != orig_token)
throw new NotImplementedException ("Resolved to wrong meta token");
// What a stupid API, does not work because field handle is imported
// metaInfo = FieldInfo.GetFieldFromHandle (metaInfo.FieldHandle, DeclaringType.MetaInfo.TypeHandle);
}
state &= ~StateFlags.PendingMetaInflate;
}
return metaInfo;
}
public override MemberSpec InflateMember (TypeParameterInflator inflator)
{
var fs = (FieldSpec) base.InflateMember (inflator);
fs.memberType = inflator.Inflate (memberType);
return fs;
}
public FieldSpec Mutate (TypeParameterMutator mutator)
{
var decl = DeclaringType;
if (DeclaringType.IsGenericOrParentIsGeneric)
decl = mutator.Mutate (decl);
if (decl == DeclaringType)
return this;
var fs = (FieldSpec) MemberwiseClone ();
fs.declaringType = decl;
fs.state |= StateFlags.PendingMetaInflate;
// Gets back FieldInfo in case of metaInfo was inflated
fs.metaInfo = MemberCache.GetMember (TypeParameterMutator.GetMemberDeclaringType (DeclaringType), this).metaInfo;
return fs;
}
public override List<TypeSpec> ResolveMissingDependencies ()
{
return memberType.ResolveMissingDependencies ();
}
}
/// <summary>
/// Fixed buffer implementation
/// </summary>
public class FixedField : FieldBase
{
public const string FixedElementName = "FixedElementField";
static int GlobalCounter = 0;
TypeBuilder fixed_buffer_type;
const Modifiers AllowedModifiers =
Modifiers.NEW |
Modifiers.PUBLIC |
Modifiers.PROTECTED |
Modifiers.INTERNAL |
Modifiers.PRIVATE |
Modifiers.UNSAFE;
public FixedField (DeclSpace parent, FullNamedExpression type, Modifiers mod, MemberName name, Attributes attrs)
: base (parent, type, mod, AllowedModifiers, name, attrs)
{
}
#region Properties
//
// Explicit struct layout set by parent
//
public CharSet? CharSet {
get; set;
}
#endregion
public override Constant ConvertInitializer (ResolveContext rc, Constant expr)
{
return expr.ImplicitConversionRequired (rc, TypeManager.int32_type, Location);
}
public override bool Define ()
{
if (!base.Define ())
return false;
if (!TypeManager.IsPrimitiveType (MemberType)) {
Report.Error (1663, Location,
"`{0}': Fixed size buffers type must be one of the following: bool, byte, short, int, long, char, sbyte, ushort, uint, ulong, float or double",
GetSignatureForError ());
} else if (declarators != null) {
var t = new TypeExpression (MemberType, TypeExpression.Location);
int index = Parent.PartialContainer.Fields.IndexOf (this);
foreach (var d in declarators) {
var f = new FixedField (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
f.initializer = d.Initializer;
((ConstInitializer) f.initializer).Name = d.Name.Value;
Parent.PartialContainer.Fields.Insert (++index, f);
}
}
// Create nested fixed buffer container
string name = String.Format ("<{0}>__FixedBuffer{1}", Name, GlobalCounter++);
fixed_buffer_type = Parent.TypeBuilder.DefineNestedType (name,
TypeAttributes.NestedPublic | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, TypeManager.value_type.GetMetaInfo ());
fixed_buffer_type.DefineField (FixedElementName, MemberType.GetMetaInfo (), FieldAttributes.Public);
FieldBuilder = Parent.TypeBuilder.DefineField (Name, fixed_buffer_type, ModifiersExtensions.FieldAttr (ModFlags));
var element_spec = new FieldSpec (null, this, MemberType, FieldBuilder, ModFlags);
spec = new FixedFieldSpec (Parent.Definition, this, FieldBuilder, element_spec, ModFlags);
Parent.MemberCache.AddMember (spec);
return true;
}
protected override void DoMemberTypeIndependentChecks ()
{
base.DoMemberTypeIndependentChecks ();
if (!IsUnsafe)
Expression.UnsafeError (Report, Location);
if (Parent.PartialContainer.Kind != MemberKind.Struct) {
Report.Error (1642, Location, "`{0}': Fixed size buffer fields may only be members of structs",
GetSignatureForError ());
}
}
public override void Emit()
{
ResolveContext rc = new ResolveContext (this);
IntConstant buffer_size_const = initializer.Resolve (rc) as IntConstant;
if (buffer_size_const == null)
return;
int buffer_size = buffer_size_const.Value;
if (buffer_size <= 0) {
Report.Error (1665, Location, "`{0}': Fixed size buffers must have a length greater than zero", GetSignatureForError ());
return;
}
int type_size = Expression.GetTypeSize (MemberType);
if (buffer_size > int.MaxValue / type_size) {
Report.Error (1664, Location, "Fixed size buffer `{0}' of length `{1}' and type `{2}' exceeded 2^31 limit",
GetSignatureForError (), buffer_size.ToString (), TypeManager.CSharpName (MemberType));
return;
}
EmitFieldSize (buffer_size);
#if STATIC
if (Module.HasDefaultCharSet)
fixed_buffer_type.__SetAttributes (fixed_buffer_type.Attributes | Module.DefaultCharSetType);
#endif
Module.PredefinedAttributes.UnsafeValueType.EmitAttribute (fixed_buffer_type);
Module.PredefinedAttributes.CompilerGenerated.EmitAttribute (fixed_buffer_type);
fixed_buffer_type.CreateType ();
base.Emit ();
}
void EmitFieldSize (int buffer_size)
{
PredefinedAttribute pa;
AttributeEncoder encoder;
pa = Module.PredefinedAttributes.StructLayout;
if (pa.Constructor == null && !pa.ResolveConstructor (Location, TypeManager.short_type))
return;
var char_set_type = Module.PredefinedTypes.CharSet.Resolve (Location);
if (char_set_type == null)
return;
var field_size = pa.GetField ("Size", TypeManager.int32_type, Location);
var field_charset = pa.GetField ("CharSet", char_set_type, Location);
if (field_size == null || field_charset == null)
return;
var char_set = CharSet ?? Module.DefaultCharSet ?? 0;
encoder = new AttributeEncoder ();
encoder.Encode ((short)LayoutKind.Sequential);
encoder.EncodeNamedArguments (
new [] { field_size, field_charset },
new Constant [] { new IntConstant (buffer_size, Location), new IntConstant ((int) char_set, Location) }
);
pa.EmitAttribute (fixed_buffer_type, encoder);
//
// Don't emit FixedBufferAttribute attribute for private types
//
if ((ModFlags & Modifiers.PRIVATE) != 0)
return;
pa = Module.PredefinedAttributes.FixedBuffer;
if (pa.Constructor == null && !pa.ResolveConstructor (Location, TypeManager.type_type, TypeManager.int32_type))
return;
encoder = new AttributeEncoder ();
encoder.EncodeTypeName (MemberType);
encoder.Encode (buffer_size);
encoder.EncodeEmptyNamedArguments ();
pa.EmitAttribute (FieldBuilder, encoder);
}
}
class FixedFieldSpec : FieldSpec
{
readonly FieldSpec element;
public FixedFieldSpec (TypeSpec declaringType, IMemberDefinition definition, FieldInfo info, FieldSpec element, Modifiers modifiers)
: base (declaringType, definition, element.MemberType, info, modifiers)
{
this.element = element;
// It's never CLS-Compliant
state &= ~StateFlags.CLSCompliant_Undetected;
}
public FieldSpec Element {
get {
return element;
}
}
public TypeSpec ElementType {
get {
return MemberType;
}
}
}
//
// The Field class is used to represents class/struct fields during parsing.
//
public class Field : FieldBase {
// <summary>
// Modifiers allowed in a class declaration
// </summary>
const Modifiers AllowedModifiers =
Modifiers.NEW |
Modifiers.PUBLIC |
Modifiers.PROTECTED |
Modifiers.INTERNAL |
Modifiers.PRIVATE |
Modifiers.STATIC |
Modifiers.VOLATILE |
Modifiers.UNSAFE |
Modifiers.READONLY;
public Field (DeclSpace parent, FullNamedExpression type, Modifiers mod, MemberName name,
Attributes attrs)
: base (parent, type, mod, AllowedModifiers, name, attrs)
{
}
bool CanBeVolatile ()
{
if (TypeManager.IsReferenceType (MemberType))
return true;
if (MemberType == TypeManager.bool_type || MemberType == TypeManager.char_type ||
MemberType == TypeManager.sbyte_type || MemberType == TypeManager.byte_type ||
MemberType == TypeManager.short_type || MemberType == TypeManager.ushort_type ||
MemberType == TypeManager.int32_type || MemberType == TypeManager.uint32_type ||
MemberType == TypeManager.float_type ||
MemberType == TypeManager.intptr_type || MemberType == TypeManager.uintptr_type)
return true;
if (MemberType.IsEnum)
return true;
return false;
}
public override bool Define ()
{
if (!base.Define ())
return false;
MetaType[] required_modifier = null;
if ((ModFlags & Modifiers.VOLATILE) != 0) {
var mod = Module.PredefinedTypes.IsVolatile.Resolve (Location);
if (mod != null)
required_modifier = new MetaType[] { mod.GetMetaInfo () };
}
FieldBuilder = Parent.TypeBuilder.DefineField (
Name, member_type.GetMetaInfo (), required_modifier, null, ModifiersExtensions.FieldAttr (ModFlags));
spec = new FieldSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags);
// Don't cache inaccessible fields
if ((ModFlags & Modifiers.BACKING_FIELD) == 0) {
Parent.MemberCache.AddMember (spec);
}
if (initializer != null) {
((TypeContainer) Parent).RegisterFieldForInitialization (this,
new FieldInitializer (spec, initializer, this));
}
if (declarators != null) {
var t = new TypeExpression (MemberType, TypeExpression.Location);
int index = Parent.PartialContainer.Fields.IndexOf (this);
foreach (var d in declarators) {
var f = new Field (Parent, t, ModFlags, new MemberName (d.Name.Value, d.Name.Location), OptAttributes);
if (d.Initializer != null)
f.initializer = d.Initializer;
Parent.PartialContainer.Fields.Insert (++index, f);
}
}
return true;
}
protected override void DoMemberTypeDependentChecks ()
{
if ((ModFlags & Modifiers.BACKING_FIELD) != 0)
return;
base.DoMemberTypeDependentChecks ();
if ((ModFlags & Modifiers.VOLATILE) != 0) {
if (!CanBeVolatile ()) {
Report.Error (677, Location, "`{0}': A volatile field cannot be of the type `{1}'",
GetSignatureForError (), TypeManager.CSharpName (MemberType));
}
if ((ModFlags & Modifiers.READONLY) != 0) {
Report.Error (678, Location, "`{0}': A field cannot be both volatile and readonly",
GetSignatureForError ());
}
}
}
protected override bool VerifyClsCompliance ()
{
if (!base.VerifyClsCompliance ())
return false;
if ((ModFlags & Modifiers.VOLATILE) != 0) {
Report.Warning (3026, 1, Location, "CLS-compliant field `{0}' cannot be volatile", GetSignatureForError ());
}
return true;
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.IO;
/// <summary>
/// Helper script for capture cubemap and save it into PNG or JPG file
/// </summary>
/// <description>
/// How it works:
/// 1) This script can be attached to a existing game object, you can also use prefab Assets\OVR\Prefabs\OVRCubemapCaptureProbe
/// There are 2 ways to trigger a capture if you attached this script to a game object.
/// * Automatic capturing: if [autoTriggerAfterLaunch] is true, a automatic capturing will be triggered after [autoTriggerDelay] seconds.
/// * Keyboard trigger: press key [triggeredByKey], a capturing will be triggered.
/// 2) If you like to trigger the screen capture in your code logic, just call static function [OVRCubemapCapture.TriggerCubemapCapture] with proper input arguments.
/// </description>
public class OVRCubemapCapture : MonoBehaviour
{
/// <summary>
/// Enable the automatic screenshot trigger, which will capture a cubemap after autoTriggerDelay (seconds)
/// </summary>
public bool autoTriggerAfterLaunch = true;
public float autoTriggerDelay = 1.0f;
private float autoTriggerElapse = 0.0f;
/// <summary>
/// Trigger cubemap screenshot if user pressed key triggeredByKey
/// </summary>
public KeyCode triggeredByKey = KeyCode.F8;
/// <summary>
/// The complete file path for saving the cubemap screenshot, including the filename and extension
/// if pathName is blank, screenshots will be saved into %USERPROFILE%\Documents\OVR_ScreenShot360
/// </summary>
public string pathName;
/// <summary>
/// The cube face resolution
/// </summary>
public int cubemapSize = 2048;
// Update is called once per frame
void Update()
{
// Trigger after autoTriggerDelay
if (autoTriggerAfterLaunch)
{
autoTriggerElapse += Time.deltaTime;
if (autoTriggerElapse >= autoTriggerDelay)
{
autoTriggerAfterLaunch = false;
TriggerCubemapCapture(transform.position, cubemapSize, pathName);
}
}
// Trigger by press triggeredByKey
if ( Input.GetKeyDown( triggeredByKey ) )
{
TriggerCubemapCapture(transform.position, cubemapSize, pathName);
}
}
/// <summary>
/// Generate unity cubemap at specific location and save into JPG/PNG
/// </summary>
/// <description>
/// Default save folder: your app's persistentDataPath
/// Default file name: using current time OVR_hh_mm_ss.png
/// Note1: this will take a few seconds to finish
/// Note2: if you only want to specify path not filename, please end [pathName] with "/"
/// </description>
public static void TriggerCubemapCapture(Vector3 capturePos, int cubemapSize = 2048, string pathName = null)
{
GameObject ownerObj = new GameObject("CubemapCamera", typeof(Camera));
ownerObj.hideFlags = HideFlags.HideAndDontSave;
ownerObj.transform.position = capturePos;
ownerObj.transform.rotation = Quaternion.identity;
Camera camComponent = ownerObj.GetComponent<Camera>();
camComponent.farClipPlane = 10000.0f;
camComponent.enabled = false;
Cubemap cubemap = new Cubemap(cubemapSize, TextureFormat.RGB24, false);
RenderIntoCubemap(camComponent, cubemap);
SaveCubemapCapture(cubemap, pathName);
DestroyImmediate(cubemap);
DestroyImmediate(ownerObj);
}
public static void RenderIntoCubemap(Camera ownerCamera, Cubemap outCubemap)
{
int width = (int)outCubemap.width;
int height = (int)outCubemap.height;
CubemapFace[] faces = new CubemapFace[] { CubemapFace.PositiveX, CubemapFace.NegativeX, CubemapFace.PositiveY, CubemapFace.NegativeY, CubemapFace.PositiveZ, CubemapFace.NegativeZ };
Vector3[] faceAngles = new Vector3[] { new Vector3(0.0f, 90.0f, 0.0f), new Vector3(0.0f, -90.0f, 0.0f), new Vector3(-90.0f, 0.0f, 0.0f), new Vector3(90.0f, 0.0f, 0.0f), new Vector3(0.0f, 0.0f, 0.0f), new Vector3(0.0f, 180.0f, 0.0f) };
// Backup states
RenderTexture backupRenderTex = RenderTexture.active;
float backupFieldOfView = ownerCamera.fieldOfView;
float backupAspect = ownerCamera.aspect;
Quaternion backupRot = ownerCamera.transform.rotation;
//RenderTexture backupRT = ownerCamera.targetTexture;
// Enable 8X MSAA
RenderTexture faceTexture = new RenderTexture(width, height, 24);
faceTexture.antiAliasing = 8;
#if !(UNITY_5_0 || UNITY_5_1 || UNITY_5_2 || UNITY_5_3)
faceTexture.dimension = UnityEngine.Rendering.TextureDimension.Tex2D;
#endif
faceTexture.hideFlags = HideFlags.HideAndDontSave;
// For intermediate saving
Texture2D swapTex = new Texture2D(width, height, TextureFormat.RGB24, false);
swapTex.hideFlags = HideFlags.HideAndDontSave;
// Capture 6 Directions
ownerCamera.targetTexture = faceTexture;
ownerCamera.fieldOfView = 90;
ownerCamera.aspect = 1.0f;
Color[] mirroredPixels = new Color[swapTex.height * swapTex.width];
for (int i = 0; i < faces.Length; i++)
{
ownerCamera.transform.eulerAngles = faceAngles[i];
ownerCamera.Render();
RenderTexture.active = faceTexture;
swapTex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
// Mirror vertically to meet the standard of unity cubemap
Color[] OrignalPixels = swapTex.GetPixels();
for (int y1 = 0; y1 < height; y1++)
{
for (int x1 = 0; x1 < width; x1++)
{
mirroredPixels[y1 * width + x1] = OrignalPixels[((height - 1 - y1) * width) + x1];
}
};
outCubemap.SetPixels(mirroredPixels, faces[i]);
}
outCubemap.SmoothEdges();
// Restore states
RenderTexture.active = backupRenderTex;
ownerCamera.fieldOfView = backupFieldOfView;
ownerCamera.aspect = backupAspect;
ownerCamera.transform.rotation = backupRot;
ownerCamera.targetTexture = backupRenderTex;
DestroyImmediate(swapTex);
DestroyImmediate(faceTexture);
}
/// <summary>
/// Save unity cubemap into NPOT 6x1 cubemap/texture atlas in the following format PX NX PY NY PZ NZ
/// </summary>
/// <description>
/// Supported format: PNG/JPG
/// Default file name: using current time OVR_hh_mm_ss.png
/// </description>
public static bool SaveCubemapCapture(Cubemap cubemap, string pathName = null)
{
string fileName;
string dirName;
int width = cubemap.width;
int height = cubemap.height;
int x = 0;
int y = 0;
bool saveToPNG = true;
if (string.IsNullOrEmpty(pathName))
{
dirName = Application.persistentDataPath + "/OVR_ScreenShot360/";
fileName = null;
}
else
{
dirName = Path.GetDirectoryName(pathName);
fileName = Path.GetFileName(pathName);
if (dirName[dirName.Length - 1] != '/' || dirName[dirName.Length - 1] != '\\')
dirName += "/";
}
if (string.IsNullOrEmpty(fileName))
fileName = "OVR_" + System.DateTime.Now.ToString("hh_mm_ss") + ".png";
string extName = Path.GetExtension(fileName);
if (extName == ".png")
{
saveToPNG = true;
}
else if (extName == ".jpg")
{
saveToPNG = false;
}
else
{
Debug.LogError("Unsupported file format" + extName);
return false;
}
// Validate path
try
{
System.IO.Directory.CreateDirectory(dirName);
}
catch (System.Exception e)
{
Debug.LogError("Failed to create path " + dirName + " since " + e.ToString());
return false;
}
// Create the new texture
Texture2D tex = new Texture2D(width * 6, height, TextureFormat.RGB24, false);
if (tex == null)
{
Debug.LogError("[OVRScreenshotWizard] Failed creating the texture!");
return false;
}
// Merge all the cubemap faces into the texture
// Reference cubemap format: http://docs.unity3d.com/Manual/class-Cubemap.html
CubemapFace[] faces = new CubemapFace[] { CubemapFace.PositiveX, CubemapFace.NegativeX, CubemapFace.PositiveY, CubemapFace.NegativeY, CubemapFace.PositiveZ, CubemapFace.NegativeZ };
for (int i = 0; i < faces.Length; i++)
{
// get the pixels from the cubemap
Color[] srcPixels = null;
Color[] pixels = cubemap.GetPixels(faces[i]);
// if desired, flip them as they are ordered left to right, bottom to top
srcPixels = new Color[pixels.Length];
for (int y1 = 0; y1 < height; y1++)
{
for (int x1 = 0; x1 < width; x1++)
{
srcPixels[y1 * width + x1] = pixels[((height - 1 - y1) * width) + x1];
}
}
// Copy them to the dest texture
tex.SetPixels(x, y, width, height, srcPixels);
x += width;
}
try
{
// Encode the texture and save it to disk
byte[] bytes = saveToPNG ? tex.EncodeToPNG() : tex.EncodeToJPG();
System.IO.File.WriteAllBytes(dirName + fileName, bytes);
Debug.Log("Cubemap file created " + dirName + fileName);
}
catch (System.Exception e)
{
Debug.LogError("Failed to save cubemap file since " + e.ToString());
return false;
}
DestroyImmediate(tex);
return true;
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Xunit;
namespace System.Xml.Tests
{
public class IntegerElementContentTests
{
[Fact]
public static void ReadElementContentAsInt1()
{
var reader = Utils.CreateFragmentReader(@"<doc a='b'>9999</doc>");
reader.PositionOnElementNonEmptyNoDoctype("doc");
Assert.Equal(new DateTime(9999, 1, 1, 0, 0, 0), reader.ReadElementContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadElementContentAsInt10()
{
var reader = Utils.CreateFragmentReader("<Root>-4<!-- Comment inbetween-->4</Root>");
reader.PositionOnElement("Root");
Assert.Equal(-44, reader.ReadElementContentAsInt());
}
[Fact]
public static void ReadElementContentAsInt11()
{
var reader = Utils.CreateFragmentReader("<Root> -<!-- Comment inbetween-->000<?a?>455 </Root>");
reader.PositionOnElement("Root");
Assert.Equal(-455, reader.ReadElementContentAsInt());
}
[Fact]
public static void ReadElementContentAsInt12()
{
var reader = Utils.CreateFragmentReader("<Root> -45.5 </Root>");
reader.PositionOnElement("Root");
Assert.Throws<XmlException>(() => reader.ReadElementContentAsInt());
}
[Fact]
public static void ReadElementContentAsInt13()
{
var reader = Utils.CreateFragmentReader("<Root> -45.5 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAsInt());
}
[Fact]
public static void ReadElementContentAsInt14()
{
var reader = Utils.CreateFragmentReader("<Root a=' 4.678'/>");
reader.PositionOnElement("Root");
reader.MoveToAttribute("a");
Assert.Throws<XmlException>(() => reader.ReadContentAsInt());
}
[Fact]
public static void ReadElementContentAsInt15()
{
var reader = Utils.CreateFragmentReader("<Root> -<![CDATA[0]]>0<!-- Comment inbetween-->5<?a?> </Root>");
reader.PositionOnElement("Root");
Assert.Equal(-5, reader.ReadElementContentAs(typeof(int), null));
}
[Fact]
public static void ReadElementContentAsInt16()
{
var reader = Utils.CreateFragmentReader("<Root> <!-- Comment inbetween-->0<?a?>00<![CDATA[1]]></Root>");
reader.PositionOnElement("Root");
Assert.Equal(1, reader.ReadElementContentAs(typeof(int), null));
}
[Fact]
public static void ReadElementContentAsInt17()
{
var reader = Utils.CreateFragmentReader("<Root><![CDATA[0]]> <!-- Comment inbetween--> </Root>");
reader.PositionOnElement("Root");
Assert.Equal(0, reader.ReadElementContentAs(typeof(int), null));
}
[Fact]
public static void ReadElementContentAsInt18()
{
var reader = Utils.CreateFragmentReader("<Root> 9<![CDATA[9]]>99<?a?>9<!-- Comment inbetween--><![CDATA[9]]> </Root>");
reader.PositionOnElement("Root");
Assert.Equal(999999, reader.ReadElementContentAs(typeof(int), null));
}
[Fact]
public static void ReadElementContentAsInt19()
{
var reader = Utils.CreateFragmentReader("<Root>-4<!-- Comment inbetween-->4</Root>");
reader.PositionOnElement("Root");
Assert.Equal(-44, reader.ReadElementContentAs(typeof(int), null));
}
[Fact]
public static void ReadElementContentAsInt2()
{
var reader = Utils.CreateFragmentReader(@"<doc a='b'>0001z</doc>");
reader.PositionOnElementNonEmptyNoDoctype("doc");
Assert.Equal(new DateTime(1, 1, 1, 0, 0, 0, 0).Add(new TimeSpan(0, 0, 0)), reader.ReadElementContentAs(typeof(DateTime), null));
}
[Fact]
public static void ReadElementContentAsInt20()
{
var reader = Utils.CreateFragmentReader("<Root> -<!-- Comment inbetween-->000<?a?>455 </Root>");
reader.PositionOnElement("Root");
Assert.Equal(-455, reader.ReadElementContentAs(typeof(int), null));
}
[Fact]
public static void ReadElementContentAsInt21()
{
var reader = Utils.CreateFragmentReader("<Root> -45.5 </Root>");
reader.PositionOnElement("Root");
Assert.Throws<XmlException>(() => reader.ReadElementContentAs(typeof(int), null));
}
[Fact]
public static void ReadElementContentAsInt22()
{
var reader = Utils.CreateFragmentReader("<Root> -45.5 </Root>");
reader.PositionOnElement("Root");
reader.Read();
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(int), null));
}
[Fact]
public static void ReadElementContentAsInt23()
{
var reader = Utils.CreateFragmentReader(@"<doc a='b'>9999</doc>");
reader.PositionOnElementNonEmptyNoDoctype("doc");
Assert.Equal(new DateTimeOffset(9999, 1, 1, 0, 0, 0, TimeZoneInfo.Local.GetUtcOffset(new DateTime(9999, 1, 1))).ToString(), reader.ReadElementContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadElementContentAsInt24()
{
var reader = Utils.CreateFragmentReader(@"<doc a='b'>0001z</doc>");
reader.PositionOnElementNonEmptyNoDoctype("doc");
Assert.Equal(new DateTimeOffset(1, 1, 1, 0, 0, 0, TimeSpan.FromHours(0)).ToString(), reader.ReadElementContentAs(typeof(DateTimeOffset), null).ToString());
}
[Fact]
public static void ReadElementContentAsInt3()
{
var reader = Utils.CreateFragmentReader(@"<doc a='b'>0001z</doc>");
reader.PositionOnElementNonEmptyNoDoctype("doc");
Assert.Equal(new DateTimeOffset(new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)), reader.ReadElementContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadElementContentAsInt4()
{
var reader = Utils.CreateFragmentReader(@"<doc a='b'>9999</doc>");
reader.PositionOnElementNonEmptyNoDoctype("doc");
Assert.Equal(new DateTimeOffset(new DateTime(9999, 1, 1, 0, 0, 0, DateTimeKind.Local)), reader.ReadElementContentAs(typeof(DateTimeOffset), null));
}
[Fact]
public static void ReadElementContentAsInt5()
{
var reader = Utils.CreateFragmentReader("<Root a=' 4.678'/>");
reader.PositionOnElement("Root");
reader.MoveToAttribute("a");
Assert.Throws<XmlException>(() => reader.ReadContentAs(typeof(int), null));
}
[Fact]
public static void ReadElementContentAsInt6()
{
var reader = Utils.CreateFragmentReader("<Root> -<![CDATA[0]]>0<!-- Comment inbetween-->5<?a?> </Root>");
reader.PositionOnElement("Root");
Assert.Equal(-5, reader.ReadElementContentAsInt());
}
[Fact]
public static void ReadElementContentAsInt7()
{
var reader = Utils.CreateFragmentReader("<Root> <!-- Comment inbetween-->0<?a?>00<![CDATA[1]]></Root>");
reader.PositionOnElement("Root");
Assert.Equal(1, reader.ReadElementContentAsInt());
}
[Fact]
public static void ReadElementContentAsInt8()
{
var reader = Utils.CreateFragmentReader("<Root><![CDATA[0]]> <!-- Comment inbetween--> </Root>");
reader.PositionOnElement("Root");
Assert.Equal(0, reader.ReadElementContentAsInt());
}
[Fact]
public static void ReadElementContentAsInt9()
{
var reader = Utils.CreateFragmentReader("<Root> 9<![CDATA[9]]>99<?a?>9<!-- Comment inbetween--><![CDATA[9]]> </Root>");
reader.PositionOnElement("Root");
Assert.Equal(999999, reader.ReadElementContentAsInt());
}
}
}
| |
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 exifstats.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json.Linq;
namespace Avro
{
/// <summary>
/// Class for enum type schemas
/// </summary>
public class EnumSchema : NamedSchema
{
/// <summary>
/// List of strings representing the enum symbols
/// </summary>
public IList<string> Symbols { get; private set; }
/// <summary>
/// Map of enum symbols and it's corresponding ordinal number
/// </summary>
private readonly IDictionary<string, int> symbolMap;
/// <summary>
/// Count of enum symbols
/// </summary>
public int Count { get { return Symbols.Count; } }
/// <summary>
/// Static function to return new instance of EnumSchema
/// </summary>
/// <param name="jtok">JSON object for enum schema</param>
/// <param name="names">list of named schema already parsed in</param>
/// <param name="encspace">enclosing namespace for the enum schema</param>
/// <returns>new instance of enum schema</returns>
internal static EnumSchema NewInstance(JToken jtok, PropertyMap props, SchemaNames names, string encspace)
{
SchemaName name = NamedSchema.GetName(jtok, encspace);
var aliases = NamedSchema.GetAliases(jtok, name.Space, name.EncSpace);
JArray jsymbols = jtok["symbols"] as JArray;
if (null == jsymbols)
throw new SchemaParseException("Enum has no symbols: " + name);
List<string> symbols = new List<string>();
IDictionary<string, int> symbolMap = new Dictionary<string, int>();
int i = 0;
foreach (JValue jsymbol in jsymbols)
{
string s = (string)jsymbol.Value;
if (symbolMap.ContainsKey(s))
throw new SchemaParseException("Duplicate symbol: " + s);
symbolMap[s] = i++;
symbols.Add(s);
}
return new EnumSchema(name, aliases, symbols, symbolMap, props, names);
}
/// <summary>
/// Constructor for enum schema
/// </summary>
/// <param name="name">name of enum</param>
/// <param name="aliases">list of aliases for the name</param>
/// <param name="symbols">list of enum symbols</param>
/// <param name="symbolMap">map of enum symbols and value</param>
/// <param name="names">list of named schema already read</param>
private EnumSchema(SchemaName name, IList<SchemaName> aliases, List<string> symbols,
IDictionary<String, int> symbolMap, PropertyMap props, SchemaNames names)
: base(Type.Enumeration, name, aliases, props, names)
{
if (null == name.Name) throw new SchemaParseException("name cannot be null for enum schema.");
this.Symbols = symbols;
this.symbolMap = symbolMap;
}
/// <summary>
/// Writes enum schema in JSON format
/// </summary>
/// <param name="writer">JSON writer</param>
/// <param name="names">list of named schema already written</param>
/// <param name="encspace">enclosing namespace of the enum schema</param>
protected internal override void WriteJsonFields(Newtonsoft.Json.JsonTextWriter writer,
SchemaNames names, string encspace)
{
base.WriteJsonFields(writer, names, encspace);
writer.WritePropertyName("symbols");
writer.WriteStartArray();
foreach (string s in this.Symbols)
writer.WriteValue(s);
writer.WriteEndArray();
}
/// <summary>
/// Returns the position of the given symbol within this enum.
/// Throws AvroException if the symbol is not found in this enum.
/// </summary>
/// <param name="symbol">name of the symbol to find</param>
/// <returns>position of the given symbol in this enum schema</returns>
public int Ordinal(string symbol)
{
int result;
if (symbolMap.TryGetValue(symbol, out result)) return result;
throw new AvroException("No such symbol: " + symbol);
}
/// <summary>
/// Returns the enum symbol of the given index to the list
/// </summary>
/// <param name="index">symbol index</param>
/// <returns>symbol name</returns>
public string this[int index]
{
get
{
if (index < Symbols.Count) return Symbols[index];
throw new AvroException("Enumeration out of range. Must be less than " + Symbols.Count + ", but is " + index);
}
}
/// <summary>
/// Checks if given symbol is in the list of enum symbols
/// </summary>
/// <param name="symbol">symbol to check</param>
/// <returns>true if symbol exist, false otherwise</returns>
public bool Contains(string symbol)
{
return symbolMap.ContainsKey(symbol);
}
/// <summary>
/// Returns an enumerator that enumerates the symbols in this enum schema in the order of their definition.
/// </summary>
/// <returns>Enumeration over the symbols of this enum schema</returns>
public IEnumerator<string> GetEnumerator()
{
return Symbols.GetEnumerator();
}
/// <summary>
/// Checks equality of two enum schema
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
public override bool Equals(object obj)
{
if (obj == this) return true;
if (obj != null && obj is EnumSchema)
{
EnumSchema that = obj as EnumSchema;
if (SchemaName.Equals(that.SchemaName) && Count == that.Count)
{
for (int i = 0; i < Count; i++) if (!Symbols[i].Equals(that.Symbols[i])) return false;
return areEqual(that.Props, this.Props);
}
}
return false;
}
/// <summary>
/// Hashcode function
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
int result = SchemaName.GetHashCode() + getHashCode(Props);
foreach (string s in Symbols) result += 23 * s.GetHashCode();
return result;
}
/// <summary>
/// Checks if this schema can read data written by the given schema. Used for decoding data.
/// </summary>
/// <param name="writerSchema">writer schema</param>
/// <returns>true if this and writer schema are compatible based on the AVRO specification, false otherwise</returns>
public override bool CanRead(Schema writerSchema)
{
if (writerSchema.Tag != Tag) return false;
EnumSchema that = writerSchema as EnumSchema;
if (!that.SchemaName.Equals(SchemaName))
if (!InAliases(that.SchemaName)) return false;
// we defer checking of symbols. Writer may have a symbol missing from the reader,
// but if writer never used the missing symbol, then reader should still be able to read the data
return true;
}
}
}
| |
// Copyright 2016 Google Inc. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using UnityEngine;
using UnityEngine.Audio;
using System.Collections;
#pragma warning disable 0618 // Ignore GvrAudio* deprecation
/// GVR audio source component that enhances AudioSource to provide advanced spatial audio features.
#if UNITY_2017_1_OR_NEWER
[System.Obsolete("Please upgrade to Resonance Audio (https://developers.google.com/resonance-audio/migrate).")]
#endif // UNITY_2017_1_OR_NEWER
[AddComponentMenu("GoogleVR/Audio/GvrAudioSource")]
public class GvrAudioSource : MonoBehaviour {
/// Denotes whether the room effects should be bypassed.
public bool bypassRoomEffects = false;
/// Directivity pattern shaping factor.
public float directivityAlpha = 0.0f;
/// Directivity pattern order.
public float directivitySharpness = 1.0f;
/// Listener directivity pattern shaping factor.
public float listenerDirectivityAlpha = 0.0f;
/// Listener directivity pattern order.
public float listenerDirectivitySharpness = 1.0f;
/// Input gain in decibels.
public float gainDb = 0.0f;
/// Occlusion effect toggle.
public bool occlusionEnabled = false;
/// Play source on awake.
public bool playOnAwake = true;
/// The default AudioClip to play.
public AudioClip clip {
get { return sourceClip; }
set {
sourceClip = value;
if (audioSource != null) {
audioSource.clip = sourceClip;
}
}
}
[SerializeField]
private AudioClip sourceClip = null;
/// Is the clip playing right now (Read Only)?
public bool isPlaying {
get {
if (audioSource != null) {
return audioSource.isPlaying;
}
return false;
}
}
/// Is the audio clip looping?
public bool loop {
get { return sourceLoop; }
set {
sourceLoop = value;
if (audioSource != null) {
audioSource.loop = sourceLoop;
}
}
}
[SerializeField]
private bool sourceLoop = false;
/// Un- / Mutes the source. Mute sets the volume=0, Un-Mute restore the original volume.
public bool mute {
get { return sourceMute; }
set {
sourceMute = value;
if (audioSource != null) {
audioSource.mute = sourceMute;
}
}
}
[SerializeField]
private bool sourceMute = false;
/// The pitch of the audio source.
public float pitch {
get { return sourcePitch; }
set {
sourcePitch = value;
if (audioSource != null) {
audioSource.pitch = sourcePitch;
}
}
}
[SerializeField]
[Range(-3.0f, 3.0f)]
private float sourcePitch = 1.0f;
/// Sets the priority of the audio source.
public int priority {
get { return sourcePriority; }
set {
sourcePriority = value;
if(audioSource != null) {
audioSource.priority = sourcePriority;
}
}
}
[SerializeField]
[Range(0, 256)]
private int sourcePriority = 128;
/// Sets how much this source is affected by 3D spatialization calculations (attenuation, doppler).
public float spatialBlend {
get { return sourceSpatialBlend; }
set {
sourceSpatialBlend = value;
if (audioSource != null) {
audioSource.spatialBlend = sourceSpatialBlend;
}
}
}
[SerializeField]
[Range(0.0f, 1.0f)]
private float sourceSpatialBlend = 1.0f;
/// Sets the Doppler scale for this audio source.
public float dopplerLevel {
get { return sourceDopplerLevel; }
set {
sourceDopplerLevel = value;
if(audioSource != null) {
audioSource.dopplerLevel = sourceDopplerLevel;
}
}
}
[SerializeField]
[Range(0.0f, 5.0f)]
private float sourceDopplerLevel = 1.0f;
/// Sets the spread angle (in degrees) in 3D space.
public float spread {
get { return sourceSpread; }
set {
sourceSpread = value;
if(audioSource != null) {
audioSource.spread = sourceSpread;
}
}
}
[SerializeField]
[Range(0.0f, 360.0f)]
private float sourceSpread = 0.0f;
/// Playback position in seconds.
public float time {
get {
if(audioSource != null) {
return audioSource.time;
}
return 0.0f;
}
set {
if(audioSource != null) {
audioSource.time = value;
}
}
}
/// Playback position in PCM samples.
public int timeSamples {
get {
if(audioSource != null) {
return audioSource.timeSamples;
}
return 0;
}
set {
if(audioSource != null) {
audioSource.timeSamples = value;
}
}
}
/// The volume of the audio source (0.0 to 1.0).
public float volume {
get { return sourceVolume; }
set {
sourceVolume = value;
if (audioSource != null) {
audioSource.volume = sourceVolume;
}
}
}
[SerializeField]
[Range(0.0f, 1.0f)]
private float sourceVolume = 1.0f;
/// Volume rolloff model with respect to the distance.
public AudioRolloffMode rolloffMode {
get { return sourceRolloffMode; }
set {
sourceRolloffMode = value;
if (audioSource != null) {
audioSource.rolloffMode = sourceRolloffMode;
if (rolloffMode == AudioRolloffMode.Custom) {
// Custom rolloff is not supported, set the curve for no distance attenuation.
audioSource.SetCustomCurve(AudioSourceCurveType.CustomRolloff,
AnimationCurve.Linear(sourceMinDistance, 1.0f,
sourceMaxDistance, 1.0f));
}
}
}
}
[SerializeField]
private AudioRolloffMode sourceRolloffMode = AudioRolloffMode.Logarithmic;
/// MaxDistance is the distance a sound stops attenuating at.
public float maxDistance {
get { return sourceMaxDistance; }
set {
sourceMaxDistance = Mathf.Clamp(value, sourceMinDistance + GvrAudio.distanceEpsilon,
GvrAudio.maxDistanceLimit);
if(audioSource != null) {
audioSource.maxDistance = sourceMaxDistance;
}
}
}
[SerializeField]
private float sourceMaxDistance = 500.0f;
/// Within the Min distance the GvrAudioSource will cease to grow louder in volume.
public float minDistance {
get { return sourceMinDistance; }
set {
sourceMinDistance = Mathf.Clamp(value, 0.0f, GvrAudio.minDistanceLimit);
if(audioSource != null) {
audioSource.minDistance = sourceMinDistance;
}
}
}
[SerializeField]
private float sourceMinDistance = 1.0f;
/// Binaural (HRTF) rendering toggle.
[SerializeField]
private bool hrtfEnabled = true;
// Unity audio source attached to the game object.
[SerializeField]
private AudioSource audioSource = null;
// Unique source id.
private int id = -1;
// Current occlusion value;
private float currentOcclusion = 0.0f;
// Next occlusion update time in seconds.
private float nextOcclusionUpdate = 0.0f;
// Denotes whether the source is currently paused or not.
private bool isPaused = false;
void Awake () {
#if UNITY_EDITOR && UNITY_2017_1_OR_NEWER
Debug.LogWarningFormat(gameObject,
"Game object '{0}' uses deprecated {1} component.\nPlease upgrade to Resonance Audio ({2}).",
name, GetType().Name, "https://developers.google.com/resonance-audio/migrate");
#endif // UNITY_EDITOR && UNITY_2017_1_OR_NEWER
if (audioSource == null) {
// Ensure the audio source gets created once.
audioSource = gameObject.AddComponent<AudioSource>();
}
audioSource.enabled = false;
audioSource.hideFlags = HideFlags.HideInInspector | HideFlags.HideAndDontSave;
audioSource.playOnAwake = false;
audioSource.bypassReverbZones = true;
#if UNITY_5_5_OR_NEWER
audioSource.spatializePostEffects = true;
#endif // UNITY_5_5_OR_NEWER
OnValidate();
// Route the source output to |GvrAudioMixer|.
AudioMixer mixer = (Resources.Load("GvrAudioMixer") as AudioMixer);
if(mixer != null) {
audioSource.outputAudioMixerGroup = mixer.FindMatchingGroups("Master")[0];
} else {
Debug.LogError("GVRAudioMixer could not be found in Resources. Make sure that the GVR SDK " +
"Unity package is imported properly.");
}
}
void OnEnable () {
audioSource.enabled = true;
if (playOnAwake && !isPlaying && InitializeSource()) {
Play();
}
}
void Start () {
if (playOnAwake && !isPlaying) {
Play();
}
}
void OnDisable () {
Stop();
audioSource.enabled = false;
}
void OnDestroy () {
Destroy(audioSource);
}
void OnApplicationPause (bool pauseStatus) {
if (pauseStatus) {
Pause();
} else {
UnPause();
}
}
void Update () {
// Update occlusion state.
if (!occlusionEnabled) {
currentOcclusion = 0.0f;
} else if (Time.time >= nextOcclusionUpdate) {
nextOcclusionUpdate = Time.time + GvrAudio.occlusionDetectionInterval;
currentOcclusion = GvrAudio.ComputeOcclusion(transform);
}
// Update source.
if (!isPlaying && !isPaused) {
Stop();
} else {
audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.Gain,
GvrAudio.ConvertAmplitudeFromDb(gainDb));
audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.MinDistance,
sourceMinDistance);
GvrAudio.UpdateAudioSource(id, this, currentOcclusion);
}
}
/// Provides a block of the currently playing source's output data.
///
/// @note The array given in samples will be filled with the requested data before spatialization.
public void GetOutputData(float[] samples, int channel) {
if (audioSource != null) {
audioSource.GetOutputData(samples, channel);
}
}
/// Provides a block of the currently playing audio source's spectrum data.
///
/// @note The array given in samples will be filled with the requested data before spatialization.
public void GetSpectrumData(float[] samples, int channel, FFTWindow window) {
if (audioSource != null) {
audioSource.GetSpectrumData(samples, channel, window);
}
}
/// Pauses playing the clip.
public void Pause () {
if (audioSource != null) {
isPaused = true;
audioSource.Pause();
}
}
/// Plays the clip.
public void Play () {
if (audioSource != null && InitializeSource()) {
audioSource.Play();
isPaused = false;
} else {
Debug.LogWarning ("GVR Audio source not initialized. Audio playback not supported " +
"until after Awake() and OnEnable(). Try calling from Start() instead.");
}
}
/// Plays the clip with a delay specified in seconds.
public void PlayDelayed (float delay) {
if (audioSource != null && InitializeSource()) {
audioSource.PlayDelayed(delay);
isPaused = false;
} else {
Debug.LogWarning ("GVR Audio source not initialized. Audio playback not supported " +
"until after Awake() and OnEnable(). Try calling from Start() instead.");
}
}
/// Plays an AudioClip.
public void PlayOneShot (AudioClip clip) {
PlayOneShot(clip, 1.0f);
}
/// Plays an AudioClip, and scales its volume.
public void PlayOneShot (AudioClip clip, float volume) {
if (audioSource != null && InitializeSource()) {
audioSource.PlayOneShot(clip, volume);
isPaused = false;
} else {
Debug.LogWarning ("GVR Audio source not initialized. Audio playback not supported " +
"until after Awake() and OnEnable(). Try calling from Start() instead.");
}
}
/// Plays the clip at a specific time on the absolute time-line that AudioSettings.dspTime reads
/// from.
public void PlayScheduled (double time) {
if (audioSource != null && InitializeSource()) {
audioSource.PlayScheduled(time);
isPaused = false;
} else {
Debug.LogWarning ("GVR Audio source not initialized. Audio playback not supported " +
"until after Awake() and OnEnable(). Try calling from Start() instead.");
}
}
/// Changes the time at which a sound that has already been scheduled to play will end.
public void SetScheduledEndTime(double time) {
if (audioSource != null) {
audioSource.SetScheduledEndTime(time);
}
}
/// Changes the time at which a sound that has already been scheduled to play will start.
public void SetScheduledStartTime(double time) {
if (audioSource != null) {
audioSource.SetScheduledStartTime(time);
}
}
/// Stops playing the clip.
public void Stop () {
if (audioSource != null) {
audioSource.Stop();
ShutdownSource();
isPaused = true;
}
}
/// Unpauses the paused playback.
public void UnPause () {
if (audioSource != null) {
audioSource.UnPause();
isPaused = false;
}
}
// Initializes the source.
private bool InitializeSource () {
if (id < 0) {
id = GvrAudio.CreateAudioSource(hrtfEnabled);
if (id >= 0) {
GvrAudio.UpdateAudioSource(id, this, currentOcclusion);
audioSource.spatialize = true;
audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.Type,
(float) GvrAudio.SpatializerType.Source);
audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.Gain,
GvrAudio.ConvertAmplitudeFromDb(gainDb));
audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.MinDistance,
sourceMinDistance);
audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.ZeroOutput, 0.0f);
// Source id must be set after all the spatializer parameters, to ensure that the source is
// properly initialized before processing.
audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.Id, (float) id);
}
}
return id >= 0;
}
// Shuts down the source.
private void ShutdownSource () {
if (id >= 0) {
audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.Id, -1.0f);
// Ensure that the output is zeroed after shutdown.
audioSource.SetSpatializerFloat((int) GvrAudio.SpatializerData.ZeroOutput, 1.0f);
audioSource.spatialize = false;
GvrAudio.DestroyAudioSource(id);
id = -1;
}
}
void OnDidApplyAnimationProperties () {
OnValidate();
}
void OnValidate () {
clip = sourceClip;
loop = sourceLoop;
mute = sourceMute;
pitch = sourcePitch;
priority = sourcePriority;
spatialBlend = sourceSpatialBlend;
volume = sourceVolume;
dopplerLevel = sourceDopplerLevel;
spread = sourceSpread;
minDistance = sourceMinDistance;
maxDistance = sourceMaxDistance;
rolloffMode = sourceRolloffMode;
}
void OnDrawGizmosSelected () {
// Draw listener directivity gizmo.
// Note that this is a very suboptimal way of finding the component, to be used in Unity Editor
// only, should not be used to access the component in run time.
GvrAudioListener listener = FindObjectOfType<GvrAudioListener>();
if(listener != null) {
Gizmos.color = GvrAudio.listenerDirectivityColor;
DrawDirectivityGizmo(listener.transform, listenerDirectivityAlpha,
listenerDirectivitySharpness, 180);
}
// Draw source directivity gizmo.
Gizmos.color = GvrAudio.sourceDirectivityColor;
DrawDirectivityGizmo(transform, directivityAlpha, directivitySharpness, 180);
}
// Draws a 3D gizmo in the Scene View that shows the selected directivity pattern.
private void DrawDirectivityGizmo (Transform target, float alpha, float sharpness,
int resolution) {
Vector2[] points = GvrAudio.Generate2dPolarPattern(alpha, sharpness, resolution);
// Compute |vertices| from the polar pattern |points|.
int numVertices = resolution + 1;
Vector3[] vertices = new Vector3[numVertices];
vertices[0] = Vector3.zero;
for (int i = 0; i < points.Length; ++i) {
vertices[i + 1] = new Vector3(points[i].x, 0.0f, points[i].y);
}
// Generate |triangles| from |vertices|. Two triangles per each sweep to avoid backface culling.
int[] triangles = new int[6 * numVertices];
for (int i = 0; i < numVertices - 1; ++i) {
int index = 6 * i;
if (i < numVertices - 2) {
triangles[index] = 0;
triangles[index + 1] = i + 1;
triangles[index + 2] = i + 2;
} else {
// Last vertex is connected back to the first for the last triangle.
triangles[index] = 0;
triangles[index + 1] = numVertices - 1;
triangles[index + 2] = 1;
}
// The second triangle facing the opposite direction.
triangles[index + 3] = triangles[index];
triangles[index + 4] = triangles[index + 2];
triangles[index + 5] = triangles[index + 1];
}
// Construct a new mesh for the gizmo.
Mesh directivityGizmoMesh = new Mesh();
directivityGizmoMesh.hideFlags = HideFlags.DontSaveInEditor;
directivityGizmoMesh.vertices = vertices;
directivityGizmoMesh.triangles = triangles;
directivityGizmoMesh.RecalculateNormals();
// Draw the mesh.
Vector3 scale = 2.0f * Mathf.Max(target.lossyScale.x, target.lossyScale.z) * Vector3.one;
Gizmos.DrawMesh(directivityGizmoMesh, target.position, target.rotation, scale);
}
}
#pragma warning restore 0618 // Restore warnings
| |
#nullable disable
using System;
using System.Collections.Generic;
using System.IO;
namespace WWT.Imaging
{
public abstract class WcsImage
{
public static WcsImage FromFile(string fileName)
{
string extension = Path.GetExtension(fileName);
switch (extension.ToLower())
{
case ".fits":
case ".fit":
case ".gz":
return null;
// return new FitsImage(fileName);
default:
return new VampWCSImageReader(fileName);
}
}
protected string copyright;
public string Copyright
{
get { return copyright; }
set { copyright = value; }
}
protected string creditsUrl;
public string CreditsUrl
{
get { return creditsUrl; }
set { creditsUrl = value; }
}
private bool validWcs = false;
public bool ValidWcs
{
get { return validWcs; }
set { validWcs = value; }
}
protected List<string> keywords = new List<string>();
public List<string> Keywords
{
get
{
if (keywords.Count == 0)
{
keywords.Add("Image File");
}
return keywords;
}
set { keywords = value; }
}
protected string description;
public string Description
{
get { return description; }
set { description = value; }
}
protected double scaleX = 1;
public double ScaleX
{
get { return scaleX; }
set { scaleX = value; }
}
protected double scaleY = 1;
public double ScaleY
{
get { return scaleY; }
set { scaleY = value; }
}
protected double centerX;
public double CenterX
{
get { return centerX; }
set { centerX = value; }
}
protected double centerY;
public double CenterY
{
get { return centerY; }
set { centerY = value; }
}
protected double rotation;
public double Rotation
{
get { return rotation; }
set { rotation = value; }
}
protected double referenceX;
public double ReferenceX
{
get { return referenceX; }
set { referenceX = value; }
}
protected double referenceY;
public double ReferenceY
{
get { return referenceY; }
set { referenceY = value; }
}
protected double sizeX;
public double SizeX
{
get { return sizeX; }
set { sizeX = value; }
}
protected double sizeY;
public double SizeY
{
get { return sizeY; }
set { sizeY = value; }
}
protected double cd1_1;
public double Cd1_1
{
get { return cd1_1; }
set { cd1_1 = value; }
}
protected double cd1_2;
public double Cd1_2
{
get { return cd1_2; }
set { cd1_2 = value; }
}
protected double cd2_1;
public double Cd2_1
{
get { return cd2_1; }
set { cd2_1 = value; }
}
protected double cd2_2;
public double Cd2_2
{
get { return cd2_2; }
set { cd2_2 = value; }
}
protected bool hasRotation = false;
protected bool hasSize = false;
protected bool hasScale = false;
protected bool hasLocation = false;
protected bool hasPixel = false;
public void AdjustScale(double width, double height)
{
//adjusts the actual height vs the reported height.
if (width != sizeX)
{
scaleX *= (sizeX / width);
referenceX /= (sizeX / width);
sizeX = width;
}
if (height != sizeY)
{
scaleY *= (sizeY / height);
referenceY /= (sizeY / height);
sizeY = height;
}
}
protected void CalculateScaleFromCD()
{
scaleX = Math.Sqrt(cd1_1 * cd1_1 + cd2_1 * cd2_1) * Math.Sign(cd1_1 * cd2_2 - cd1_2 * cd2_1);
scaleY = Math.Sqrt(cd1_2 * cd1_2 + cd2_2 * cd2_2);
}
protected void CalculateRotationFromCD()
{
double sign = Math.Sign(cd1_1 * cd2_2 - cd1_2 * cd2_1);
double rot2 = Math.Atan2((-sign * cd1_2), cd2_2);
rotation = rot2 / Math.PI * 180;
}
protected string filename;
public string Filename
{
get { return filename; }
set { filename = value; }
}
private System.Drawing.Color color = System.Drawing.Color.White;
public System.Drawing.Color Color
{
get { return color; }
set { color = value; }
}
private bool colorCombine = false;
public bool ColorCombine
{
get { return colorCombine; }
set { colorCombine = value; }
}
public abstract System.Drawing.Bitmap GetBitmap();
}
}
| |
namespace android.os
{
[global::MonoJavaBridge.JavaClass()]
public sealed partial class Bundle : java.lang.Object, Parcelable, java.lang.Cloneable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
internal Bundle(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
private static global::MonoJavaBridge.MethodId _m0;
public global::java.lang.Object get(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Bundle.staticClass, "get", "(Ljava/lang/String;)Ljava/lang/Object;", ref global::android.os.Bundle._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m1;
public sealed override global::java.lang.String toString()
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.os.Bundle.staticClass, "toString", "()Ljava/lang/String;", ref global::android.os.Bundle._m1) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m2;
public global::java.lang.Object clone()
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Bundle.staticClass, "clone", "()Ljava/lang/Object;", ref global::android.os.Bundle._m2) as java.lang.Object;
}
private static global::MonoJavaBridge.MethodId _m3;
public bool getBoolean(java.lang.String arg0, bool arg1)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.os.Bundle.staticClass, "getBoolean", "(Ljava/lang/String;Z)Z", ref global::android.os.Bundle._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m4;
public bool getBoolean(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.os.Bundle.staticClass, "getBoolean", "(Ljava/lang/String;)Z", ref global::android.os.Bundle._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m5;
public void putBoolean(java.lang.String arg0, bool arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putBoolean", "(Ljava/lang/String;Z)V", ref global::android.os.Bundle._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m6;
public byte getByte(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallByteMethod(this, global::android.os.Bundle.staticClass, "getByte", "(Ljava/lang/String;)B", ref global::android.os.Bundle._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m7;
public global::java.lang.Byte getByte(java.lang.String arg0, byte arg1)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.Byte>(this, global::android.os.Bundle.staticClass, "getByte", "(Ljava/lang/String;B)Ljava/lang/Byte;", ref global::android.os.Bundle._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)) as java.lang.Byte;
}
private static global::MonoJavaBridge.MethodId _m8;
public void putByte(java.lang.String arg0, byte arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putByte", "(Ljava/lang/String;B)V", ref global::android.os.Bundle._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m9;
public short getShort(java.lang.String arg0, short arg1)
{
return global::MonoJavaBridge.JavaBridge.CallShortMethod(this, global::android.os.Bundle.staticClass, "getShort", "(Ljava/lang/String;S)S", ref global::android.os.Bundle._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m10;
public short getShort(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallShortMethod(this, global::android.os.Bundle.staticClass, "getShort", "(Ljava/lang/String;)S", ref global::android.os.Bundle._m10, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m11;
public void putShort(java.lang.String arg0, short arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putShort", "(Ljava/lang/String;S)V", ref global::android.os.Bundle._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m12;
public char getChar(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallCharMethod(this, global::android.os.Bundle.staticClass, "getChar", "(Ljava/lang/String;)C", ref global::android.os.Bundle._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m13;
public char getChar(java.lang.String arg0, char arg1)
{
return global::MonoJavaBridge.JavaBridge.CallCharMethod(this, global::android.os.Bundle.staticClass, "getChar", "(Ljava/lang/String;C)C", ref global::android.os.Bundle._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m14;
public void putChar(java.lang.String arg0, char arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putChar", "(Ljava/lang/String;C)V", ref global::android.os.Bundle._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m15;
public int getInt(java.lang.String arg0, int arg1)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.os.Bundle.staticClass, "getInt", "(Ljava/lang/String;I)I", ref global::android.os.Bundle._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m16;
public int getInt(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.os.Bundle.staticClass, "getInt", "(Ljava/lang/String;)I", ref global::android.os.Bundle._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m17;
public void putInt(java.lang.String arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putInt", "(Ljava/lang/String;I)V", ref global::android.os.Bundle._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m18;
public long getLong(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.os.Bundle.staticClass, "getLong", "(Ljava/lang/String;)J", ref global::android.os.Bundle._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m19;
public long getLong(java.lang.String arg0, long arg1)
{
return global::MonoJavaBridge.JavaBridge.CallLongMethod(this, global::android.os.Bundle.staticClass, "getLong", "(Ljava/lang/String;J)J", ref global::android.os.Bundle._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m20;
public void putLong(java.lang.String arg0, long arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putLong", "(Ljava/lang/String;J)V", ref global::android.os.Bundle._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m21;
public float getFloat(java.lang.String arg0, float arg1)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.os.Bundle.staticClass, "getFloat", "(Ljava/lang/String;F)F", ref global::android.os.Bundle._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m22;
public float getFloat(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallFloatMethod(this, global::android.os.Bundle.staticClass, "getFloat", "(Ljava/lang/String;)F", ref global::android.os.Bundle._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m23;
public void putFloat(java.lang.String arg0, float arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putFloat", "(Ljava/lang/String;F)V", ref global::android.os.Bundle._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m24;
public double getDouble(java.lang.String arg0, double arg1)
{
return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::android.os.Bundle.staticClass, "getDouble", "(Ljava/lang/String;D)D", ref global::android.os.Bundle._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m25;
public double getDouble(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallDoubleMethod(this, global::android.os.Bundle.staticClass, "getDouble", "(Ljava/lang/String;)D", ref global::android.os.Bundle._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m26;
public void putDouble(java.lang.String arg0, double arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putDouble", "(Ljava/lang/String;D)V", ref global::android.os.Bundle._m26, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m27;
public void clear()
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "clear", "()V", ref global::android.os.Bundle._m27);
}
private static global::MonoJavaBridge.MethodId _m28;
public bool isEmpty()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.os.Bundle.staticClass, "isEmpty", "()Z", ref global::android.os.Bundle._m28);
}
private static global::MonoJavaBridge.MethodId _m29;
public int size()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.os.Bundle.staticClass, "size", "()I", ref global::android.os.Bundle._m29);
}
private static global::MonoJavaBridge.MethodId _m30;
public void putAll(android.os.Bundle arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putAll", "(Landroid/os/Bundle;)V", ref global::android.os.Bundle._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m31;
public void remove(java.lang.String arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "remove", "(Ljava/lang/String;)V", ref global::android.os.Bundle._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m32;
public global::java.util.Set keySet()
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.util.Set>(this, global::android.os.Bundle.staticClass, "keySet", "()Ljava/util/Set;", ref global::android.os.Bundle._m32) as java.util.Set;
}
private static global::MonoJavaBridge.MethodId _m33;
public bool containsKey(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.os.Bundle.staticClass, "containsKey", "(Ljava/lang/String;)Z", ref global::android.os.Bundle._m33, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m34;
public global::android.os.Bundle getBundle(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<android.os.Bundle>(this, global::android.os.Bundle.staticClass, "getBundle", "(Ljava/lang/String;)Landroid/os/Bundle;", ref global::android.os.Bundle._m34, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.os.Bundle;
}
private static global::MonoJavaBridge.MethodId _m35;
public global::java.lang.String getString(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallSealedClassObjectMethod<java.lang.String>(this, global::android.os.Bundle.staticClass, "getString", "(Ljava/lang/String;)Ljava/lang/String;", ref global::android.os.Bundle._m35, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String;
}
private static global::MonoJavaBridge.MethodId _m36;
public void writeToParcel(android.os.Parcel arg0, int arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "writeToParcel", "(Landroid/os/Parcel;I)V", ref global::android.os.Bundle._m36, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m37;
public int describeContents()
{
return global::MonoJavaBridge.JavaBridge.CallIntMethod(this, global::android.os.Bundle.staticClass, "describeContents", "()I", ref global::android.os.Bundle._m37);
}
private static global::MonoJavaBridge.MethodId _m38;
public bool hasFileDescriptors()
{
return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::android.os.Bundle.staticClass, "hasFileDescriptors", "()Z", ref global::android.os.Bundle._m38);
}
private static global::MonoJavaBridge.MethodId _m39;
public void readFromParcel(android.os.Parcel arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "readFromParcel", "(Landroid/os/Parcel;)V", ref global::android.os.Bundle._m39, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m40;
public global::java.lang.String[] getStringArray(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.String>(this, global::android.os.Bundle.staticClass, "getStringArray", "(Ljava/lang/String;)[Ljava/lang/String;", ref global::android.os.Bundle._m40, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.String[];
}
private static global::MonoJavaBridge.MethodId _m41;
public int[] getIntArray(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<int>(this, global::android.os.Bundle.staticClass, "getIntArray", "(Ljava/lang/String;)[I", ref global::android.os.Bundle._m41, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as int[];
}
public new global::java.lang.ClassLoader ClassLoader
{
set
{
setClassLoader(value);
}
}
private static global::MonoJavaBridge.MethodId _m42;
public void setClassLoader(java.lang.ClassLoader arg0)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "setClassLoader", "(Ljava/lang/ClassLoader;)V", ref global::android.os.Bundle._m42, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
private static global::MonoJavaBridge.MethodId _m43;
public void putString(java.lang.String arg0, java.lang.String arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putString", "(Ljava/lang/String;Ljava/lang/String;)V", ref global::android.os.Bundle._m43, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m44;
public void putCharSequence(java.lang.String arg0, java.lang.CharSequence arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putCharSequence", "(Ljava/lang/String;Ljava/lang/CharSequence;)V", ref global::android.os.Bundle._m44, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
public void putCharSequence(java.lang.String arg0, string arg1)
{
putCharSequence(arg0, (global::java.lang.CharSequence)(global::java.lang.String)arg1);
}
private static global::MonoJavaBridge.MethodId _m45;
public void putParcelable(java.lang.String arg0, android.os.Parcelable arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putParcelable", "(Ljava/lang/String;Landroid/os/Parcelable;)V", ref global::android.os.Bundle._m45, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m46;
public void putParcelableArray(java.lang.String arg0, android.os.Parcelable[] arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putParcelableArray", "(Ljava/lang/String;[Landroid/os/Parcelable;)V", ref global::android.os.Bundle._m46, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m47;
public void putParcelableArrayList(java.lang.String arg0, java.util.ArrayList arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putParcelableArrayList", "(Ljava/lang/String;Ljava/util/ArrayList;)V", ref global::android.os.Bundle._m47, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m48;
public void putSparseParcelableArray(java.lang.String arg0, android.util.SparseArray arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putSparseParcelableArray", "(Ljava/lang/String;Landroid/util/SparseArray;)V", ref global::android.os.Bundle._m48, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m49;
public void putIntegerArrayList(java.lang.String arg0, java.util.ArrayList arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putIntegerArrayList", "(Ljava/lang/String;Ljava/util/ArrayList;)V", ref global::android.os.Bundle._m49, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m50;
public void putStringArrayList(java.lang.String arg0, java.util.ArrayList arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putStringArrayList", "(Ljava/lang/String;Ljava/util/ArrayList;)V", ref global::android.os.Bundle._m50, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m51;
public void putCharSequenceArrayList(java.lang.String arg0, java.util.ArrayList arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putCharSequenceArrayList", "(Ljava/lang/String;Ljava/util/ArrayList;)V", ref global::android.os.Bundle._m51, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m52;
public void putSerializable(java.lang.String arg0, java.io.Serializable arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putSerializable", "(Ljava/lang/String;Ljava/io/Serializable;)V", ref global::android.os.Bundle._m52, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m53;
public void putBooleanArray(java.lang.String arg0, bool[] arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putBooleanArray", "(Ljava/lang/String;[Z)V", ref global::android.os.Bundle._m53, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m54;
public void putByteArray(java.lang.String arg0, byte[] arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putByteArray", "(Ljava/lang/String;[B)V", ref global::android.os.Bundle._m54, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m55;
public void putShortArray(java.lang.String arg0, short[] arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putShortArray", "(Ljava/lang/String;[S)V", ref global::android.os.Bundle._m55, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m56;
public void putCharArray(java.lang.String arg0, char[] arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putCharArray", "(Ljava/lang/String;[C)V", ref global::android.os.Bundle._m56, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m57;
public void putIntArray(java.lang.String arg0, int[] arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putIntArray", "(Ljava/lang/String;[I)V", ref global::android.os.Bundle._m57, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m58;
public void putLongArray(java.lang.String arg0, long[] arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putLongArray", "(Ljava/lang/String;[J)V", ref global::android.os.Bundle._m58, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m59;
public void putFloatArray(java.lang.String arg0, float[] arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putFloatArray", "(Ljava/lang/String;[F)V", ref global::android.os.Bundle._m59, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m60;
public void putDoubleArray(java.lang.String arg0, double[] arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putDoubleArray", "(Ljava/lang/String;[D)V", ref global::android.os.Bundle._m60, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m61;
public void putStringArray(java.lang.String arg0, java.lang.String[] arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putStringArray", "(Ljava/lang/String;[Ljava/lang/String;)V", ref global::android.os.Bundle._m61, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m62;
public void putCharSequenceArray(java.lang.String arg0, java.lang.CharSequence[] arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putCharSequenceArray", "(Ljava/lang/String;[Ljava/lang/CharSequence;)V", ref global::android.os.Bundle._m62, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m63;
public void putBundle(java.lang.String arg0, android.os.Bundle arg1)
{
global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::android.os.Bundle.staticClass, "putBundle", "(Ljava/lang/String;Landroid/os/Bundle;)V", ref global::android.os.Bundle._m63, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1));
}
private static global::MonoJavaBridge.MethodId _m64;
public global::java.lang.CharSequence getCharSequence(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.lang.CharSequence>(this, global::android.os.Bundle.staticClass, "getCharSequence", "(Ljava/lang/String;)Ljava/lang/CharSequence;", ref global::android.os.Bundle._m64, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.CharSequence;
}
private static global::MonoJavaBridge.MethodId _m65;
public global::android.os.Parcelable getParcelable(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<android.os.Parcelable>(this, global::android.os.Bundle.staticClass, "getParcelable", "(Ljava/lang/String;)Landroid/os/Parcelable;", ref global::android.os.Bundle._m65, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.os.Parcelable;
}
private static global::MonoJavaBridge.MethodId _m66;
public global::android.os.Parcelable[] getParcelableArray(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<android.os.Parcelable>(this, global::android.os.Bundle.staticClass, "getParcelableArray", "(Ljava/lang/String;)[Landroid/os/Parcelable;", ref global::android.os.Bundle._m66, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.os.Parcelable[];
}
private static global::MonoJavaBridge.MethodId _m67;
public global::java.util.ArrayList getParcelableArrayList(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Bundle.staticClass, "getParcelableArrayList", "(Ljava/lang/String;)Ljava/util/ArrayList;", ref global::android.os.Bundle._m67, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.ArrayList;
}
private static global::MonoJavaBridge.MethodId _m68;
public global::android.util.SparseArray getSparseParcelableArray(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Bundle.staticClass, "getSparseParcelableArray", "(Ljava/lang/String;)Landroid/util/SparseArray;", ref global::android.os.Bundle._m68, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as android.util.SparseArray;
}
private static global::MonoJavaBridge.MethodId _m69;
public global::java.io.Serializable getSerializable(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallIJavaObjectMethod<java.io.Serializable>(this, global::android.os.Bundle.staticClass, "getSerializable", "(Ljava/lang/String;)Ljava/io/Serializable;", ref global::android.os.Bundle._m69, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.io.Serializable;
}
private static global::MonoJavaBridge.MethodId _m70;
public global::java.util.ArrayList getIntegerArrayList(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Bundle.staticClass, "getIntegerArrayList", "(Ljava/lang/String;)Ljava/util/ArrayList;", ref global::android.os.Bundle._m70, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.ArrayList;
}
private static global::MonoJavaBridge.MethodId _m71;
public global::java.util.ArrayList getStringArrayList(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Bundle.staticClass, "getStringArrayList", "(Ljava/lang/String;)Ljava/util/ArrayList;", ref global::android.os.Bundle._m71, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.ArrayList;
}
private static global::MonoJavaBridge.MethodId _m72;
public global::java.util.ArrayList getCharSequenceArrayList(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::android.os.Bundle.staticClass, "getCharSequenceArrayList", "(Ljava/lang/String;)Ljava/util/ArrayList;", ref global::android.os.Bundle._m72, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.util.ArrayList;
}
private static global::MonoJavaBridge.MethodId _m73;
public bool[] getBooleanArray(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<bool>(this, global::android.os.Bundle.staticClass, "getBooleanArray", "(Ljava/lang/String;)[Z", ref global::android.os.Bundle._m73, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as bool[];
}
private static global::MonoJavaBridge.MethodId _m74;
public byte[] getByteArray(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<byte>(this, global::android.os.Bundle.staticClass, "getByteArray", "(Ljava/lang/String;)[B", ref global::android.os.Bundle._m74, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as byte[];
}
private static global::MonoJavaBridge.MethodId _m75;
public short[] getShortArray(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<short>(this, global::android.os.Bundle.staticClass, "getShortArray", "(Ljava/lang/String;)[S", ref global::android.os.Bundle._m75, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as short[];
}
private static global::MonoJavaBridge.MethodId _m76;
public char[] getCharArray(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<char>(this, global::android.os.Bundle.staticClass, "getCharArray", "(Ljava/lang/String;)[C", ref global::android.os.Bundle._m76, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as char[];
}
private static global::MonoJavaBridge.MethodId _m77;
public long[] getLongArray(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<long>(this, global::android.os.Bundle.staticClass, "getLongArray", "(Ljava/lang/String;)[J", ref global::android.os.Bundle._m77, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as long[];
}
private static global::MonoJavaBridge.MethodId _m78;
public float[] getFloatArray(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<float>(this, global::android.os.Bundle.staticClass, "getFloatArray", "(Ljava/lang/String;)[F", ref global::android.os.Bundle._m78, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as float[];
}
private static global::MonoJavaBridge.MethodId _m79;
public double[] getDoubleArray(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<double>(this, global::android.os.Bundle.staticClass, "getDoubleArray", "(Ljava/lang/String;)[D", ref global::android.os.Bundle._m79, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as double[];
}
private static global::MonoJavaBridge.MethodId _m80;
public global::java.lang.CharSequence[] getCharSequenceArray(java.lang.String arg0)
{
return global::MonoJavaBridge.JavaBridge.CallArrayObjectMethod<java.lang.CharSequence>(this, global::android.os.Bundle.staticClass, "getCharSequenceArray", "(Ljava/lang/String;)[Ljava/lang/CharSequence;", ref global::android.os.Bundle._m80, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.CharSequence[];
}
private static global::MonoJavaBridge.MethodId _m81;
public Bundle(android.os.Bundle arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Bundle._m81.native == global::System.IntPtr.Zero)
global::android.os.Bundle._m81 = @__env.GetMethodIDNoThrow(global::android.os.Bundle.staticClass, "<init>", "(Landroid/os/Bundle;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.Bundle.staticClass, global::android.os.Bundle._m81, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m82;
public Bundle(java.lang.ClassLoader arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Bundle._m82.native == global::System.IntPtr.Zero)
global::android.os.Bundle._m82 = @__env.GetMethodIDNoThrow(global::android.os.Bundle.staticClass, "<init>", "(Ljava/lang/ClassLoader;)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.Bundle.staticClass, global::android.os.Bundle._m82, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m83;
public Bundle(int arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Bundle._m83.native == global::System.IntPtr.Zero)
global::android.os.Bundle._m83 = @__env.GetMethodIDNoThrow(global::android.os.Bundle.staticClass, "<init>", "(I)V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.Bundle.staticClass, global::android.os.Bundle._m83, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static global::MonoJavaBridge.MethodId _m84;
public Bundle() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (global::android.os.Bundle._m84.native == global::System.IntPtr.Zero)
global::android.os.Bundle._m84 = @__env.GetMethodIDNoThrow(global::android.os.Bundle.staticClass, "<init>", "()V");
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.os.Bundle.staticClass, global::android.os.Bundle._m84);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.FieldId _EMPTY3946;
public static global::android.os.Bundle EMPTY
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapJavaObjectSealedClass<android.os.Bundle>(@__env.GetStaticObjectField(global::android.os.Bundle.staticClass, _EMPTY3946)) as android.os.Bundle;
}
}
internal static global::MonoJavaBridge.FieldId _CREATOR3947;
public static global::android.os.Parcelable_Creator CREATOR
{
get
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
return global::MonoJavaBridge.JavaBridge.WrapIJavaObject<global::android.os.Parcelable_Creator>(@__env.GetStaticObjectField(global::android.os.Bundle.staticClass, _CREATOR3947)) as android.os.Parcelable_Creator;
}
}
static Bundle()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.os.Bundle.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/os/Bundle"));
global::android.os.Bundle._EMPTY3946 = @__env.GetStaticFieldIDNoThrow(global::android.os.Bundle.staticClass, "EMPTY", "Landroid/os/Bundle;");
global::android.os.Bundle._CREATOR3947 = @__env.GetStaticFieldIDNoThrow(global::android.os.Bundle.staticClass, "CREATOR", "Landroid/os/Parcelable$Creator;");
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Threading;
namespace Apache.Geode.Client.UnitTests
{
using NUnit.Framework;
using Apache.Geode.DUnitFramework;
using Apache.Geode.Client.Tests;
using Apache.Geode.Client;
[TestFixture]
[Category("group3")]
[Category("unicast_only")]
[Category("generics")]
public class ThinClientSecurityAuthzTests : ThinClientSecurityAuthzTestBase
{
#region Private members
IRegion<object, object> region;
IRegion<object, object> region1;
private UnitProcess m_client1;
private UnitProcess m_client2;
private UnitProcess m_client3;
private TallyListener<object, object> m_listener;
private TallyWriter<object, object> m_writer;
private string keys = "Key";
private string value = "Value";
#endregion
protected override ClientBase[] GetClients()
{
m_client1 = new UnitProcess();
m_client2 = new UnitProcess();
m_client3 = new UnitProcess();
return new ClientBase[] { m_client1, m_client2, m_client3 };
}
public void CreateRegion(string locators, bool caching,
bool listener, bool writer)
{
if (listener)
{
m_listener = new TallyListener<object, object>();
}
else
{
m_listener = null;
}
IRegion<object, object> region = null;
region = CacheHelper.CreateTCRegion_Pool<object, object>(RegionName, true, caching,
m_listener, locators, "__TESTPOOL1_", true);
if (writer)
{
m_writer = new TallyWriter<object, object>();
}
else
{
m_writer = null;
}
AttributesMutator<object, object> at = region.AttributesMutator;
at.SetCacheWriter(m_writer);
}
public void DoPut()
{
region = CacheHelper.GetRegion<object, object>(RegionName);
region[keys] = value;
}
public void CheckAssert()
{
Assert.AreEqual(true, m_writer.IsWriterInvoked, "Writer Should be invoked");
Assert.AreEqual(false, m_listener.IsListenerInvoked, "Listener Should not be invoked");
Assert.IsFalse(region.GetLocalView().ContainsKey(keys), "Key should have been found in the region");
}
public void DoLocalPut()
{
region1 = CacheHelper.GetRegion<object, object>(RegionName);
region1.GetLocalView()[m_keys[2]] = m_vals[2];
Assert.IsTrue(region1.GetLocalView().ContainsKey(m_keys[2]), "Key should have been found in the region");
Assert.AreEqual(true, m_writer.IsWriterInvoked, "Writer Should be invoked");
Assert.AreEqual(true, m_listener.IsListenerInvoked, "Listener Should be invoked");
//try Update
try
{
Util.Log("Trying UpdateEntry");
m_listener.ResetListenerInvokation();
UpdateEntry(RegionName, m_keys[2], m_nvals[2], false);
Assert.Fail("Should have got NotAuthorizedException during updateEntry");
}
catch (NotAuthorizedException)
{
Util.Log("NotAuthorizedException Caught");
Util.Log("Success");
}
catch (Exception other)
{
Util.Log("Stack trace: {0} ", other.StackTrace);
Util.Log("Got exception : {0}", other.Message);
}
Assert.AreEqual(true, m_writer.IsWriterInvoked, "Writer should be invoked");
Assert.AreEqual(false, m_listener.IsListenerInvoked, "Listener should not be invoked");
Assert.IsTrue(region1.GetLocalView().ContainsKey(m_keys[2]), "Key should have been found in the region");
VerifyEntry(RegionName, m_keys[2], m_vals[2]);
m_writer.SetWriterFailed();
//test CacheWriter
try
{
Util.Log("Testing CacheWriterException");
UpdateEntry(RegionName, m_keys[2], m_nvals[2], false);
Assert.Fail("Should have got NotAuthorizedException during updateEntry");
}
catch (CacheWriterException)
{
Util.Log("CacheWriterException Caught");
Util.Log("Success");
}
}
[TestFixtureTearDown]
public override void EndTests()
{
CacheHelper.StopJavaServers();
base.EndTests();
}
[TearDown]
public override void EndTest()
{
try
{
if (m_clients != null)
{
foreach (ClientBase client in m_clients)
{
client.Call(CacheHelper.Close);
}
}
CacheHelper.Close();
CacheHelper.ClearEndpoints();
}
finally
{
CacheHelper.StopJavaServers();
}
base.EndTest();
}
void runAllowPutsGets()
{
CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2);
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(false))
{
CredentialGenerator cGen = authzGen.GetCredentialGenerator();
Properties<string, string> extraAuthProps = cGen.SystemProperties;
Properties<string, string> javaProps = cGen.JavaProperties;
Properties<string, string> extraAuthzProps = authzGen.SystemProperties;
string authenticator = cGen.Authenticator;
string authInit = cGen.AuthInit;
string accessor = authzGen.AccessControl;
Util.Log("testAllowPutsGets: Using authinit: " + authInit);
Util.Log("testAllowPutsGets: Using authenticator: " + authenticator);
Util.Log("testAllowPutsGets: Using accessor: " + accessor);
// Start servers with all required properties
string serverArgs = SecurityTestUtil.GetServerArgs(authenticator,
accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps,
extraAuthzProps), javaProps);
// Start the two servers.
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs);
Util.Log("Cacheserver 1 started.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs);
Util.Log("Cacheserver 2 started.");
// Start client1 with valid CREATE credentials
Properties<string, string> createCredentials = authzGen.GetAllowedCredentials(
new OperationCode[] { OperationCode.Put },
new string[] { RegionName }, 1);
javaProps = cGen.JavaProperties;
Util.Log("AllowPutsGets: For first client PUT credentials: " +
createCredentials);
m_client1.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, createCredentials);
// Start client2 with valid GET credentials
Properties<string, string> getCredentials = authzGen.GetAllowedCredentials(
new OperationCode[] { OperationCode.Get },
new string[] { RegionName }, 2);
javaProps = cGen.JavaProperties;
Util.Log("AllowPutsGets: For second client GET credentials: " +
getCredentials);
m_client2.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, getCredentials);
// Perform some put operations from client1
m_client1.Call(DoPuts, 2);
// Verify that the gets succeed
m_client2.Call(DoGets, 2);
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaServer(2);
}
CacheHelper.StopJavaLocator(1);
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runDisallowPutsGets()
{
CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2);
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(false))
{
CredentialGenerator cGen = authzGen.GetCredentialGenerator();
Properties<string, string> extraAuthProps = cGen.SystemProperties;
Properties<string, string> javaProps = cGen.JavaProperties;
Properties<string, string> extraAuthzProps = authzGen.SystemProperties;
string authenticator = cGen.Authenticator;
string authInit = cGen.AuthInit;
string accessor = authzGen.AccessControl;
Util.Log("DisallowPutsGets: Using authinit: " + authInit);
Util.Log("DisallowPutsGets: Using authenticator: " + authenticator);
Util.Log("DisallowPutsGets: Using accessor: " + accessor);
// Check that we indeed can obtain valid credentials not allowed to do
// gets
Properties<string, string> createCredentials = authzGen.GetAllowedCredentials(
new OperationCode[] { OperationCode.Put },
new string[] { RegionName }, 1);
Properties<string, string> createJavaProps = cGen.JavaProperties;
Properties<string, string> getCredentials = authzGen.GetDisallowedCredentials(
new OperationCode[] { OperationCode.Get },
new string[] { RegionName }, 2);
Properties<string, string> getJavaProps = cGen.JavaProperties;
if (getCredentials == null || getCredentials.Size == 0)
{
Util.Log("DisallowPutsGets: Unable to obtain valid credentials " +
"with no GET permission; skipping this combination.");
continue;
}
// Start servers with all required properties
string serverArgs = SecurityTestUtil.GetServerArgs(authenticator,
accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps,
extraAuthzProps), javaProps);
// Start the two servers.
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs);
Util.Log("Cacheserver 1 started.");
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs);
Util.Log("Cacheserver 2 started.");
// Start client1 with valid CREATE credentials
createCredentials = authzGen.GetAllowedCredentials(
new OperationCode[] { OperationCode.Put },
new string[] { RegionName }, 1);
javaProps = cGen.JavaProperties;
Util.Log("DisallowPutsGets: For first client PUT credentials: " +
createCredentials);
m_client1.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, createCredentials);
// Start client2 with invalid GET credentials
getCredentials = authzGen.GetDisallowedCredentials(
new OperationCode[] { OperationCode.Get },
new string[] { RegionName }, 2);
javaProps = cGen.JavaProperties;
Util.Log("DisallowPutsGets: For second client invalid GET " +
"credentials: " + getCredentials);
m_client2.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, getCredentials);
// Perform some put operations from client1
m_client1.Call(DoPuts, 2);
// Verify that the gets throw exception
m_client2.Call(DoGets, 2, false, ExpectedResult.NotAuthorizedException);
// Try to connect client2 with reader credentials
getCredentials = authzGen.GetAllowedCredentials(
new OperationCode[] { OperationCode.Get },
new string[] { RegionName }, 5);
javaProps = cGen.JavaProperties;
Util.Log("DisallowPutsGets: For second client valid GET " +
"credentials: " + getCredentials);
m_client2.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, getCredentials);
// Verify that the gets succeed
m_client2.Call(DoGets, 2);
// Verify that the puts throw exception
m_client2.Call(DoPuts, 2, true, ExpectedResult.NotAuthorizedException);
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(1);
CacheHelper.StopJavaServer(2);
}
CacheHelper.StopJavaLocator(1);
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runInvalidAccessor()
{
CacheHelper.SetupJavaServers(true, CacheXml1, CacheXml2);
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(false))
{
CredentialGenerator cGen = authzGen.GetCredentialGenerator();
Properties<string, string> extraAuthProps = cGen.SystemProperties;
Properties<string, string> javaProps = cGen.JavaProperties;
Properties<string, string> extraAuthzProps = authzGen.SystemProperties;
string authenticator = cGen.Authenticator;
string authInit = cGen.AuthInit;
string accessor = authzGen.AccessControl;
Util.Log("InvalidAccessor: Using authinit: " + authInit);
Util.Log("InvalidAccessor: Using authenticator: " + authenticator);
// Start server1 with invalid accessor
string serverArgs = SecurityTestUtil.GetServerArgs(authenticator,
"com.gemstone.none", null, SecurityTestUtil.ConcatProperties(extraAuthProps,
extraAuthzProps), javaProps);
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs);
Util.Log("Cacheserver 1 started.");
// Client creation should throw exceptions
Properties<string, string> createCredentials = authzGen.GetAllowedCredentials(
new OperationCode[] { OperationCode.Put },
new string[] { RegionName }, 3);
javaProps = cGen.JavaProperties;
Util.Log("InvalidAccessor: For first client PUT credentials: " +
createCredentials);
m_client1.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, createCredentials,
ExpectedResult.OtherException);
Properties<string, string> getCredentials = authzGen.GetAllowedCredentials(
new OperationCode[] { OperationCode.Get },
new string[] { RegionName }, 7);
javaProps = cGen.JavaProperties;
Util.Log("InvalidAccessor: For second client GET credentials: " +
getCredentials);
m_client2.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, getCredentials,
ExpectedResult.OtherException);
// Now start server2 that has valid accessor
Util.Log("InvalidAccessor: Using accessor: " + accessor);
serverArgs = SecurityTestUtil.GetServerArgs(authenticator,
accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps,
extraAuthzProps), javaProps);
CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1, serverArgs);
Util.Log("Cacheserver 2 started.");
CacheHelper.StopJavaServer(1);
// Client creation should be successful now
m_client1.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, createCredentials);
m_client2.Call(SecurityTestUtil.CreateClient, RegionName,
CacheHelper.Locators, authInit, getCredentials);
// Now perform some put operations from client1
m_client1.Call(DoPuts, 4);
// Verify that the gets succeed
m_client2.Call(DoGets, 4);
m_client1.Call(Close);
m_client2.Call(Close);
CacheHelper.StopJavaServer(2);
}
CacheHelper.StopJavaLocator(1);
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
void runAllOpsWithFailover()
{
runAllOpsWithFailover(false, false);
}
void runAllOpsWithFailover(bool ssl, bool withPassword)
{
OperationWithAction[] allOps = {
// Test CREATE and verify with a GET
new OperationWithAction(OperationCode.Put, 3, OpFlags.CheckNotAuthz, 4),
new OperationWithAction(OperationCode.Put),
new OperationWithAction(OperationCode.Get, 3, OpFlags.CheckNoKey
| OpFlags.CheckNotAuthz, 4),
new OperationWithAction(OperationCode.Get, 2, OpFlags.CheckNoKey, 4),
// OPBLOCK_END indicates end of an operation block; the above block of
// three operations will be first executed on server1 and then on
// server2 after failover
OperationWithAction.OpBlockEnd,
// Test GetServerKeys (KEY_SET) operation.
new OperationWithAction(OperationCode.GetServerKeys),
new OperationWithAction(OperationCode.GetServerKeys, 3, OpFlags.CheckNotAuthz, 4),
OperationWithAction.OpBlockEnd,
// Test UPDATE and verify with a GET
new OperationWithAction(OperationCode.Put, 3, OpFlags.UseNewVal
| OpFlags.CheckNotAuthz, 4),
new OperationWithAction(OperationCode.Put, 1, OpFlags.UseNewVal, 4),
new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn
| OpFlags.UseNewVal, 4),
OperationWithAction.OpBlockEnd,
// Test DESTROY and verify with a GET and that key should not exist
new OperationWithAction(OperationCode.Destroy, 3, OpFlags.UseNewVal
| OpFlags.CheckNotAuthz, 4),
new OperationWithAction(OperationCode.Destroy),
new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn
| OpFlags.CheckFail, 4),
// Repopulate the region
new OperationWithAction(OperationCode.Put, 1, OpFlags.UseNewVal, 4),
OperationWithAction.OpBlockEnd,
// Check QUERY
new OperationWithAction(OperationCode.Put),
new OperationWithAction(OperationCode.Query, 3,
OpFlags.CheckNotAuthz, 4),
new OperationWithAction(OperationCode.Query),
OperationWithAction.OpBlockEnd,
// Register interest in all keys
new OperationWithAction(OperationCode.RegisterInterest, 3,
OpFlags.UseAllKeys | OpFlags.CheckNotAuthz, 4),
new OperationWithAction(OperationCode.RegisterInterest, 2,
OpFlags.UseAllKeys, 4),
// UPDATE and test with GET
new OperationWithAction(OperationCode.Put),
new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn
| OpFlags.LocalOp, 4),
// Unregister interest in all keys
new OperationWithAction(OperationCode.UnregisterInterest, 2,
OpFlags.UseAllKeys | OpFlags.UseOldConn, 4),
// UPDATE and test with GET for no updates
new OperationWithAction(OperationCode.Put, 1, OpFlags.UseOldConn
| OpFlags.UseNewVal, 4),
new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn
| OpFlags.LocalOp, 4),
OperationWithAction.OpBlockEnd,
/// PutAll, GetAll, ExecuteCQ and ExecuteFunction ops
new OperationWithAction(OperationCode.PutAll),
// NOTE: GetAll depends on previous PutAll so it should happen right after.
new OperationWithAction(OperationCode.GetAll),
new OperationWithAction(OperationCode.RemoveAll),
new OperationWithAction(OperationCode.ExecuteCQ),
new OperationWithAction(OperationCode.ExecuteFunction),
OperationWithAction.OpBlockEnd,
// Register interest in all keys using list
new OperationWithAction(OperationCode.RegisterInterest, 3,
OpFlags.UseList | OpFlags.CheckNotAuthz, 4),
new OperationWithAction(OperationCode.RegisterInterest, 1,
OpFlags.UseList, 4),
// UPDATE and test with GET
new OperationWithAction(OperationCode.Put, 2),
new OperationWithAction(OperationCode.Get, 1, OpFlags.UseOldConn
| OpFlags.LocalOp, 4),
// Unregister interest in all keys using list
new OperationWithAction(OperationCode.UnregisterInterest, 1,
OpFlags.UseOldConn | OpFlags.UseList, 4),
// UPDATE and test with GET for no updates
new OperationWithAction(OperationCode.Put, 2, OpFlags.UseOldConn
| OpFlags.UseNewVal, 4),
new OperationWithAction(OperationCode.Get, 1, OpFlags.UseOldConn
| OpFlags.LocalOp, 4),
OperationWithAction.OpBlockEnd,
// Register interest in all keys using regular expression
new OperationWithAction(OperationCode.RegisterInterest, 3,
OpFlags.UseRegex | OpFlags.CheckNotAuthz, 4),
new OperationWithAction(OperationCode.RegisterInterest, 2,
OpFlags.UseRegex, 4),
// UPDATE and test with GET
new OperationWithAction(OperationCode.Put),
new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn
| OpFlags.LocalOp, 4),
// Unregister interest in all keys using regular expression
new OperationWithAction(OperationCode.UnregisterInterest, 2,
OpFlags.UseOldConn | OpFlags.UseRegex, 4),
// UPDATE and test with GET for no updates
new OperationWithAction(OperationCode.Put, 1, OpFlags.UseOldConn
| OpFlags.UseNewVal, 4),
new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn
| OpFlags.LocalOp, 4),
OperationWithAction.OpBlockEnd,
// Do REGION_DESTROY of the sub-region and check with GET
new OperationWithAction(OperationCode.Put, 1, OpFlags.UseSubRegion,
8),
new OperationWithAction(OperationCode.RegionDestroy, 3,
OpFlags.UseSubRegion | OpFlags.CheckNotAuthz, 1),
new OperationWithAction(OperationCode.RegionDestroy, 1,
OpFlags.UseSubRegion, 1),
new OperationWithAction(OperationCode.Get, 2, OpFlags.UseSubRegion
| OpFlags.CheckNoKey | OpFlags.CheckException, 8),
// Do REGION_DESTROY of the region and check with GET
new OperationWithAction(OperationCode.RegionDestroy, 3,
OpFlags.CheckNotAuthz, 1),
new OperationWithAction(OperationCode.RegionDestroy, 1, OpFlags.None,
1),
new OperationWithAction(OperationCode.Get, 2, OpFlags.UseOldConn
| OpFlags.CheckNoKey | OpFlags.CheckException, 8),
// Skip failover for region destroy since it shall fail
// without restarting the server
OperationWithAction.OpBlockNoFailover
};
if (ssl == true && withPassword == true)
{
RunOpsWithFailoverSSL(allOps, "AllOpsWithFailover", true);
}
else if(ssl == true)
RunOpsWithFailoverSSL(allOps, "AllOpsWithFailover", false);
else
RunOpsWithFailover(allOps, "AllOpsWithFailover");
}
void runThinClientWriterExceptionTest()
{
CacheHelper.SetupJavaServers(true, CacheXml1);
CacheHelper.StartJavaLocator(1, "GFELOC");
Util.Log("Locator started");
foreach (AuthzCredentialGenerator authzGen in GetAllGeneratorCombos(false))
{
for (int i = 1; i <= 2; ++i)
{
CredentialGenerator cGen = authzGen.GetCredentialGenerator();
Properties<string, string> extraAuthProps = cGen.SystemProperties;
Properties<string, string> javaProps = cGen.JavaProperties;
Properties<string, string> extraAuthzProps = authzGen.SystemProperties;
string authenticator = cGen.Authenticator;
string authInit = cGen.AuthInit;
string accessor = authzGen.AccessControl;
Util.Log("ThinClientWriterException: Using authinit: " + authInit);
Util.Log("ThinClientWriterException: Using authenticator: " + authenticator);
Util.Log("ThinClientWriterException: Using accessor: " + accessor);
// Start servers with all required properties
string serverArgs = SecurityTestUtil.GetServerArgs(authenticator,
accessor, null, SecurityTestUtil.ConcatProperties(extraAuthProps,
extraAuthzProps), javaProps);
// Start the server.
CacheHelper.StartJavaServerWithLocators(1, "GFECS1", 1, serverArgs);
Util.Log("Cacheserver 1 started.");
// Start client1 with valid CREATE credentials
Properties<string, string> createCredentials = authzGen.GetDisallowedCredentials(
new OperationCode[] { OperationCode.Put },
new string[] { RegionName }, 1);
javaProps = cGen.JavaProperties;
Util.Log("DisallowPuts: For first client PUT credentials: " +
createCredentials);
m_client1.Call(SecurityTestUtil.CreateClientR0, RegionName,
CacheHelper.Locators, authInit, createCredentials);
Util.Log("Creating region in client1 , no-ack, no-cache, with listener and writer");
m_client1.Call(CreateRegion,CacheHelper.Locators,
true, true, true);
m_client1.Call(RegisterAllKeys, new string[] { RegionName });
try
{
Util.Log("Trying put Operation");
m_client1.Call(DoPut);
Util.Log(" Put Operation Successful");
Assert.Fail("Should have got NotAuthorizedException during put");
}
catch (NotAuthorizedException)
{
Util.Log("NotAuthorizedException Caught");
Util.Log("Success");
}
catch (Exception other)
{
Util.Log("Stack trace: {0} ", other.StackTrace);
Util.Log("Got exception : {0}",
other.Message);
}
m_client1.Call(CheckAssert);
// Do LocalPut
m_client1.Call(DoLocalPut);
m_client1.Call(Close);
CacheHelper.StopJavaServer(1);
}
}
CacheHelper.StopJavaLocator(1);
CacheHelper.ClearEndpoints();
CacheHelper.ClearLocators();
}
#region Tests
[Test]
public void AllowPutsGets()
{
runAllowPutsGets();
}
[Test]
public void DisallowPutsGets()
{
runDisallowPutsGets();
}
//this test no more valid as the way we do auth now change, so it gets different exception
//[Test]
public void InvalidAccessor()
{
//runInvalidAccessor();
}
[Test]
public void AllOpsWithFailover()
{
runAllOpsWithFailover();
}
[Test]
public void AllOpsWithFailoverWithSSL()
{
// SSL CAN ONLY BE ENABLED WITH LOCATORS THUS REQUIRING POOLS.
runAllOpsWithFailover(true, false); // pool with locator with ssl
}
[Test]
public void AllOpsWithFailoverWithSSLWithPassword()
{
// SSL CAN ONLY BE ENABLED WITH LOCATORS THUS REQUIRING POOLS.
runAllOpsWithFailover(true, true); // pool with locator with ssl
}
[Test]
public void ThinClientWriterExceptionTest()
{
runThinClientWriterExceptionTest();
}
#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.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
namespace System.ComponentModel
{
/// <devdoc>
/// <para>Specifies the default value for a property.</para>
/// </devdoc>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1019:DefineAccessorsForAttributeArguments")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes")]
[AttributeUsage(AttributeTargets.All)]
public class DefaultValueAttribute : Attribute
{
/// <devdoc>
/// This is the default value.
/// </devdoc>
private object _value;
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class, converting the
/// specified value to the
/// specified type, and using the U.S. English culture as the
/// translation
/// context.</para>
/// </devdoc>
public DefaultValueAttribute(Type type, string value)
{
// The try/catch here is because attributes should never throw exceptions. We would fail to
// load an otherwise normal class.
try
{
if (type.IsSubclassOf(typeof(Enum)))
{
_value = Enum.Parse(type, value, true);
}
else if (type == typeof(TimeSpan))
{
_value = TimeSpan.Parse(value);
}
else
{
_value = Convert.ChangeType(value, type, CultureInfo.InvariantCulture);
}
}
catch
{
}
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a Unicode
/// character.</para>
/// </devdoc>
public DefaultValueAttribute(char value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using an 8-bit unsigned
/// integer.</para>
/// </devdoc>
public DefaultValueAttribute(byte value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a 16-bit signed
/// integer.</para>
/// </devdoc>
public DefaultValueAttribute(short value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a 32-bit signed
/// integer.</para>
/// </devdoc>
public DefaultValueAttribute(int value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a 64-bit signed
/// integer.</para>
/// </devdoc>
public DefaultValueAttribute(long value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a
/// single-precision floating point
/// number.</para>
/// </devdoc>
public DefaultValueAttribute(float value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a
/// double-precision floating point
/// number.</para>
/// </devdoc>
public DefaultValueAttribute(double value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.Boolean'/>
/// value.</para>
/// </devdoc>
public DefaultValueAttribute(bool value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.String'/>.</para>
/// </devdoc>
public DefaultValueAttribute(string value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/>
/// class.</para>
/// </devdoc>
public DefaultValueAttribute(object value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.SByte'/>
/// value.</para>
/// </devdoc>
[CLSCompliant(false)]
public DefaultValueAttribute(sbyte value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.UInt16'/>
/// value.</para>
/// </devdoc>
[CLSCompliant(false)]
public DefaultValueAttribute(ushort value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.UInt32'/>
/// value.</para>
/// </devdoc>
[CLSCompliant(false)]
public DefaultValueAttribute(uint value)
{
_value = value;
}
/// <devdoc>
/// <para>Initializes a new instance of the <see cref='System.ComponentModel.DefaultValueAttribute'/> class using a <see cref='System.UInt64'/>
/// value.</para>
/// </devdoc>
[CLSCompliant(false)]
public DefaultValueAttribute(ulong value)
{
_value = value;
}
/// <devdoc>
/// <para>
/// Gets the default value of the property this
/// attribute is
/// bound to.
/// </para>
/// </devdoc>
public virtual object Value
{
get
{
return _value;
}
}
public override bool Equals(object obj)
{
if (obj == this)
{
return true;
}
DefaultValueAttribute other = obj as DefaultValueAttribute;
if (other != null)
{
if (Value != null)
{
return Value.Equals(other.Value);
}
else
{
return (other.Value == null);
}
}
return false;
}
public override int GetHashCode()
{
return base.GetHashCode();
}
protected void SetValue(object value)
{
_value = value;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using GlmSharp.Swizzle;
// ReSharper disable InconsistentNaming
namespace GlmSharp
{
/// <summary>
/// Static class that contains static glm functions
/// </summary>
public static partial class glm
{
/// <summary>
/// Returns an object that can be used for arbitrary swizzling (e.g. swizzle.zy)
/// </summary>
public static swizzle_ivec4 swizzle(ivec4 v) => v.swizzle;
/// <summary>
/// Returns an array with all values
/// </summary>
public static int[] Values(ivec4 v) => v.Values;
/// <summary>
/// Returns an enumerator that iterates through all components.
/// </summary>
public static IEnumerator<int> GetEnumerator(ivec4 v) => v.GetEnumerator();
/// <summary>
/// Returns a string representation of this vector using ', ' as a seperator.
/// </summary>
public static string ToString(ivec4 v) => v.ToString();
/// <summary>
/// Returns a string representation of this vector using a provided seperator.
/// </summary>
public static string ToString(ivec4 v, string sep) => v.ToString(sep);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format provider for each component.
/// </summary>
public static string ToString(ivec4 v, string sep, IFormatProvider provider) => v.ToString(sep, provider);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format for each component.
/// </summary>
public static string ToString(ivec4 v, string sep, string format) => v.ToString(sep, format);
/// <summary>
/// Returns a string representation of this vector using a provided seperator and a format and format provider for each component.
/// </summary>
public static string ToString(ivec4 v, string sep, string format, IFormatProvider provider) => v.ToString(sep, format, provider);
/// <summary>
/// Returns the number of components (4).
/// </summary>
public static int Count(ivec4 v) => v.Count;
/// <summary>
/// Returns true iff this equals rhs component-wise.
/// </summary>
public static bool Equals(ivec4 v, ivec4 rhs) => v.Equals(rhs);
/// <summary>
/// Returns true iff this equals rhs type- and component-wise.
/// </summary>
public static bool Equals(ivec4 v, object obj) => v.Equals(obj);
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
public static int GetHashCode(ivec4 v) => v.GetHashCode();
/// <summary>
/// Returns a bvec4 from component-wise application of Equal (lhs == rhs).
/// </summary>
public static bvec4 Equal(ivec4 lhs, ivec4 rhs) => ivec4.Equal(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of NotEqual (lhs != rhs).
/// </summary>
public static bvec4 NotEqual(ivec4 lhs, ivec4 rhs) => ivec4.NotEqual(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of GreaterThan (lhs > rhs).
/// </summary>
public static bvec4 GreaterThan(ivec4 lhs, ivec4 rhs) => ivec4.GreaterThan(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of GreaterThanEqual (lhs >= rhs).
/// </summary>
public static bvec4 GreaterThanEqual(ivec4 lhs, ivec4 rhs) => ivec4.GreaterThanEqual(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of LesserThan (lhs < rhs).
/// </summary>
public static bvec4 LesserThan(ivec4 lhs, ivec4 rhs) => ivec4.LesserThan(lhs, rhs);
/// <summary>
/// Returns a bvec4 from component-wise application of LesserThanEqual (lhs <= rhs).
/// </summary>
public static bvec4 LesserThanEqual(ivec4 lhs, ivec4 rhs) => ivec4.LesserThanEqual(lhs, rhs);
/// <summary>
/// Returns a ivec4 from component-wise application of Abs (Math.Abs(v)).
/// </summary>
public static ivec4 Abs(ivec4 v) => ivec4.Abs(v);
/// <summary>
/// Returns a ivec4 from component-wise application of HermiteInterpolationOrder3 ((3 - 2 * v) * v * v).
/// </summary>
public static ivec4 HermiteInterpolationOrder3(ivec4 v) => ivec4.HermiteInterpolationOrder3(v);
/// <summary>
/// Returns a ivec4 from component-wise application of HermiteInterpolationOrder5 (((6 * v - 15) * v + 10) * v * v * v).
/// </summary>
public static ivec4 HermiteInterpolationOrder5(ivec4 v) => ivec4.HermiteInterpolationOrder5(v);
/// <summary>
/// Returns a ivec4 from component-wise application of Sqr (v * v).
/// </summary>
public static ivec4 Sqr(ivec4 v) => ivec4.Sqr(v);
/// <summary>
/// Returns a ivec4 from component-wise application of Pow2 (v * v).
/// </summary>
public static ivec4 Pow2(ivec4 v) => ivec4.Pow2(v);
/// <summary>
/// Returns a ivec4 from component-wise application of Pow3 (v * v * v).
/// </summary>
public static ivec4 Pow3(ivec4 v) => ivec4.Pow3(v);
/// <summary>
/// Returns a ivec4 from component-wise application of Step (v >= 0 ? 1 : 0).
/// </summary>
public static ivec4 Step(ivec4 v) => ivec4.Step(v);
/// <summary>
/// Returns a ivec4 from component-wise application of Sqrt ((int)Math.Sqrt((double)v)).
/// </summary>
public static ivec4 Sqrt(ivec4 v) => ivec4.Sqrt(v);
/// <summary>
/// Returns a ivec4 from component-wise application of InverseSqrt ((int)(1.0 / Math.Sqrt((double)v))).
/// </summary>
public static ivec4 InverseSqrt(ivec4 v) => ivec4.InverseSqrt(v);
/// <summary>
/// Returns a ivec4 from component-wise application of Sign (Math.Sign(v)).
/// </summary>
public static ivec4 Sign(ivec4 v) => ivec4.Sign(v);
/// <summary>
/// Returns a ivec4 from component-wise application of Max (Math.Max(lhs, rhs)).
/// </summary>
public static ivec4 Max(ivec4 lhs, ivec4 rhs) => ivec4.Max(lhs, rhs);
/// <summary>
/// Returns a ivec4 from component-wise application of Min (Math.Min(lhs, rhs)).
/// </summary>
public static ivec4 Min(ivec4 lhs, ivec4 rhs) => ivec4.Min(lhs, rhs);
/// <summary>
/// Returns a ivec4 from component-wise application of Pow ((int)Math.Pow((double)lhs, (double)rhs)).
/// </summary>
public static ivec4 Pow(ivec4 lhs, ivec4 rhs) => ivec4.Pow(lhs, rhs);
/// <summary>
/// Returns a ivec4 from component-wise application of Log ((int)Math.Log((double)lhs, (double)rhs)).
/// </summary>
public static ivec4 Log(ivec4 lhs, ivec4 rhs) => ivec4.Log(lhs, rhs);
/// <summary>
/// Returns a ivec4 from component-wise application of Clamp (Math.Min(Math.Max(v, min), max)).
/// </summary>
public static ivec4 Clamp(ivec4 v, ivec4 min, ivec4 max) => ivec4.Clamp(v, min, max);
/// <summary>
/// Returns a ivec4 from component-wise application of Mix (min * (1-a) + max * a).
/// </summary>
public static ivec4 Mix(ivec4 min, ivec4 max, ivec4 a) => ivec4.Mix(min, max, a);
/// <summary>
/// Returns a ivec4 from component-wise application of Lerp (min * (1-a) + max * a).
/// </summary>
public static ivec4 Lerp(ivec4 min, ivec4 max, ivec4 a) => ivec4.Lerp(min, max, a);
/// <summary>
/// Returns a ivec4 from component-wise application of Smoothstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder3()).
/// </summary>
public static ivec4 Smoothstep(ivec4 edge0, ivec4 edge1, ivec4 v) => ivec4.Smoothstep(edge0, edge1, v);
/// <summary>
/// Returns a ivec4 from component-wise application of Smootherstep (((v - edge0) / (edge1 - edge0)).Clamp().HermiteInterpolationOrder5()).
/// </summary>
public static ivec4 Smootherstep(ivec4 edge0, ivec4 edge1, ivec4 v) => ivec4.Smootherstep(edge0, edge1, v);
/// <summary>
/// Returns a ivec4 from component-wise application of Fma (a * b + c).
/// </summary>
public static ivec4 Fma(ivec4 a, ivec4 b, ivec4 c) => ivec4.Fma(a, b, c);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static imat2x4 OuterProduct(ivec4 c, ivec2 r) => ivec4.OuterProduct(c, r);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static imat3x4 OuterProduct(ivec4 c, ivec3 r) => ivec4.OuterProduct(c, r);
/// <summary>
/// OuterProduct treats the first parameter c as a column vector (matrix with one column) and the second parameter r as a row vector (matrix with one row) and does a linear algebraic matrix multiply c * r, yielding a matrix whose number of rows is the number of components in c and whose number of columns is the number of components in r.
/// </summary>
public static imat4 OuterProduct(ivec4 c, ivec4 r) => ivec4.OuterProduct(c, r);
/// <summary>
/// Returns a ivec4 from component-wise application of Add (lhs + rhs).
/// </summary>
public static ivec4 Add(ivec4 lhs, ivec4 rhs) => ivec4.Add(lhs, rhs);
/// <summary>
/// Returns a ivec4 from component-wise application of Sub (lhs - rhs).
/// </summary>
public static ivec4 Sub(ivec4 lhs, ivec4 rhs) => ivec4.Sub(lhs, rhs);
/// <summary>
/// Returns a ivec4 from component-wise application of Mul (lhs * rhs).
/// </summary>
public static ivec4 Mul(ivec4 lhs, ivec4 rhs) => ivec4.Mul(lhs, rhs);
/// <summary>
/// Returns a ivec4 from component-wise application of Div (lhs / rhs).
/// </summary>
public static ivec4 Div(ivec4 lhs, ivec4 rhs) => ivec4.Div(lhs, rhs);
/// <summary>
/// Returns a ivec4 from component-wise application of Xor (lhs ^ rhs).
/// </summary>
public static ivec4 Xor(ivec4 lhs, ivec4 rhs) => ivec4.Xor(lhs, rhs);
/// <summary>
/// Returns a ivec4 from component-wise application of BitwiseOr (lhs | rhs).
/// </summary>
public static ivec4 BitwiseOr(ivec4 lhs, ivec4 rhs) => ivec4.BitwiseOr(lhs, rhs);
/// <summary>
/// Returns a ivec4 from component-wise application of BitwiseAnd (lhs & rhs).
/// </summary>
public static ivec4 BitwiseAnd(ivec4 lhs, ivec4 rhs) => ivec4.BitwiseAnd(lhs, rhs);
/// <summary>
/// Returns a ivec4 from component-wise application of LeftShift (lhs << rhs).
/// </summary>
public static ivec4 LeftShift(ivec4 lhs, ivec4 rhs) => ivec4.LeftShift(lhs, rhs);
/// <summary>
/// Returns a ivec4 from component-wise application of RightShift (lhs >> rhs).
/// </summary>
public static ivec4 RightShift(ivec4 lhs, ivec4 rhs) => ivec4.RightShift(lhs, rhs);
/// <summary>
/// Returns the minimal component of this vector.
/// </summary>
public static int MinElement(ivec4 v) => v.MinElement;
/// <summary>
/// Returns the maximal component of this vector.
/// </summary>
public static int MaxElement(ivec4 v) => v.MaxElement;
/// <summary>
/// Returns the euclidean length of this vector.
/// </summary>
public static float Length(ivec4 v) => v.Length;
/// <summary>
/// Returns the squared euclidean length of this vector.
/// </summary>
public static float LengthSqr(ivec4 v) => v.LengthSqr;
/// <summary>
/// Returns the sum of all components.
/// </summary>
public static int Sum(ivec4 v) => v.Sum;
/// <summary>
/// Returns the euclidean norm of this vector.
/// </summary>
public static float Norm(ivec4 v) => v.Norm;
/// <summary>
/// Returns the one-norm of this vector.
/// </summary>
public static float Norm1(ivec4 v) => v.Norm1;
/// <summary>
/// Returns the two-norm (euclidean length) of this vector.
/// </summary>
public static float Norm2(ivec4 v) => v.Norm2;
/// <summary>
/// Returns the max-norm of this vector.
/// </summary>
public static float NormMax(ivec4 v) => v.NormMax;
/// <summary>
/// Returns the p-norm of this vector.
/// </summary>
public static double NormP(ivec4 v, double p) => v.NormP(p);
/// <summary>
/// Returns the inner product (dot product, scalar product) of the two vectors.
/// </summary>
public static int Dot(ivec4 lhs, ivec4 rhs) => ivec4.Dot(lhs, rhs);
/// <summary>
/// Returns the euclidean distance between the two vectors.
/// </summary>
public static float Distance(ivec4 lhs, ivec4 rhs) => ivec4.Distance(lhs, rhs);
/// <summary>
/// Returns the squared euclidean distance between the two vectors.
/// </summary>
public static float DistanceSqr(ivec4 lhs, ivec4 rhs) => ivec4.DistanceSqr(lhs, rhs);
/// <summary>
/// Calculate the reflection direction for an incident vector (N should be normalized in order to achieve the desired result).
/// </summary>
public static ivec4 Reflect(ivec4 I, ivec4 N) => ivec4.Reflect(I, N);
/// <summary>
/// Calculate the refraction direction for an incident vector (The input parameters I and N should be normalized in order to achieve the desired result).
/// </summary>
public static ivec4 Refract(ivec4 I, ivec4 N, int eta) => ivec4.Refract(I, N, eta);
/// <summary>
/// Returns a vector pointing in the same direction as another (faceforward orients a vector to point away from a surface as defined by its normal. If dot(Nref, I) is negative faceforward returns N, otherwise it returns -N).
/// </summary>
public static ivec4 FaceForward(ivec4 N, ivec4 I, ivec4 Nref) => ivec4.FaceForward(N, I, Nref);
/// <summary>
/// Returns a ivec4 with independent and identically distributed uniform integer values between 0 (inclusive) and maxValue (exclusive). (A maxValue of 0 is allowed and returns 0.)
/// </summary>
public static ivec4 Random(Random random, ivec4 maxValue) => ivec4.Random(random, maxValue);
/// <summary>
/// Returns a ivec4 with independent and identically distributed uniform integer values between minValue (inclusive) and maxValue (exclusive). (minValue == maxValue is allowed and returns minValue. Negative values are allowed.)
/// </summary>
public static ivec4 Random(Random random, ivec4 minValue, ivec4 maxValue) => ivec4.Random(random, minValue, maxValue);
/// <summary>
/// Returns a ivec4 with independent and identically distributed uniform integer values between minValue (inclusive) and maxValue (exclusive). (minValue == maxValue is allowed and returns minValue. Negative values are allowed.)
/// </summary>
public static ivec4 RandomUniform(Random random, ivec4 minValue, ivec4 maxValue) => ivec4.RandomUniform(random, minValue, maxValue);
/// <summary>
/// Returns a ivec4 with independent and identically distributed integer values according to a poisson distribution with given lambda parameter.
/// </summary>
public static ivec4 RandomPoisson(Random random, dvec4 lambda) => ivec4.RandomPoisson(random, lambda);
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Cnblogs.Droid.Utils
{
public class RSAUtils
{
private RSACryptoServiceProvider publicKeyRsaProvider;
public RSAUtils(string publicKey)
{
publicKeyRsaProvider = CreateRsaProviderFromPublicKey(publicKey);
}
public string Encrypt(string text)
{
return Convert.ToBase64String(publicKeyRsaProvider.Encrypt(Encoding.UTF8.GetBytes(text), false));
}
private RSACryptoServiceProvider CreateRsaProviderFromPrivateKey(string privateKey)
{
var privateKeyBits = System.Convert.FromBase64String(privateKey);
var RSA = new RSACryptoServiceProvider();
var RSAparams = new RSAParameters();
using (BinaryReader binr = new BinaryReader(new MemoryStream(privateKeyBits)))
{
byte bt = 0;
ushort twobytes = 0;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130)
binr.ReadByte();
else if (twobytes == 0x8230)
binr.ReadInt16();
else
throw new Exception("Unexpected value read binr.ReadUInt16()");
twobytes = binr.ReadUInt16();
if (twobytes != 0x0102)
throw new Exception("Unexpected version");
bt = binr.ReadByte();
if (bt != 0x00)
throw new Exception("Unexpected value read binr.ReadByte()");
RSAparams.Modulus = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.Exponent = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.D = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.P = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.Q = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.DP = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.DQ = binr.ReadBytes(GetIntegerSize(binr));
RSAparams.InverseQ = binr.ReadBytes(GetIntegerSize(binr));
}
RSA.ImportParameters(RSAparams);
return RSA;
}
private int GetIntegerSize(BinaryReader binr)
{
byte bt = 0;
byte lowbyte = 0x00;
byte highbyte = 0x00;
int count = 0;
bt = binr.ReadByte();
if (bt != 0x02)
return 0;
bt = binr.ReadByte();
if (bt == 0x81)
count = binr.ReadByte();
else
if (bt == 0x82)
{
highbyte = binr.ReadByte();
lowbyte = binr.ReadByte();
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 };
count = BitConverter.ToInt32(modint, 0);
}
else
{
count = bt;
}
while (binr.ReadByte() == 0x00)
{
count -= 1;
}
binr.BaseStream.Seek(-1, SeekOrigin.Current);
return count;
}
private RSACryptoServiceProvider CreateRsaProviderFromPublicKey(string publicKeyString)
{
// encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1"
byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 };
byte[] x509key;
byte[] seq = new byte[15];
int x509size;
x509key = Convert.FromBase64String(publicKeyString);
x509size = x509key.Length;
// --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ------
using (MemoryStream mem = new MemoryStream(x509key))
{
using (BinaryReader binr = new BinaryReader(mem)) //wrap Memory Stream with BinaryReader for easy reading
{
byte bt = 0;
ushort twobytes = 0;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
seq = binr.ReadBytes(15); //read the Sequence OID
if (!CompareBytearrays(seq, SeqOID)) //make sure Sequence for OID is correct
return null;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8203)
binr.ReadInt16(); //advance 2 bytes
else
return null;
bt = binr.ReadByte();
if (bt != 0x00) //expect null byte next
return null;
twobytes = binr.ReadUInt16();
if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81)
binr.ReadByte(); //advance 1 byte
else if (twobytes == 0x8230)
binr.ReadInt16(); //advance 2 bytes
else
return null;
twobytes = binr.ReadUInt16();
byte lowbyte = 0x00;
byte highbyte = 0x00;
if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81)
lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus
else if (twobytes == 0x8202)
{
highbyte = binr.ReadByte(); //advance 2 bytes
lowbyte = binr.ReadByte();
}
else
return null;
byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order
int modsize = BitConverter.ToInt32(modint, 0);
int firstbyte = binr.PeekChar();
if (firstbyte == 0x00)
{ //if first byte (highest order) of modulus is zero, don't include it
binr.ReadByte(); //skip this null byte
modsize -= 1; //reduce modulus buffer size by 1
}
byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes
if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data
return null;
int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values)
byte[] exponent = binr.ReadBytes(expbytes);
// ------- create RSACryptoServiceProvider instance and initialize with public key -----
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = new RSAParameters();
RSAKeyInfo.Modulus = modulus;
RSAKeyInfo.Exponent = exponent;
RSA.ImportParameters(RSAKeyInfo);
return RSA;
}
}
}
private bool CompareBytearrays(byte[] a, byte[] b)
{
if (a.Length != b.Length)
return false;
int i = 0;
foreach (byte c in a)
{
if (c != b[i])
return false;
i++;
}
return true;
}
}
}
| |
// ==========================================================================
// This software is subject to the provisions of the Zope Public License,
// Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
// THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
// WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
// FOR A PARTICULAR PURPOSE.
// ==========================================================================
using System;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Python.Runtime {
/// <summary>
/// The AssemblyManager maintains information about loaded assemblies
/// namespaces and provides an interface for name-based type lookup.
/// </summary>
internal class AssemblyManager {
static Dictionary<string, Dictionary<Assembly, string>> namespaces;
//static Dictionary<string, Dictionary<string, string>> generics;
static AssemblyLoadEventHandler lhandler;
static ResolveEventHandler rhandler;
static Dictionary<string, int> probed;
static List<Assembly> assemblies;
internal static List<string> pypath;
private AssemblyManager() {}
//===================================================================
// Initialization performed on startup of the Python runtime. Here we
// scan all of the currently loaded assemblies to determine exported
// names, and register to be notified of new assembly loads.
//===================================================================
internal static void Initialize() {
namespaces = new
Dictionary<string, Dictionary<Assembly, string>>(32);
probed = new Dictionary<string, int>(32);
//generics = new Dictionary<string, Dictionary<string, string>>();
assemblies = new List<Assembly>(16);
pypath = new List<string>(16);
AppDomain domain = AppDomain.CurrentDomain;
lhandler = new AssemblyLoadEventHandler(AssemblyLoadHandler);
domain.AssemblyLoad += lhandler;
rhandler = new ResolveEventHandler(ResolveHandler);
domain.AssemblyResolve += rhandler;
Assembly[] items = domain.GetAssemblies();
for (int i = 0; i < items.Length; i++) {
Assembly a = items[i];
assemblies.Add(a);
ScanAssembly(a);
}
}
//===================================================================
// Cleanup resources upon shutdown of the Python runtime.
//===================================================================
internal static void Shutdown() {
AppDomain domain = AppDomain.CurrentDomain;
domain.AssemblyLoad -= lhandler;
domain.AssemblyResolve -= rhandler;
}
//===================================================================
// Event handler for assembly load events. At the time the Python
// runtime loads, we scan the app domain to map the assemblies that
// are loaded at the time. We also have to register this event handler
// so that we can know about assemblies that get loaded after the
// Python runtime is initialized.
//===================================================================
static void AssemblyLoadHandler(Object ob, AssemblyLoadEventArgs args){
Assembly assembly = args.LoadedAssembly;
assemblies.Add(assembly);
ScanAssembly(assembly);
}
//===================================================================
// Event handler for assembly resolve events. This is needed because
// we augment the assembly search path with the PYTHONPATH when we
// load an assembly from Python. Because of that, we need to listen
// for failed loads, because they might be dependencies of something
// we loaded from Python which also needs to be found on PYTHONPATH.
//===================================================================
static Assembly ResolveHandler(Object ob, ResolveEventArgs args){
string name = args.Name.ToLower();
for (int i = 0; i < assemblies.Count; i++) {
Assembly a = (Assembly)assemblies[i];
string full = a.FullName.ToLower();
if (full.StartsWith(name)) {
return a;
}
}
return LoadAssemblyPath(args.Name);
}
//===================================================================
// We __really__ want to avoid using Python objects or APIs when
// probing for assemblies to load, since our ResolveHandler may be
// called in contexts where we don't have the Python GIL and can't
// even safely try to get it without risking a deadlock ;(
//
// To work around that, we update a managed copy of sys.path (which
// is the main thing we care about) when UpdatePath is called. The
// import hook calls this whenever it knows its about to use the
// assembly manager, which lets us keep up with changes to sys.path
// in a relatively lightweight and low-overhead way.
//===================================================================
internal static void UpdatePath() {
IntPtr list = Runtime.PySys_GetObject("path");
int count = Runtime.PyList_Size(list);
if (count != pypath.Count) {
pypath.Clear();
probed.Clear();
for (int i = 0; i < count; i++) {
IntPtr item = Runtime.PyList_GetItem(list, i);
string path = Runtime.GetManagedString(item);
if (path != null) {
pypath.Add(path);
}
}
}
}
//===================================================================
// Given an assembly name, try to find this assembly file using the
// PYTHONPATH. If not found, return null to indicate implicit load
// using standard load semantics (app base directory then GAC, etc.)
//===================================================================
public static string FindAssembly(string name) {
char sep = Path.DirectorySeparatorChar;
string path;
string temp;
for (int i = 0; i < pypath.Count; i++) {
string head = pypath[i];
if (head == null || head.Length == 0) {
path = name;
}
else {
path = head + sep + name;
}
temp = path + ".dll";
if (File.Exists(temp)) {
return temp;
}
temp = path + ".exe";
if (File.Exists(temp)) {
return temp;
}
}
return null;
}
//===================================================================
// Loads an assembly from the application directory or the GAC
// given a simple assembly name. Returns the assembly if loaded.
//===================================================================
public static Assembly LoadAssembly(string name) {
Assembly assembly = null;
try {
assembly = Assembly.Load(name);
}
catch { }
return assembly;
}
//===================================================================
// Loads an assembly using an augmented search path (the python path).
//===================================================================
public static Assembly LoadAssemblyPath(string name) {
string path = FindAssembly(name);
Assembly assembly = null;
if (path != null) {
try { assembly = Assembly.LoadFrom(path); }
catch {}
}
return assembly;
}
//===================================================================
// Given a qualified name of the form A.B.C.D, attempt to load
// an assembly named after each of A.B.C.D, A.B.C, A.B, A. This
// will only actually probe for the assembly once for each unique
// namespace. Returns true if any assemblies were loaded.
// TODO item 3 "* Deprecate implicit loading of assemblies":
// Set the fromFile flag if the name of the loaded assembly matches
// the fully qualified name that was requested if the framework
// actually loads an assembly.
// Call ONLY for namespaces that HAVE NOT been cached yet.
//===================================================================
public static bool LoadImplicit(string name, out bool fromFile) {
// 2010-08-16: Deprecation support
// Added out param to detect fully qualified name load
fromFile = false;
string[] names = name.Split('.');
bool loaded = false;
string s = "";
for (int i = 0; i < names.Length; i++) {
s = (i == 0) ? names[0] : s + "." + names[i];
if (!probed.ContainsKey(s)) {
if (LoadAssemblyPath(s) != null) {
loaded = true;
/* 2010-08-16: Deprecation support */
if (s == name) {
fromFile = true;
}
}
else if (LoadAssembly(s) != null) {
loaded = true;
/* 2010-08-16: Deprecation support */
if (s == name) {
fromFile = true;
}
}
probed[s] = 1;
// 2010-12-24: Deprecation logic
/* if (loaded && (s == name)) {
fromFile = true;
break;
} */
}
}
return loaded;
}
//===================================================================
// Scans an assembly for exported namespaces, adding them to the
// mapping of valid namespaces. Note that for a given namespace
// a.b.c.d, each of a, a.b, a.b.c and a.b.c.d are considered to
// be valid namespaces (to better match Python import semantics).
//===================================================================
static void ScanAssembly(Assembly assembly) {
// A couple of things we want to do here: first, we want to
// gather a list of all of the namespaces contributed to by
// the assembly.
Type[] types = assembly.GetTypes();
for (int i = 0; i < types.Length; i++) {
Type t = types[i];
string ns = t.Namespace;
if ((ns != null) && (!namespaces.ContainsKey(ns))) {
string[] names = ns.Split('.');
string s = "";
for (int n = 0; n < names.Length; n++) {
s = (n == 0) ? names[0] : s + "." + names[n];
if (!namespaces.ContainsKey(s)) {
namespaces.Add(s,
new Dictionary<Assembly, string>()
);
}
}
}
if (ns != null && !namespaces[ns].ContainsKey(assembly)) {
namespaces[ns].Add(assembly, String.Empty);
}
if (t.IsGenericTypeDefinition) {
GenericUtil.Register(t);
}
}
}
public static AssemblyName[] ListAssemblies()
{
AssemblyName[] names = new AssemblyName[assemblies.Count];
Assembly assembly;
for (int i=0; i < assemblies.Count; i++)
{
assembly = assemblies[i];
names.SetValue(assembly.GetName(), i);
}
return names;
}
//===================================================================
// Returns true if the given qualified name matches a namespace
// exported by an assembly loaded in the current app domain.
//===================================================================
public static bool IsValidNamespace(string name) {
return namespaces.ContainsKey(name);
}
//===================================================================
// Returns the current list of valid names for the input namespace.
//===================================================================
public static List<string> GetNames(string nsname) {
//Dictionary<string, int> seen = new Dictionary<string, int>();
List<string> names = new List<string>(8);
List<string> g = GenericUtil.GetGenericBaseNames(nsname);
if (g != null) {
foreach (string n in g) {
names.Add(n);
}
}
if (namespaces.ContainsKey(nsname)) {
foreach (Assembly a in namespaces[nsname].Keys) {
Type[] types = a.GetTypes();
for (int i = 0; i < types.Length; i++) {
Type t = types[i];
if (t.Namespace == nsname) {
names.Add(t.Name);
}
}
}
int nslen = nsname.Length;
foreach (string key in namespaces.Keys) {
if (key.Length > nslen && key.StartsWith(nsname)) {
//string tail = key.Substring(nslen);
if (key.IndexOf('.') == -1) {
names.Add(key);
}
}
}
}
return names;
}
//===================================================================
// Returns the System.Type object for a given qualified name,
// looking in the currently loaded assemblies for the named
// type. Returns null if the named type cannot be found.
//===================================================================
public static Type LookupType(string qname) {
for (int i = 0; i < assemblies.Count; i++) {
Assembly assembly = (Assembly)assemblies[i];
Type type = assembly.GetType(qname);
if (type != null) {
return type;
}
}
return null;
}
}
}
| |
// Copyright 2011 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
namespace Microsoft.Data.OData.Atom
{
#region Namespaces
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Xml;
#endregion Namespaces
/// <summary>
/// OData ATOM deserializer for ATOM metadata in a service document
/// </summary>
internal sealed class ODataAtomServiceDocumentMetadataDeserializer : ODataAtomMetadataDeserializer
{
#region Atomized strings
/// <summary>Schema namespace for Atom.</summary>
private readonly string AtomNamespace;
/// <summary>The name of the 'category' element in a service document.</summary>
private readonly string AtomCategoryElementName;
/// <summary>The name of the 'href' attribute in an 'app:categories' element.</summary>
private readonly string AtomHRefAttributeName;
/// <summary>The name of the 'fixed' attribute in an 'app:categories' element.</summary>
private readonly string AtomPublishingFixedAttributeName;
/// <summary>The name of the 'scheme' attribute in an 'app:categories' or 'atom:category' element.</summary>
private readonly string AtomCategorySchemeAttributeName;
/// <summary>The name of the 'term' attribute in an 'atom:category' element.</summary>
private readonly string AtomCategoryTermAttributeName;
/// <summary>The name of the 'label' attribute in an 'atom:category' element.</summary>
private readonly string AtomCategoryLabelAttributeName;
/// <summary>The empty namespace</summary>
private readonly string EmptyNamespace;
#endregion
/// <summary>
/// Constructor.
/// </summary>
/// <param name="atomInputContext">The ATOM input context to read from.</param>
internal ODataAtomServiceDocumentMetadataDeserializer(ODataAtomInputContext atomInputContext)
: base(atomInputContext)
{
DebugUtils.CheckNoExternalCallers();
XmlNameTable nameTable = this.XmlReader.NameTable;
this.AtomNamespace = nameTable.Add(AtomConstants.AtomNamespace);
this.AtomCategoryElementName = nameTable.Add(AtomConstants.AtomCategoryElementName);
this.AtomHRefAttributeName = nameTable.Add(AtomConstants.AtomHRefAttributeName);
this.AtomPublishingFixedAttributeName = nameTable.Add(AtomConstants.AtomPublishingFixedAttributeName);
this.AtomCategorySchemeAttributeName = nameTable.Add(AtomConstants.AtomCategorySchemeAttributeName);
this.AtomCategoryTermAttributeName = nameTable.Add(AtomConstants.AtomCategoryTermAttributeName);
this.AtomCategoryLabelAttributeName = nameTable.Add(AtomConstants.AtomCategoryLabelAttributeName);
this.EmptyNamespace = nameTable.Add(string.Empty);
}
/// <summary>
/// Reads an atom:title element and adds the new information to <paramref name="workspaceMetadata"/>.
/// </summary>
/// <param name="workspaceMetadata">The non-null workspace metadata object to augment.</param>
/// <remarks>
/// Pre-Condition: XmlNodeType.Element - The start of the atom:title element.
/// Post-Condition: Any - The next node after the atom:title element.
/// </remarks>
internal void ReadTitleElementInWorkspace(AtomWorkspaceMetadata workspaceMetadata)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(workspaceMetadata != null, "workspaceMetadata != null");
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(this.XmlReader.LocalName == AtomConstants.AtomTitleElementName, "Expected element named 'title'.");
Debug.Assert(this.XmlReader.NamespaceURI == AtomConstants.AtomNamespace, "Element 'title' should be in the atom namespace.");
if (workspaceMetadata.Title != null)
{
throw new ODataException(Strings.ODataAtomServiceDocumentMetadataDeserializer_MultipleTitleElementsFound(AtomConstants.AtomPublishingWorkspaceElementName));
}
workspaceMetadata.Title = this.ReadTitleElement();
}
/// <summary>
/// Reads an atom:title element and adds the new information to <paramref name="collectionMetadata"/>.
/// </summary>
/// <param name="collectionMetadata">The non-null collection metadata object to augment.</param>
/// <remarks>
/// Pre-Condition: XmlNodeType.Element - The start of the title element.
/// Post-Condition: Any - The next node after the title element.
/// </remarks>
internal void ReadTitleElementInCollection(AtomResourceCollectionMetadata collectionMetadata)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(collectionMetadata != null, "collectionMetadata != null");
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(this.XmlReader.LocalName == AtomConstants.AtomTitleElementName, "Expected element named 'title'.");
Debug.Assert(this.XmlReader.NamespaceURI == AtomConstants.AtomNamespace, "Element 'title' should be in the atom namespace.");
if (collectionMetadata.Title != null)
{
throw new ODataException(Strings.ODataAtomServiceDocumentMetadataDeserializer_MultipleTitleElementsFound(AtomConstants.AtomPublishingCollectionElementName));
}
collectionMetadata.Title = this.ReadTitleElement();
}
/// <summary>
/// Reads an app:categories element as well as each atom:category element contained within it, and adds the new information to <paramref name="collectionMetadata"/>.
/// </summary>
/// <param name="collectionMetadata">The non-null collection metadata object to augment.</param>
/// <remarks>
/// Pre-Condition: XmlNodeType.Element - The start of the app:categories element.
/// Post-Condition: Any - The next node after the app:categories element.
/// </remarks>
internal void ReadCategoriesElementInCollection(AtomResourceCollectionMetadata collectionMetadata)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(collectionMetadata != null, "collectionMetadata != null");
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(this.XmlReader.LocalName == AtomConstants.AtomPublishingCategoriesElementName, "Expected element named 'categories'.");
Debug.Assert(this.XmlReader.NamespaceURI == AtomConstants.AtomPublishingNamespace, "Element 'categories' should be in the atom publishing namespace.");
AtomCategoriesMetadata categoriesMetadata = new AtomCategoriesMetadata();
List<AtomCategoryMetadata> categoryList = new List<AtomCategoryMetadata>();
while (this.XmlReader.MoveToNextAttribute())
{
string attributeValue = this.XmlReader.Value;
if (this.XmlReader.NamespaceEquals(this.EmptyNamespace))
{
if (this.XmlReader.LocalNameEquals(this.AtomHRefAttributeName))
{
categoriesMetadata.Href = this.ProcessUriFromPayload(attributeValue, this.XmlReader.XmlBaseUri);
}
else if (this.XmlReader.LocalNameEquals(this.AtomPublishingFixedAttributeName))
{
if (String.CompareOrdinal(attributeValue, AtomConstants.AtomPublishingFixedYesValue) == 0)
{
categoriesMetadata.Fixed = true;
}
else if (String.CompareOrdinal(attributeValue, AtomConstants.AtomPublishingFixedNoValue) == 0)
{
categoriesMetadata.Fixed = false;
}
else
{
throw new ODataException(Strings.ODataAtomServiceDocumentMetadataDeserializer_InvalidFixedAttributeValue(attributeValue));
}
}
else if (this.XmlReader.LocalNameEquals(this.AtomCategorySchemeAttributeName))
{
categoriesMetadata.Scheme = attributeValue;
}
}
}
this.XmlReader.MoveToElement();
if (!this.XmlReader.IsEmptyElement)
{
// read over the categories element
this.XmlReader.ReadStartElement();
do
{
switch (this.XmlReader.NodeType)
{
case XmlNodeType.Element:
if (this.XmlReader.NamespaceEquals(this.AtomNamespace) && this.XmlReader.LocalNameEquals(this.AtomCategoryElementName))
{
categoryList.Add(this.ReadCategoryElementInCollection());
}
break;
case XmlNodeType.EndElement:
// end of 'categories' element.
break;
default:
// ignore all other nodes.
this.XmlReader.Skip();
break;
}
}
while (this.XmlReader.NodeType != XmlNodeType.EndElement);
} // if (!this.XmlReader.IsEmptyElement)
// read over the end tag of the categories element or the start tag if the categories element is empty.
this.XmlReader.Read();
categoriesMetadata.Categories = new ReadOnlyEnumerable<AtomCategoryMetadata>(categoryList);
collectionMetadata.Categories = categoriesMetadata;
}
/// <summary>
/// Reads an "app:accept" element and adds the new information to <paramref name="collectionMetadata"/>.
/// </summary>
/// <param name="collectionMetadata">The non-null collection metadata object to augment.</param>
/// <remarks>
/// Pre-Condition: XmlNodeType.Element - The start of the app:accept element.
/// Post-Condition: Any - The next node after the app:accept element.
/// </remarks>
internal void ReadAcceptElementInCollection(AtomResourceCollectionMetadata collectionMetadata)
{
DebugUtils.CheckNoExternalCallers();
Debug.Assert(collectionMetadata != null, "collectionMetadata != null");
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(this.XmlReader.LocalName == AtomConstants.AtomPublishingAcceptElementName, "Expected element named 'accept'.");
Debug.Assert(this.XmlReader.NamespaceURI == AtomConstants.AtomPublishingNamespace, "Element 'accept' should be in the atom publishing namespace.");
if (collectionMetadata.Accept != null)
{
throw new ODataException(Strings.ODataAtomServiceDocumentMetadataDeserializer_MultipleAcceptElementsFoundInCollection);
}
collectionMetadata.Accept = this.XmlReader.ReadElementValue();
}
/// <summary>
/// Reads an "atom:category" element and returns the data as an <seealso cref="AtomCategoryMetadata"/> object.
/// </summary>
/// <returns>An <seealso cref="AtomCategoryMetadata"/> object with its properties filled in according to what was found in the XML.</returns>
/// <remarks>
/// Pre-Condition: XmlNodeType.Element - The start of the atom:category element.
/// Post-Condition: Any - The next node after the atom:category element.
/// </remarks>
private AtomCategoryMetadata ReadCategoryElementInCollection()
{
this.AssertXmlCondition(XmlNodeType.Element);
Debug.Assert(this.XmlReader.LocalName == AtomConstants.AtomCategoryElementName, "Expected element named 'category'.");
Debug.Assert(this.XmlReader.NamespaceURI == AtomConstants.AtomNamespace, "Element 'category' should be in the atom namespace.");
AtomCategoryMetadata categoryMetadata = new AtomCategoryMetadata();
while (this.XmlReader.MoveToNextAttribute())
{
string attributeValue = this.XmlReader.Value;
if (this.XmlReader.NamespaceEquals(this.EmptyNamespace))
{
if (this.XmlReader.LocalNameEquals(this.AtomCategoryTermAttributeName))
{
categoryMetadata.Term = attributeValue;
}
else if (this.XmlReader.LocalNameEquals(this.AtomCategorySchemeAttributeName))
{
categoryMetadata.Scheme = attributeValue;
}
else if (this.XmlReader.LocalNameEquals(this.AtomCategoryLabelAttributeName))
{
categoryMetadata.Label = attributeValue;
}
}
}
return categoryMetadata;
}
}
}
| |
// Copyright (c) Valve Corporation, All rights reserved. ======================================================================================================
#if ( UNITY_EDITOR )
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor.VersionControl;
//---------------------------------------------------------------------------------------------------------------------------------------------------
public class ValveMenuTools {
static void SaveAssetsAndFreeMemory(string assetPath) {
UnityEditor.AssetDatabase.SaveAssets();
GC.Collect();
UnityEditor.EditorUtility.UnloadUnusedAssetsImmediate();
//UnityEditor.AssetDatabase.ImportAsset( assetPath, UnityEditor.ImportAssetOptions.ForceSynchronousImport );
UnityEditor.AssetDatabase.Refresh();
}
private static void RenameShadersInAllMaterials(string nameBefore, string nameAfter) {
Shader destShader = Shader.Find(nameAfter);
if (destShader == null) {
return;
}
int i = 0;
int nCount = 0;
foreach (string s in UnityEditor.AssetDatabase.GetAllAssetPaths()) {
if (s.EndsWith(".mat", StringComparison.OrdinalIgnoreCase)) {
nCount++;
}
}
foreach (string s in UnityEditor.AssetDatabase.GetAllAssetPaths()) {
if (s.EndsWith(".mat", StringComparison.OrdinalIgnoreCase)) {
i++;
if (UnityEditor.EditorUtility.DisplayCancelableProgressBar("Valve Material Conversion", string.Format("({0} of {1}) {2}", i, nCount, s), (float) i / (float) nCount)) {
break;
}
Material m = UnityEditor.AssetDatabase.LoadMainAssetAtPath(s) as Material;
//Debug.Log( m.name + "\n" );
//Debug.Log( m.shader.name + "\n" );
if (m.shader.name.Equals(nameBefore)) {
Debug.Log("Converting from \"" + nameBefore + "\"-->\"" + nameAfter + "\": " + m.name + "\n");
m.shader = destShader;
SaveAssetsAndFreeMemory(s);
}
}
}
//object[] obj = GameObject.FindObjectsOfType( typeof( GameObject ) );
//foreach ( object o in obj )
//{
// GameObject g = ( GameObject )o;
//
// Renderer[] renderers = g.GetComponents<Renderer>();
// foreach ( Renderer r in renderers )
// {
// foreach ( Material m in r.sharedMaterials )
// {
// //Debug.Log( m.name + "\n" );
// //Debug.Log( m.shader.name + "\n" );
// if ( m.shader.name.Equals( "Standard" ) )
// {
// Debug.Log( "Refreshing Standard shader for material: " + m.name + "\n" );
// m.shader = destShader;
// SaveAssetsAndFreeMemory();
// }
// }
// }
//}
UnityEditor.EditorUtility.ClearProgressBar();
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
public static bool StandardToValveSingleMaterial(Material m, Shader srcShader, Shader destShader, bool bRecordUnknownShaders, List<string> unknownShaders) {
string n = srcShader.name;
if (n.Equals(destShader.name)) {
// Do nothing
//Debug.Log( " Skipping " + m.name + "\n" );
return false;
} else if (n.Equals("Standard") || n.Equals("Valve/VR/Standard")) {
// Metallic specular
Debug.Log(" Converting from \"" + n + "\"-->\"" + destShader.name + "\": " + m.name + "\n");
m.shader = destShader;
m.SetOverrideTag("OriginalShader", n);
m.SetInt("_SpecularMode", 2);
m.DisableKeyword("S_SPECULAR_NONE");
m.DisableKeyword("S_SPECULAR_BLINNPHONG");
m.EnableKeyword("S_SPECULAR_METALLIC");
return true;
} else if (n.Equals("Standard (Specular setup)") || n.Equals("Legacy Shaders/Bumped Diffuse") || n.Equals("Legacy Shaders/Transparent/Diffuse")) {
// Regular specular
Debug.Log(" Converting from \"" + n + "\"-->\"" + destShader.name + "\": " + m.name + "\n");
m.shader = destShader;
m.SetOverrideTag("OriginalShader", n);
m.SetInt("_SpecularMode", 1);
m.DisableKeyword("S_SPECULAR_NONE");
m.EnableKeyword("S_SPECULAR_BLINNPHONG");
m.DisableKeyword("S_SPECULAR_METALLIC");
if (n.Equals("Legacy Shaders/Transparent/Diffuse")) {
m.SetFloat("_Mode", 2);
m.SetOverrideTag("RenderType", "Transparent");
m.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.SrcAlpha);
m.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
m.SetInt("_ZWrite", 0);
m.DisableKeyword("_ALPHATEST_ON");
m.EnableKeyword("_ALPHABLEND_ON");
m.DisableKeyword("_ALPHAPREMULTIPLY_ON");
m.renderQueue = 3000;
}
return true;
} else if (n.Equals("Unlit/Color") || n.Equals("Unlit/Texture") || n.Equals("Unlit/Transparent") || n.Equals("Unlit/Transparent Cutout")) {
// Unlit
Debug.Log(" Converting from \"" + n + "\"-->\"" + destShader.name + "\": " + m.name + "\n");
m.shader = destShader;
m.SetOverrideTag("OriginalShader", n);
m.SetInt("g_bUnlit", 1);
m.EnableKeyword("S_UNLIT");
m.SetColor("_EmissionColor", Color.black);
if (n.Equals("Unlit/Color")) {
m.SetTexture("_MainTex", Texture2D.whiteTexture);
} else {
m.SetColor("_Color", Color.white);
if (n.Equals("Unlit/Transparent Cutout")) {
m.SetFloat("_Mode", 1);
m.SetOverrideTag("RenderType", "TransparentCutout");
m.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.One);
m.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.Zero);
m.SetInt("_ZWrite", 1);
m.EnableKeyword("_ALPHATEST_ON");
m.DisableKeyword("_ALPHABLEND_ON");
m.DisableKeyword("_ALPHAPREMULTIPLY_ON");
m.renderQueue = 2450;
} else if (n.Equals("Unlit/Transparent")) {
m.SetFloat("_Mode", 2);
m.SetOverrideTag("RenderType", "Transparent");
m.SetInt("_SrcBlend", (int) UnityEngine.Rendering.BlendMode.SrcAlpha);
m.SetInt("_DstBlend", (int) UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
m.SetInt("_ZWrite", 0);
m.DisableKeyword("_ALPHATEST_ON");
m.EnableKeyword("_ALPHABLEND_ON");
m.DisableKeyword("_ALPHAPREMULTIPLY_ON");
m.renderQueue = 3000;
}
}
return true;
} else if (bRecordUnknownShaders) {
if (n.StartsWith("Valve/")) {
// Don't report unknown shaders if in the top level Valve folder
return false;
}
// Don't know how to convert, so add to list to spew at the end
Debug.LogWarning(" Don't know how to convert shader \"" + n + "\"" + " in material \"" + m.name + "\"" + "\n");
if (!unknownShaders.Contains(n)) {
unknownShaders.Add(n);
}
return false;
}
return false;
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
private static void StandardToValve(bool bConvertAllMaterials) {
int nNumMaterialsConverted = 0;
Debug.Log("Begin Convert to Valve Shaders\n\n" + Time.realtimeSinceStartup);
Shader destShader = Shader.Find("Valve/vr_standard");
if (destShader == null) {
Debug.LogWarning(" ERROR! Cannot find the \"Valve/vr_standard\" shader!" + "\n");
return;
}
List<string> unknownShaders = new List<string>();
List<string> alreadyConvertedMaterials = new List<string>();
if (bConvertAllMaterials) {
int i = 0;
int nCount = 0;
foreach (string s in UnityEditor.AssetDatabase.GetAllAssetPaths()) {
if (s.EndsWith(".mat", StringComparison.OrdinalIgnoreCase)) {
nCount++;
}
}
foreach (string s in UnityEditor.AssetDatabase.GetAllAssetPaths()) {
if (s.EndsWith(".mat", StringComparison.OrdinalIgnoreCase)) {
i++;
if (UnityEditor.EditorUtility.DisplayCancelableProgressBar("Valve Material Conversion to Valve Shaders", string.Format("({0} of {1}) {2}", i, nCount, s), (float) i / (float) nCount)) {
break;
}
Material m = UnityEditor.AssetDatabase.LoadMainAssetAtPath(s) as Material;
if ((m == null) || (m.shader == null))
continue;
if (!m.name.StartsWith(""))
continue;
if (alreadyConvertedMaterials.Contains(m.name))
continue;
alreadyConvertedMaterials.Add(m.name);
if (StandardToValveSingleMaterial(m, m.shader, destShader, true, unknownShaders)) {
nNumMaterialsConverted++;
}
SaveAssetsAndFreeMemory(s);
}
}
} else {
int i = 0;
int nCount = 0;
Renderer[] renderers = GameObject.FindObjectsOfType<Renderer>();
List<string> countedMaterials = new List<string>();
foreach (Renderer r in renderers) {
if (r.sharedMaterials == null)
continue;
foreach (Material m in r.sharedMaterials) {
if ((m == null) || (m.shader == null))
continue;
if (!m.name.StartsWith(""))
continue;
if (countedMaterials.Contains(m.name))
continue;
countedMaterials.Add(m.name);
string assetPath = UnityEditor.AssetDatabase.GetAssetPath(m);
Material mainAsset = UnityEditor.AssetDatabase.LoadMainAssetAtPath(assetPath) as Material;
if (!mainAsset) {
//Debug.LogError( "Error calling LoadMainAssetAtPath( " + assetPath + " for material " + m.name + " )!\n\n" );
continue;
}
nCount++;
}
}
bool bCanceled = false;
foreach (Renderer r in renderers) {
if (r.sharedMaterials == null)
continue;
foreach (Material m in r.sharedMaterials) {
if ((m == null) || (m.shader == null))
continue;
if (!m.name.StartsWith(""))
continue;
if (alreadyConvertedMaterials.Contains(m.name))
continue;
alreadyConvertedMaterials.Add(m.name);
string assetPath = UnityEditor.AssetDatabase.GetAssetPath(m);
Material mainAsset = UnityEditor.AssetDatabase.LoadMainAssetAtPath(assetPath) as Material;
if (!mainAsset) {
//Debug.LogError( "Error calling LoadMainAssetAtPath( " + assetPath + " )!\n\n" );
continue;
}
i++;
if (UnityEditor.EditorUtility.DisplayCancelableProgressBar("Valve Material Conversion to Valve Shaders", string.Format("({0} of {1}) {2}", i, nCount, assetPath), (float) i / (float) nCount)) {
bCanceled = true;
break;
}
if (StandardToValveSingleMaterial(mainAsset, mainAsset.shader, destShader, true, unknownShaders)) {
nNumMaterialsConverted++;
}
SaveAssetsAndFreeMemory(assetPath);
}
if (bCanceled)
break;
}
}
foreach (string s in unknownShaders) {
Debug.LogWarning(" Don't know how to convert shader \"" + s + "\"" + "\n");
}
Debug.Log("Converted " + nNumMaterialsConverted + " materials to Valve Shaders\n\n" + Time.realtimeSinceStartup);
UnityEditor.EditorUtility.ClearProgressBar();
EnsureConsistencyInValveMaterials();
}
[UnityEditor.MenuItem("Valve/Shader Dev/Convert Active Materials to Valve Shaders", false, 50)]
private static void StandardToValveCurrent() {
StandardToValve(false);
}
[UnityEditor.MenuItem("Valve/Shader Dev/Convert All Materials to Valve Shaders", false, 100)]
private static void StandardToValveAll() {
StandardToValve(true);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
private static bool ValveToStandardSingleMaterial(Material m, Shader destShaderStandard, Shader destShaderStandardSpecular) {
if (m.shader.name.Equals("Valve/vr_standard")) {
if ((m.GetTag("OriginalShader", true) != null) && (m.GetTag("OriginalShader", true).Length > 0)) {
Debug.Log(" Converting from \"" + m.shader.name + "\"-->\"" + m.GetTag("OriginalShader", true) + "\": " + m.name + "\n");
m.shader = Shader.Find(m.GetTag("OriginalShader", true));
return true;
} else if (m.GetInt("_SpecularMode") == 2) {
// Metallic specular
Debug.Log(" Converting from \"" + m.shader.name + "\"-->\"" + destShaderStandard.name + "\": " + m.name + "\n");
m.shader = destShaderStandard;
return true;
} else {
// Regular specular
Debug.Log(" Converting from \"" + m.shader.name + "\"-->\"" + destShaderStandardSpecular.name + "\": " + m.name + "\n");
m.shader = destShaderStandardSpecular;
return true;
}
}
return false;
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
[UnityEditor.MenuItem("Valve/Shader Dev/Convert All Materials Back to Unity Shaders", false, 101)]
private static void ValveToStandard(bool bConvertAllMaterials) {
int nNumMaterialsConverted = 0;
Debug.Log("Begin Convert to Unity Shaders\n\n" + Time.realtimeSinceStartup);
Shader destShaderStandard = Shader.Find("Standard");
if (destShaderStandard == null) {
Debug.LogWarning(" ERROR! Cannot find the \"Standard\" shader!" + "\n");
return;
}
Shader destShaderStandardSpecular = Shader.Find("Standard (Specular setup)");
if (destShaderStandardSpecular == null) {
Debug.LogWarning(" ERROR! Cannot find the \"Standard (Specular setup)\" shader!" + "\n");
return;
}
List<string> alreadyConvertedMaterials = new List<string>();
if (bConvertAllMaterials) {
int i = 0;
int nCount = 0;
foreach (string s in UnityEditor.AssetDatabase.GetAllAssetPaths()) {
if (s.EndsWith(".mat", StringComparison.OrdinalIgnoreCase)) {
nCount++;
}
}
foreach (string s in UnityEditor.AssetDatabase.GetAllAssetPaths()) {
if (s.EndsWith(".mat", StringComparison.OrdinalIgnoreCase)) {
i++;
if (UnityEditor.EditorUtility.DisplayCancelableProgressBar("Valve Material Conversion Back to Unity Shaders", string.Format("({0} of {1}) {2}", i, nCount, s), (float) i / (float) nCount)) {
break;
}
Material m = UnityEditor.AssetDatabase.LoadMainAssetAtPath(s) as Material;
if (ValveToStandardSingleMaterial(m, destShaderStandard, destShaderStandardSpecular)) {
nNumMaterialsConverted++;
}
SaveAssetsAndFreeMemory(s);
}
}
} else {
int i = 0;
int nCount = 0;
Renderer[] renderers = GameObject.FindObjectsOfType<Renderer>();
List<string> countedMaterials = new List<string>();
foreach (Renderer r in renderers) {
if (r.sharedMaterials == null)
continue;
foreach (Material m in r.sharedMaterials) {
if ((m == null) || (m.shader == null))
continue;
if (!m.name.StartsWith(""))
continue;
if (countedMaterials.Contains(m.name))
continue;
countedMaterials.Add(m.name);
string assetPath = UnityEditor.AssetDatabase.GetAssetPath(m);
Material mainAsset = UnityEditor.AssetDatabase.LoadMainAssetAtPath(assetPath) as Material;
if (!mainAsset) {
//Debug.LogError( "Error calling LoadMainAssetAtPath( " + assetPath + " )!\n\n" );
continue;
}
nCount++;
}
}
bool bCanceled = false;
foreach (Renderer r in renderers) {
if (r.sharedMaterials == null)
continue;
foreach (Material m in r.sharedMaterials) {
if ((m == null) || (m.shader == null))
continue;
if (!m.name.StartsWith(""))
continue;
if (alreadyConvertedMaterials.Contains(m.name))
continue;
alreadyConvertedMaterials.Add(m.name);
string assetPath = UnityEditor.AssetDatabase.GetAssetPath(m);
Material mainAsset = UnityEditor.AssetDatabase.LoadMainAssetAtPath(assetPath) as Material;
if (!mainAsset) {
//Debug.LogError( "Error calling LoadMainAssetAtPath( " + assetPath + " )!\n\n" );
continue;
}
i++;
if (UnityEditor.EditorUtility.DisplayCancelableProgressBar("Valve Material Conversion Back to Unity Shaders", string.Format("({0} of {1}) {2}", i, nCount, assetPath), (float) i / (float) nCount)) {
bCanceled = true;
break;
}
if (ValveToStandardSingleMaterial(mainAsset, destShaderStandard, destShaderStandardSpecular)) {
nNumMaterialsConverted++;
}
SaveAssetsAndFreeMemory(assetPath);
}
if (bCanceled)
break;
}
}
Debug.Log("Converted " + nNumMaterialsConverted + " materials to Unity Shaders\n\n" + Time.realtimeSinceStartup);
UnityEditor.EditorUtility.ClearProgressBar();
}
[UnityEditor.MenuItem("Valve/Shader Dev/Convert Active Materials Back to Unity Shaders", false, 51)]
private static void ValveToStandardCurrent() {
ValveToStandard(false);
}
[UnityEditor.MenuItem("Valve/Shader Dev/Convert All Materials Back to Unity Shaders", false, 101)]
private static void ValveToStandardAll() {
ValveToStandard(true);
}
//---------------------------------------------------------------------------------------------------------------------------------------------------
//[UnityEditor.MenuItem( "Valve/Shader Dev/Refresh Standard", false, 150 )]
//private static void RefreshStandard()
//{
// RenameShadersInAllMaterials( "Standard", "Standard" );
//}
//---------------------------------------------------------------------------------------------------------------------------------------------------
[UnityEditor.MenuItem("Valve/Shader Dev/Ensure Consistency in Valve Materials", false, 200)]
private static void EnsureConsistencyInValveMaterials() {
int nNumMaterialChanges = 0;
Debug.Log("Begin consistency check for all Valve materials\n\n" + Time.realtimeSinceStartup);
int i = 0;
int nCount = 0;
foreach (string s in UnityEditor.AssetDatabase.GetAllAssetPaths()) {
if (s.EndsWith(".mat", StringComparison.OrdinalIgnoreCase)) {
nCount++;
}
}
foreach (string s in UnityEditor.AssetDatabase.GetAllAssetPaths()) {
if (s.EndsWith(".mat", StringComparison.OrdinalIgnoreCase)) {
i++;
if (UnityEditor.EditorUtility.DisplayCancelableProgressBar("Consistency check for all Valve materials", string.Format("({0} of {1}) {2}", i, nCount, s), (float) i / (float) nCount)) {
break;
}
Material m = UnityEditor.AssetDatabase.LoadMainAssetAtPath(s) as Material;
if (m.shader.name.Equals("Valve/vr_standard")) {
// Enable S_RECEIVE_SHADOWS if g_bReceiveShadows == 1
if ((m.GetInt("g_bReceiveShadows") == 1) && (m.GetInt("g_bUnlit") == 0) && (!m.IsKeywordEnabled("S_RECEIVE_SHADOWS"))) {
Debug.Log(" Enabling S_RECEIVE_SHADOWS on material \"" + m.name + "\"\n");
m.EnableKeyword("S_RECEIVE_SHADOWS");
nNumMaterialChanges++;
}
// Remove old combo RECEIVE_SHADOWS
if (m.IsKeywordEnabled("RECEIVE_SHADOWS")) {
Debug.Log(" Disabling old combo RECEIVE_SHADOWS on material \"" + m.name + "\"\n");
m.DisableKeyword("RECEIVE_SHADOWS");
nNumMaterialChanges++;
}
// Convert old metallic bool to new specular mode
if ((m.HasProperty("g_bEnableMetallic") && m.GetInt("g_bEnableMetallic") == 1) || (m.IsKeywordEnabled("_METALLIC_ENABLED"))) {
Debug.Log(" Converting old metallic checkbox to specular mode on material \"" + m.name + "\"\n");
m.DisableKeyword("_METALLIC_ENABLED");
m.SetInt("g_bEnableMetallic", 0);
m.SetInt("_SpecularMode", 2);
m.EnableKeyword("S_SPECULAR_METALLIC");
nNumMaterialChanges++;
} else if (!m.IsKeywordEnabled("S_SPECULAR_NONE") && !m.IsKeywordEnabled("S_SPECULAR_BLINNPHONG") && !m.IsKeywordEnabled("S_SPECULAR_METALLIC")) {
Debug.Log(" Converting old specular to BlinnPhong specular mode on material \"" + m.name + "\"\n");
m.SetInt("_SpecularMode", 1);
m.EnableKeyword("S_SPECULAR_BLINNPHONG");
nNumMaterialChanges++;
}
// If occlusion map is set, enable S_OCCLUSION static combo
if (m.GetTexture("_OcclusionMap") && !m.IsKeywordEnabled("S_OCCLUSION")) {
Debug.Log(" Enabling new occlusion combo S_OCCLUSION on material \"" + m.name + "\"\n");
m.EnableKeyword("S_OCCLUSION");
nNumMaterialChanges++;
}
SaveAssetsAndFreeMemory(s);
}
}
}
Debug.Log("Consistency check made " + nNumMaterialChanges + " changes to Valve materials\n\n" + Time.realtimeSinceStartup);
UnityEditor.EditorUtility.ClearProgressBar();
}
}
#endif
| |
using System.Data;
using System.Data.Common;
using System.Data.Odbc;
using System.Threading.Tasks;
namespace appMpower.Db
{
public class PooledCommand : IDbCommand
{
private OdbcCommand _odbcCommand;
private PooledConnection _pooledConnection;
public PooledCommand(PooledConnection pooledConnection)
{
_odbcCommand = (OdbcCommand)pooledConnection.CreateCommand();
_pooledConnection = pooledConnection;
}
public PooledCommand(string commandText, PooledConnection pooledConnection)
{
pooledConnection.GetCommand(commandText, this);
}
internal PooledCommand(OdbcCommand odbcCommand, PooledConnection pooledConnection)
{
_odbcCommand = odbcCommand;
_pooledConnection = pooledConnection;
}
internal OdbcCommand OdbcCommand
{
get
{
return _odbcCommand;
}
set
{
_odbcCommand = value;
}
}
internal PooledConnection PooledConnection
{
get
{
return _pooledConnection;
}
set
{
_pooledConnection = value;
}
}
public string CommandText
{
get
{
return _odbcCommand.CommandText;
}
set
{
_odbcCommand.CommandText = value;
}
}
public int CommandTimeout
{
get
{
return _odbcCommand.CommandTimeout;
}
set
{
_odbcCommand.CommandTimeout = value;
}
}
public CommandType CommandType
{
get
{
return _odbcCommand.CommandType;
}
set
{
_odbcCommand.CommandType = value;
}
}
#nullable enable
public IDbConnection? Connection
{
get
{
return _odbcCommand.Connection;
}
set
{
_odbcCommand.Connection = (OdbcConnection?)value;
}
}
#nullable disable
public IDataParameterCollection Parameters
{
get
{
return _odbcCommand.Parameters;
}
}
#nullable enable
public IDbTransaction? Transaction
{
get
{
return _odbcCommand.Transaction;
}
set
{
_odbcCommand.Transaction = (OdbcTransaction?)value;
}
}
#nullable disable
public UpdateRowSource UpdatedRowSource
{
get
{
return _odbcCommand.UpdatedRowSource;
}
set
{
_odbcCommand.UpdatedRowSource = value;
}
}
public void Cancel()
{
_odbcCommand.Cancel();
}
public IDbDataParameter CreateParameter()
{
return _odbcCommand.CreateParameter();
}
public IDbDataParameter CreateParameter(string name, DbType dbType, object value)
{
OdbcParameter odbcParameter = null;
if (this.Parameters.Contains(name))
{
odbcParameter = (OdbcParameter)this.Parameters[name];
odbcParameter.Value = value;
}
else
{
odbcParameter = _odbcCommand.CreateParameter();
odbcParameter.ParameterName = name;
odbcParameter.DbType = dbType;
odbcParameter.Value = value;
this.Parameters.Add(odbcParameter);
}
return odbcParameter;
}
public int ExecuteNonQuery()
{
return _odbcCommand.ExecuteNonQuery();
}
public IDataReader ExecuteReader()
{
return _odbcCommand.ExecuteReader();
}
public async Task<int> ExecuteNonQueryAsync()
{
return await _odbcCommand.ExecuteNonQueryAsync();
}
public async Task<DbDataReader> ExecuteReaderAsync(CommandBehavior behavior)
{
return await _odbcCommand.ExecuteReaderAsync(behavior);
}
public IDataReader ExecuteReader(CommandBehavior behavior)
{
return _odbcCommand.ExecuteReader(behavior);
}
#nullable enable
public object? ExecuteScalar()
{
return _odbcCommand.ExecuteScalar();
}
#nullable disable
public void Prepare()
{
_odbcCommand.Prepare();
}
public void Dispose()
{
_pooledConnection.ReleaseCommand(this);
}
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace SpyUO
{
internal sealed class NativeMethods
{
[StructLayout( LayoutKind.Sequential )]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout( LayoutKind.Sequential )]
public struct STARTUPINFO
{
public uint cb;
[MarshalAs( UnmanagedType.LPTStr )]
public string lpReserved;
[MarshalAs( UnmanagedType.LPTStr )]
public string lpDesktop;
[MarshalAs( UnmanagedType.LPTStr )]
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public ushort wShowWindow;
public ushort cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[Flags]
public enum CreationFlag : uint
{
DEBUG_PROCESS = 0x00000001,
DEBUG_ONLY_THIS_PROCESS = 0x00000002,
CREATE_SUSPENDED = 0x00000004,
DETACHED_PROCESS = 0x00000008,
CREATE_NEW_CONSOLE = 0x00000010,
NORMAL_PRIORITY_CLASS = 0x00000020,
IDLE_PRIORITY_CLASS = 0x00000040,
HIGH_PRIORITY_CLASS = 0x00000080,
REALTIME_PRIORITY_CLASS = 0x00000100,
CREATE_NEW_PROCESS_GROUP = 0x00000200,
CREATE_UNICODE_ENVIRONMENT = 0x00000400,
CREATE_SEPARATE_WOW_VDM = 0x00000800,
CREATE_SHARED_WOW_VDM = 0x00001000,
CREATE_FORCEDOS = 0x00002000,
BELOW_NORMAL_PRIORITY_CLASS = 0x00004000,
ABOVE_NORMAL_PRIORITY_CLASS = 0x00008000,
STACK_SIZE_PARAM_IS_A_RESERVATION = 0x00010000,
CREATE_BREAKAWAY_FROM_JOB = 0x01000000,
CREATE_PRESERVE_CODE_AUTHZ_LEVEL = 0x02000000,
CREATE_DEFAULT_ERROR_MODE = 0x04000000,
CREATE_NO_WINDOW = 0x08000000,
PROFILE_USER = 0x10000000,
PROFILE_KERNEL = 0x20000000,
PROFILE_SERVER = 0x40000000,
CREATE_IGNORE_SYSTEM_DEFAULT = 0x80000000
}
[DllImport( "Kernel32" )]
public static extern bool CreateProcess
(
[MarshalAs( UnmanagedType.LPStr )] string lpApplicationName,
[MarshalAs( UnmanagedType.LPStr )] string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
CreationFlag dwCreationFlags,
IntPtr lpEnvironment,
[MarshalAs( UnmanagedType.LPStr )] string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation
);
[DllImport( "Kernel32" )]
public static extern bool DebugActiveProcess
(
uint dwProcessId
);
[DllImport( "Kernel32" )]
public static extern bool DebugActiveProcessStop
(
uint dwProcessId
);
[Flags]
public enum DesiredAccessProcess : uint
{
PROCESS_TERMINATE = 0x0001,
PROCESS_CREATE_THREAD = 0x0002,
PROCESS_VM_OPERATION = 0x0008,
PROCESS_VM_READ = 0x0010,
PROCESS_VM_WRITE = 0x0020,
PROCESS_DUP_HANDLE = 0x0040,
PROCESS_CREATE_PROCESS = 0x0080,
PROCESS_SET_QUOTA = 0x0100,
PROCESS_SET_INFORMATION = 0x0200,
PROCESS_QUERY_INFORMATION = 0x0400,
SYNCHRONIZE = 0x00100000,
PROCESS_ALL_ACCESS = SYNCHRONIZE | 0xF0FFF
}
[DllImport( "Kernel32" )]
public static extern IntPtr OpenProcess
(
DesiredAccessProcess dwDesiredAccess,
bool bInheritHandle,
uint dwProcessId
);
[Flags]
public enum DesiredAccessThread : uint
{
SYNCHRONIZE = 0x00100000,
THREAD_TERMINATE = 0x0001,
THREAD_SUSPEND_RESUME = 0x0002,
THREAD_GET_CONTEXT = 0x0008,
THREAD_SET_CONTEXT = 0x0010,
THREAD_SET_INFORMATION = 0x0020,
THREAD_QUERY_INFORMATION = 0x0040,
THREAD_SET_THREAD_TOKEN = 0x0080,
THREAD_IMPERSONATE = 0x0100,
THREAD_DIRECT_IMPERSONATION = 0x0200,
THREAD_ALL_ACCESS = SYNCHRONIZE | 0xF03FF
}
[DllImport( "Kernel32" )]
public static extern IntPtr OpenThread
(
DesiredAccessThread dwDesiredAccess,
bool bInheritHandle,
uint dwThreadId
);
[DllImport( "Kernel32" )]
public static extern bool CloseHandle
(
IntPtr hObject
);
public enum DebugEventCode : uint
{
EXCEPTION_DEBUG_EVENT = 1,
CREATE_THREAD_DEBUG_EVENT = 2,
CREATE_PROCESS_DEBUG_EVENT = 3,
EXIT_THREAD_DEBUG_EVENT = 4,
EXIT_PROCESS_DEBUG_EVENT = 5,
LOAD_DLL_DEBUG_EVENT = 6,
UNLOAD_DLL_DEBUG_EVENT = 7,
OUTPUT_DEBUG_STRING_EVENT = 8,
RIP_EVENT = 9
}
public const int EXCEPTION_MAXIMUM_PARAMETERS = 15;
[StructLayout( LayoutKind.Sequential )]
public struct EXCEPTION_RECORD
{
public uint ExceptionCode;
public uint ExceptionFlags;
public IntPtr ExceptionRecord;
public IntPtr ExceptionAddress;
public uint NumberParameters;
[MarshalAs( UnmanagedType.ByValArray, SizeConst = EXCEPTION_MAXIMUM_PARAMETERS)]
public uint[] ExceptionInformation;
}
[StructLayout( LayoutKind.Sequential )]
public struct EXCEPTION_DEBUG_INFO
{
public EXCEPTION_RECORD ExceptionRecord;
public uint dwFirstChance;
}
[StructLayout( LayoutKind.Sequential )]
public struct DEBUG_EVENT_EXCEPTION
{
public DebugEventCode dwDebugEventCode;
public uint dwProcessId;
public uint dwThreadId;
[StructLayout( LayoutKind.Explicit )]
public struct UnionException
{
[FieldOffset( 0 )]
public EXCEPTION_DEBUG_INFO Exception;
}
public UnionException u;
}
[DllImport( "Kernel32" )]
public static extern bool WaitForDebugEvent
(
ref DEBUG_EVENT_EXCEPTION lpDebugEvent,
uint dwMilliseconds
);
[Flags]
public enum ContinueStatus : uint
{
DBG_CONTINUE = 0x00010002,
DBG_EXCEPTION_NOT_HANDLED = 0x80010001
}
[DllImport( "Kernel32" )]
public static extern bool ContinueDebugEvent
(
uint dwProcessId,
uint dwThreadId,
ContinueStatus dwContinueStatus
);
[DllImport( "Kernel32" )]
public static extern bool ReadProcessMemory
(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpBuffer,
uint nSize,
out uint lpNumberOfBytesRead
);
[DllImport( "Kernel32" )]
public static extern bool WriteProcessMemory
(
IntPtr hProcess,
IntPtr lpBaseAddress,
byte[] lpBuffer,
uint nSize,
out uint lpNumberOfBytesWritten
);
[DllImport( "Kernel32" )]
public static extern bool FlushInstructionCache
(
IntPtr hProcess,
IntPtr lpBaseAddress,
uint dwSize
);
[Flags]
public enum ContextFlags : uint
{
CONTEXT_i386 = 0x00010000,
CONTEXT_i486 = 0x00010000,
CONTEXT_CONTROL = CONTEXT_i386 | 0x00000001,
CONTEXT_INTEGER = CONTEXT_i386 | 0x00000002,
CONTEXT_SEGMENTS = CONTEXT_i386 | 0x00000004,
CONTEXT_FLOATING_POINT = CONTEXT_i386 | 0x00000008,
CONTEXT_DEBUG_REGISTERS = CONTEXT_i386 | 0x00000010,
CONTEXT_EXTENDED_REGISTERS = CONTEXT_i386 | 0x00000020,
CONTEXT_FULL = CONTEXT_CONTROL | CONTEXT_INTEGER | CONTEXT_SEGMENTS
}
[StructLayout( LayoutKind.Sequential )]
public struct FLOATING_SAVE_AREA
{
public uint ControlWord;
public uint StatusWord;
public uint TagWord;
public uint ErrorOffset;
public uint ErrorSelector;
public uint DataOffset;
public uint DataSelector;
[MarshalAs( UnmanagedType.ByValArray, SizeConst = 80 )]
public byte[] RegisterArea;
public uint Cr0NpxState;
}
[StructLayout( LayoutKind.Sequential )]
public struct CONTEXT
{
public ContextFlags ContextFlags;
public uint Dr0;
public uint Dr1;
public uint Dr2;
public uint Dr3;
public uint Dr6;
public uint Dr7;
public FLOATING_SAVE_AREA FloatSave;
public uint SegGs;
public uint SegFs;
public uint SegEs;
public uint SegDs;
public uint Edi;
public uint Esi;
public uint Ebx;
public uint Edx;
public uint Ecx;
public uint Eax;
public uint Ebp;
public uint Eip;
public uint SegCs;
public uint EFlags;
public uint Esp;
public uint SegSs;
[MarshalAs( UnmanagedType.ByValArray, SizeConst = 512 )]
public byte[] ExtendedRegisters;
}
[DllImport( "Kernel32" )]
public static extern bool GetThreadContext
(
IntPtr hThread,
ref CONTEXT lpContext
);
[DllImport( "Kernel32" )]
public static extern bool SetThreadContext
(
IntPtr hThread,
ref CONTEXT lpContext
);
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal partial class CSharpMethodExtractor
{
private abstract partial class CSharpCodeGenerator
{
private class CallSiteContainerRewriter : CSharpSyntaxRewriter
{
private readonly SyntaxNode _outmostCallSiteContainer;
private readonly IEnumerable<SyntaxNode> _statementsOrFieldToInsert;
private readonly HashSet<SyntaxAnnotation> _variableToRemoveMap;
private readonly SyntaxNode _firstStatementOrFieldToReplace;
private readonly SyntaxNode _lastStatementOrFieldToReplace;
public CallSiteContainerRewriter(
SyntaxNode outmostCallSiteContainer,
HashSet<SyntaxAnnotation> variableToRemoveMap,
SyntaxNode firstStatementOrFieldToReplace,
SyntaxNode lastStatementOrFieldToReplace,
IEnumerable<SyntaxNode> statementsOrFieldToInsert)
{
Contract.ThrowIfNull(outmostCallSiteContainer);
Contract.ThrowIfNull(variableToRemoveMap);
Contract.ThrowIfNull(firstStatementOrFieldToReplace);
Contract.ThrowIfNull(lastStatementOrFieldToReplace);
Contract.ThrowIfNull(statementsOrFieldToInsert);
Contract.ThrowIfTrue(statementsOrFieldToInsert.IsEmpty());
_outmostCallSiteContainer = outmostCallSiteContainer;
_variableToRemoveMap = variableToRemoveMap;
_statementsOrFieldToInsert = statementsOrFieldToInsert;
_firstStatementOrFieldToReplace = firstStatementOrFieldToReplace;
_lastStatementOrFieldToReplace = lastStatementOrFieldToReplace;
Contract.ThrowIfFalse(_firstStatementOrFieldToReplace.Parent == _lastStatementOrFieldToReplace.Parent);
}
public SyntaxNode Generate()
{
return Visit(_outmostCallSiteContainer);
}
private SyntaxNode ContainerOfStatementsOrFieldToReplace
{
get { return _firstStatementOrFieldToReplace.Parent; }
}
public override SyntaxNode VisitLocalDeclarationStatement(LocalDeclarationStatementSyntax node)
{
node = (LocalDeclarationStatementSyntax)base.VisitLocalDeclarationStatement(node);
var list = new List<VariableDeclaratorSyntax>();
var triviaList = new List<SyntaxTrivia>();
// go through each var decls in decl statement
foreach (var variable in node.Declaration.Variables)
{
if (_variableToRemoveMap.HasSyntaxAnnotation(variable))
{
// if it had initialization, it shouldn't reach here.
Contract.ThrowIfFalse(variable.Initializer == null);
// we don't remove trivia around tokens we remove
triviaList.AddRange(variable.GetLeadingTrivia());
triviaList.AddRange(variable.GetTrailingTrivia());
continue;
}
if (triviaList.Count > 0)
{
list.Add(variable.WithPrependedLeadingTrivia(triviaList));
triviaList.Clear();
continue;
}
list.Add(variable);
}
if (list.Count == 0)
{
// nothing has survived. remove this from the list
if (triviaList.Count == 0)
{
return null;
}
// well, there are trivia associated with the node.
// we can't just delete the node since then, we will lose
// the trivia. unfortunately, it is not easy to attach the trivia
// to next token. for now, create an empty statement and associate the
// trivia to the statement
// TODO : think about a way to move the trivia to next token.
return SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxFactory.TriviaList(triviaList), SyntaxKind.SemicolonToken, SyntaxTriviaList.Create(SyntaxFactory.ElasticMarker)));
}
if (list.Count == node.Declaration.Variables.Count)
{
// nothing has changed, return as it is
return node;
}
// TODO : fix how it manipulate trivia later
// if there is left over syntax trivia, it will be attached to leading trivia
// of semicolon
return
SyntaxFactory.LocalDeclarationStatement(
node.Modifiers,
node.RefKeyword,
SyntaxFactory.VariableDeclaration(
node.Declaration.Type,
SyntaxFactory.SeparatedList(list)),
node.SemicolonToken.WithPrependedLeadingTrivia(triviaList));
}
// for every kind of extract methods
public override SyntaxNode VisitBlock(BlockSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
// make sure we visit nodes under the block
return base.VisitBlock(node);
}
return node.WithStatements(VisitList(ReplaceStatements(node.Statements)).ToSyntaxList());
}
public override SyntaxNode VisitSwitchSection(SwitchSectionSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
// make sure we visit nodes under the switch section
return base.VisitSwitchSection(node);
}
return node.WithStatements(VisitList(ReplaceStatements(node.Statements)).ToSyntaxList());
}
// only for single statement or expression
public override SyntaxNode VisitLabeledStatement(LabeledStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitLabeledStatement(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitElseClause(ElseClauseSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitElseClause(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitIfStatement(IfStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitIfStatement(node);
}
return node.WithCondition(VisitNode(node.Condition))
.WithStatement(ReplaceStatementIfNeeded(node.Statement))
.WithElse(VisitNode(node.Else));
}
public override SyntaxNode VisitLockStatement(LockStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitLockStatement(node);
}
return node.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitFixedStatement(FixedStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitFixedStatement(node);
}
return node.WithDeclaration(VisitNode(node.Declaration))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitUsingStatement(UsingStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitUsingStatement(node);
}
return node.WithDeclaration(VisitNode(node.Declaration))
.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitForEachStatement(ForEachStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitForEachStatement(node);
}
return node.WithExpression(VisitNode(node.Expression))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitForStatement(ForStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitForStatement(node);
}
return node.WithDeclaration(VisitNode(node.Declaration))
.WithInitializers(VisitList(node.Initializers))
.WithCondition(VisitNode(node.Condition))
.WithIncrementors(VisitList(node.Incrementors))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitDoStatement(DoStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitDoStatement(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement))
.WithCondition(VisitNode(node.Condition));
}
public override SyntaxNode VisitWhileStatement(WhileStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitWhileStatement(node);
}
return node.WithCondition(VisitNode(node.Condition))
.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
private TNode VisitNode<TNode>(TNode node) where TNode : SyntaxNode
{
return (TNode)Visit(node);
}
private StatementSyntax ReplaceStatementIfNeeded(StatementSyntax statement)
{
Contract.ThrowIfNull(statement);
// if all three same
if ((statement != _firstStatementOrFieldToReplace) || (_firstStatementOrFieldToReplace != _lastStatementOrFieldToReplace))
{
return statement;
}
// replace one statement with another
if (_statementsOrFieldToInsert.Count() == 1)
{
return _statementsOrFieldToInsert.Cast<StatementSyntax>().Single();
}
// replace one statement with multiple statements (see bug # 6310)
return SyntaxFactory.Block(SyntaxFactory.List(_statementsOrFieldToInsert.Cast<StatementSyntax>()));
}
private SyntaxList<StatementSyntax> ReplaceStatements(SyntaxList<StatementSyntax> statements)
{
// okay, this visit contains the statement
var newStatements = new List<StatementSyntax>(statements);
var firstStatementIndex = newStatements.FindIndex(s => s == _firstStatementOrFieldToReplace);
Contract.ThrowIfFalse(firstStatementIndex >= 0);
var lastStatementIndex = newStatements.FindIndex(s => s == _lastStatementOrFieldToReplace);
Contract.ThrowIfFalse(lastStatementIndex >= 0);
Contract.ThrowIfFalse(firstStatementIndex <= lastStatementIndex);
// remove statement that must be removed
newStatements.RemoveRange(firstStatementIndex, lastStatementIndex - firstStatementIndex + 1);
// add new statements to replace
newStatements.InsertRange(firstStatementIndex, _statementsOrFieldToInsert.Cast<StatementSyntax>());
return newStatements.ToSyntaxList();
}
private SyntaxList<MemberDeclarationSyntax> ReplaceMembers(SyntaxList<MemberDeclarationSyntax> members, bool global)
{
// okay, this visit contains the statement
var newMembers = new List<MemberDeclarationSyntax>(members);
var firstMemberIndex = newMembers.FindIndex(s => s == (global ? _firstStatementOrFieldToReplace.Parent : _firstStatementOrFieldToReplace));
Contract.ThrowIfFalse(firstMemberIndex >= 0);
var lastMemberIndex = newMembers.FindIndex(s => s == (global ? _lastStatementOrFieldToReplace.Parent : _lastStatementOrFieldToReplace));
Contract.ThrowIfFalse(lastMemberIndex >= 0);
Contract.ThrowIfFalse(firstMemberIndex <= lastMemberIndex);
// remove statement that must be removed
newMembers.RemoveRange(firstMemberIndex, lastMemberIndex - firstMemberIndex + 1);
// add new statements to replace
newMembers.InsertRange(firstMemberIndex,
_statementsOrFieldToInsert.Select(s => global ? SyntaxFactory.GlobalStatement((StatementSyntax)s) : (MemberDeclarationSyntax)s));
return newMembers.ToSyntaxList();
}
public override SyntaxNode VisitGlobalStatement(GlobalStatementSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitGlobalStatement(node);
}
return node.WithStatement(ReplaceStatementIfNeeded(node.Statement));
}
public override SyntaxNode VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitConstructorDeclaration(node);
}
Contract.ThrowIfFalse(_firstStatementOrFieldToReplace == _lastStatementOrFieldToReplace);
return node.WithInitializer((ConstructorInitializerSyntax)_statementsOrFieldToInsert.Single());
}
public override SyntaxNode VisitClassDeclaration(ClassDeclarationSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitClassDeclaration(node);
}
var newMembers = VisitList(ReplaceMembers(node.Members, global: false));
return node.WithMembers(newMembers);
}
public override SyntaxNode VisitStructDeclaration(StructDeclarationSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace)
{
return base.VisitStructDeclaration(node);
}
var newMembers = VisitList(ReplaceMembers(node.Members, global: false));
return node.WithMembers(newMembers);
}
public override SyntaxNode VisitCompilationUnit(CompilationUnitSyntax node)
{
if (node != this.ContainerOfStatementsOrFieldToReplace.Parent)
{
// make sure we visit nodes under the block
return base.VisitCompilationUnit(node);
}
var newMembers = VisitList(ReplaceMembers(node.Members, global: true));
return node.WithMembers(newMembers);
}
}
}
}
}
| |
using Signum.Engine.Authorization;
using Signum.Engine.Chart;
using Signum.Engine.Dashboard;
using Signum.Engine.Translation;
using Signum.Engine.UserAssets;
using Signum.Engine.UserQueries;
using Signum.Engine.Workflow;
using Signum.Entities.Authorization;
using Signum.Entities.Basics;
using Signum.Entities.Chart;
using Signum.Entities.Dashboard;
using Signum.Entities.Toolbar;
using Signum.Entities.UserAssets;
using Signum.Entities.UserQueries;
using Signum.Entities.Workflow;
using Signum.Utilities.DataStructures;
using System.Text.Json.Serialization;
namespace Signum.Engine.Toolbar;
public static class ToolbarLogic
{
public static ResetLazy<Dictionary<Lite<ToolbarEntity>, ToolbarEntity>> Toolbars = null!;
public static ResetLazy<Dictionary<Lite<ToolbarMenuEntity>, ToolbarMenuEntity>> ToolbarMenus = null!;
public static Dictionary<PermissionSymbol, Func<List<ToolbarResponse>>> CustomPermissionResponse =
new Dictionary<PermissionSymbol, Func<List<ToolbarResponse>>>();
public static void Start(SchemaBuilder sb)
{
if (sb.NotDefined(MethodInfo.GetCurrentMethod()))
{
sb.Include<ToolbarEntity>()
.WithSave(ToolbarOperation.Save)
.WithDelete(ToolbarOperation.Delete)
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name,
e.Owner,
e.Priority
});
sb.Schema.EntityEvents<ToolbarEntity>().Saving += IToolbar_Saving;
sb.Schema.EntityEvents<ToolbarMenuEntity>().Saving += IToolbar_Saving;
sb.Include<ToolbarMenuEntity>()
.WithSave(ToolbarMenuOperation.Save)
.WithDelete(ToolbarMenuOperation.Delete)
.WithQuery(() => e => new
{
Entity = e,
e.Id,
e.Name
});
UserAssetsImporter.Register<ToolbarEntity>("Toolbar", ToolbarOperation.Save);
UserAssetsImporter.Register<ToolbarMenuEntity>("ToolbarMenu", ToolbarMenuOperation.Save);
RegisterDelete<UserQueryEntity>(sb);
RegisterDelete<UserChartEntity>(sb);
RegisterDelete<QueryEntity>(sb);
RegisterDelete<DashboardEntity>(sb);
RegisterDelete<ToolbarMenuEntity>(sb);
RegisterDelete<WorkflowEntity>(sb);
RegisterContentConfig<ToolbarMenuEntity>(
lite => true,
lite => TranslatedInstanceLogic.TranslatedField(ToolbarMenus.Value.GetOrCreate(lite), a => a.Name));
RegisterContentConfig<ToolbarEntity>(
lite => true,
lite => TranslatedInstanceLogic.TranslatedField(Toolbars.Value.GetOrCreate(lite), a => a.Name));
RegisterContentConfig<UserQueryEntity>(
lite => { var uq = UserQueryLogic.UserQueries.Value.GetOrCreate(lite); return InMemoryFilter(uq) && QueryLogic.Queries.QueryAllowed(uq.Query.ToQueryName(), true); },
lite => TranslatedInstanceLogic.TranslatedField(UserQueryLogic.UserQueries.Value.GetOrCreate(lite), a => a.DisplayName));
RegisterContentConfig<UserChartEntity>(
lite => { var uc = UserChartLogic.UserCharts.Value.GetOrCreate(lite); return InMemoryFilter(uc) && QueryLogic.Queries.QueryAllowed(uc.Query.ToQueryName(), true); },
lite => TranslatedInstanceLogic.TranslatedField(UserChartLogic.UserCharts.Value.GetOrCreate(lite), a => a.DisplayName));
RegisterContentConfig<QueryEntity>(
lite => IsQueryAllowed(lite),
lite => QueryUtils.GetNiceName(QueryLogic.QueryNames.GetOrThrow(lite.ToString()!)));
RegisterContentConfig<DashboardEntity>(
lite => InMemoryFilter(DashboardLogic.Dashboards.Value.GetOrCreate(lite)),
lite => TranslatedInstanceLogic.TranslatedField(DashboardLogic.Dashboards.Value.GetOrCreate(lite), a => a.DisplayName));
RegisterContentConfig<PermissionSymbol>(
lite => PermissionAuthLogic.IsAuthorized(SymbolLogic<PermissionSymbol>.ToSymbol(lite.ToString()!)),
lite => SymbolLogic<PermissionSymbol>.ToSymbol(lite.ToString()!).NiceToString());
ToolbarLogic.GetContentConfig<PermissionSymbol>().CustomResponses = lite =>
{
var action = CustomPermissionResponse.TryGetC(lite.Retrieve());
if (action != null)
return action();
return null;
};
RegisterContentConfig<WorkflowEntity>(
lite => { var wf = WorkflowLogic.WorkflowGraphLazy.Value.GetOrCreate(lite); return InMemoryFilter(wf.Workflow) && wf.IsStartCurrentUser(); },
lite => TranslatedInstanceLogic.TranslatedField(WorkflowLogic.WorkflowGraphLazy.Value.GetOrCreate(lite).Workflow, a => a.Name));
// { typeof(QueryEntity), a => IsQueryAllowed((Lite<QueryEntity>)a) },
//{ typeof(PermissionSymbol), a => PermissionAuthLogic.IsAuthorized((PermissionSymbol)a.RetrieveAndRemember()) },
//{ typeof(UserQueryEntity), a => ,
//{ typeof(UserChartEntity), a => { var uc = UserChartLogic.UserCharts.Value.GetOrCreate((Lite<UserChartEntity>)a); return InMemoryFilter(uc) && QueryLogic.Queries.QueryAllowed(uc.Query.ToQueryName(), true); } },
//{ typeof(DashboardEntity), a => InMemoryFilter(DashboardLogic.Dashboards.Value.GetOrCreate((Lite<DashboardEntity>)a)) },
//{ typeof(WorkflowEntity), a => { var wf = WorkflowLogic.WorkflowGraphLazy.Value.GetOrCreate((Lite<WorkflowEntity>)a); return InMemoryFilter(wf.Workflow) && wf.IsStartCurrentUser(); } },
Toolbars = sb.GlobalLazy(() => Database.Query<ToolbarEntity>().ToDictionary(a => a.ToLite()),
new InvalidateWith(typeof(ToolbarEntity)));
ToolbarMenus = sb.GlobalLazy(() => Database.Query<ToolbarMenuEntity>().ToDictionary(a => a.ToLite()),
new InvalidateWith(typeof(ToolbarMenuEntity)));
}
}
private static void IToolbar_Saving(IToolbarEntity tool)
{
if (!tool.IsNew && tool.Elements.IsGraphModified)
{
using (new EntityCache(EntityCacheType.ForceNew))
{
EntityCache.AddFullGraph((Entity)tool);
var toolbarGraph = DirectedGraph<IToolbarEntity>.Generate(tool, t => t.Elements.Select(a => a.Content).Where(c => c is Lite<IToolbarEntity>).Select(t => (IToolbarEntity)t!.Retrieve()));
var problems = toolbarGraph.FeedbackEdgeSet().Edges.ToList();
if (problems.Count > 0)
throw new ApplicationException(
ToolbarMessage._0CyclesHaveBeenFoundInTheToolbarDueToTheRelationships.NiceToString().FormatWith(problems.Count) +
problems.ToString("\r\n"));
}
}
}
public static void RegisterUserTypeCondition(SchemaBuilder sb, TypeConditionSymbol typeCondition)
{
sb.Schema.Settings.AssertImplementedBy((ToolbarEntity t) => t.Owner, typeof(UserEntity));
TypeConditionLogic.RegisterCompile<ToolbarEntity>(typeCondition,
t => t.Owner.Is(UserEntity.Current));
sb.Schema.Settings.AssertImplementedBy((ToolbarMenuEntity t) => t.Owner, typeof(UserEntity));
TypeConditionLogic.RegisterCompile<ToolbarMenuEntity>(typeCondition,
t => t.Owner.Is(UserEntity.Current));
}
public static void RegisterRoleTypeCondition(SchemaBuilder sb, TypeConditionSymbol typeCondition)
{
sb.Schema.Settings.AssertImplementedBy((ToolbarEntity t) => t.Owner, typeof(RoleEntity));
TypeConditionLogic.RegisterCompile<ToolbarEntity>(typeCondition,
t => AuthLogic.CurrentRoles().Contains(t.Owner) || t.Owner == null);
sb.Schema.Settings.AssertImplementedBy((ToolbarMenuEntity t) => t.Owner, typeof(RoleEntity));
TypeConditionLogic.RegisterCompile<ToolbarMenuEntity>(typeCondition,
t => AuthLogic.CurrentRoles().Contains(t.Owner) || t.Owner == null);
}
public static void RegisterDelete<T>(SchemaBuilder sb) where T : Entity
{
if (sb.Settings.ImplementedBy((ToolbarEntity tb) => tb.Elements.First().Content, typeof(T)))
{
sb.Schema.EntityEvents<T>().PreUnsafeDelete += query =>
{
if (Schema.Current.IsAllowed(typeof(ToolbarEntity), false) == null)
Database.MListQuery((ToolbarEntity tb) => tb.Elements).Where(mle => query.Contains((T)mle.Element.Content!.Entity)).UnsafeDeleteMList();
return null;
};
sb.Schema.Table<T>().PreDeleteSqlSync += arg =>
{
var entity = (T)arg;
var parts = Administrator.UnsafeDeletePreCommandMList((ToolbarEntity tb) => tb.Elements, Database.MListQuery((ToolbarEntity tb) => tb.Elements)
.Where(mle => mle.Element.Content!.Entity == entity));
return parts;
};
}
if (sb.Settings.ImplementedBy((ToolbarMenuEntity tb) => tb.Elements.First().Content, typeof(T)))
{
sb.Schema.EntityEvents<T>().PreUnsafeDelete += query =>
{
if (Schema.Current.IsAllowed(typeof(ToolbarMenuEntity), false) == null)
Database.MListQuery((ToolbarMenuEntity tb) => tb.Elements).Where(mle => query.Contains((T)mle.Element.Content!.Entity)).UnsafeDeleteMList();
return null;
};
sb.Schema.Table<T>().PreDeleteSqlSync += arg =>
{
var entity = (T)arg;
var parts = Administrator.UnsafeDeletePreCommandMList((ToolbarMenuEntity tb) => tb.Elements, Database.MListQuery((ToolbarMenuEntity tb) => tb.Elements)
.Where(mle => mle.Element.Content!.Entity == entity));
return parts;
};
}
}
public static void RegisterTranslatableRoutes()
{
TranslatedInstanceLogic.AddRoute((ToolbarEntity tb) => tb.Name);
TranslatedInstanceLogic.AddRoute((ToolbarEntity tb) => tb.Elements[0].Label);
TranslatedInstanceLogic.AddRoute((ToolbarMenuEntity tm) => tm.Name);
TranslatedInstanceLogic.AddRoute((ToolbarMenuEntity tb) => tb.Elements[0].Label);
}
public static ToolbarEntity? GetCurrent(ToolbarLocation location)
{
var isAllowed = Schema.Current.GetInMemoryFilter<ToolbarEntity>(userInterface: false);
var result = Toolbars.Value.Values
.Where(t => isAllowed(t) && t.Location == location)
.OrderByDescending(a => a.Priority)
.FirstOrDefault();
return result;
}
public static ToolbarResponse? GetCurrentToolbarResponse(ToolbarLocation location)
{
var curr = GetCurrent(location);
if (curr == null)
return null;
var responses = ToResponseList(TranslatedInstanceLogic.TranslatedMList(curr, c => c.Elements).ToList());
if (responses.Count == 0)
return null;
return new ToolbarResponse
{
type = ToolbarElementType.Header,
content = curr.ToLite(),
label = TranslatedInstanceLogic.TranslatedField(curr, a => a.Name),
elements = responses,
};
}
private static List<ToolbarResponse> ToResponseList(List<TranslatableElement<ToolbarElementEmbedded>> elements)
{
var result = elements.SelectMany(a => ToResponse(a) ?? Enumerable.Empty<ToolbarResponse>()).NotNull().ToList();
retry:
var extraDividers = result.Where((a, i) => a.type == ToolbarElementType.Divider && (
i == 0 ||
result[i - 1].type == ToolbarElementType.Divider ||
i == result.Count
)).ToList();
result.RemoveAll(extraDividers.Contains);
var extraHeaders = result.Where((a, i) => IsPureHeader(a) && (
i == result.Count - 1 ||
IsPureHeader(result[i + 1]) ||
result[i + 1].type == ToolbarElementType.Divider ||
result[i + 1].type == ToolbarElementType.Header && result[i + 1].content is Lite<ToolbarMenuEntity>
)).ToList();
result.RemoveAll(extraHeaders.Contains);
if (extraDividers.Any() || extraHeaders.Any())
goto retry;
return result;
}
private static bool IsPureHeader(ToolbarResponse tr)
{
return tr.type == ToolbarElementType.Header && tr.content == null && string.IsNullOrEmpty(tr.url);
}
private static IEnumerable<ToolbarResponse>? ToResponse(TranslatableElement<ToolbarElementEmbedded> transElement)
{
var element = transElement.Value;
IContentConfig? config = null;
if (element.Content != null)
{
config = ContentCondigDictionary.GetOrThrow(element.Content.EntityType);
if (!config.IsAuhorized(element.Content))
return null;
var customResponse = config.CustomResponses(element.Content);
if (customResponse != null)
return customResponse;
}
var result = new ToolbarResponse
{
type = element.Type,
content = element.Content,
url = element.Url,
label = transElement.TranslatedElement(a => a.Label!).DefaultText(null) ?? config?.DefaultLabel(element.Content!),
iconName = element.IconName,
iconColor = element.IconColor,
autoRefreshPeriod = element.AutoRefreshPeriod,
openInPopup = element.OpenInPopup,
};
if (element.Content is Lite<ToolbarMenuEntity>)
{
var tme = ToolbarMenus.Value.GetOrThrow((Lite<ToolbarMenuEntity>)element.Content);
result.elements = ToResponseList(TranslatedInstanceLogic.TranslatedMList(tme, t => t.Elements).ToList());
if (result.elements.Count == 0)
return null;
}
if (element.Content is Lite<ToolbarEntity>)
{
var tme = Toolbars.Value.GetOrThrow((Lite<ToolbarEntity>)element.Content);
var res = ToResponseList(TranslatedInstanceLogic.TranslatedMList(tme, t => t.Elements).ToList());
if (res.Count == 0)
return null;
return res;
}
return new[] { result };
}
public static void RegisterContentConfig<T>(Func<Lite<T>, bool> isAuthorized, Func<Lite<T>, string> defaultLabel)
where T : Entity
{
ContentCondigDictionary.Add(typeof(T), new ContentConfig<T>(isAuthorized, defaultLabel));
}
public static ContentConfig<T> GetContentConfig<T>() where T: Entity
{
return (ContentConfig<T>)ContentCondigDictionary.GetOrThrow(typeof(T));
}
static Dictionary<Type, IContentConfig> ContentCondigDictionary = new Dictionary<Type, IContentConfig>();
public interface IContentConfig
{
bool IsAuhorized(Lite<Entity> lite);
string DefaultLabel(Lite<Entity> lite);
List<ToolbarResponse>? CustomResponses(Lite<Entity> lite);
}
public class ContentConfig<T> : IContentConfig where T : Entity
{
public Func<Lite<T>, bool> IsAuthorized;
public Func<Lite<T>, string> DefaultLabel;
public Func<Lite<T>, List<ToolbarResponse>?>? CustomResponses;
public ContentConfig(Func<Lite<T>, bool> isAuthorized, Func<Lite<T>, string> defaultLabel)
{
IsAuthorized = isAuthorized;
DefaultLabel = defaultLabel;
}
bool IContentConfig.IsAuhorized(Lite<Entity> lite) => IsAuthorized((Lite<T>)lite);
string IContentConfig.DefaultLabel(Lite<Entity> lite) => DefaultLabel((Lite<T>)lite);
List<ToolbarResponse>? IContentConfig.CustomResponses(Lite<Entity> lite)
{
foreach (var item in CustomResponses.GetInvocationListTyped())
{
var resp = item.Invoke((Lite<T>)lite);
if (resp != null)
return resp;
}
return null;
}
}
static bool IsQueryAllowed(Lite<QueryEntity> query)
{
try
{
return QueryLogic.Queries.QueryAllowed(QueryLogic.QueryNames.GetOrThrow(query.ToString()!), true);
}
catch (Exception e) when (StartParameters.IgnoredDatabaseMismatches != null)
{
//Could happen when not 100% synchronized
StartParameters.IgnoredDatabaseMismatches.Add(e);
return false;
}
}
static bool InMemoryFilter<T>(T entity) where T : Entity
{
if (Schema.Current.IsAllowed(typeof(T), inUserInterface: false) != null)
return false;
var isAllowed = Schema.Current.GetInMemoryFilter<T>(userInterface: false);
return isAllowed(entity);
}
}
public class ToolbarResponse
{
public ToolbarElementType type;
public string? label;
public Lite<Entity>? content;
public string? url;
public List<ToolbarResponse>? elements;
public string? iconName;
public string? iconColor;
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public int? autoRefreshPeriod;
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
public bool openInPopup;
public override string ToString() => $"{type} {label} {content} {url}";
}
| |
using System;
using System.Linq;
using System.ComponentModel;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis;
using System.Reflection;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
using System.Runtime.ExceptionServices;
namespace RefactoringEssentials
{
[EditorBrowsableAttribute(EditorBrowsableState.Never)]
#if NR6
public
#endif
static class ITypeSymbolExtensions
{
readonly static MethodInfo generateTypeSyntax;
readonly static MethodInfo inheritsFromOrEqualsIgnoringConstructionMethod;
static ITypeSymbolExtensions()
{
var typeInfo = Type.GetType("Microsoft.CodeAnalysis.CSharp.Extensions.ITypeSymbolExtensions" + ReflectionNamespaces.CSWorkspacesAsmName, true);
generateTypeSyntax = typeInfo.GetMethod("GenerateTypeSyntax", new[] { typeof(ITypeSymbol) });
containingTypesOrSelfHasUnsafeKeywordMethod = typeInfo.GetMethod("ContainingTypesOrSelfHasUnsafeKeyword", BindingFlags.Public | BindingFlags.Static);
typeInfo = Type.GetType("Microsoft.CodeAnalysis.Shared.Extensions.ITypeSymbolExtensions" + ReflectionNamespaces.WorkspacesAsmName, true);
inheritsFromOrEqualsIgnoringConstructionMethod = typeInfo.GetMethod("InheritsFromOrEqualsIgnoringConstruction");
removeUnavailableTypeParametersMethod = typeInfo.GetMethod("RemoveUnavailableTypeParameters");
removeUnnamedErrorTypesMethod = typeInfo.GetMethod("RemoveUnnamedErrorTypes");
replaceTypeParametersBasedOnTypeConstraintsMethod = typeInfo.GetMethod("ReplaceTypeParametersBasedOnTypeConstraints");
foreach (var m in typeInfo.GetMethods(BindingFlags.Public | BindingFlags.Static))
{
if (m.Name != "SubstituteTypes")
continue;
var parameters = m.GetParameters();
if (parameters.Length != 3)
continue;
if (parameters[2].Name == "typeGenerator")
{
substituteTypesMethod2 = m;
}
else if (parameters[2].Name == "compilation")
{
substituteTypesMethod = m;
}
break;
}
}
public static TypeSyntax GenerateTypeSyntax(this ITypeSymbol typeSymbol)
{
return (TypeSyntax)generateTypeSyntax.Invoke(null, new[] { typeSymbol });
}
readonly static MethodInfo containingTypesOrSelfHasUnsafeKeywordMethod;
public static bool ContainingTypesOrSelfHasUnsafeKeyword(this ITypeSymbol containingType)
{
return (bool)containingTypesOrSelfHasUnsafeKeywordMethod.Invoke(null, new object[] { containingType });
}
private const string DefaultParameterName = "p";
private const string DefaultBuiltInParameterName = "v";
public static IList<INamedTypeSymbol> GetAllInterfacesIncludingThis(this ITypeSymbol type)
{
var allInterfaces = type.AllInterfaces;
var namedType = type as INamedTypeSymbol;
if (namedType != null && namedType.TypeKind == TypeKind.Interface && !allInterfaces.Contains(namedType))
{
var result = new List<INamedTypeSymbol>(allInterfaces.Length + 1);
result.Add(namedType);
result.AddRange(allInterfaces);
return result;
}
return allInterfaces;
}
public static bool IsAbstractClass(this ITypeSymbol symbol)
{
return symbol?.TypeKind == TypeKind.Class && symbol.IsAbstract;
}
public static bool IsSystemVoid(this ITypeSymbol symbol)
{
return symbol?.SpecialType == SpecialType.System_Void;
}
public static bool IsNullable(this ITypeSymbol symbol)
{
return symbol?.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T;
}
public static bool IsErrorType(this ITypeSymbol symbol)
{
return symbol?.TypeKind == TypeKind.Error;
}
public static bool IsModuleType(this ITypeSymbol symbol)
{
return symbol?.TypeKind == TypeKind.Module;
}
public static bool IsInterfaceType(this ITypeSymbol symbol)
{
return symbol?.TypeKind == TypeKind.Interface;
}
public static bool IsDelegateType(this ITypeSymbol symbol)
{
return symbol?.TypeKind == TypeKind.Delegate;
}
public static bool IsAnonymousType(this INamedTypeSymbol symbol)
{
return symbol?.IsAnonymousType == true;
}
// public static ITypeSymbol RemoveNullableIfPresent(this ITypeSymbol symbol)
// {
// if (symbol.IsNullable())
// {
// return symbol.GetTypeArguments().Single();
// }
//
// return symbol;
// }
// /// <summary>
// /// Returns the corresponding symbol in this type or a base type that implements
// /// interfaceMember (either implicitly or explicitly), or null if no such symbol exists
// /// (which might be either because this type doesn't implement the container of
// /// interfaceMember, or this type doesn't supply a member that successfully implements
// /// interfaceMember).
// /// </summary>
// public static IEnumerable<ISymbol> FindImplementationsForInterfaceMember(
// this ITypeSymbol typeSymbol,
// ISymbol interfaceMember,
// Workspace workspace,
// CancellationToken cancellationToken)
// {
// // This method can return multiple results. Consider the case of:
// //
// // interface IFoo<X> { void Foo(X x); }
// //
// // class C : IFoo<int>, IFoo<string> { void Foo(int x); void Foo(string x); }
// //
// // If you're looking for the implementations of IFoo<X>.Foo then you want to find both
// // results in C.
//
// // TODO(cyrusn): Implement this using the actual code for
// // TypeSymbol.FindImplementationForInterfaceMember
//
// if (typeSymbol == null || interfaceMember == null)
// {
// yield break;
// }
//
// if (interfaceMember.Kind != SymbolKind.Event &&
// interfaceMember.Kind != SymbolKind.Method &&
// interfaceMember.Kind != SymbolKind.Property)
// {
// yield break;
// }
//
// // WorkItem(4843)
// //
// // 'typeSymbol' has to at least implement the interface containing the member. note:
// // this just means that the interface shows up *somewhere* in the inheritance chain of
// // this type. However, this type may not actually say that it implements it. For
// // example:
// //
// // interface I { void Foo(); }
// //
// // class B { }
// //
// // class C : B, I { }
// //
// // class D : C { }
// //
// // D does implement I transitively through C. However, even if D has a "Foo" method, it
// // won't be an implementation of I.Foo. The implementation of I.Foo must be from a type
// // that actually has I in it's direct interface chain, or a type that's a base type of
// // that. in this case, that means only classes C or B.
// var interfaceType = interfaceMember.ContainingType;
// if (!typeSymbol.ImplementsIgnoringConstruction(interfaceType))
// {
// yield break;
// }
//
// // We've ascertained that the type T implements some constructed type of the form I<X>.
// // However, we're not precisely sure which constructions of I<X> are being used. For
// // example, a type C might implement I<int> and I<string>. If we're searching for a
// // method from I<X> we might need to find several methods that implement different
// // instantiations of that method.
// var originalInterfaceType = interfaceMember.ContainingType.OriginalDefinition;
// var originalInterfaceMember = interfaceMember.OriginalDefinition;
// var constructedInterfaces = typeSymbol.AllInterfaces.Where(i =>
// SymbolEquivalenceComparer.Instance.Equals(i.OriginalDefinition, originalInterfaceType));
//
// foreach (var constructedInterface in constructedInterfaces)
// {
// cancellationToken.ThrowIfCancellationRequested();
// var constructedInterfaceMember = constructedInterface.GetMembers().FirstOrDefault(m =>
// SymbolEquivalenceComparer.Instance.Equals(m.OriginalDefinition, originalInterfaceMember));
//
// if (constructedInterfaceMember == null)
// {
// continue;
// }
//
// // Now we need to walk the base type chain, but we start at the first type that actually
// // has the interface directly in its interface hierarchy.
// var seenTypeDeclaringInterface = false;
// for (var currentType = typeSymbol; currentType != null; currentType = currentType.BaseType)
// {
// seenTypeDeclaringInterface = seenTypeDeclaringInterface ||
// currentType.GetOriginalInterfacesAndTheirBaseInterfaces().Contains(interfaceType.OriginalDefinition);
//
// if (seenTypeDeclaringInterface)
// {
// var result = constructedInterfaceMember.TypeSwitch(
// (IEventSymbol eventSymbol) => FindImplementations(currentType, eventSymbol, workspace, e => e.ExplicitInterfaceImplementations),
// (IMethodSymbol methodSymbol) => FindImplementations(currentType, methodSymbol, workspace, m => m.ExplicitInterfaceImplementations),
// (IPropertySymbol propertySymbol) => FindImplementations(currentType, propertySymbol, workspace, p => p.ExplicitInterfaceImplementations));
//
// if (result != null)
// {
// yield return result;
// break;
// }
// }
// }
// }
// }
//
// private static HashSet<INamedTypeSymbol> GetOriginalInterfacesAndTheirBaseInterfaces(
// this ITypeSymbol type,
// HashSet<INamedTypeSymbol> symbols = null)
// {
// symbols = symbols ?? new HashSet<INamedTypeSymbol>(SymbolEquivalenceComparer.Instance);
//
// foreach (var interfaceType in type.Interfaces)
// {
// symbols.Add(interfaceType.OriginalDefinition);
// symbols.AddRange(interfaceType.AllInterfaces.Select(i => i.OriginalDefinition));
// }
//
// return symbols;
// }
// private static ISymbol FindImplementations<TSymbol>(
// ITypeSymbol typeSymbol,
// TSymbol interfaceSymbol,
// Workspace workspace,
// Func<TSymbol, ImmutableArray<TSymbol>> getExplicitInterfaceImplementations) where TSymbol : class, ISymbol
// {
// // Check the current type for explicit interface matches. Otherwise, check
// // the current type and base types for implicit matches.
// var explicitMatches =
// from member in typeSymbol.GetMembers().OfType<TSymbol>()
// where getExplicitInterfaceImplementations(member).Length > 0
// from explicitInterfaceMethod in getExplicitInterfaceImplementations(member)
// where SymbolEquivalenceComparer.Instance.Equals(explicitInterfaceMethod, interfaceSymbol)
// select member;
//
// var provider = workspace.Services.GetLanguageServices(typeSymbol.Language);
// var semanticFacts = provider.GetService<ISemanticFactsService>();
//
// // Even if a language only supports explicit interface implementation, we
// // can't enforce it for types from metadata. For example, a VB symbol
// // representing System.Xml.XmlReader will say it implements IDisposable, but
// // the XmlReader.Dispose() method will not be an explicit implementation of
// // IDisposable.Dispose()
// if (!semanticFacts.SupportsImplicitInterfaceImplementation &&
// typeSymbol.Locations.Any(location => location.IsInSource))
// {
// return explicitMatches.FirstOrDefault();
// }
//
// var syntaxFacts = provider.GetService<ISyntaxFactsService>();
// var implicitMatches =
// from baseType in typeSymbol.GetBaseTypesAndThis()
// from member in baseType.GetMembers(interfaceSymbol.Name).OfType<TSymbol>()
// where member.DeclaredAccessibility == Accessibility.Public &&
// !member.IsStatic &&
// SignatureComparer.Instance.HaveSameSignatureAndConstraintsAndReturnTypeAndAccessors(member, interfaceSymbol, syntaxFacts.IsCaseSensitive)
// select member;
//
// return explicitMatches.FirstOrDefault() ?? implicitMatches.FirstOrDefault();
// }
public static IEnumerable<ITypeSymbol> GetBaseTypesAndThis(this ITypeSymbol type)
{
var current = type;
while (current != null)
{
yield return current;
current = current.BaseType;
}
}
public static IEnumerable<INamedTypeSymbol> GetBaseTypes(this ITypeSymbol type)
{
var current = type.BaseType;
while (current != null)
{
yield return current;
current = current.BaseType;
}
}
public static IEnumerable<ITypeSymbol> GetContainingTypesAndThis(this ITypeSymbol type)
{
var current = type;
while (current != null)
{
yield return current;
current = current.ContainingType;
}
}
public static IEnumerable<INamedTypeSymbol> GetContainingTypes(this ITypeSymbol type)
{
var current = type.ContainingType;
while (current != null)
{
yield return current;
current = current.ContainingType;
}
}
// // Determine if "type" inherits from "baseType", ignoring constructed types, and dealing
// // only with original types.
// public static bool InheritsFromOrEquals(
// this ITypeSymbol type, ITypeSymbol baseType)
// {
// return type.GetBaseTypesAndThis().Contains(t => SymbolEquivalenceComparer.Instance.Equals(t, baseType));
// }
//
// Determine if "type" inherits from "baseType", ignoring constructed types, and dealing
// only with original types.
public static bool InheritsFromOrEqualsIgnoringConstruction(
this ITypeSymbol type, ITypeSymbol baseType)
{
return (bool)inheritsFromOrEqualsIgnoringConstructionMethod.Invoke(null, new[] { type, baseType });
}
//
// // Determine if "type" inherits from "baseType", ignoring constructed types, and dealing
// // only with original types.
// public static bool InheritsFromIgnoringConstruction(
// this ITypeSymbol type, ITypeSymbol baseType)
// {
// var originalBaseType = baseType.OriginalDefinition;
//
// // We could just call GetBaseTypes and foreach over it, but this
// // is a hot path in Find All References. This avoid the allocation
// // of the enumerator type.
// var currentBaseType = type.BaseType;
// while (currentBaseType != null)
// {
// if (SymbolEquivalenceComparer.Instance.Equals(currentBaseType.OriginalDefinition, originalBaseType))
// {
// return true;
// }
//
// currentBaseType = currentBaseType.BaseType;
// }
//
// return false;
// }
// public static bool ImplementsIgnoringConstruction(
// this ITypeSymbol type, ITypeSymbol interfaceType)
// {
// var originalInterfaceType = interfaceType.OriginalDefinition;
// if (type is INamedTypeSymbol && type.TypeKind == TypeKind.Interface)
// {
// // Interfaces don't implement other interfaces. They extend them.
// return false;
// }
//
// return type.AllInterfaces.Any(t => SymbolEquivalenceComparer.Instance.Equals(t.OriginalDefinition, originalInterfaceType));
// }
//
// public static bool Implements(
// this ITypeSymbol type, ITypeSymbol interfaceType)
// {
// return type.AllInterfaces.Contains(t => SymbolEquivalenceComparer.Instance.Equals(t, interfaceType));
// }
//
public static bool IsAttribute(this ITypeSymbol symbol)
{
for (var b = symbol.BaseType; b != null; b = b.BaseType)
{
if (b.MetadataName == "Attribute" &&
b.ContainingType == null &&
b.ContainingNamespace != null &&
b.ContainingNamespace.Name == "System" &&
b.ContainingNamespace.ContainingNamespace != null &&
b.ContainingNamespace.ContainingNamespace.IsGlobalNamespace)
{
return true;
}
}
return false;
}
readonly static MethodInfo removeUnavailableTypeParametersMethod;
public static ITypeSymbol RemoveUnavailableTypeParameters(
this ITypeSymbol type,
Compilation compilation,
IEnumerable<ITypeParameterSymbol> availableTypeParameters)
{
try
{
return (ITypeSymbol)removeUnavailableTypeParametersMethod.Invoke(null, new object[] { type, compilation, availableTypeParameters });
}
catch (TargetInvocationException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
return null;
}
}
public static ITypeSymbol RemoveAnonymousTypes(
this ITypeSymbol type,
Compilation compilation)
{
return type?.Accept(new AnonymousTypeRemover(compilation));
}
private class AnonymousTypeRemover : SymbolVisitor<ITypeSymbol>
{
private readonly Compilation _compilation;
public AnonymousTypeRemover(Compilation compilation)
{
_compilation = compilation;
}
public override ITypeSymbol DefaultVisit(ISymbol node)
{
throw new NotImplementedException();
}
public override ITypeSymbol VisitDynamicType(IDynamicTypeSymbol symbol)
{
return symbol;
}
public override ITypeSymbol VisitArrayType(IArrayTypeSymbol symbol)
{
var elementType = symbol.ElementType.Accept(this);
if (elementType != null && elementType.Equals(symbol.ElementType))
{
return symbol;
}
return _compilation.CreateArrayTypeSymbol(elementType, symbol.Rank);
}
public override ITypeSymbol VisitNamedType(INamedTypeSymbol symbol)
{
if (symbol.IsNormalAnonymousType() ||
symbol.IsAnonymousDelegateType())
{
return _compilation.ObjectType;
}
var arguments = symbol.TypeArguments.Select(t => t.Accept(this)).ToArray();
if (arguments.SequenceEqual(symbol.TypeArguments))
{
return symbol;
}
return symbol.ConstructedFrom.Construct(arguments.ToArray());
}
public override ITypeSymbol VisitPointerType(IPointerTypeSymbol symbol)
{
var elementType = symbol.PointedAtType.Accept(this);
if (elementType != null && elementType.Equals(symbol.PointedAtType))
{
return symbol;
}
return _compilation.CreatePointerTypeSymbol(elementType);
}
public override ITypeSymbol VisitTypeParameter(ITypeParameterSymbol symbol)
{
return symbol;
}
}
readonly static MethodInfo replaceTypeParametersBasedOnTypeConstraintsMethod;
public static ITypeSymbol ReplaceTypeParametersBasedOnTypeConstraints(
this ITypeSymbol type,
Compilation compilation,
IEnumerable<ITypeParameterSymbol> availableTypeParameters,
Solution solution,
CancellationToken cancellationToken)
{
try
{
return (ITypeSymbol)replaceTypeParametersBasedOnTypeConstraintsMethod.Invoke(null, new object[] { type, compilation, availableTypeParameters, solution, cancellationToken });
}
catch (TargetInvocationException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
return null;
}
}
readonly static MethodInfo removeUnnamedErrorTypesMethod;
public static ITypeSymbol RemoveUnnamedErrorTypes(
this ITypeSymbol type,
Compilation compilation)
{
try
{
return (ITypeSymbol)removeUnnamedErrorTypesMethod.Invoke(null, new object[] { type, compilation });
}
catch (TargetInvocationException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
return null;
}
}
public static IList<ITypeParameterSymbol> GetReferencedMethodTypeParameters(
this ITypeSymbol type, IList<ITypeParameterSymbol> result = null)
{
result = result ?? new List<ITypeParameterSymbol>();
type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: true));
return result;
}
public static IList<ITypeParameterSymbol> GetReferencedTypeParameters(
this ITypeSymbol type, IList<ITypeParameterSymbol> result = null)
{
result = result ?? new List<ITypeParameterSymbol>();
type?.Accept(new CollectTypeParameterSymbolsVisitor(result, onlyMethodTypeParameters: false));
return result;
}
private class CollectTypeParameterSymbolsVisitor : SymbolVisitor
{
private readonly HashSet<ISymbol> _visited = new HashSet<ISymbol>();
private readonly bool _onlyMethodTypeParameters;
private readonly IList<ITypeParameterSymbol> _typeParameters;
public CollectTypeParameterSymbolsVisitor(
IList<ITypeParameterSymbol> typeParameters,
bool onlyMethodTypeParameters)
{
_onlyMethodTypeParameters = onlyMethodTypeParameters;
_typeParameters = typeParameters;
}
public override void DefaultVisit(ISymbol node)
{
throw new NotImplementedException();
}
public override void VisitDynamicType(IDynamicTypeSymbol symbol)
{
}
public override void VisitArrayType(IArrayTypeSymbol symbol)
{
if (!_visited.Add(symbol))
{
return;
}
symbol.ElementType.Accept(this);
}
public override void VisitNamedType(INamedTypeSymbol symbol)
{
if (_visited.Add(symbol))
{
foreach (var child in symbol.GetAllTypeArguments())
{
child.Accept(this);
}
}
}
public override void VisitPointerType(IPointerTypeSymbol symbol)
{
if (!_visited.Add(symbol))
{
return;
}
symbol.PointedAtType.Accept(this);
}
public override void VisitTypeParameter(ITypeParameterSymbol symbol)
{
if (_visited.Add(symbol))
{
if (symbol.TypeParameterKind == TypeParameterKind.Method || !_onlyMethodTypeParameters)
{
if (!_typeParameters.Contains(symbol))
{
_typeParameters.Add(symbol);
}
}
foreach (var constraint in symbol.ConstraintTypes)
{
constraint.Accept(this);
}
}
}
}
readonly static MethodInfo substituteTypesMethod;
public static ITypeSymbol SubstituteTypes<TType1, TType2>(
this ITypeSymbol type,
IDictionary<TType1, TType2> mapping,
Compilation compilation)
where TType1 : ITypeSymbol
where TType2 : ITypeSymbol
{
if (type == null)
throw new ArgumentNullException("type");
try
{
return (ITypeSymbol)substituteTypesMethod.MakeGenericMethod(typeof(TType1), typeof(TType2)).Invoke(null, new object[] { type, mapping, compilation });
}
catch (TargetInvocationException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
return null;
}
}
readonly static MethodInfo substituteTypesMethod2;
public static ITypeSymbol SubstituteTypes<TType1, TType2>(
this ITypeSymbol type,
IDictionary<TType1, TType2> mapping,
TypeGenerator typeGenerator)
where TType1 : ITypeSymbol
where TType2 : ITypeSymbol
{
try
{
return (ITypeSymbol)substituteTypesMethod2.MakeGenericMethod(typeof(TType1), typeof(TType2)).Invoke(null, new object[] { type, mapping, typeGenerator.Instance });
}
catch (TargetInvocationException ex)
{
ExceptionDispatchInfo.Capture(ex.InnerException).Throw();
return null;
}
}
public static bool IsUnexpressableTypeParameterConstraint(this ITypeSymbol typeSymbol)
{
if (typeSymbol.IsSealed || typeSymbol.IsValueType)
{
return true;
}
switch (typeSymbol.TypeKind)
{
case TypeKind.Array:
case TypeKind.Delegate:
return true;
}
switch (typeSymbol.SpecialType)
{
case SpecialType.System_Array:
case SpecialType.System_Delegate:
case SpecialType.System_MulticastDelegate:
case SpecialType.System_Enum:
case SpecialType.System_ValueType:
return true;
}
return false;
}
public static bool IsNumericType(this ITypeSymbol type)
{
if (type != null)
{
switch (type.SpecialType)
{
case SpecialType.System_Byte:
case SpecialType.System_SByte:
case SpecialType.System_Int16:
case SpecialType.System_UInt16:
case SpecialType.System_Int32:
case SpecialType.System_UInt32:
case SpecialType.System_Int64:
case SpecialType.System_UInt64:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_Decimal:
return true;
}
}
return false;
}
public static Accessibility DetermineMinimalAccessibility(this ITypeSymbol typeSymbol)
{
return typeSymbol.Accept(MinimalAccessibilityVisitor.Instance);
}
private class MinimalAccessibilityVisitor : SymbolVisitor<Accessibility>
{
public static readonly SymbolVisitor<Accessibility> Instance = new MinimalAccessibilityVisitor();
public override Accessibility DefaultVisit(ISymbol node)
{
throw new NotImplementedException();
}
public override Accessibility VisitAlias(IAliasSymbol symbol)
{
return symbol.Target.Accept(this);
}
public override Accessibility VisitArrayType(IArrayTypeSymbol symbol)
{
return symbol.ElementType.Accept(this);
}
public override Accessibility VisitDynamicType(IDynamicTypeSymbol symbol)
{
return Accessibility.Public;
}
public override Accessibility VisitNamedType(INamedTypeSymbol symbol)
{
var accessibility = symbol.DeclaredAccessibility;
foreach (var arg in symbol.TypeArguments)
{
accessibility = CommonAccessibilityUtilities.Minimum(accessibility, arg.Accept(this));
}
if (symbol.ContainingType != null)
{
accessibility = CommonAccessibilityUtilities.Minimum(accessibility, symbol.ContainingType.Accept(this));
}
return accessibility;
}
public override Accessibility VisitPointerType(IPointerTypeSymbol symbol)
{
return symbol.PointedAtType.Accept(this);
}
public override Accessibility VisitTypeParameter(ITypeParameterSymbol symbol)
{
// TODO(cyrusn): Do we have to consider the constraints?
return Accessibility.Public;
}
}
public static bool ContainsAnonymousType(this ITypeSymbol symbol)
{
return symbol.TypeSwitch(
(IArrayTypeSymbol a) => ContainsAnonymousType(a.ElementType),
(IPointerTypeSymbol p) => ContainsAnonymousType(p.PointedAtType),
(INamedTypeSymbol n) => ContainsAnonymousType(n),
_ => false);
}
private static bool ContainsAnonymousType(INamedTypeSymbol type)
{
if (type.IsAnonymousType)
{
return true;
}
foreach (var typeArg in type.GetAllTypeArguments())
{
if (ContainsAnonymousType(typeArg))
{
return true;
}
}
return false;
}
public static string CreateParameterName(this ITypeSymbol type, bool capitalize = false)
{
while (true)
{
var arrayType = type as IArrayTypeSymbol;
if (arrayType != null)
{
type = arrayType.ElementType;
continue;
}
var pointerType = type as IPointerTypeSymbol;
if (pointerType != null)
{
type = pointerType.PointedAtType;
continue;
}
break;
}
var shortName = GetParameterName(type);
return capitalize ? shortName.ToPascalCase() : shortName.ToCamelCase();
}
private static string GetParameterName(ITypeSymbol type)
{
if (type == null || type.IsAnonymousType())
{
return DefaultParameterName;
}
if (type.IsSpecialType() || type.OriginalDefinition.SpecialType == SpecialType.System_Nullable_T)
{
return DefaultBuiltInParameterName;
}
var shortName = type.GetShortName();
return shortName.Length == 0
? DefaultParameterName
: shortName;
}
private static bool IsSpecialType(this ITypeSymbol symbol)
{
if (symbol != null)
{
switch (symbol.SpecialType)
{
case SpecialType.System_Object:
case SpecialType.System_Void:
case SpecialType.System_Boolean:
case SpecialType.System_SByte:
case SpecialType.System_Byte:
case SpecialType.System_Decimal:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_Int16:
case SpecialType.System_Int32:
case SpecialType.System_Int64:
case SpecialType.System_Char:
case SpecialType.System_String:
case SpecialType.System_UInt16:
case SpecialType.System_UInt32:
case SpecialType.System_UInt64:
return true;
}
}
return false;
}
public static bool CanSupportCollectionInitializer(this ITypeSymbol typeSymbol)
{
if (typeSymbol.AllInterfaces.Any(i => i.SpecialType == SpecialType.System_Collections_IEnumerable))
{
var curType = typeSymbol;
while (curType != null)
{
if (HasAddMethod(curType))
return true;
curType = curType.BaseType;
}
}
return false;
}
static bool HasAddMethod(ITypeSymbol typeSymbol)
{
return typeSymbol
.GetMembers(WellKnownMemberNames.CollectionInitializerAddMethodName)
.OfType<IMethodSymbol>().Any(m => m.Parameters.Any());
}
//public static INamedTypeSymbol GetDelegateType(this ITypeSymbol typeSymbol, Compilation compilation)
//{
// if (typeSymbol != null)
// {
// var expressionOfT = compilation.ExpressionOfTType();
// if (typeSymbol.OriginalDefinition.Equals(expressionOfT))
// {
// var typeArgument = ((INamedTypeSymbol)typeSymbol).TypeArguments[0];
// return typeArgument as INamedTypeSymbol;
// }
// if (typeSymbol.IsDelegateType())
// {
// return typeSymbol as INamedTypeSymbol;
// }
// }
// return null;
//}
public static IEnumerable<T> GetAccessibleMembersInBaseTypes<T>(this ITypeSymbol containingType, ISymbol within) where T : class, ISymbol
{
if (containingType == null)
{
return SpecializedCollections.EmptyEnumerable<T>();
}
var types = containingType.GetBaseTypes();
return types.SelectMany(x => x.GetMembers().OfType<T>().Where(m => m.IsAccessibleWithin(within)));
}
public static IEnumerable<T> GetAccessibleMembersInThisAndBaseTypes<T>(this ITypeSymbol containingType, ISymbol within) where T : class, ISymbol
{
if (containingType == null)
{
return SpecializedCollections.EmptyEnumerable<T>();
}
var types = containingType.GetBaseTypesAndThis();
return types.SelectMany(x => x.GetMembers().OfType<T>().Where(m => m.IsAccessibleWithin(within)));
}
public static bool? AreMoreSpecificThan(this IList<ITypeSymbol> t1, IList<ITypeSymbol> t2)
{
if (t1.Count != t2.Count)
{
return null;
}
// For t1 to be more specific than t2, it has to be not less specific in every member,
// and more specific in at least one.
bool? result = null;
for (int i = 0; i < t1.Count; ++i)
{
var r = t1[i].IsMoreSpecificThan(t2[i]);
if (r == null)
{
// We learned nothing. Do nothing.
}
else if (result == null)
{
// We have found the first more specific type. See if
// all the rest on this side are not less specific.
result = r;
}
else if (result != r)
{
// We have more specific types on both left and right, so we
// cannot succeed in picking a better type list. Bail out now.
return null;
}
}
return result;
}
private static bool? IsMoreSpecificThan(this ITypeSymbol t1, ITypeSymbol t2)
{
// SPEC: A type parameter is less specific than a non-type parameter.
var isTypeParameter1 = t1 is ITypeParameterSymbol;
var isTypeParameter2 = t2 is ITypeParameterSymbol;
if (isTypeParameter1 && !isTypeParameter2)
{
return false;
}
if (!isTypeParameter1 && isTypeParameter2)
{
return true;
}
if (isTypeParameter1)
{
Debug.Assert(isTypeParameter2);
return null;
}
if (t1.TypeKind != t2.TypeKind)
{
return null;
}
// There is an identity conversion between the types and they are both substitutions on type parameters.
// They had better be the same kind.
// UNDONE: Strip off the dynamics.
// SPEC: An array type is more specific than another
// SPEC: array type (with the same number of dimensions)
// SPEC: if the element type of the first is
// SPEC: more specific than the element type of the second.
if (t1 is IArrayTypeSymbol)
{
var arr1 = (IArrayTypeSymbol)t1;
var arr2 = (IArrayTypeSymbol)t2;
// We should not have gotten here unless there were identity conversions
// between the two types.
return arr1.ElementType.IsMoreSpecificThan(arr2.ElementType);
}
// SPEC EXTENSION: We apply the same rule to pointer types.
if (t1 is IPointerTypeSymbol)
{
var p1 = (IPointerTypeSymbol)t1;
var p2 = (IPointerTypeSymbol)t2;
return p1.PointedAtType.IsMoreSpecificThan(p2.PointedAtType);
}
// SPEC: A constructed type is more specific than another
// SPEC: constructed type (with the same number of type arguments) if at least one type
// SPEC: argument is more specific and no type argument is less specific than the
// SPEC: corresponding type argument in the other.
var n1 = t1 as INamedTypeSymbol;
var n2 = t2 as INamedTypeSymbol;
if (n1 == null)
{
return null;
}
// We should not have gotten here unless there were identity conversions between the
// two types.
var allTypeArgs1 = n1.GetAllTypeArguments().ToList();
var allTypeArgs2 = n2.GetAllTypeArguments().ToList();
return allTypeArgs1.AreMoreSpecificThan(allTypeArgs2);
}
//public static bool IsOrDerivesFromExceptionType(this ITypeSymbol type, Compilation compilation)
//{
// if (type != null)
// {
// foreach (var baseType in type.GetBaseTypesAndThis())
// {
// if (baseType.Equals(compilation.ExceptionType()))
// {
// return true;
// }
// }
// }
// return false;
//}
public static bool IsEnumType(this ITypeSymbol type)
{
return type.IsValueType && type.TypeKind == TypeKind.Enum;
}
//public static async Task<ISymbol> FindApplicableAlias(this ITypeSymbol type, int position, SemanticModel semanticModel, CancellationToken cancellationToken)
//{
// if (semanticModel.IsSpeculativeSemanticModel)
// {
// position = semanticModel.OriginalPositionForSpeculation;
// semanticModel = semanticModel.ParentModel;
// }
// var root = await semanticModel.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false);
// IEnumerable<UsingDirectiveSyntax> applicableUsings = GetApplicableUsings(position, root as CompilationUnitSyntax);
// foreach (var applicableUsing in applicableUsings)
// {
// var alias = semanticModel.GetOriginalSemanticModel().GetDeclaredSymbol(applicableUsing, cancellationToken) as IAliasSymbol;
// if (alias != null && alias.Target == type)
// {
// return alias;
// }
// }
// return null;
//}
private static IEnumerable<UsingDirectiveSyntax> GetApplicableUsings(int position, SyntaxNode root)
{
var namespaceUsings = root.FindToken(position).Parent.GetAncestors<NamespaceDeclarationSyntax>().SelectMany(n => n.Usings);
var allUsings = root is CompilationUnitSyntax
? ((CompilationUnitSyntax)root).Usings.Concat(namespaceUsings)
: namespaceUsings;
return allUsings.Where(u => u.Alias != null);
}
public static ITypeSymbol RemoveNullableIfPresent(this ITypeSymbol symbol)
{
if (symbol.IsNullable())
{
return symbol.GetTypeArguments().Single();
}
return symbol;
}
public static bool IsIEnumerable(this ITypeSymbol typeSymbol)
{
return typeSymbol.GetAllInterfacesIncludingThis().Any(x => x.SpecialType == SpecialType.System_Collections_IEnumerable);
}
}
}
| |
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 SpaStore.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>();
}
/// <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 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 get sample provided for a specific mediaType, controllerName, actionName and parameterNames.
// If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames
// If still not found, try get the sample provided for a specific type and 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))
{
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="ObjectGenerator"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// Try create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
sampleObject = objectGenerator.GenerateObject(type);
}
return sampleObject;
}
/// <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.ActionDescriptor.ReturnType;
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,
e.Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
[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 (c) 2016, Alachisoft. 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 Alachisoft.NosDB.Common.Configuration.DOM;
using Alachisoft.NosDB.Common.Configuration.Services;
using Alachisoft.NosDB.Common.Enum;
using Alachisoft.NosDB.Common.Logger;
using Alachisoft.NosDB.Common.Toplogies.Impl.Distribution;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace Alachisoft.NosDB.Core.Configuration.Services
{
internal class MetaStore
{
private Hashtable _clusterMetaData = Hashtable.Synchronized(new Hashtable(StringComparer.InvariantCultureIgnoreCase));
// private Dictionary<string,ClusterInfo> _clusterMetaData = new Dictionary<string, ClusterInfo>();
private IConfigurationStore _configurationStore;
public MetaStore(IConfigurationStore configStore)
{
_configurationStore = configStore;
}
//IDictionary<string, ClusterInfo> _clusterMetaData = new Dictionary<string, ClusterInfo>();
public void AddDistributionStrategy(string cluster, string database, string collection, IDistributionStrategy strategy, DistributionStrategyConfiguration configuration, Boolean needTransfer)
{
ClusterInfo clusterInfo = (ClusterInfo)_clusterMetaData[cluster];
if (clusterInfo.Databases != null)
{
DatabaseInfo databaseInfo = clusterInfo.GetDatabase(database);
CollectionInfo collectionInfo = databaseInfo.GetCollection(collection);
collectionInfo.SetDistributionStrategy(configuration, strategy);
if (collectionInfo.DistributionStrategy.Name.Equals(DistributionType.NonSharded.ToString()))
{
collectionInfo.DistributionStrategy.AddShard(collectionInfo.CollectionShard, null, needTransfer);
//In case of NonShardedDistributionStrategy: The shard told by user must be added first. That is why this check is placed
}
_clusterMetaData[cluster] = clusterInfo;
_configurationStore.InsertOrUpdateDistributionStrategy(clusterInfo, database, collection);
}
}
//public Dictionary<string, ClusterInfo> ClusterMetaData
//{
// get { return _clusterMetaData; }
// set { _clusterMetaData = value; }
//}
public void RemoveDistributionStrategy(string cluster, string database, string collection)
{
ClusterInfo clusterInfo = (ClusterInfo)_clusterMetaData[cluster];
if (clusterInfo.Databases != null)
{
clusterInfo.GetDatabase(database).GetCollection(collection).RemoveDistributionStrategy();
_clusterMetaData[cluster] = clusterInfo;
_configurationStore.InsertOrUpdateDistributionStrategy(clusterInfo, database, collection);
}
}
public IDistribution GetDistribution(string cluster, string database, string collection)
{
ClusterInfo clusterInfo = (ClusterInfo)_clusterMetaData[cluster];
if (clusterInfo.Databases != null)
{
return clusterInfo.GetDatabase(database).GetCollection(collection).DataDistribution;
}
return null;
}
public ClusterInfo[] GetAllClusterInfo()
{
if (_clusterMetaData != null && _clusterMetaData.Values.Count > 0)
{
ClusterInfo[] clusterInfo = new ClusterInfo[_clusterMetaData.Values.Count];
_clusterMetaData.Values.CopyTo(clusterInfo, 0);
return clusterInfo;
}
return null;
}
public void SetDistributionStrategy(string cluster, string database, string collection, IDistributionStrategy distribution)
{
ClusterInfo clusterInfo = (ClusterInfo)_clusterMetaData[cluster];
if (clusterInfo.Databases != null)
{
clusterInfo.GetDatabase(database).GetCollection(collection).DistributionStrategy = distribution;
_configurationStore.InsertOrUpdateDistributionStrategy(clusterInfo, database, collection);
}
}
public IDistributionStrategy GetDistributionStrategy(string cluster, string database, string collection)
{
ClusterInfo clusterInfo = (ClusterInfo)_clusterMetaData[cluster];
if (clusterInfo.Databases != null)
{
return clusterInfo.GetDatabase(database).GetCollection(collection).DistributionStrategy;
}
return null;
}
public ClusterInfo GetClusterInfo(string clusterName)
{
if (_clusterMetaData.ContainsKey(clusterName))
return (ClusterInfo)_clusterMetaData[clusterName];
return null;
}
public void AddClusterInfo(string clusterName, ClusterInfo clusterInfo)
{
if (clusterName != null)
{
_clusterMetaData[clusterName.ToLower()] = clusterInfo;
//_configurationStore.InsertOrUpdateBucketInfo(clusterInfo);
}
}
public void RemoveClusterInfo(string clusterName)
{
if (clusterName != null)
{
_clusterMetaData.Remove(clusterName.ToLower());
_configurationStore.RemoveClusterInfo(clusterName.ToLower());
}
}
//public void Load()
//{
// string metaFilePath = ServiceConfiguration.CSBasePath + "//MetaData.bin";
//_clusterMetaData = (Hashtable)Alachisoft.NosDB.Serialization.Formatters.CompactBinaryFormatter.FromByteBuffer(data, string.Empty);
// if (File.Exists(metaFilePath))
// {
// Stream stream = File.Open(metaFilePath, FileMode.Open);
// try
// {
// byte[] len = new byte[4];
// stream.Read(len, 0, 4);
// int length = BitConverter.ToInt32(len, 0);
// byte[] data = new byte[length];
// stream.Read(data, 0, length);
// _clusterMetaData = (Dictionary<string, ClusterInfo>)Alachisoft.NoSQL.Serialization.Formatters.CompactBinaryFormatter.FromByteBuffer(data, string.Empty);
//try
//{
// //BinaryFormatter bformatter = new BinaryFormatter();
// byte[] data = Alachisoft.NosDB.Serialization.Formatters.CompactBinaryFormatter.ToByteBuffer(_clusterMetaData, String.Empty);
public void Load()
{
ClusterInfo[] clusterinfo;
clusterinfo = _configurationStore.GetAllClusterInfo();
_configurationStore.GetAllDistributionStrategies(clusterinfo);
foreach (ClusterInfo info in clusterinfo)
{
if (info != null && info.Name != null && !_clusterMetaData.Contains(info.Name.ToLower()))
_clusterMetaData.Add(info.Name.ToLower(), info);
}
}
#region recovery operation
public void RestoreDistributionStrategy(string cluster, string database, string collection, IDistributionStrategy strategy)
{
ClusterInfo clusterInfo = (ClusterInfo)_clusterMetaData[cluster];
if (clusterInfo.Databases != null)
{
clusterInfo.GetDatabase(database).GetCollection(collection).DistributionStrategy = strategy;
//clusterInfo.GetDatabase(database).GetCollection(collection).DataDistribution = strategy.GetCurrentBucketDistribution();
_configurationStore.InsertOrUpdateDistributionStrategy(clusterInfo, database, collection);
if (LoggerManager.Instance.RecoveryLogger != null && LoggerManager.Instance.RecoveryLogger.IsInfoEnabled)
LoggerManager.Instance.RecoveryLogger.Info("MetaStore.RestoreDistributionStrrategy()", "Updated");
}
}
#endregion
//public void Save(IDatabaseStore dbStore,string colName,string dbName)
//{
// JsonSerializer<Dictionary<string, ClusterInfo>> serializer =
// new JsonSerializer<Dictionary<string, ClusterInfo>>();
// List<IJSONDocument> jdocList=new List<IJSONDocument>();
// if (dbStore != null && _clusterMetaData != null && colName != null)
// {
// JSONDocument jdoc=new JSONDocument();
// jdoc=serializer.Serialize(_clusterMetaData);
// jdocList.Add(jdoc);
// IDocumentsWriteOperation insertOperation=new InsertDocumentsOperation();
// insertOperation.Collection = colName;
// insertOperation.Database = dbName;
// insertOperation.Documents = jdocList;
// dbStore.InserDocuments(insertOperation);
// }
//}
//public void Save()
//{
// if (_clusterMetaData != null)
// {
// foreach (KeyValuePair<string, ClusterInfo> entry in _clusterMetaData)
// {
// _configurationStore.InsertOrUpdateClusterInfo(entry.Value);
// }
// }
//}
//public void Save()
//{
// string metaFilePath = ServiceConfiguration.CSBasePath + "//MetaData.bin";
// string path = Path.GetDirectoryName(metaFilePath);
// if (Directory.Exists(path))
// {
// Stream stream = File.Open(metaFilePath, FileMode.Create);
// try
// {
// //BinaryFormatter bformatter = new BinaryFormatter();
// byte[] data = Alachisoft.NoSQL.Serialization.Formatters.CompactBinaryFormatter.ToByteBuffer(_clusterMetaData, String.Empty);
// int len = data.Length;
// stream.Write(BitConverter.GetBytes(len), 0, 4);
// stream.Write(data, 0, data.Length);
// stream.Close();
// }
// catch (Exception ex)
// {
// stream.Close();
// }
// }
//}
}
}
| |
// Copyright 2010 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
using System.IO;
using NUnit.Framework;
namespace NodaTime.Test.TimeZones.IO
{
/// <summary>
/// Provides a simple, fized-size, pipe-like stream that has a writer and a reader.
/// </summary>
/// <remarks>
/// When the buffer fills up an exception is thrown and currently the buffer is fixed at 4096. The write
/// pointer does not wrap so only a total of 4096 bytes can ever be written to the stream. This is designed
/// for testing purposes and not real-world uses.
/// </remarks>
internal class IoStream
{
private readonly byte[] buffer = new byte[4096];
private int readIndex;
private Stream? readStream;
private int writeIndex;
private Stream? writeStream;
/// <summary>
/// Returns the next byte from the stream if there is one.
/// </summary>
/// <returns>The next byte.</returns>
/// <exception cref="InternalBufferOverflowException">There are no more bytes in the buffer.</exception>
private byte GetByte()
{
if (readIndex >= writeIndex)
{
throw new IOException("IoStream buffer empty in GetByte()");
}
return buffer[readIndex++];
}
public void AssertEndOfStream()
{
Assert.AreEqual(readIndex, writeIndex);
}
public void AssertUnreadContents(byte[] expected)
{
Assert.AreEqual(expected.Length, writeIndex - readIndex);
var actual = new byte[expected.Length];
Array.Copy(buffer, readIndex, actual, 0, writeIndex - readIndex);
Assert.AreEqual(expected, actual);
readIndex = writeIndex;
}
/// <summary>
/// Returns a <see cref="Stream" /> that can be used to read from the buffer.
/// </summary>
/// <remarks>
/// This can only be called once for each instance i.e. only one reader is permitted per buffer.
/// </remarks>
/// <returns>The read-only <see cref="Stream" />.</returns>
/// <exception cref="InvalidOperationException">A reader was already requested.</exception>
public Stream GetReadStream()
{
if (readStream != null)
{
throw new InvalidOperationException("Cannot call GetReadStream() twice on the same object.");
}
readStream = new ReadStreamImpl(this);
return readStream;
}
/// <summary>
/// Returns a <see cref="Stream" /> that can be used to write to the buffer.
/// </summary>
/// <remarks>
/// This can only be called once for each instance i.e. only one writer is permitted per buffer.
/// </remarks>
/// <returns>The write-only <see cref="Stream" />.</returns>
/// <exception cref="InvalidOperationException">A writer was already requested.</exception>
public Stream GetWriteStream()
{
if (writeStream != null)
{
throw new InvalidOperationException("Cannot call GetWriteStream() twice on the same object.");
}
writeStream = new WriteStreamImpl(this);
return writeStream;
}
/// <summary>
/// Adds a byte to the buffer.
/// </summary>
/// <param name="value">The byte to add.</param>
/// <exception cref="InternalBufferOverflowException">The buffer has been filled.</exception>
private void PutByte(byte value)
{
if (writeIndex >= buffer.Length)
{
throw new IOException("Exceeded the IoStream buffer size of " + buffer.Length);
}
buffer[writeIndex++] = value;
}
/// <summary>
/// Resets the stream to be empty.
/// </summary>
internal void Reset()
{
writeIndex = 0;
readIndex = 0;
}
#region Nested type: ReadStreamImpl
/// <summary>
/// Provides a read-only <see cref="Stream" /> implementaion for reading from the buffer.
/// </summary>
private class ReadStreamImpl : Stream
{
private readonly IoStream ioStream;
/// <summary>
/// Initializes a new instance of the <see cref="ReadStreamImpl" /> class.
/// </summary>
/// <param name="stream">The <see cref="ioStream" /> to read from.</param>
public ReadStreamImpl(IoStream stream)
{
ioStream = stream;
}
/// <summary>
/// When overridden in a derived class, gets a value indicating whether the current stream supports reading.
/// </summary>
/// <returns>
/// true if the stream supports reading; otherwise, false.
/// </returns>
/// <filterpriority>1</filterpriority>
public override bool CanRead => true;
/// <summary>
/// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
/// </summary>
/// <returns>
/// true if the stream supports seeking; otherwise, false.
/// </returns>
/// <filterpriority>1</filterpriority>
public override bool CanSeek => false;
/// <summary>
/// When overridden in a derived class, gets a value indicating whether the current stream supports writing.
/// </summary>
/// <returns>
/// true if the stream supports writing; otherwise, false.
/// </returns>
/// <filterpriority>1</filterpriority>
public override bool CanWrite => false;
/// <summary>
/// When overridden in a derived class, gets the length in bytes of the stream.
/// </summary>
/// <returns>
/// A long value representing the length of the stream in bytes.
/// </returns>
/// <exception cref="T:System.NotSupportedException">A class derived from Stream does not support seeking.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.
/// </exception>
/// <filterpriority>1</filterpriority>
public override long Length
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// When overridden in a derived class, gets or sets the position within the current stream.
/// </summary>
/// <returns>
/// The current position within the stream.
/// </returns>
/// <exception cref="T:System.IO.IOException">An I/O error occurs.
/// </exception>
/// <exception cref="T:System.NotSupportedException">The stream does not support seeking.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.
/// </exception>
/// <filterpriority>1</filterpriority>
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
/// <summary>
/// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
/// </summary>
/// <exception cref="T:System.IO.IOException">An I/O error occurs.
/// </exception>
/// <filterpriority>2</filterpriority>
public override void Flush()
{
}
/// <summary>
/// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
/// </summary>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
/// </returns>
/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name = "offset" /> and (<paramref name = "offset" /> + <paramref name = "count" /> - 1) replaced by the bytes read from the current source.
/// </param>
/// <param name="offset">The zero-based byte offset in <paramref name = "buffer" /> at which to begin storing the data read from the current stream.
/// </param>
/// <param name="count">The maximum number of bytes to be read from the current stream.
/// </param>
/// <exception cref="T:System.ArgumentException">The sum of <paramref name = "offset" /> and <paramref name = "count" /> is larger than the buffer length.
/// </exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name = "buffer" /> is null.
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name = "offset" /> or <paramref name = "count" /> is negative.
/// </exception>
/// <exception cref="T:System.IO.IOException">An I/O error occurs.
/// </exception>
/// <exception cref="T:System.NotSupportedException">The stream does not support reading.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.
/// </exception>
/// <filterpriority>1</filterpriority>
public override int Read(byte[] buffer, int offset, int count)
{
count = Math.Min(count, ioStream.writeIndex - ioStream.readIndex);
for (int i = 0; i < count; i++)
{
buffer[i + offset] = ioStream.GetByte();
}
return count;
}
/// <summary>
/// When overridden in a derived class, sets the position within the current stream.
/// </summary>
/// <returns>
/// The new position within the current stream.
/// </returns>
/// <param name="offset">A byte offset relative to the <paramref name = "origin" /> parameter.
/// </param>
/// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin" /> indicating the reference point used to obtain the new position.
/// </param>
/// <exception cref="T:System.IO.IOException">An I/O error occurs.
/// </exception>
/// <exception cref="T:System.NotSupportedException">The stream does not support seeking, such as if the stream is constructed from a pipe or console output.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.
/// </exception>
/// <filterpriority>1</filterpriority>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// When overridden in a derived class, sets the length of the current stream.
/// </summary>
/// <param name="value">The desired length of the current stream in bytes.
/// </param>
/// <exception cref="T:System.IO.IOException">An I/O error occurs.
/// </exception>
/// <exception cref="T:System.NotSupportedException">The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.
/// </exception>
/// <filterpriority>2</filterpriority>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">An array of bytes. This method copies <paramref name = "count" /> bytes from <paramref name = "buffer" /> to the current stream.
/// </param>
/// <param name="offset">The zero-based byte offset in <paramref name = "buffer" /> at which to begin copying bytes to the current stream.
/// </param>
/// <param name="count">The number of bytes to be written to the current stream.
/// </param>
/// <exception cref="T:System.ArgumentException">The sum of <paramref name = "offset" /> and <paramref name = "count" /> is greater than the buffer length.
/// </exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name = "buffer" /> is null.
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name = "offset" /> or <paramref name = "count" /> is negative.
/// </exception>
/// <exception cref="T:System.IO.IOException">An I/O error occurs.
/// </exception>
/// <exception cref="T:System.NotSupportedException">The stream does not support writing.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.
/// </exception>
/// <filterpriority>1</filterpriority>
public override void Write(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
}
#endregion
#region Nested type: WriteStreamImpl
/// <summary>
/// Provides a write-only <see cref="Stream" /> implementaion for writing to the buffer.
/// </summary>
private class WriteStreamImpl : Stream
{
private readonly IoStream ioStream;
/// <summary>
/// Initializes a new instance of the <see cref="WriteStreamImpl" /> class.
/// </summary>
/// <param name="stream">The <see cref="IoStream" /> to read from.</param>
public WriteStreamImpl(IoStream stream)
{
ioStream = stream;
}
/// <summary>
/// When overridden in a derived class, gets a value indicating whether the current stream supports reading.
/// </summary>
/// <returns>
/// true if the stream supports reading; otherwise, false.
/// </returns>
/// <filterpriority>1</filterpriority>
public override bool CanRead => false;
/// <summary>
/// When overridden in a derived class, gets a value indicating whether the current stream supports seeking.
/// </summary>
/// <returns>
/// true if the stream supports seeking; otherwise, false.
/// </returns>
/// <filterpriority>1</filterpriority>
public override bool CanSeek => false;
/// <summary>
/// When overridden in a derived class, gets a value indicating whether the current stream supports writing.
/// </summary>
/// <returns>
/// true if the stream supports writing; otherwise, false.
/// </returns>
/// <filterpriority>1</filterpriority>
public override bool CanWrite => true;
/// <summary>
/// When overridden in a derived class, gets the length in bytes of the stream.
/// </summary>
/// <returns>
/// A long value representing the length of the stream in bytes.
/// </returns>
/// <exception cref="T:System.NotSupportedException">A class derived from Stream does not support seeking.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.
/// </exception>
/// <filterpriority>1</filterpriority>
public override long Length
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// When overridden in a derived class, gets or sets the position within the current stream.
/// </summary>
/// <returns>
/// The current position within the stream.
/// </returns>
/// <exception cref="T:System.IO.IOException">An I/O error occurs.
/// </exception>
/// <exception cref="T:System.NotSupportedException">The stream does not support seeking.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.
/// </exception>
/// <filterpriority>1</filterpriority>
public override long Position
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
/// <summary>
/// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.
/// </summary>
/// <exception cref="T:System.IO.IOException">An I/O error occurs.
/// </exception>
/// <filterpriority>2</filterpriority>
public override void Flush()
{
}
/// <summary>
/// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
/// </summary>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
/// </returns>
/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name = "offset" /> and (<paramref name = "offset" /> + <paramref name = "count" /> - 1) replaced by the bytes read from the current source.
/// </param>
/// <param name="offset">The zero-based byte offset in <paramref name = "buffer" /> at which to begin storing the data read from the current stream.
/// </param>
/// <param name="count">The maximum number of bytes to be read from the current stream.
/// </param>
/// <exception cref="T:System.ArgumentException">The sum of <paramref name = "offset" /> and <paramref name = "count" /> is larger than the buffer length.
/// </exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name = "buffer" /> is null.
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name = "offset" /> or <paramref name = "count" /> is negative.
/// </exception>
/// <exception cref="T:System.IO.IOException">An I/O error occurs.
/// </exception>
/// <exception cref="T:System.NotSupportedException">The stream does not support reading.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.
/// </exception>
/// <filterpriority>1</filterpriority>
public override int Read(byte[] buffer, int offset, int count)
{
throw new NotSupportedException();
}
/// <summary>
/// When overridden in a derived class, sets the position within the current stream.
/// </summary>
/// <returns>
/// The new position within the current stream.
/// </returns>
/// <param name="offset">A byte offset relative to the <paramref name = "origin" /> parameter.
/// </param>
/// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin" /> indicating the reference point used to obtain the new position.
/// </param>
/// <exception cref="T:System.IO.IOException">An I/O error occurs.
/// </exception>
/// <exception cref="T:System.NotSupportedException">The stream does not support seeking, such as if the stream is constructed from a pipe or console output.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.
/// </exception>
/// <filterpriority>1</filterpriority>
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
/// <summary>
/// When overridden in a derived class, sets the length of the current stream.
/// </summary>
/// <param name="value">The desired length of the current stream in bytes.
/// </param>
/// <exception cref="T:System.IO.IOException">An I/O error occurs.
/// </exception>
/// <exception cref="T:System.NotSupportedException">The stream does not support both writing and seeking, such as if the stream is constructed from a pipe or console output.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.
/// </exception>
/// <filterpriority>2</filterpriority>
public override void SetLength(long value)
{
throw new NotSupportedException();
}
/// <summary>
/// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">An array of bytes. This method copies <paramref name = "count" /> bytes from <paramref name = "buffer" /> to the current stream.
/// </param>
/// <param name="offset">The zero-based byte offset in <paramref name = "buffer" /> at which to begin copying bytes to the current stream.
/// </param>
/// <param name="count">The number of bytes to be written to the current stream.
/// </param>
/// <exception cref="T:System.ArgumentException">The sum of <paramref name = "offset" /> and <paramref name = "count" /> is greater than the buffer length.
/// </exception>
/// <exception cref="T:System.ArgumentNullException"><paramref name = "buffer" /> is null.
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name = "offset" /> or <paramref name = "count" /> is negative.
/// </exception>
/// <exception cref="T:System.IO.IOException">An I/O error occurs.
/// </exception>
/// <exception cref="T:System.NotSupportedException">The stream does not support writing.
/// </exception>
/// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.
/// </exception>
/// <filterpriority>1</filterpriority>
public override void Write(byte[] buffer, int offset, int count)
{
if (count > ioStream.buffer.Length - ioStream.writeIndex)
{
throw new InvalidOperationException("The I/O buffer is full");
}
for (int i = 0; i < count; i++)
{
ioStream.PutByte(buffer[i + offset]);
}
}
}
#endregion
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Security;
using System.Timers;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using RegionFlags = OpenMetaverse.RegionFlags;
namespace OpenSim.Region.CoreModules.World.Estate
{
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "EstateManagementModule")]
public class EstateManagementModule : IEstateModule, INonSharedRegionModule
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Timer m_regionChangeTimer = new Timer();
public Scene Scene { get; private set; }
public IUserManagement UserManager { get; private set; }
protected EstateManagementCommands m_commands;
/// <summary>
/// If false, region restart requests from the client are blocked even if they are otherwise legitimate.
/// </summary>
public bool AllowRegionRestartFromClient { get; set; }
private EstateTerrainXferHandler TerrainUploader;
public TelehubManager m_Telehub;
public event ChangeDelegate OnRegionInfoChange;
public event ChangeDelegate OnEstateInfoChange;
public event MessageDelegate OnEstateMessage;
#region Region Module interface
public string Name { get { return "EstateManagementModule"; } }
public Type ReplaceableInterface { get { return null; } }
public void Initialise(IConfigSource source)
{
AllowRegionRestartFromClient = true;
IConfig config = source.Configs["EstateManagement"];
if (config != null)
AllowRegionRestartFromClient = config.GetBoolean("AllowRegionRestartFromClient", true);
}
public void AddRegion(Scene scene)
{
Scene = scene;
Scene.RegisterModuleInterface<IEstateModule>(this);
Scene.EventManager.OnNewClient += EventManager_OnNewClient;
Scene.EventManager.OnRequestChangeWaterHeight += changeWaterHeight;
m_Telehub = new TelehubManager(scene);
m_commands = new EstateManagementCommands(this);
m_commands.Initialise();
}
public void RemoveRegion(Scene scene) {}
public void RegionLoaded(Scene scene)
{
// Sets up the sun module based no the saved Estate and Region Settings
// DO NOT REMOVE or the sun will stop working
scene.TriggerEstateSunUpdate();
UserManager = scene.RequestModuleInterface<IUserManagement>();
}
public void Close()
{
m_commands.Close();
}
#endregion
#region IEstateModule Functions
public uint GetRegionFlags()
{
RegionFlags flags = RegionFlags.None;
// Fully implemented
//
if (Scene.RegionInfo.RegionSettings.AllowDamage)
flags |= RegionFlags.AllowDamage;
if (Scene.RegionInfo.RegionSettings.BlockTerraform)
flags |= RegionFlags.BlockTerraform;
if (!Scene.RegionInfo.RegionSettings.AllowLandResell)
flags |= RegionFlags.BlockLandResell;
if (Scene.RegionInfo.RegionSettings.DisableCollisions)
flags |= RegionFlags.SkipCollisions;
if (Scene.RegionInfo.RegionSettings.DisableScripts)
flags |= RegionFlags.SkipScripts;
if (Scene.RegionInfo.RegionSettings.DisablePhysics)
flags |= RegionFlags.SkipPhysics;
if (Scene.RegionInfo.RegionSettings.BlockFly)
flags |= RegionFlags.NoFly;
if (Scene.RegionInfo.RegionSettings.RestrictPushing)
flags |= RegionFlags.RestrictPushObject;
if (Scene.RegionInfo.RegionSettings.AllowLandJoinDivide)
flags |= RegionFlags.AllowParcelChanges;
if (Scene.RegionInfo.RegionSettings.BlockShowInSearch)
flags |= RegionFlags.BlockParcelSearch;
if (Scene.RegionInfo.RegionSettings.FixedSun)
flags |= RegionFlags.SunFixed;
if (Scene.RegionInfo.RegionSettings.Sandbox)
flags |= RegionFlags.Sandbox;
if (Scene.RegionInfo.EstateSettings.AllowVoice)
flags |= RegionFlags.AllowVoice;
if (Scene.RegionInfo.EstateSettings.AllowLandmark)
flags |= RegionFlags.AllowLandmark;
if (Scene.RegionInfo.EstateSettings.AllowSetHome)
flags |= RegionFlags.AllowSetHome;
if (Scene.RegionInfo.EstateSettings.BlockDwell)
flags |= RegionFlags.BlockDwell;
if (Scene.RegionInfo.EstateSettings.ResetHomeOnTeleport)
flags |= RegionFlags.ResetHomeOnTeleport;
// TODO: SkipUpdateInterestList
// Omitted
//
// Omitted: NullLayer (what is that?)
// Omitted: SkipAgentAction (what does it do?)
return (uint)flags;
}
public bool IsManager(UUID avatarID)
{
if (avatarID == Scene.RegionInfo.EstateSettings.EstateOwner)
return true;
List<UUID> ems = new List<UUID>(Scene.RegionInfo.EstateSettings.EstateManagers);
if (ems.Contains(avatarID))
return true;
return false;
}
public void sendRegionHandshakeToAll()
{
Scene.ForEachClient(sendRegionHandshake);
}
public void TriggerEstateInfoChange()
{
ChangeDelegate change = OnEstateInfoChange;
if (change != null)
change(Scene.RegionInfo.RegionID);
}
public void TriggerRegionInfoChange()
{
m_regionChangeTimer.Stop();
m_regionChangeTimer.Start();
ChangeDelegate change = OnRegionInfoChange;
if (change != null)
change(Scene.RegionInfo.RegionID);
}
public void setEstateTerrainBaseTexture(int level, UUID texture)
{
setEstateTerrainBaseTexture(null, level, texture);
sendRegionHandshakeToAll();
}
public void setEstateTerrainTextureHeights(int corner, float lowValue, float highValue)
{
setEstateTerrainTextureHeights(null, corner, lowValue, highValue);
}
public bool IsTerrainXfer(ulong xferID)
{
lock (this)
{
if (TerrainUploader == null)
return false;
else
return TerrainUploader.XferID == xferID;
}
}
public string SetEstateOwner(int estateID, UserAccount account)
{
string response;
// get the current settings from DB
EstateSettings dbSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
if (dbSettings.EstateID == 0)
{
response = String.Format("No estate found with ID {0}", estateID);
}
else if (account.PrincipalID == dbSettings.EstateOwner)
{
response = String.Format("Estate already belongs to {0} ({1} {2})", account.PrincipalID, account.FirstName, account.LastName);
}
else
{
dbSettings.EstateOwner = account.PrincipalID;
Scene.EstateDataService.StoreEstateSettings(dbSettings);
response = String.Empty;
// make sure there's a log entry to document the change
m_log.InfoFormat("[ESTATE]: Estate Owner for {0} changed to {1} ({2} {3})", dbSettings.EstateName,
account.PrincipalID, account.FirstName, account.LastName);
// propagate the change
List<UUID> regions = Scene.GetEstateRegions(estateID);
UUID regionId = (regions.Count() > 0) ? regions.ElementAt(0) : UUID.Zero;
if (regionId != UUID.Zero)
{
ChangeDelegate change = OnEstateInfoChange;
if (change != null)
change(regionId);
}
}
return response;
}
public string SetEstateName(int estateID, string newName)
{
string response;
// get the current settings from DB
EstateSettings dbSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
if (dbSettings.EstateID == 0)
{
response = String.Format("No estate found with ID {0}", estateID);
}
else if (newName == dbSettings.EstateName)
{
response = String.Format("Estate {0} is already named \"{1}\"", estateID, newName);
}
else
{
List<int> estates = Scene.EstateDataService.GetEstates(newName);
if (estates.Count() > 0)
{
response = String.Format("An estate named \"{0}\" already exists.", newName);
}
else
{
string oldName = dbSettings.EstateName;
dbSettings.EstateName = newName;
Scene.EstateDataService.StoreEstateSettings(dbSettings);
response = String.Empty;
// make sure there's a log entry to document the change
m_log.InfoFormat("[ESTATE]: Estate {0} renamed from \"{1}\" to \"{2}\"", estateID, oldName, newName);
// propagate the change
List<UUID> regions = Scene.GetEstateRegions(estateID);
UUID regionId = (regions.Count() > 0) ? regions.ElementAt(0) : UUID.Zero;
if (regionId != UUID.Zero)
{
ChangeDelegate change = OnEstateInfoChange;
if (change != null)
change(regionId);
}
}
}
return response;
}
public string SetRegionEstate(RegionInfo regionInfo, int estateID)
{
string response;
if (regionInfo.EstateSettings.EstateID == estateID)
{
response = String.Format("\"{0}\" is already part of estate {1}", regionInfo.RegionName, estateID);
}
else
{
// get the current settings from DB
EstateSettings dbSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
if (dbSettings.EstateID == 0)
{
response = String.Format("No estate found with ID {0}", estateID);
}
else if (Scene.EstateDataService.LinkRegion(regionInfo.RegionID, estateID))
{
// make sure there's a log entry to document the change
m_log.InfoFormat("[ESTATE]: Region {0} ({1}) moved to Estate {2} ({3}).", regionInfo.RegionID, regionInfo.RegionName, estateID, dbSettings.EstateName);
// propagate the change
ChangeDelegate change = OnEstateInfoChange;
if (change != null)
change(regionInfo.RegionID);
response = String.Empty;
}
else
{
response = String.Format("Could not move \"{0}\" to estate {1}", regionInfo.RegionName, estateID);
}
}
return response;
}
public string CreateEstate(string estateName, UUID ownerID)
{
string response;
if (string.IsNullOrEmpty(estateName))
{
response = "No estate name specified.";
}
else
{
List<int> estates = Scene.EstateDataService.GetEstates(estateName);
if (estates.Count() > 0)
{
response = String.Format("An estate named \"{0}\" already exists.", estateName);
}
else
{
EstateSettings settings = Scene.EstateDataService.CreateNewEstate();
if (settings == null)
response = String.Format("Unable to create estate \"{0}\" at this simulator", estateName);
else
{
settings.EstateOwner = ownerID;
settings.EstateName = estateName;
Scene.EstateDataService.StoreEstateSettings(settings);
response = String.Empty;
}
}
}
return response;
}
#endregion
#region Packet Data Responders
private void clientSendDetailedEstateData(IClientAPI remote_client, UUID invoice)
{
sendDetailedEstateData(remote_client, invoice);
sendEstateLists(remote_client, invoice);
}
private void sendDetailedEstateData(IClientAPI remote_client, UUID invoice)
{
uint sun = 0;
if (Scene.RegionInfo.EstateSettings.FixedSun)
sun = (uint)(Scene.RegionInfo.EstateSettings.SunPosition * 1024.0) + 0x1800;
UUID estateOwner;
estateOwner = Scene.RegionInfo.EstateSettings.EstateOwner;
if (Scene.Permissions.IsGod(remote_client.AgentId))
estateOwner = remote_client.AgentId;
remote_client.SendDetailedEstateData(invoice,
Scene.RegionInfo.EstateSettings.EstateName,
Scene.RegionInfo.EstateSettings.EstateID,
Scene.RegionInfo.EstateSettings.ParentEstateID,
GetEstateFlags(),
sun,
Scene.RegionInfo.RegionSettings.Covenant,
(uint) Scene.RegionInfo.RegionSettings.CovenantChangedDateTime,
Scene.RegionInfo.EstateSettings.AbuseEmail,
estateOwner);
}
private void sendEstateLists(IClientAPI remote_client, UUID invoice)
{
remote_client.SendEstateList(invoice,
(int)Constants.EstateAccessCodex.EstateManagers,
Scene.RegionInfo.EstateSettings.EstateManagers,
Scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendEstateList(invoice,
(int)Constants.EstateAccessCodex.AccessOptions,
Scene.RegionInfo.EstateSettings.EstateAccess,
Scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendEstateList(invoice,
(int)Constants.EstateAccessCodex.AllowedGroups,
Scene.RegionInfo.EstateSettings.EstateGroups,
Scene.RegionInfo.EstateSettings.EstateID);
remote_client.SendBannedUserList(invoice,
Scene.RegionInfo.EstateSettings.EstateBans,
Scene.RegionInfo.EstateSettings.EstateID);
}
private void estateSetRegionInfoHandler(bool blockTerraform, bool noFly, bool allowDamage, bool blockLandResell, int maxAgents, float objectBonusFactor,
int matureLevel, bool restrictPushObject, bool allowParcelChanges)
{
if (blockTerraform)
Scene.RegionInfo.RegionSettings.BlockTerraform = true;
else
Scene.RegionInfo.RegionSettings.BlockTerraform = false;
if (noFly)
Scene.RegionInfo.RegionSettings.BlockFly = true;
else
Scene.RegionInfo.RegionSettings.BlockFly = false;
if (allowDamage)
Scene.RegionInfo.RegionSettings.AllowDamage = true;
else
Scene.RegionInfo.RegionSettings.AllowDamage = false;
if (blockLandResell)
Scene.RegionInfo.RegionSettings.AllowLandResell = false;
else
Scene.RegionInfo.RegionSettings.AllowLandResell = true;
if((byte)maxAgents <= Scene.RegionInfo.AgentCapacity)
Scene.RegionInfo.RegionSettings.AgentLimit = (byte) maxAgents;
else
Scene.RegionInfo.RegionSettings.AgentLimit = Scene.RegionInfo.AgentCapacity;
Scene.RegionInfo.RegionSettings.ObjectBonus = objectBonusFactor;
if (matureLevel <= 13)
Scene.RegionInfo.RegionSettings.Maturity = 0;
else if (matureLevel <= 21)
Scene.RegionInfo.RegionSettings.Maturity = 1;
else
Scene.RegionInfo.RegionSettings.Maturity = 2;
if (restrictPushObject)
Scene.RegionInfo.RegionSettings.RestrictPushing = true;
else
Scene.RegionInfo.RegionSettings.RestrictPushing = false;
if (allowParcelChanges)
Scene.RegionInfo.RegionSettings.AllowLandJoinDivide = true;
else
Scene.RegionInfo.RegionSettings.AllowLandJoinDivide = false;
Scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionInfoPacketToAll();
}
public void setEstateTerrainBaseTexture(IClientAPI remoteClient, int level, UUID texture)
{
if (texture == UUID.Zero)
return;
switch (level)
{
case 0:
Scene.RegionInfo.RegionSettings.TerrainTexture1 = texture;
break;
case 1:
Scene.RegionInfo.RegionSettings.TerrainTexture2 = texture;
break;
case 2:
Scene.RegionInfo.RegionSettings.TerrainTexture3 = texture;
break;
case 3:
Scene.RegionInfo.RegionSettings.TerrainTexture4 = texture;
break;
}
Scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionInfoPacketToAll();
}
public void setEstateTerrainTextureHeights(IClientAPI client, int corner, float lowValue, float highValue)
{
switch (corner)
{
case 0:
Scene.RegionInfo.RegionSettings.Elevation1SW = lowValue;
Scene.RegionInfo.RegionSettings.Elevation2SW = highValue;
break;
case 1:
Scene.RegionInfo.RegionSettings.Elevation1NW = lowValue;
Scene.RegionInfo.RegionSettings.Elevation2NW = highValue;
break;
case 2:
Scene.RegionInfo.RegionSettings.Elevation1SE = lowValue;
Scene.RegionInfo.RegionSettings.Elevation2SE = highValue;
break;
case 3:
Scene.RegionInfo.RegionSettings.Elevation1NE = lowValue;
Scene.RegionInfo.RegionSettings.Elevation2NE = highValue;
break;
}
Scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
sendRegionHandshakeToAll();
sendRegionInfoPacketToAll();
}
private void handleCommitEstateTerrainTextureRequest(IClientAPI remoteClient)
{
// sendRegionHandshakeToAll();
}
public void setRegionTerrainSettings(float WaterHeight,
float TerrainRaiseLimit, float TerrainLowerLimit,
bool UseEstateSun, bool UseFixedSun, float SunHour,
bool UseGlobal, bool EstateFixedSun, float EstateSunHour)
{
// Water Height
Scene.RegionInfo.RegionSettings.WaterHeight = WaterHeight;
// Terraforming limits
Scene.RegionInfo.RegionSettings.TerrainRaiseLimit = TerrainRaiseLimit;
Scene.RegionInfo.RegionSettings.TerrainLowerLimit = TerrainLowerLimit;
// Time of day / fixed sun
Scene.RegionInfo.RegionSettings.UseEstateSun = UseEstateSun;
Scene.RegionInfo.RegionSettings.FixedSun = UseFixedSun;
Scene.RegionInfo.RegionSettings.SunPosition = SunHour;
Scene.TriggerEstateSunUpdate();
//m_log.Debug("[ESTATE]: UFS: " + UseFixedSun.ToString());
//m_log.Debug("[ESTATE]: SunHour: " + SunHour.ToString());
sendRegionInfoPacketToAll();
Scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
}
private void handleEstateRestartSimRequest(IClientAPI remoteClient, int timeInSeconds)
{
if (!AllowRegionRestartFromClient)
{
remoteClient.SendAlertMessage("Region restart has been disabled on this simulator.");
return;
}
IRestartModule restartModule = Scene.RequestModuleInterface<IRestartModule>();
if (restartModule != null)
{
List<int> times = new List<int>();
while (timeInSeconds > 0)
{
times.Add(timeInSeconds);
if (timeInSeconds > 300)
timeInSeconds -= 120;
else if (timeInSeconds > 30)
timeInSeconds -= 30;
else
timeInSeconds -= 15;
}
restartModule.ScheduleRestart(UUID.Zero, "Region will restart in {0}", times.ToArray(), false);
m_log.InfoFormat(
"User {0} requested restart of region {1} in {2} seconds",
remoteClient.Name, Scene.Name, times.Count != 0 ? times[0] : 0);
}
}
private void handleChangeEstateCovenantRequest(IClientAPI remoteClient, UUID estateCovenantID)
{
// m_log.DebugFormat(
// "[ESTATE MANAGEMENT MODULE]: Handling request from {0} to change estate covenant to {1}",
// remoteClient.Name, estateCovenantID);
Scene.RegionInfo.RegionSettings.Covenant = estateCovenantID;
Scene.RegionInfo.RegionSettings.CovenantChangedDateTime = Util.UnixTimeSinceEpoch();
Scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
}
private void handleEstateAccessDeltaRequest(IClientAPI remote_client, UUID invoice, int estateAccessType, UUID user)
{
// EstateAccessDelta handles Estate Managers, Sim Access, Sim Banlist, allowed Groups.. etc.
if (user == Scene.RegionInfo.EstateSettings.EstateOwner)
return; // never process EO
if ((estateAccessType & 4) != 0) // User add
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true))
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.AddEstateUser(user);
Scene.EstateDataService.StoreEstateSettings(estateSettings);
}
}
}
Scene.RegionInfo.EstateSettings.AddEstateUser(user);
Scene.EstateDataService.StoreEstateSettings(Scene.RegionInfo.EstateSettings);
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, Scene.RegionInfo.EstateSettings.EstateAccess, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 8) != 0) // User remove
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true))
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.RemoveEstateUser(user);
Scene.EstateDataService.StoreEstateSettings(estateSettings);
}
}
}
Scene.RegionInfo.EstateSettings.RemoveEstateUser(user);
Scene.EstateDataService.StoreEstateSettings(Scene.RegionInfo.EstateSettings);
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AccessOptions, Scene.RegionInfo.EstateSettings.EstateAccess, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 16) != 0) // Group add
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true))
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.AddEstateGroup(user);
Scene.EstateDataService.StoreEstateSettings(estateSettings);
}
}
}
Scene.RegionInfo.EstateSettings.AddEstateGroup(user);
Scene.EstateDataService.StoreEstateSettings(Scene.RegionInfo.EstateSettings);
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, Scene.RegionInfo.EstateSettings.EstateGroups, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 32) != 0) // Group remove
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true))
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.RemoveEstateGroup(user);
Scene.EstateDataService.StoreEstateSettings(estateSettings);
}
}
}
Scene.RegionInfo.EstateSettings.RemoveEstateGroup(user);
Scene.EstateDataService.StoreEstateSettings(Scene.RegionInfo.EstateSettings);
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.AllowedGroups, Scene.RegionInfo.EstateSettings.EstateGroups, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 64) != 0) // Ban add
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false))
{
EstateBan[] banlistcheck = Scene.RegionInfo.EstateSettings.EstateBans;
bool alreadyInList = false;
for (int i = 0; i < banlistcheck.Length; i++)
{
if (user == banlistcheck[i].BannedUserID)
{
alreadyInList = true;
break;
}
}
if (!alreadyInList)
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
EstateBan bitem = new EstateBan();
bitem.BannedUserID = user;
bitem.EstateID = (uint)estateID;
bitem.BannedHostAddress = "0.0.0.0";
bitem.BannedHostIPMask = "0.0.0.0";
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.AddBan(bitem);
Scene.EstateDataService.StoreEstateSettings(estateSettings);
}
}
}
EstateBan item = new EstateBan();
item.BannedUserID = user;
item.EstateID = Scene.RegionInfo.EstateSettings.EstateID;
item.BannedHostAddress = "0.0.0.0";
item.BannedHostIPMask = "0.0.0.0";
Scene.RegionInfo.EstateSettings.AddBan(item);
Scene.EstateDataService.StoreEstateSettings(Scene.RegionInfo.EstateSettings);
TriggerEstateInfoChange();
ScenePresence s = Scene.GetScenePresence(user);
if (s != null)
{
if (!s.IsChildAgent)
{
if (!Scene.TeleportClientHome(user, s.ControllingClient))
{
s.ControllingClient.Kick("Your access to the region was revoked and TP home failed - you have been logged out.");
Scene.CloseAgent(s.UUID, false);
}
}
}
}
else
{
remote_client.SendAlertMessage("User is already on the region ban list");
}
//Scene.RegionInfo.regionBanlist.Add(Manager(user);
remote_client.SendBannedUserList(invoice, Scene.RegionInfo.EstateSettings.EstateBans, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 128) != 0) // Ban remove
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, false))
{
EstateBan[] banlistcheck = Scene.RegionInfo.EstateSettings.EstateBans;
bool alreadyInList = false;
EstateBan listitem = null;
for (int i = 0; i < banlistcheck.Length; i++)
{
if (user == banlistcheck[i].BannedUserID)
{
alreadyInList = true;
listitem = banlistcheck[i];
break;
}
}
if (alreadyInList && listitem != null)
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.RemoveBan(user);
Scene.EstateDataService.StoreEstateSettings(estateSettings);
}
}
}
Scene.RegionInfo.EstateSettings.RemoveBan(listitem.BannedUserID);
Scene.EstateDataService.StoreEstateSettings(Scene.RegionInfo.EstateSettings);
TriggerEstateInfoChange();
}
else
{
remote_client.SendAlertMessage("User is not on the region ban list");
}
//Scene.RegionInfo.regionBanlist.Add(Manager(user);
remote_client.SendBannedUserList(invoice, Scene.RegionInfo.EstateSettings.EstateBans, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 256) != 0) // Manager add
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true))
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.AddEstateManager(user);
Scene.EstateDataService.StoreEstateSettings(estateSettings);
}
}
}
Scene.RegionInfo.EstateSettings.AddEstateManager(user);
Scene.EstateDataService.StoreEstateSettings(Scene.RegionInfo.EstateSettings);
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, Scene.RegionInfo.EstateSettings.EstateManagers, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
if ((estateAccessType & 512) != 0) // Manager remove
{
if (Scene.Permissions.CanIssueEstateCommand(remote_client.AgentId, true))
{
if ((estateAccessType & 1) != 0) // All estates
{
List<int> estateIDs = Scene.EstateDataService.GetEstatesByOwner(Scene.RegionInfo.EstateSettings.EstateOwner);
EstateSettings estateSettings;
foreach (int estateID in estateIDs)
{
if (estateID != Scene.RegionInfo.EstateSettings.EstateID)
{
estateSettings = Scene.EstateDataService.LoadEstateSettings(estateID);
estateSettings.RemoveEstateManager(user);
Scene.EstateDataService.StoreEstateSettings(estateSettings);
}
}
}
Scene.RegionInfo.EstateSettings.RemoveEstateManager(user);
Scene.EstateDataService.StoreEstateSettings(Scene.RegionInfo.EstateSettings);
TriggerEstateInfoChange();
remote_client.SendEstateList(invoice, (int)Constants.EstateAccessCodex.EstateManagers, Scene.RegionInfo.EstateSettings.EstateManagers, Scene.RegionInfo.EstateSettings.EstateID);
}
else
{
remote_client.SendAlertMessage("Method EstateAccessDelta Failed, you don't have permissions");
}
}
}
public void HandleOnEstateManageTelehub(IClientAPI client, UUID invoice, UUID senderID, string cmd, uint param1)
{
SceneObjectPart part;
switch (cmd)
{
case "info ui":
break;
case "connect":
// Add the Telehub
part = Scene.GetSceneObjectPart((uint)param1);
if (part == null)
return;
SceneObjectGroup grp = part.ParentGroup;
m_Telehub.Connect(grp);
break;
case "delete":
// Disconnect Telehub
m_Telehub.Disconnect();
break;
case "spawnpoint add":
// Add SpawnPoint to the Telehub
part = Scene.GetSceneObjectPart((uint)param1);
if (part == null)
return;
m_Telehub.AddSpawnPoint(part.AbsolutePosition);
break;
case "spawnpoint remove":
// Remove SpawnPoint from Telehub
m_Telehub.RemoveSpawnPoint((int)param1);
break;
default:
break;
}
if (client != null)
SendTelehubInfo(client);
}
private void SendSimulatorBlueBoxMessage(
IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message)
{
IDialogModule dm = Scene.RequestModuleInterface<IDialogModule>();
if (dm != null)
dm.SendNotificationToUsersInRegion(senderID, senderName, message);
}
private void SendEstateBlueBoxMessage(
IClientAPI remote_client, UUID invoice, UUID senderID, UUID sessionID, string senderName, string message)
{
TriggerEstateMessage(senderID, senderName, message);
}
private void handleEstateDebugRegionRequest(
IClientAPI remote_client, UUID invoice, UUID senderID,
bool disableScripts, bool disableCollisions, bool disablePhysics)
{
Scene.RegionInfo.RegionSettings.DisablePhysics = disablePhysics;
Scene.RegionInfo.RegionSettings.DisableScripts = disableScripts;
Scene.RegionInfo.RegionSettings.DisableCollisions = disableCollisions;
Scene.RegionInfo.RegionSettings.Save();
TriggerRegionInfoChange();
ISceneCommandsModule scm = Scene.RequestModuleInterface<ISceneCommandsModule>();
if (scm != null)
{
scm.SetSceneDebugOptions(
new Dictionary<string, string>() {
{ "scripting", (!disableScripts).ToString() },
{ "collisions", (!disableCollisions).ToString() },
{ "physics", (!disablePhysics).ToString() }
}
);
}
}
private void handleEstateTeleportOneUserHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID, UUID prey)
{
if (!Scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false))
return;
if (prey != UUID.Zero)
{
ScenePresence s = Scene.GetScenePresence(prey);
if (s != null)
{
if (!Scene.TeleportClientHome(prey, s.ControllingClient))
{
s.ControllingClient.Kick("You were teleported home by the region owner, but the TP failed - you have been logged out.");
Scene.CloseAgent(s.UUID, false);
}
}
}
}
private void handleEstateTeleportAllUsersHomeRequest(IClientAPI remover_client, UUID invoice, UUID senderID)
{
if (!Scene.Permissions.CanIssueEstateCommand(remover_client.AgentId, false))
return;
Scene.ForEachRootClient(delegate(IClientAPI client)
{
if (client.AgentId != senderID)
{
// make sure they are still there, we could be working down a long list
// Also make sure they are actually in the region
ScenePresence p;
if(Scene.TryGetScenePresence(client.AgentId, out p))
{
if (!Scene.TeleportClientHome(p.UUID, p.ControllingClient))
{
p.ControllingClient.Kick("You were teleported home by the region owner, but the TP failed - you have been logged out.");
Scene.CloseAgent(p.UUID, false);
}
}
}
});
}
private void AbortTerrainXferHandler(IClientAPI remoteClient, ulong XferID)
{
lock (this)
{
if ((TerrainUploader != null) && (XferID == TerrainUploader.XferID))
{
remoteClient.OnXferReceive -= TerrainUploader.XferReceive;
remoteClient.OnAbortXfer -= AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone -= HandleTerrainApplication;
TerrainUploader = null;
remoteClient.SendAlertMessage("Terrain Upload aborted by the client");
}
}
}
private void HandleTerrainApplication(string filename, byte[] terrainData, IClientAPI remoteClient)
{
lock (this)
{
remoteClient.OnXferReceive -= TerrainUploader.XferReceive;
remoteClient.OnAbortXfer -= AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone -= HandleTerrainApplication;
TerrainUploader = null;
}
m_log.DebugFormat("[CLIENT]: Terrain upload from {0} to {1} complete.", remoteClient.Name, Scene.Name);
remoteClient.SendAlertMessage("Terrain Upload Complete. Loading....");
ITerrainModule terr = Scene.RequestModuleInterface<ITerrainModule>();
if (terr != null)
{
try
{
using (MemoryStream terrainStream = new MemoryStream(terrainData))
terr.LoadFromStream(filename, terrainStream);
FileInfo x = new FileInfo(filename);
remoteClient.SendAlertMessage("Your terrain was loaded as a " + x.Extension + " file. It may take a few moments to appear.");
}
catch (IOException e)
{
m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was an IO Exception loading your terrain. Please check free space.");
return;
}
catch (SecurityException e)
{
m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive");
return;
}
catch (UnauthorizedAccessException e)
{
m_log.ErrorFormat("[TERRAIN]: Error Saving a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was a security Exception loading your terrain. Please check the security on the simulator drive");
return;
}
catch (Exception e)
{
m_log.ErrorFormat("[TERRAIN]: Error loading a terrain file uploaded via the estate tools. It gave us the following error: {0}", e.ToString());
remoteClient.SendAlertMessage("There was a general error loading your terrain. Please fix the terrain file and try again");
}
}
else
{
remoteClient.SendAlertMessage("Unable to apply terrain. Cannot get an instance of the terrain module");
}
}
private void handleUploadTerrain(IClientAPI remote_client, string clientFileName)
{
lock (this)
{
if (TerrainUploader == null)
{
m_log.DebugFormat(
"[TERRAIN]: Started receiving terrain upload for region {0} from {1}",
Scene.Name, remote_client.Name);
TerrainUploader = new EstateTerrainXferHandler(remote_client, clientFileName);
remote_client.OnXferReceive += TerrainUploader.XferReceive;
remote_client.OnAbortXfer += AbortTerrainXferHandler;
TerrainUploader.TerrainUploadDone += HandleTerrainApplication;
TerrainUploader.RequestStartXfer(remote_client);
}
else
{
remote_client.SendAlertMessage("Another Terrain Upload is in progress. Please wait your turn!");
}
}
}
private void handleTerrainRequest(IClientAPI remote_client, string clientFileName)
{
// Save terrain here
ITerrainModule terr = Scene.RequestModuleInterface<ITerrainModule>();
if (terr != null)
{
// m_log.Warn("[CLIENT]: Got Request to Send Terrain in region " + Scene.RegionInfo.RegionName);
if (File.Exists(Util.dataDir() + "/terrain.raw"))
{
File.Delete(Util.dataDir() + "/terrain.raw");
}
terr.SaveToFile(Util.dataDir() + "/terrain.raw");
FileStream input = new FileStream(Util.dataDir() + "/terrain.raw", FileMode.Open);
byte[] bdata = new byte[input.Length];
input.Read(bdata, 0, (int)input.Length);
remote_client.SendAlertMessage("Terrain file written, starting download...");
Scene.XferManager.AddNewFile("terrain.raw", bdata);
m_log.DebugFormat("[CLIENT]: Sending terrain for region {0} to {1}", Scene.Name, remote_client.Name);
remote_client.SendInitiateDownload("terrain.raw", clientFileName);
}
}
private void HandleRegionInfoRequest(IClientAPI remote_client)
{
RegionInfoForEstateMenuArgs args = new RegionInfoForEstateMenuArgs();
args.billableFactor = Scene.RegionInfo.EstateSettings.BillableFactor;
args.estateID = Scene.RegionInfo.EstateSettings.EstateID;
args.maxAgents = (byte)Scene.RegionInfo.RegionSettings.AgentLimit;
args.objectBonusFactor = (float)Scene.RegionInfo.RegionSettings.ObjectBonus;
args.parentEstateID = Scene.RegionInfo.EstateSettings.ParentEstateID;
args.pricePerMeter = Scene.RegionInfo.EstateSettings.PricePerMeter;
args.redirectGridX = Scene.RegionInfo.EstateSettings.RedirectGridX;
args.redirectGridY = Scene.RegionInfo.EstateSettings.RedirectGridY;
args.regionFlags = GetRegionFlags();
args.simAccess = Scene.RegionInfo.AccessLevel;
args.sunHour = (float)Scene.RegionInfo.RegionSettings.SunPosition;
args.terrainLowerLimit = (float)Scene.RegionInfo.RegionSettings.TerrainLowerLimit;
args.terrainRaiseLimit = (float)Scene.RegionInfo.RegionSettings.TerrainRaiseLimit;
args.useEstateSun = Scene.RegionInfo.RegionSettings.UseEstateSun;
args.waterHeight = (float)Scene.RegionInfo.RegionSettings.WaterHeight;
args.simName = Scene.RegionInfo.RegionName;
args.regionType = Scene.RegionInfo.RegionType;
remote_client.SendRegionInfoToEstateMenu(args);
}
private void HandleEstateCovenantRequest(IClientAPI remote_client)
{
remote_client.SendEstateCovenantInformation(Scene.RegionInfo.RegionSettings.Covenant);
}
private void HandleLandStatRequest(int parcelID, uint reportType, uint requestFlags, string filter, IClientAPI remoteClient)
{
if (!Scene.Permissions.CanIssueEstateCommand(remoteClient.AgentId, false))
return;
Dictionary<uint, float> sceneData = null;
if (reportType == 1)
{
sceneData = Scene.PhysicsScene.GetTopColliders();
}
else if (reportType == 0)
{
IScriptModule scriptModule = Scene.RequestModuleInterface<IScriptModule>();
if (scriptModule != null)
sceneData = scriptModule.GetObjectScriptsExecutionTimes();
}
List<LandStatReportItem> SceneReport = new List<LandStatReportItem>();
if (sceneData != null)
{
var sortedSceneData
= sceneData.Select(
item => new { Measurement = item.Value, Part = Scene.GetSceneObjectPart(item.Key) });
sortedSceneData.OrderBy(item => item.Measurement);
int items = 0;
foreach (var entry in sortedSceneData)
{
// The object may have been deleted since we received the data.
if (entry.Part == null)
continue;
// Don't show scripts that haven't executed or where execution time is below one microsecond in
// order to produce a more readable report.
if (entry.Measurement < 0.001)
continue;
items++;
SceneObjectGroup so = entry.Part.ParentGroup;
LandStatReportItem lsri = new LandStatReportItem();
lsri.LocationX = so.AbsolutePosition.X;
lsri.LocationY = so.AbsolutePosition.Y;
lsri.LocationZ = so.AbsolutePosition.Z;
lsri.Score = entry.Measurement;
lsri.TaskID = so.UUID;
lsri.TaskLocalID = so.LocalId;
lsri.TaskName = entry.Part.Name;
lsri.OwnerName = UserManager.GetUserName(so.OwnerID);
if (filter.Length != 0)
{
if ((lsri.OwnerName.Contains(filter) || lsri.TaskName.Contains(filter)))
{
}
else
{
continue;
}
}
SceneReport.Add(lsri);
if (items >= 100)
break;
}
}
remoteClient.SendLandStatReply(reportType, requestFlags, (uint)SceneReport.Count,SceneReport.ToArray());
}
#endregion
#region Outgoing Packets
public void sendRegionInfoPacketToAll()
{
Scene.ForEachRootClient(delegate(IClientAPI client)
{
HandleRegionInfoRequest(client);
});
}
public void sendRegionHandshake(IClientAPI remoteClient)
{
RegionHandshakeArgs args = new RegionHandshakeArgs();
args.isEstateManager = Scene.RegionInfo.EstateSettings.IsEstateManagerOrOwner(remoteClient.AgentId);
if (Scene.RegionInfo.EstateSettings.EstateOwner != UUID.Zero && Scene.RegionInfo.EstateSettings.EstateOwner == remoteClient.AgentId)
args.isEstateManager = true;
args.billableFactor = Scene.RegionInfo.EstateSettings.BillableFactor;
args.terrainStartHeight0 = (float)Scene.RegionInfo.RegionSettings.Elevation1SW;
args.terrainHeightRange0 = (float)Scene.RegionInfo.RegionSettings.Elevation2SW;
args.terrainStartHeight1 = (float)Scene.RegionInfo.RegionSettings.Elevation1NW;
args.terrainHeightRange1 = (float)Scene.RegionInfo.RegionSettings.Elevation2NW;
args.terrainStartHeight2 = (float)Scene.RegionInfo.RegionSettings.Elevation1SE;
args.terrainHeightRange2 = (float)Scene.RegionInfo.RegionSettings.Elevation2SE;
args.terrainStartHeight3 = (float)Scene.RegionInfo.RegionSettings.Elevation1NE;
args.terrainHeightRange3 = (float)Scene.RegionInfo.RegionSettings.Elevation2NE;
args.simAccess = Scene.RegionInfo.AccessLevel;
args.waterHeight = (float)Scene.RegionInfo.RegionSettings.WaterHeight;
args.regionFlags = GetRegionFlags();
args.regionName = Scene.RegionInfo.RegionName;
args.SimOwner = Scene.RegionInfo.EstateSettings.EstateOwner;
args.terrainBase0 = UUID.Zero;
args.terrainBase1 = UUID.Zero;
args.terrainBase2 = UUID.Zero;
args.terrainBase3 = UUID.Zero;
args.terrainDetail0 = Scene.RegionInfo.RegionSettings.TerrainTexture1;
args.terrainDetail1 = Scene.RegionInfo.RegionSettings.TerrainTexture2;
args.terrainDetail2 = Scene.RegionInfo.RegionSettings.TerrainTexture3;
args.terrainDetail3 = Scene.RegionInfo.RegionSettings.TerrainTexture4;
// m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 1 {0} for region {1}", args.terrainDetail0, Scene.RegionInfo.RegionName);
// m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 2 {0} for region {1}", args.terrainDetail1, Scene.RegionInfo.RegionName);
// m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 3 {0} for region {1}", args.terrainDetail2, Scene.RegionInfo.RegionName);
// m_log.DebugFormat("[ESTATE MANAGEMENT MODULE]: Sending terrain texture 4 {0} for region {1}", args.terrainDetail3, Scene.RegionInfo.RegionName);
remoteClient.SendRegionHandshake(Scene.RegionInfo,args);
}
public void handleEstateChangeInfo(IClientAPI remoteClient, UUID invoice, UUID senderID, UInt32 parms1, UInt32 parms2)
{
if (parms2 == 0)
{
Scene.RegionInfo.EstateSettings.UseGlobalTime = true;
Scene.RegionInfo.EstateSettings.SunPosition = 0.0;
}
else
{
Scene.RegionInfo.EstateSettings.UseGlobalTime = false;
Scene.RegionInfo.EstateSettings.SunPosition = (parms2 - 0x1800)/1024.0;
// Warning: FixedSun should be set to True, otherwise this sun position won't be used.
}
if ((parms1 & 0x00000010) != 0)
Scene.RegionInfo.EstateSettings.FixedSun = true;
else
Scene.RegionInfo.EstateSettings.FixedSun = false;
if ((parms1 & 0x00008000) != 0)
Scene.RegionInfo.EstateSettings.PublicAccess = true;
else
Scene.RegionInfo.EstateSettings.PublicAccess = false;
if ((parms1 & 0x10000000) != 0)
Scene.RegionInfo.EstateSettings.AllowVoice = true;
else
Scene.RegionInfo.EstateSettings.AllowVoice = false;
if ((parms1 & 0x00100000) != 0)
Scene.RegionInfo.EstateSettings.AllowDirectTeleport = true;
else
Scene.RegionInfo.EstateSettings.AllowDirectTeleport = false;
if ((parms1 & 0x00800000) != 0)
Scene.RegionInfo.EstateSettings.DenyAnonymous = true;
else
Scene.RegionInfo.EstateSettings.DenyAnonymous = false;
if ((parms1 & 0x01000000) != 0)
Scene.RegionInfo.EstateSettings.DenyIdentified = true;
else
Scene.RegionInfo.EstateSettings.DenyIdentified = false;
if ((parms1 & 0x02000000) != 0)
Scene.RegionInfo.EstateSettings.DenyTransacted = true;
else
Scene.RegionInfo.EstateSettings.DenyTransacted = false;
if ((parms1 & 0x40000000) != 0)
Scene.RegionInfo.EstateSettings.DenyMinors = true;
else
Scene.RegionInfo.EstateSettings.DenyMinors = false;
Scene.EstateDataService.StoreEstateSettings(Scene.RegionInfo.EstateSettings);
TriggerEstateInfoChange();
Scene.TriggerEstateSunUpdate();
sendDetailedEstateData(remoteClient, invoice);
}
#endregion
#region Other Functions
public void changeWaterHeight(float height)
{
setRegionTerrainSettings(height,
(float)Scene.RegionInfo.RegionSettings.TerrainRaiseLimit,
(float)Scene.RegionInfo.RegionSettings.TerrainLowerLimit,
Scene.RegionInfo.RegionSettings.UseEstateSun,
Scene.RegionInfo.RegionSettings.FixedSun,
(float)Scene.RegionInfo.RegionSettings.SunPosition,
Scene.RegionInfo.EstateSettings.UseGlobalTime,
Scene.RegionInfo.EstateSettings.FixedSun,
(float)Scene.RegionInfo.EstateSettings.SunPosition);
sendRegionInfoPacketToAll();
}
#endregion
private void EventManager_OnNewClient(IClientAPI client)
{
client.OnDetailedEstateDataRequest += clientSendDetailedEstateData;
client.OnSetEstateFlagsRequest += estateSetRegionInfoHandler;
// client.OnSetEstateTerrainBaseTexture += setEstateTerrainBaseTexture;
client.OnSetEstateTerrainDetailTexture += setEstateTerrainBaseTexture;
client.OnSetEstateTerrainTextureHeights += setEstateTerrainTextureHeights;
client.OnCommitEstateTerrainTextureRequest += handleCommitEstateTerrainTextureRequest;
client.OnSetRegionTerrainSettings += setRegionTerrainSettings;
client.OnEstateRestartSimRequest += handleEstateRestartSimRequest;
client.OnEstateChangeCovenantRequest += handleChangeEstateCovenantRequest;
client.OnEstateChangeInfo += handleEstateChangeInfo;
client.OnEstateManageTelehub += HandleOnEstateManageTelehub;
client.OnUpdateEstateAccessDeltaRequest += handleEstateAccessDeltaRequest;
client.OnSimulatorBlueBoxMessageRequest += SendSimulatorBlueBoxMessage;
client.OnEstateBlueBoxMessageRequest += SendEstateBlueBoxMessage;
client.OnEstateDebugRegionRequest += handleEstateDebugRegionRequest;
client.OnEstateTeleportOneUserHomeRequest += handleEstateTeleportOneUserHomeRequest;
client.OnEstateTeleportAllUsersHomeRequest += handleEstateTeleportAllUsersHomeRequest;
client.OnRequestTerrain += handleTerrainRequest;
client.OnUploadTerrain += handleUploadTerrain;
client.OnRegionInfoRequest += HandleRegionInfoRequest;
client.OnEstateCovenantRequest += HandleEstateCovenantRequest;
client.OnLandStatRequest += HandleLandStatRequest;
sendRegionHandshake(client);
}
private uint GetEstateFlags()
{
RegionFlags flags = RegionFlags.None;
if (Scene.RegionInfo.EstateSettings.FixedSun)
flags |= RegionFlags.SunFixed;
if (Scene.RegionInfo.EstateSettings.PublicAccess)
flags |= (RegionFlags.PublicAllowed |
RegionFlags.ExternallyVisible);
if (Scene.RegionInfo.EstateSettings.AllowVoice)
flags |= RegionFlags.AllowVoice;
if (Scene.RegionInfo.EstateSettings.AllowDirectTeleport)
flags |= RegionFlags.AllowDirectTeleport;
if (Scene.RegionInfo.EstateSettings.DenyAnonymous)
flags |= RegionFlags.DenyAnonymous;
if (Scene.RegionInfo.EstateSettings.DenyIdentified)
flags |= RegionFlags.DenyIdentified;
if (Scene.RegionInfo.EstateSettings.DenyTransacted)
flags |= RegionFlags.DenyTransacted;
if (Scene.RegionInfo.EstateSettings.AbuseEmailToEstateOwner)
flags |= RegionFlags.AbuseEmailToEstateOwner;
if (Scene.RegionInfo.EstateSettings.BlockDwell)
flags |= RegionFlags.BlockDwell;
if (Scene.RegionInfo.EstateSettings.EstateSkipScripts)
flags |= RegionFlags.EstateSkipScripts;
if (Scene.RegionInfo.EstateSettings.ResetHomeOnTeleport)
flags |= RegionFlags.ResetHomeOnTeleport;
if (Scene.RegionInfo.EstateSettings.TaxFree)
flags |= RegionFlags.TaxFree;
if (Scene.RegionInfo.EstateSettings.AllowLandmark)
flags |= RegionFlags.AllowLandmark;
if (Scene.RegionInfo.EstateSettings.AllowParcelChanges)
flags |= RegionFlags.AllowParcelChanges;
if (Scene.RegionInfo.EstateSettings.AllowSetHome)
flags |= RegionFlags.AllowSetHome;
if (Scene.RegionInfo.EstateSettings.DenyMinors)
flags |= (RegionFlags)(1 << 30);
return (uint)flags;
}
public void TriggerEstateMessage(UUID fromID, string fromName, string message)
{
MessageDelegate onmessage = OnEstateMessage;
if (onmessage != null)
onmessage(Scene.RegionInfo.RegionID, fromID, fromName, message);
}
private void SendTelehubInfo(IClientAPI client)
{
RegionSettings settings =
this.Scene.RegionInfo.RegionSettings;
SceneObjectGroup telehub = null;
if (settings.TelehubObject != UUID.Zero &&
(telehub = Scene.GetSceneObjectGroup(settings.TelehubObject)) != null)
{
List<Vector3> spawnPoints = new List<Vector3>();
foreach (SpawnPoint sp in settings.SpawnPoints())
{
spawnPoints.Add(sp.GetLocation(Vector3.Zero, Quaternion.Identity));
}
client.SendTelehubInfo(settings.TelehubObject,
telehub.Name,
telehub.AbsolutePosition,
telehub.GroupRotation,
spawnPoints);
}
else
{
client.SendTelehubInfo(UUID.Zero,
String.Empty,
Vector3.Zero,
Quaternion.Identity,
new List<Vector3>());
}
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2013, Daniel Murphy
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
using System;
using System.Diagnostics;
namespace SharpBox2D.Common
{
/**
* A 2D column vector
*/
public struct Vec2 : IEquatable<Vec2>
{
public float x, y;
public Vec2(float x, float y)
{
this.x = x;
this.y = y;
}
public Vec2(Vec2 toCopy) : this(toCopy.x, toCopy.y)
{
}
/** Zero ref this vector. */
public void setZero()
{
x = 0.0f;
y = 0.0f;
}
/** Set the vector component-wise. */
public void set(float x, float y)
{
this.x = x;
this.y = y;
}
/** Set this vector to another vector. */
public void set(Vec2 v)
{
this.x = v.x;
this.y = v.y;
}
/** Return the sum of this vector and another; does not alter either one. */
public Vec2 add(Vec2 v)
{
return new Vec2(x + v.x, y + v.y);
}
/** Return the difference of this vector and another; does not alter either one. */
public Vec2 sub(Vec2 v)
{
return new Vec2(x - v.x, y - v.y);
}
/** Return this vector multiplied by a scalar; does not alter this vector. */
public Vec2 mul(float a)
{
return new Vec2(x*a, y*a);
}
/** Return the negation of this vector; does not alter this vector. */
public Vec2 negate()
{
return new Vec2(-x, -y);
}
/** Flip the vector and return it - alters this vector. */
public void negateLocal()
{
x = -x;
y = -y;
}
/** Add another vector to this one and returns result - alters this vector. */
public void addLocal(Vec2 v)
{
x += v.x;
y += v.y;
}
/** Adds values to this vector and returns result - alters this vector. */
public void addLocal(float x, float y)
{
this.x += x;
this.y += y;
}
/** Subtract another vector from this one and return result - alters this vector. */
public void subLocal(Vec2 v)
{
x -= v.x;
y -= v.y;
}
/** Multiply this vector by a number and return result - alters this vector. */
public void mulLocal(float a)
{
x *= a;
y *= a;
}
/** Get the skew vector such that dot(skew_vec, other) == cross(vec, other) */
public Vec2 skew()
{
return new Vec2(-y, x);
}
/** Get the skew vector such that dot(skew_vec, other) == cross(vec, other) */
public void skew(ref Vec2 v)
{
v.x = -y;
v.y = x;
}
/** Return the length of this vector. */
public float length()
{
return MathUtils.sqrt(x*x + y*y);
}
/** Return the squared length of this vector. */
public float lengthSquared()
{
return (x*x + y*y);
}
/** Normalize this vector and return the length before normalization. Alters this vector. */
public float normalize()
{
float length = this.length();
if (length < Settings.EPSILON)
{
return 0f;
}
float invLength = 1.0f/length;
x *= invLength;
y *= invLength;
return length;
}
/** True if the vector represents a pair of valid, non-infinite floating point numbers. */
public bool isValid()
{
return !float.IsNaN(x) && !float.IsInfinity(x) && !float.IsNaN(y) && !float.IsInfinity(y);
}
/** Return a new vector that has positive components. */
public Vec2 abs()
{
return new Vec2(MathUtils.abs(x), MathUtils.abs(y));
}
public void absLocal()
{
x = MathUtils.abs(x);
y = MathUtils.abs(y);
}
// @Override // annotation omitted for GWT-compatibility
/** Return a copy of this vector. */
public Vec2 clone()
{
return new Vec2(x, y);
}
public override String ToString()
{
return "(" + x + "," + y + ")";
}
/*
* Static
*/
public static Vec2 abs(Vec2 a)
{
return new Vec2(MathUtils.abs(a.x), MathUtils.abs(a.y));
}
public static void absToOut(Vec2 a, ref Vec2 b)
{
b.x = MathUtils.abs(a.x);
b.y = MathUtils.abs(a.y);
}
public static float dot(Vec2 a, Vec2 b)
{
return a.x*b.x + a.y*b.y;
}
public static float cross(Vec2 a, Vec2 b)
{
return a.x*b.y - a.y*b.x;
}
public static Vec2 cross(Vec2 a, float s)
{
return new Vec2(s*a.y, -s*a.x);
}
public static void crossToOut(Vec2 a, float s, ref Vec2 b)
{
float tempy = -s*a.x;
b.x = s*a.y;
b.y = tempy;
}
public static void crossToOutUnsafe(Vec2 a, float s, ref Vec2 b)
{
Debug.Assert(b != a);
b.x = s*a.y;
b.y = -s*a.x;
}
public static Vec2 cross(float s, Vec2 a)
{
return new Vec2(-s*a.y, s*a.x);
}
public static void crossToOut(float s, Vec2 a, ref Vec2 b)
{
float tempY = s*a.x;
b.x = -s*a.y;
b.y = tempY;
}
public static void crossToOutUnsafe(float s, Vec2 a, ref Vec2 b)
{
Debug.Assert(b != a);
b.x = -s*a.y;
b.y = s*a.x;
}
public static void negateToOut(Vec2 a, ref Vec2 b)
{
b.x = -a.x;
b.y = -a.y;
}
public static Vec2 min(Vec2 a, Vec2 b)
{
return new Vec2(a.x < b.x ? a.x : b.x, a.y < b.y ? a.y : b.y);
}
public static Vec2 max(Vec2 a, Vec2 b)
{
return new Vec2(a.x > b.x ? a.x : b.x, a.y > b.y ? a.y : b.y);
}
public bool Equals(Vec2 other)
{
return x.Equals(other.x) && y.Equals(other.y);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
return false;
return obj is Vec2 && Equals((Vec2) obj);
}
public override int GetHashCode()
{
unchecked
{
return (x.GetHashCode()*397) ^ y.GetHashCode();
}
}
public static bool operator ==(Vec2 left, Vec2 right)
{
return left.Equals(right);
}
public static bool operator !=(Vec2 left, Vec2 right)
{
return !left.Equals(right);
}
public static void minToOut(Vec2 a, Vec2 b, ref Vec2 c)
{
c.x = a.x < b.x ? a.x : b.x;
c.y = a.y < b.y ? a.y : b.y;
}
public static void maxToOut(Vec2 a, Vec2 b, ref Vec2 c)
{
c.x = a.x > b.x ? a.x : b.x;
c.y = a.y > b.y ? a.y : b.y;
}
}
}
| |
/*
* 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.
*/
namespace NPOI.DDF
{
using System;
using System.IO;
using System.Text;
using System.Collections;
using System.Drawing;
using NPOI.Util;
using Ionic.Zlib;
/// <summary>
/// @author Daniel Noll
/// </summary>
internal class EscherMetafileBlip:EscherBlipRecord
{
private static POILogger log = POILogFactory.GetLogger(typeof(EscherMetafileBlip));
public const short RECORD_ID_EMF = unchecked((short) 0xF018) + 2;
public const short RECORD_ID_WMF = unchecked((short)0xF018) + 3;
public const short RECORD_ID_PICT = unchecked((short)0xF018) + 4;
/**
* BLIP signatures as defined in the escher spec
*/
public const short SIGNATURE_EMF = 0x3D40;
public const short SIGNATURE_WMF = 0x2160;
public const short SIGNATURE_PICT = 0x5420;
private const int HEADER_SIZE = 8;
private byte[] field_1_UID;
/**
* The primary UID is only saved to disk if (blip_instance ^ blip_signature == 1)
*/
private byte[] field_2_UID;
private int field_2_cb;
private int field_3_rcBounds_x1;
private int field_3_rcBounds_y1;
private int field_3_rcBounds_x2;
private int field_3_rcBounds_y2;
private int field_4_ptSize_w;
private int field_4_ptSize_h;
private int field_5_cbSave;
private byte field_6_fCompression;
private byte field_7_fFilter;
private byte[] raw_pictureData;
private byte[] remainingData;
/// <summary>
/// This method deSerializes the record from a byte array.
/// </summary>
/// <param name="data">The byte array containing the escher record information</param>
/// <param name="offset">The starting offset into</param>
/// <param name="recordFactory">May be null since this is not a container record.</param>
/// <returns>
/// The number of bytes Read from the byte array.
/// </returns>
public override int FillFields( byte[] data, int offset, EscherRecordFactory recordFactory )
{
int bytesAfterHeader = ReadHeader( data, offset );
int pos = offset + HEADER_SIZE;
field_1_UID = new byte[16];
Array.Copy( data, pos, field_1_UID, 0, 16 ); pos += 16;
if((Options ^ Signature) == 0x10){
field_2_UID = new byte[16];
Array.Copy( data, pos, field_2_UID, 0, 16 ); pos += 16;
}
field_2_cb = LittleEndian.GetInt( data, pos ); pos += 4;
field_3_rcBounds_x1 = LittleEndian.GetInt( data, pos ); pos += 4;
field_3_rcBounds_y1 = LittleEndian.GetInt( data, pos ); pos += 4;
field_3_rcBounds_x2 = LittleEndian.GetInt( data, pos ); pos += 4;
field_3_rcBounds_y2 = LittleEndian.GetInt( data, pos ); pos += 4;
field_4_ptSize_w = LittleEndian.GetInt( data, pos ); pos += 4;
field_4_ptSize_h = LittleEndian.GetInt( data, pos ); pos += 4;
field_5_cbSave = LittleEndian.GetInt( data, pos ); pos += 4;
field_6_fCompression = data[pos]; pos++;
field_7_fFilter = data[pos]; pos++;
raw_pictureData = new byte[field_5_cbSave];
Array.Copy( data, pos, raw_pictureData, 0, field_5_cbSave );
pos += field_5_cbSave;
// 0 means DEFLATE compression
// 0xFE means no compression
if (field_6_fCompression == 0)
{
field_pictureData = InflatePictureData(raw_pictureData);
}
else
{
field_pictureData = raw_pictureData;
}
int remaining = bytesAfterHeader - pos + offset + HEADER_SIZE;
if (remaining > 0)
{
remainingData = new byte[remaining];
Array.Copy(data, pos, remainingData, 0, remaining);
}
return bytesAfterHeader + HEADER_SIZE;
}
/// <summary>
/// Serializes the record to an existing byte array.
/// </summary>
/// <param name="offset">the offset within the byte array</param>
/// <param name="data">the data array to Serialize to</param>
/// <param name="listener">a listener for begin and end serialization events.</param>
/// <returns>the number of bytes written.</returns>
public override int Serialize(int offset, byte[] data, EscherSerializationListener listener)
{
listener.BeforeRecordSerialize(offset, RecordId, this);
int pos = offset;
LittleEndian.PutShort( data, pos, Options ); pos += 2;
LittleEndian.PutShort( data, pos, RecordId ); pos += 2;
LittleEndian.PutInt( data, pos, RecordSize - HEADER_SIZE ); pos += 4;
Array.Copy( field_1_UID, 0, data, pos, field_1_UID.Length ); pos += field_1_UID.Length;
if((Options ^ Signature) == 0x10){
Array.Copy( field_2_UID, 0, data, pos, field_2_UID.Length ); pos += field_2_UID.Length;
}
LittleEndian.PutInt( data, pos, field_2_cb ); pos += 4;
LittleEndian.PutInt( data, pos, field_3_rcBounds_x1 ); pos += 4;
LittleEndian.PutInt( data, pos, field_3_rcBounds_y1 ); pos += 4;
LittleEndian.PutInt( data, pos, field_3_rcBounds_x2 ); pos += 4;
LittleEndian.PutInt( data, pos, field_3_rcBounds_y2 ); pos += 4;
LittleEndian.PutInt( data, pos, field_4_ptSize_w ); pos += 4;
LittleEndian.PutInt( data, pos, field_4_ptSize_h ); pos += 4;
LittleEndian.PutInt( data, pos, field_5_cbSave ); pos += 4;
data[pos] = field_6_fCompression; pos++;
data[pos] = field_7_fFilter; pos++;
Array.Copy( raw_pictureData, 0, data, pos, raw_pictureData.Length );
pos += raw_pictureData.Length;
if (remainingData != null)
{
Array.Copy(remainingData, 0, data, pos, remainingData.Length);
pos += remainingData.Length;
}
listener.AfterRecordSerialize(offset + RecordSize, RecordId, RecordSize, this);
return RecordSize;
}
/// <summary>
/// Decompresses the provided data, returning the inflated result.
/// </summary>
/// <param name="data">the deflated picture data.</param>
/// <returns>the inflated picture data.</returns>
private static byte[] InflatePictureData(byte[] data)
{
using (MemoryStream in1 = new MemoryStream(data))
{
using (MemoryStream out1 = new MemoryStream())
{
ZlibStream zIn = null;
try
{
zIn = new ZlibStream(in1, CompressionMode.Decompress, true);
byte[] buf = new byte[4096];
int ReadBytes;
while ((ReadBytes = zIn.Read(buf, 0, buf.Length)) > 0)
{
out1.Write(buf, 0, ReadBytes);
}
return out1.ToArray();
}
catch (IOException e)
{
log.Log(POILogger.WARN, "Possibly corrupt compression or non-compressed data", e);
return data;
}
}
}
}
/// <summary>
/// Returns the number of bytes that are required to Serialize this record.
/// </summary>
/// <value>Number of bytes</value>
public override int RecordSize
{
get
{
int size = 8 + 50 + raw_pictureData.Length;
if (remainingData != null) size += remainingData.Length;
if ((Options ^ Signature) == 0x10)
{
size += field_2_UID.Length;
}
return size;
}
}
/// <summary>
/// Gets or sets the UID.
/// </summary>
/// <value>The UID.</value>
public byte[] UID
{
get { return field_1_UID; }
set { this.field_1_UID = value; }
}
/// <summary>
/// Gets or sets the primary UID.
/// </summary>
/// <value>The primary UID.</value>
public byte[] PrimaryUID
{
get{return field_2_UID;}
set { this.field_2_UID = value; }
}
/// <summary>
/// Gets or sets the size of the uncompressed.
/// </summary>
/// <value>The size of the uncompressed.</value>
public int UncompressedSize
{
get { return field_2_cb; }
set { field_2_cb = value; }
}
/// <summary>
/// Gets or sets the bounds.
/// </summary>
/// <value>The bounds.</value>
public Rectangle Bounds
{
get
{
return new Rectangle(field_3_rcBounds_x1,
field_3_rcBounds_y1,
field_3_rcBounds_x2 - field_3_rcBounds_x1,
field_3_rcBounds_y2 - field_3_rcBounds_y1);
}
set
{
field_3_rcBounds_x1 = value.X;
field_3_rcBounds_y1 = value.Y;
field_3_rcBounds_x2 = value.X + value.Width;
field_3_rcBounds_y2 = value.Y + value.Height;
}
}
/// <summary>
/// Gets or sets the size EMU.
/// </summary>
/// <value>The size EMU.</value>
public Size SizeEMU
{
get{
return new Size(field_4_ptSize_w, field_4_ptSize_h);
}
set
{
field_4_ptSize_w = value.Width;
field_4_ptSize_h = value.Height;
}
}
/// <summary>
/// Gets or sets the size of the compressed.
/// </summary>
/// <value>The size of the compressed.</value>
public int CompressedSize
{
get{return field_5_cbSave;}
set{field_5_cbSave=value;}
}
/// <summary>
/// Gets or sets a value indicating whether this instance is compressed.
/// </summary>
/// <value>
/// <c>true</c> if this instance is compressed; otherwise, <c>false</c>.
/// </value>
public bool IsCompressed
{
get{return (field_6_fCompression == 0);}
set { field_6_fCompression = value ? (byte)0 : (byte)0xFE; }
}
public byte[] RemainingData
{
get
{
return remainingData;
}
}
/// <summary>
/// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </summary>
/// <returns>
/// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>.
/// </returns>
public override String ToString()
{
String nl = Environment.NewLine;
String extraData;
using (MemoryStream b = new MemoryStream())
{
try
{
HexDump.Dump(this.field_pictureData, 0, b, 0);
extraData = b.ToString();
}
catch (Exception e)
{
extraData = e.ToString();
}
return GetType().Name + ":" + nl +
" RecordId: 0x" + HexDump.ToHex(RecordId) + nl +
" Options: 0x" + HexDump.ToHex(Options) + nl +
" UID: 0x" + HexDump.ToHex(field_1_UID) + nl +
(field_2_UID == null ? "" : (" UID2: 0x" + HexDump.ToHex(field_2_UID) + nl)) +
" Uncompressed Size: " + HexDump.ToHex(field_2_cb) + nl +
" Bounds: " + Bounds + nl +
" Size in EMU: " + SizeEMU + nl +
" Compressed Size: " + HexDump.ToHex(field_5_cbSave) + nl +
" Compression: " + HexDump.ToHex(field_6_fCompression) + nl +
" Filter: " + HexDump.ToHex(field_7_fFilter) + nl +
" Extra Data:" + nl + extraData +
(remainingData == null ? null : ("\n" +
" Remaining Data: " + HexDump.ToHex(remainingData, 32)));
}
}
/// <summary>
/// Return the blip signature
/// </summary>
/// <value>the blip signature</value>
public short Signature
{
get{
short sig = 0;
switch(RecordId){
case RECORD_ID_EMF:
sig = SIGNATURE_EMF;
break;
case RECORD_ID_WMF:
sig = SIGNATURE_WMF;
break;
case RECORD_ID_PICT:
sig = SIGNATURE_PICT;
break;
default: log.Log(POILogger.WARN, "Unknown metafile: " + RecordId); break;
}
return sig;
}
}
}
}
| |
#region File Description
//-----------------------------------------------------------------------------
// Material.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion
#region Using Statements
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
#endregion
namespace MaterialsAndLightsSample
{
public class Material
{
//graphics and Game references
Effect effectInstance;
ContentManager content;
GraphicsDevice device;
private Texture diffuseTexture = null;
private Texture specularTexture = null;
//shadow parameters
private float textureURepsValue = 2f;
private float textureVRepsValue = 2f;
private float specularPowerValue = 4f;
private float specularIntensityValue = 200f;
private string diffuseTextureNameValue = null;
private string specularTextureNameValue = null;
private Color colorValue = Color.White;
#region Initialization
public Material(ContentManager contentManager, GraphicsDevice graphicsDevice,
Effect baseEffect)
{
if (graphicsDevice == null)
{
throw new ArgumentNullException("graphicsDevice");
}
device = graphicsDevice;
if (contentManager == null)
{
throw new ArgumentNullException("contentManager");
}
content = contentManager;
if (baseEffect == null)
{
throw new ArgumentNullException("baseEffect");
}
//////////////////////////////////////////////////////////////
// Example 2.1 //
// //
// There are many ways to store and organize the constants //
// used for a material. For this example, an entiire //
// Effect instance is cloned from the basic material shader //
// and the material parameters are bound to that instance. //
// The result is a vastly simplified way of rendering a //
// material by simply setting the appropriate shader and //
// starting to draw. This is also a very efficient //
// technique on the XBox 360, but typically less so on a //
// PC. //
//////////////////////////////////////////////////////////////
effectInstance = baseEffect.Clone(device);
effectInstance.CurrentTechnique =
effectInstance.Techniques[0];
device = graphicsDevice;
// Set the defaults for the effect
effectInstance.Parameters["specularPower"].SetValue(specularPowerValue);
effectInstance.Parameters["specularIntensity"].SetValue(
specularIntensityValue);
effectInstance.Parameters["materialColor"].SetValue(colorValue.ToVector4());
effectInstance.Parameters["textureUReps"].SetValue(textureURepsValue);
effectInstance.Parameters["textureVReps"].SetValue(textureVRepsValue);
}
public void SetTexturedMaterial(Color color, float specularPower,
float specularIntensity, string diffuseTextureName,
string specularTextureName, float textureUReps, float textureVReps)
{
Color = color;
SpecularIntensity = specularIntensity;
SpecularPower = specularPower;
DiffuseTexture = diffuseTextureName;
SpecularTexture = specularTextureName;
TextureVReps = textureVReps;
TextureUReps = textureUReps;
}
public void SetBasicProperties(Color color, float specularPower, float
specularIntensity)
{
Color = color;
SpecularIntensity = specularIntensity;
SpecularPower = specularPower;
}
#endregion
#region Material Properties
public string SpecularTexture
{
set
{
specularTextureNameValue = value;
if (specularTextureNameValue == null)
{
specularTexture = null;
effectInstance.Parameters["specularTexture"].SetValue(
(Texture)null);
effectInstance.Parameters["specularTexEnabled"].SetValue(false);
}
else
{
specularTexture = content.Load<Texture>("Textures\\" +
specularTextureNameValue);
effectInstance.Parameters["specularTexture"].SetValue(
specularTexture);
effectInstance.Parameters["specularTexEnabled"].SetValue(true);
}
}
get
{
return specularTextureNameValue;
}
}
public string DiffuseTexture
{
set
{
diffuseTextureNameValue = value;
if (diffuseTextureNameValue == null)
{
diffuseTexture = null;
effectInstance.Parameters["diffuseTexture"].SetValue((Texture)null);
effectInstance.Parameters["diffuseTexEnabled"].SetValue(false);
}
else
{
diffuseTexture = content.Load<Texture>("Textures\\" +
diffuseTextureNameValue);
effectInstance.Parameters["diffuseTexture"].SetValue(
diffuseTexture);
effectInstance.Parameters["diffuseTexEnabled"].SetValue(true);
}
}
get
{
return diffuseTextureNameValue;
}
}
public Color Color
{
set
{
colorValue = value;
effectInstance.Parameters["materialColor"].SetValue(
colorValue.ToVector4());
}
get
{
return colorValue;
}
}
public float SpecularIntensity
{
set
{
specularIntensityValue = value;
effectInstance.Parameters["specularIntensity"].SetValue(
specularIntensityValue);
}
get
{
return specularIntensityValue;
}
}
public float SpecularPower
{
set
{
specularPowerValue = value;
effectInstance.Parameters["specularPower"].SetValue(specularPowerValue);
}
get
{
return specularPowerValue;
}
}
public float TextureUReps
{
set
{
textureURepsValue = value;
effectInstance.Parameters["textureUReps"].SetValue(textureURepsValue);
}
get
{
return textureURepsValue;
}
}
public float TextureVReps
{
set
{
textureVRepsValue = value;
effectInstance.Parameters["textureVReps"].SetValue(textureVRepsValue);
}
get
{
return textureVRepsValue;
}
}
#endregion
#region Draw Function
/// <summary>
/// The draw function for the material has been moved off to
/// the material. Sorting draws on the material is generally a
/// good way to reduce state switching and thusly CPU performance
/// overhead.
/// </summary>
/// <param name="model"></param>
/// <param name="world"></param>
public void DrawModelWithMaterial(Model model, ref Matrix world)
{
if (model == null)
{
throw new ArgumentNullException("model");
}
// our sample meshes only contain a single part, so we don't need to bother
// looping over the ModelMesh and ModelMeshPart collections. If the meshes
// were more complex, we would repeat all the following code for each part
ModelMesh mesh = model.Meshes[0];
ModelMeshPart meshPart = mesh.MeshParts[0];
// set the vertex source to the mesh's vertex buffer
device.Vertices[0].SetSource(
mesh.VertexBuffer, meshPart.StreamOffset, meshPart.VertexStride);
// set the vertex declaration
device.VertexDeclaration = meshPart.VertexDeclaration;
// set the current index buffer to the sample mesh's index buffer
device.Indices = mesh.IndexBuffer;
//set the world parameter of this instance of the model
effectInstance.Parameters["world"].SetValue(world);
//////////////////////////////////////////////////////////////
// Example 2.2 //
// //
// On Effect Instance.Begin(), the effect states are //
// applied to the device. This can be an expensive call //
// if there are lots of paramters in a given scene. //
// Aggressive optimization can yeild decent gains here, //
// particularly on PC hardware, but for clarity, this //
// sample is using Effect Pools which will re-set shared //
// paramters each time, even if they do not change between //
// effect instances. //
//////////////////////////////////////////////////////////////
effectInstance.Begin(SaveStateMode.None);
// EffectPass.Begin will update the device to
// begin using the state information defined in the current pass
effectInstance.CurrentTechnique.Passes[0].Begin();
// sampleMesh contains all of the information required to draw
// the current mesh
device.DrawIndexedPrimitives(
PrimitiveType.TriangleList, meshPart.BaseVertex, 0,
meshPart.NumVertices, meshPart.StartIndex, meshPart.PrimitiveCount);
// EffectPass.End must be called when the effect is no longer needed
effectInstance.CurrentTechnique.Passes[0].End();
// likewise, Effect.End will end the current technique
effectInstance.End();
}
#endregion
}
}
| |
//
// FolderTreeModel.cs
//
// Author:
// Ruben Vermeersch <ruben@savanne.be>
// Stephane Delcroix <stephane@delcroix.org>
//
// Copyright (C) 2009-2010 Novell, Inc.
// Copyright (C) 2010 Ruben Vermeersch
// Copyright (C) 2009 Stephane Delcroix
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using FSpot;
using FSpot.Database;
using FSpot.Core;
using Hyena;
using Hyena.Data.Sqlite;
namespace FSpot.Widgets
{
public class FolderTreeModel : TreeStore
{
protected FolderTreeModel (IntPtr raw) : base (raw) { }
Db database;
const string query_string =
"SELECT base_uri, COUNT(*) AS count " +
"FROM photos " +
"GROUP BY base_uri " +
"ORDER BY base_uri ASC";
public FolderTreeModel ()
: base (typeof (string), typeof (int), typeof (SafeUri))
{
database = App.Instance.Database;
database.Photos.ItemsChanged += HandlePhotoItemsChanged;
UpdateFolderTree ();
}
void HandlePhotoItemsChanged (object sender, DbItemEventArgs<Photo> e)
{
UpdateFolderTree ();
}
public string GetFolderNameByIter (TreeIter iter)
{
if ( ! IterIsValid (iter))
return null;
return (string) GetValue (iter, 0);
}
public int GetPhotoCountByIter (TreeIter iter)
{
if ( ! IterIsValid (iter))
return -1;
return (int) GetValue (iter, 1);
}
public SafeUri GetUriByIter (TreeIter iter)
{
if ( ! IterIsValid (iter))
return null;
return (SafeUri) GetValue (iter, 2);
}
public SafeUri GetUriByPath (TreePath row)
{
TreeIter iter;
GetIter (out iter, row);
return GetUriByIter (iter);
}
int count_all;
public int Count {
get { return count_all; }
}
/*
* UpdateFolderTree queries for directories in database and updates
* a possibly existing folder-tree to the queried structure
*/
private void UpdateFolderTree ()
{
Clear ();
count_all = 0;
/* points at start of each iteration to the leaf of the last inserted uri */
TreeIter iter = TreeIter.Zero;
/* stores the segments of the last inserted uri */
string[] last_segments = new string[] {};
int last_count = 0;
IDataReader reader = database.Database.Query (query_string);
while (reader.Read ()) {
var base_uri = new SafeUri (reader["base_uri"].ToString (), true);
int count = Convert.ToInt32 (reader["count"]);
// FIXME: this is a workaround hack to stop things from crashing - https://bugzilla.gnome.org/show_bug.cgi?id=622318
int index = base_uri.ToString ().IndexOf ("://");
var hack = base_uri.ToString ().Substring (index + 3);
hack = hack.IndexOf ('/') == 0 ? hack : "/" + hack;
string[] segments = hack.TrimEnd ('/').Split ('/');
/* First segment contains nothing (since we split by /), so we
* can overwrite the first segment for our needs and put the
* scheme here.
*/
segments[0] = base_uri.Scheme;
int i = 0;
/* find first difference of last inserted an current uri */
while (i < last_segments.Length && i < segments.Length) {
if (segments[i] != last_segments[i])
break;
i++;
}
/* points to the parent node of the current iter */
TreeIter parent_iter = iter;
/* step back to the level, where the difference occur */
for (int j = 0; j + i < last_segments.Length; j++) {
iter = parent_iter;
if (IterParent (out parent_iter, iter)) {
last_count += (int)GetValue (parent_iter, 1);
SetValue (parent_iter, 1, last_count);
} else
count_all += (int)last_count;
}
while (i < segments.Length) {
if (IterIsValid (parent_iter)) {
iter =
AppendValues (parent_iter,
Uri.UnescapeDataString (segments[i]),
(segments.Length - 1 == i)? count : 0,
(GetValue (parent_iter, 2) as SafeUri).Append (String.Format ("{0}/", segments[i]))
);
} else {
iter =
AppendValues (Uri.UnescapeDataString (segments[i]),
(segments.Length - 1 == i)? count : 0,
new SafeUri (String.Format ("{0}:///", base_uri.Scheme), true));
}
parent_iter = iter;
i++;
}
last_count = count;
last_segments = segments;
}
if (IterIsValid (iter)) {
/* and at least, step back and update photo count */
while (IterParent (out iter, iter)) {
last_count += (int)GetValue (iter, 1);
SetValue (iter, 1, last_count);
}
count_all += last_count;
}
}
}
}
| |
//==============================================================================
// MyGeneration.dOOdads
//
// PostgreSqlDynamicQuery.cs
// Version 5.0
// Updated - 10/09/2005
//------------------------------------------------------------------------------
// Copyright 2004, 2005 by MyGeneration Software.
// All Rights Reserved.
//
// Permission to use, copy, modify, and distribute this software and its
// documentation for any purpose and without fee is hereby granted,
// provided that the above copyright notice appear in all copies and that
// both that copyright notice and this permission notice appear in
// supporting documentation.
//
// MYGENERATION SOFTWARE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
// SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS, IN NO EVENT SHALL MYGENERATION SOFTWARE BE LIABLE FOR ANY
// SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
// WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
// TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE
// OR PERFORMANCE OF THIS SOFTWARE.
//==============================================================================
using System;
using System.Configuration;
using System.Data;
using Npgsql;
using System.Collections;
namespace MyGeneration.dOOdads
{
/// <summary>
/// PostgreSqlDynamicQuery is the PostgreSQL implementation of DynamicQuery
/// </summary>
public class PostgreSqlDynamicQuery : DynamicQuery
{
public PostgreSqlDynamicQuery(BusinessEntity entity)
: base(entity)
{
}
public override void AddOrderBy(string column, MyGeneration.dOOdads.WhereParameter.Dir direction)
{
base.AddOrderBy ("\"" + column + "\"", direction);
}
public override void AddOrderBy(DynamicQuery countAll, MyGeneration.dOOdads.WhereParameter.Dir direction)
{
if(countAll.CountAll)
{
base.AddOrderBy ("COUNT(*)", direction);
}
}
public override void AddOrderBy(AggregateParameter aggregate, MyGeneration.dOOdads.WhereParameter.Dir direction)
{
base.AddOrderBy (GetAggregate(aggregate, false), direction);
}
public override void AddGroupBy(string column)
{
base.AddGroupBy ("\"" + column + "\"");
}
public override void AddGroupBy(AggregateParameter aggregate)
{
// Support aggregates in a GROUP BY.
// Common method
base.AddGroupBy (GetAggregate(aggregate, false));
}
public override void AddResultColumn(string columnName)
{
base.AddResultColumn ("\"" + columnName + "\"");
}
protected string GetAggregate(AggregateParameter wItem, bool withAlias)
{
string query = string.Empty;
switch(wItem.Function)
{
case AggregateParameter.Func.Avg:
query += "AVG(";
break;
case AggregateParameter.Func.Count:
query += "COUNT(";
break;
case AggregateParameter.Func.Max:
query += "MAX(";
break;
case AggregateParameter.Func.Min:
query += "MIN(";
break;
case AggregateParameter.Func.Sum:
query += "SUM(";
break;
case AggregateParameter.Func.StdDev:
query += "STDDEV(";
break;
case AggregateParameter.Func.Var:
query += "VARIANCE(";
break;
}
if(wItem.Distinct)
{
query += "DISTINCT ";
}
query += "\"" + wItem.Column + "\")";
if(withAlias && wItem.Alias != string.Empty)
{
// Need DBMS string delimiter here
query += " AS \"" + wItem.Alias + "\"";
}
return query;
}
override protected IDbCommand _Load(string conjuction)
{
bool hasColumn = false;
bool selectAll = true;
string query;
query = "SELECT ";
if( this._distinct) query += " DISTINCT ";
if(this._resultColumns.Length > 0)
{
query += this._resultColumns;
hasColumn = true;
selectAll = false;
}
if(this._countAll)
{
if(hasColumn)
{
query += ", ";
}
query += "COUNT(*)";
if(this._countAllAlias != string.Empty)
{
// Need DBMS string delimiter here
query += " AS \"" + this._countAllAlias + "\"";
}
hasColumn = true;
selectAll = false;
}
if(_aggregateParameters != null && _aggregateParameters.Count > 0)
{
bool isFirst = true;
if(hasColumn)
{
query += ", ";
}
AggregateParameter wItem;
foreach(object obj in _aggregateParameters)
{
wItem = obj as AggregateParameter;
if(wItem.IsDirty)
{
if(isFirst)
{
query += GetAggregate(wItem, true);
isFirst = false;
}
else
{
query += ", " + GetAggregate(wItem, true);
}
}
}
selectAll = false;
}
if(selectAll)
{
query += "*";
}
query += " FROM \"" + this._entity.QuerySource + "\"";
NpgsqlCommand cmd = new NpgsqlCommand();
if(_whereParameters != null && _whereParameters.Count > 0)
{
query += " WHERE ";
bool first = true;
bool requiresParam;
WhereParameter wItem;
bool skipConjuction = false;
string paramName;
string columnName;
foreach(object obj in _whereParameters)
{
// Maybe we injected text or a WhereParameter
if(obj.GetType().ToString() == "System.String")
{
string text = obj as string;
query += text;
if(text == "(")
{
skipConjuction = true;
}
}
else
{
wItem = obj as WhereParameter;
if(wItem.IsDirty)
{
if(!first && !skipConjuction)
{
if(wItem.Conjuction != WhereParameter.Conj.UseDefault)
{
if(wItem.Conjuction == WhereParameter.Conj.And)
query += " AND ";
else
query += " OR ";
}
else
{
query += " " + conjuction + " ";
}
}
requiresParam = true;
columnName = "\"" + wItem.Column + "\"";
paramName = "@" + wItem.Column + (++inc).ToString();
wItem.Param.ParameterName = paramName;
switch(wItem.Operator)
{
case WhereParameter.Operand.Equal:
query += columnName + " = " + paramName + " ";
break;
case WhereParameter.Operand.NotEqual:
query += columnName + " <> " + paramName + " ";
break;
case WhereParameter.Operand.GreaterThan:
query += columnName + " > " + paramName + " ";
break;
case WhereParameter.Operand.LessThan:
query += columnName + " < " + paramName + " ";
break;
case WhereParameter.Operand.LessThanOrEqual:
query += columnName + " <= " + paramName + " ";
break;
case WhereParameter.Operand.GreaterThanOrEqual:
query += columnName + " >= " + paramName + " ";
break;
case WhereParameter.Operand.Like:
query += columnName + " LIKE " + paramName + " ";
break;
case WhereParameter.Operand.NotLike:
query += columnName + " NOT LIKE " + paramName + " ";
break;
case WhereParameter.Operand.IsNull:
query += columnName + " IS NULL ";
requiresParam = false;
break;
case WhereParameter.Operand.IsNotNull:
query += columnName + " IS NOT NULL ";
requiresParam = false;
break;
case WhereParameter.Operand.In:
query += columnName + " IN (" + wItem.Value + ") ";
requiresParam = false;
break;
case WhereParameter.Operand.NotIn:
query += columnName + " NOT IN (" + wItem.Value + ") ";
requiresParam = false;
break;
case WhereParameter.Operand.Between:
query += columnName + " BETWEEN " + paramName;
cmd.Parameters.Add(paramName, wItem.BetweenBeginValue);
paramName = "@" + wItem.Column + (++inc).ToString();
query += " AND " + paramName;
cmd.Parameters.Add(paramName, wItem.BetweenEndValue);
requiresParam = false;
break;
}
if(requiresParam)
{
IDbCommand dbCmd = cmd as IDbCommand;
dbCmd.Parameters.Add(wItem.Param);
wItem.Param.Value = wItem.Value;
}
first = false;
skipConjuction = false;
}
}
}
}
if(_groupBy.Length > 0)
{
query += " GROUP BY " + _groupBy;
if(this._withRollup)
{
query += " WITH ROLLUP";
}
}
if(_orderBy.Length > 0)
{
query += " ORDER BY " + _orderBy;
}
if( this._top >= 0) query += " LIMIT " + this._top.ToString() + " ";
cmd.CommandText = query;
return cmd;
}
}
}
| |
// 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\Engine\Classes\GameFramework\GameStateBase.h:29
namespace UnrealEngine
{
[ManageType("ManageGameStateBase")]
public partial class ManageGameStateBase : AGameStateBase, IManageWrapper
{
public ManageGameStateBase(IntPtr adress)
: base(adress)
{
}
#region DLLInmport
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_HandleBeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_OnRep_GameModeClass(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_OnRep_ReplicatedHasBegunPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_OnRep_ReplicatedWorldTimeSeconds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_OnRep_SpectatorClass(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_ReceivedGameModeClass(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_ReceivedSpectatorClass(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_SeamlessTravelTransitionCheckpoint(IntPtr self, bool bToTransitionMap);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_UpdateServerTimeSeconds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_BeginPlay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_ClearCrossLevelReferences(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_Destroyed(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_ForceNetRelevant(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_ForceNetUpdate(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_GatherCurrentMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_InvalidateLightingCacheDetailed(IntPtr self, bool bTranslationOnly);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_K2_DestroyActor(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_LifeSpanExpired(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_MarkComponentsAsPendingKill(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_NotifyActorBeginCursorOver(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_NotifyActorEndCursorOver(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_OnRep_AttachmentReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_OnRep_Instigator(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_OnRep_Owner(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_OnRep_ReplicatedMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_OnRep_ReplicateMovement(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_OnReplicationPausedChanged(IntPtr self, bool bIsReplicationPaused);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_OutsideWorldBounds(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostActorCreated(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostInitializeComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostNetInit(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostNetReceiveLocationAndRotation(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostNetReceivePhysicState(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostNetReceiveRole(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostRegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostUnregisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PreInitializeComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PreRegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PrestreamTextures(IntPtr self, float seconds, bool bEnableStreaming, int cinematicTextureGroups);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_RegisterActorTickFunctions(IntPtr self, bool bRegister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_RegisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_ReregisterAllComponents(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_RerunConstructionScripts(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_Reset(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_RewindForReplay(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_SetActorHiddenInGame(IntPtr self, bool bNewHidden);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_SetLifeSpan(IntPtr self, float inLifespan);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_SetReplicateMovement(IntPtr self, bool bInReplicateMovement);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_TearOff(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_TeleportSucceeded(IntPtr self, bool bIsATest);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_Tick(IntPtr self, float deltaSeconds);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_TornOff(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_UnregisterAllComponents(IntPtr self, bool bForReregister);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_BeginDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_FinishDestroy(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_MarkAsEditorOnlySubobject(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostCDOContruct(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostEditImport(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostInitProperties(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostLoad(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostRepNotifies(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PostSaveRoot(IntPtr self, bool bCleanupIsRequired);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PreDestroyFromReplication(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_PreNetReceive(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_ShutdownAfterError(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_CreateCluster(IntPtr self);
[DllImport(NativeManager.UnrealDotNetDll, CallingConvention = CallingConvention.Cdecl)]
private static extern void E__Supper__AGameStateBase_OnClusterMarkedAsPendingKill(IntPtr self);
#endregion
#region Methods
/// <summary>
/// Called by game mode to set the started play bool
/// </summary>
public override void HandleBeginPlay()
=> E__Supper__AGameStateBase_HandleBeginPlay(this);
protected override void OnRep_GameModeClass()
=> E__Supper__AGameStateBase_OnRep_GameModeClass(this);
protected override void OnRep_ReplicatedHasBegunPlay()
=> E__Supper__AGameStateBase_OnRep_ReplicatedHasBegunPlay(this);
protected override void OnRep_ReplicatedWorldTimeSeconds()
=> E__Supper__AGameStateBase_OnRep_ReplicatedWorldTimeSeconds(this);
protected override void OnRep_SpectatorClass()
=> E__Supper__AGameStateBase_OnRep_SpectatorClass(this);
/// <summary>
/// Called when the GameClass property is set (at startup for the server, after the variable has been replicated on clients)
/// </summary>
public override void ReceivedGameModeClass()
=> E__Supper__AGameStateBase_ReceivedGameModeClass(this);
/// <summary>
/// Called when the SpectatorClass property is set (at startup for the server, after the variable has been replicated on clients)
/// </summary>
public override void ReceivedSpectatorClass()
=> E__Supper__AGameStateBase_ReceivedSpectatorClass(this);
/// <summary>
/// Called during seamless travel transition twice (once when the transition map is loaded, once when destination map is loaded)
/// </summary>
public override void SeamlessTravelTransitionCheckpoint(bool bToTransitionMap)
=> E__Supper__AGameStateBase_SeamlessTravelTransitionCheckpoint(this, bToTransitionMap);
/// <summary>
/// Called periodically to update ReplicatedWorldTimeSeconds
/// </summary>
protected override void UpdateServerTimeSeconds()
=> E__Supper__AGameStateBase_UpdateServerTimeSeconds(this);
/// <summary>
/// Overridable native event for when play begins for this actor.
/// </summary>
protected override void BeginPlay()
=> E__Supper__AGameStateBase_BeginPlay(this);
/// <summary>
/// Do anything needed to clear out cross level references; Called from ULevel::PreSave
/// </summary>
public override void ClearCrossLevelReferences()
=> E__Supper__AGameStateBase_ClearCrossLevelReferences(this);
/// <summary>
/// Called when this actor is explicitly being destroyed during gameplay or in the editor, not called during level streaming or gameplay ending
/// </summary>
public override void Destroyed()
=> E__Supper__AGameStateBase_Destroyed(this);
/// <summary>
/// Forces this actor to be net relevant if it is not already by default
/// </summary>
public override void ForceNetRelevant()
=> E__Supper__AGameStateBase_ForceNetRelevant(this);
/// <summary>
/// Force actor to be updated to clients/demo net drivers
/// </summary>
public override void ForceNetUpdate()
=> E__Supper__AGameStateBase_ForceNetUpdate(this);
/// <summary>
/// Fills ReplicatedMovement property
/// </summary>
public override void GatherCurrentMovement()
=> E__Supper__AGameStateBase_GatherCurrentMovement(this);
/// <summary>
/// Invalidates anything produced by the last lighting build.
/// </summary>
public override void InvalidateLightingCacheDetailed(bool bTranslationOnly)
=> E__Supper__AGameStateBase_InvalidateLightingCacheDetailed(this, bTranslationOnly);
/// <summary>
/// Destroy the actor
/// </summary>
public override void DestroyActor()
=> E__Supper__AGameStateBase_K2_DestroyActor(this);
/// <summary>
/// Called when the lifespan of an actor expires (if he has one).
/// </summary>
public override void LifeSpanExpired()
=> E__Supper__AGameStateBase_LifeSpanExpired(this);
/// <summary>
/// Called to mark all components as pending kill when the actor is being destroyed
/// </summary>
public override void MarkComponentsAsPendingKill()
=> E__Supper__AGameStateBase_MarkComponentsAsPendingKill(this);
/// <summary>
/// Event when this actor has the mouse moved over it with the clickable interface.
/// </summary>
public override void NotifyActorBeginCursorOver()
=> E__Supper__AGameStateBase_NotifyActorBeginCursorOver(this);
/// <summary>
/// Event when this actor has the mouse moved off of it with the clickable interface.
/// </summary>
public override void NotifyActorEndCursorOver()
=> E__Supper__AGameStateBase_NotifyActorEndCursorOver(this);
public override void OnRep_AttachmentReplication()
=> E__Supper__AGameStateBase_OnRep_AttachmentReplication(this);
public override void OnRep_Instigator()
=> E__Supper__AGameStateBase_OnRep_Instigator(this);
protected override void OnRep_Owner()
=> E__Supper__AGameStateBase_OnRep_Owner(this);
public override void OnRep_ReplicatedMovement()
=> E__Supper__AGameStateBase_OnRep_ReplicatedMovement(this);
public override void OnRep_ReplicateMovement()
=> E__Supper__AGameStateBase_OnRep_ReplicateMovement(this);
/// <summary>
/// Called on the client when the replication paused value is changed
/// </summary>
public override void OnReplicationPausedChanged(bool bIsReplicationPaused)
=> E__Supper__AGameStateBase_OnReplicationPausedChanged(this, bIsReplicationPaused);
/// <summary>
/// Called when the Actor is outside the hard limit on world bounds
/// </summary>
public override void OutsideWorldBounds()
=> E__Supper__AGameStateBase_OutsideWorldBounds(this);
/// <summary>
/// Called when an actor is done spawning into the world (from UWorld::SpawnActor), both in the editor and during gameplay
/// <para>For actors with a root component, the location and rotation will have already been set. </para>
/// This is called before calling construction scripts, but after native components have been created
/// </summary>
public override void PostActorCreated()
=> E__Supper__AGameStateBase_PostActorCreated(this);
/// <summary>
/// Allow actors to initialize themselves on the C++ side after all of their components have been initialized, only called during gameplay
/// </summary>
public override void PostInitializeComponents()
=> E__Supper__AGameStateBase_PostInitializeComponents(this);
/// <summary>
/// Always called immediately after spawning and reading in replicated properties
/// </summary>
public override void PostNetInit()
=> E__Supper__AGameStateBase_PostNetInit(this);
/// <summary>
/// Update location and rotation from ReplicatedMovement. Not called for simulated physics!
/// </summary>
public override void PostNetReceiveLocationAndRotation()
=> E__Supper__AGameStateBase_PostNetReceiveLocationAndRotation(this);
/// <summary>
/// Update and smooth simulated physic state, replaces PostNetReceiveLocation() and PostNetReceiveVelocity()
/// </summary>
public override void PostNetReceivePhysicState()
=> E__Supper__AGameStateBase_PostNetReceivePhysicState(this);
/// <summary>
/// Always called immediately after a new Role is received from the remote.
/// </summary>
public override void PostNetReceiveRole()
=> E__Supper__AGameStateBase_PostNetReceiveRole(this);
/// <summary>
/// Called after all the components in the Components array are registered, called both in editor and during gameplay
/// </summary>
public override void PostRegisterAllComponents()
=> E__Supper__AGameStateBase_PostRegisterAllComponents(this);
/// <summary>
/// Called after all currently registered components are cleared
/// </summary>
public override void PostUnregisterAllComponents()
=> E__Supper__AGameStateBase_PostUnregisterAllComponents(this);
/// <summary>
/// Called right before components are initialized, only called during gameplay
/// </summary>
public override void PreInitializeComponents()
=> E__Supper__AGameStateBase_PreInitializeComponents(this);
/// <summary>
/// Called before all the components in the Components array are registered, called both in editor and during gameplay
/// </summary>
public override void PreRegisterAllComponents()
=> E__Supper__AGameStateBase_PreRegisterAllComponents(this);
/// <summary>
/// Calls PrestreamTextures() for all the actor's meshcomponents.
/// </summary>
/// <param name="seconds">Number of seconds to force all mip-levels to be resident</param>
/// <param name="bEnableStreaming">Whether to start (true) or stop (false) streaming</param>
/// <param name="cinematicTextureGroups">Bitfield indicating which texture groups that use extra high-resolution mips</param>
public override void PrestreamTextures(float seconds, bool bEnableStreaming, int cinematicTextureGroups)
=> E__Supper__AGameStateBase_PrestreamTextures(this, seconds, bEnableStreaming, cinematicTextureGroups);
/// <summary>
/// Virtual call chain to register all tick functions for the actor class hierarchy
/// </summary>
/// <param name="bRegister">true to register, false, to unregister</param>
protected override void RegisterActorTickFunctions(bool bRegister)
=> E__Supper__AGameStateBase_RegisterActorTickFunctions(this, bRegister);
/// <summary>
/// Ensure that all the components in the Components array are registered
/// </summary>
public override void RegisterAllComponents()
=> E__Supper__AGameStateBase_RegisterAllComponents(this);
/// <summary>
/// Will reregister all components on this actor. Does a lot of work - should only really be used in editor, generally use UpdateComponentTransforms or MarkComponentsRenderStateDirty.
/// </summary>
public override void ReregisterAllComponents()
=> E__Supper__AGameStateBase_ReregisterAllComponents(this);
/// <summary>
/// Rerun construction scripts, destroying all autogenerated components; will attempt to preserve the root component location.
/// </summary>
public override void RerunConstructionScripts()
=> E__Supper__AGameStateBase_RerunConstructionScripts(this);
/// <summary>
/// Reset actor to initial state - used when restarting level without reloading.
/// </summary>
public override void Reset()
=> E__Supper__AGameStateBase_Reset(this);
/// <summary>
/// Called on the actor before checkpoint data is applied during a replay.
/// <para>Only called if bReplayRewindable is set. </para>
/// </summary>
public override void RewindForReplay()
=> E__Supper__AGameStateBase_RewindForReplay(this);
/// <summary>
/// Sets the actor to be hidden in the game
/// </summary>
/// <param name="bNewHidden">Whether or not to hide the actor and all its components</param>
public override void SetActorHiddenInGame(bool bNewHidden)
=> E__Supper__AGameStateBase_SetActorHiddenInGame(this, bNewHidden);
/// <summary>
/// Set the lifespan of this actor. When it expires the object will be destroyed. If requested lifespan is 0, the timer is cleared and the actor will not be destroyed.
/// </summary>
public override void SetLifeSpan(float inLifespan)
=> E__Supper__AGameStateBase_SetLifeSpan(this, inLifespan);
/// <summary>
/// Set whether this actor's movement replicates to network clients.
/// </summary>
/// <param name="bInReplicateMovement">Whether this Actor's movement replicates to clients.</param>
public override void SetReplicateMovement(bool bInReplicateMovement)
=> E__Supper__AGameStateBase_SetReplicateMovement(this, bInReplicateMovement);
/// <summary>
/// Networking - Server - TearOff this actor to stop replication to clients. Will set bTearOff to true.
/// </summary>
public override void TearOff()
=> E__Supper__AGameStateBase_TearOff(this);
/// <summary>
/// Called from TeleportTo() when teleport succeeds
/// </summary>
public override void TeleportSucceeded(bool bIsATest)
=> E__Supper__AGameStateBase_TeleportSucceeded(this, bIsATest);
/// <summary>
/// Function called every frame on this Actor. Override this function to implement custom logic to be executed every frame.
/// <para>Note that Tick is disabled by default, and you will need to check PrimaryActorTick.bCanEverTick is set to true to enable it. </para>
/// </summary>
/// <param name="deltaSeconds">Game time elapsed during last frame modified by the time dilation</param>
public override void Tick(float deltaSeconds)
=> E__Supper__AGameStateBase_Tick(this, deltaSeconds);
/// <summary>
/// Networking - called on client when actor is torn off (bTearOff==true), meaning it's no longer replicated to clients.
/// <para>@see bTearOff </para>
/// </summary>
public override void TornOff()
=> E__Supper__AGameStateBase_TornOff(this);
/// <summary>
/// Unregister all currently registered components
/// </summary>
/// <param name="bForReregister">If true, RegisterAllComponents will be called immediately after this so some slow operations can be avoided</param>
public override void UnregisterAllComponents(bool bForReregister)
=> E__Supper__AGameStateBase_UnregisterAllComponents(this, bForReregister);
/// <summary>
/// Called before destroying the object. This is called immediately upon deciding to destroy the object, to allow the object to begin an
/// <para>asynchronous cleanup process. </para>
/// </summary>
public override void BeginDestroy()
=> E__Supper__AGameStateBase_BeginDestroy(this);
/// <summary>
/// Called to finish destroying the object. After UObject::FinishDestroy is called, the object's memory should no longer be accessed.
/// <para>@warning Because properties are destroyed here, Super::FinishDestroy() should always be called at the end of your child class's FinishDestroy() method, rather than at the beginning. </para>
/// </summary>
public override void FinishDestroy()
=> E__Supper__AGameStateBase_FinishDestroy(this);
/// <summary>
/// Called during subobject creation to mark this component as editor only, which causes it to get stripped in packaged builds
/// </summary>
public override void MarkAsEditorOnlySubobject()
=> E__Supper__AGameStateBase_MarkAsEditorOnlySubobject(this);
/// <summary>
/// Called after the C++ constructor has run on the CDO for a class. This is an obscure routine used to deal with the recursion
/// <para>in the construction of the default materials </para>
/// </summary>
public override void PostCDOContruct()
=> E__Supper__AGameStateBase_PostCDOContruct(this);
/// <summary>
/// Called after importing property values for this object (paste, duplicate or .t3d import)
/// <para>Allow the object to perform any cleanup for properties which shouldn't be duplicated or </para>
/// are unsupported by the script serialization
/// </summary>
public override void PostEditImport()
=> E__Supper__AGameStateBase_PostEditImport(this);
/// <summary>
/// Called after the C++ constructor and after the properties have been initialized, including those loaded from config.
/// <para>This is called before any serialization or other setup has happened. </para>
/// </summary>
public override void PostInitProperties()
=> E__Supper__AGameStateBase_PostInitProperties(this);
/// <summary>
/// Do any object-specific cleanup required immediately after loading an object.
/// <para>This is not called for newly-created objects, and by default will always execute on the game thread. </para>
/// </summary>
public override void PostLoad()
=> E__Supper__AGameStateBase_PostLoad(this);
/// <summary>
/// Called right after receiving a bunch
/// </summary>
public override void PostNetReceive()
=> E__Supper__AGameStateBase_PostNetReceive(this);
/// <summary>
/// Called right after calling all OnRep notifies (called even when there are no notifies)
/// </summary>
public override void PostRepNotifies()
=> E__Supper__AGameStateBase_PostRepNotifies(this);
/// <summary>
/// Called from within SavePackage on the passed in base/root object.
/// <para>This function is called after the package has been saved and can perform cleanup. </para>
/// </summary>
/// <param name="bCleanupIsRequired">Whether PreSaveRoot dirtied state that needs to be cleaned up</param>
public override void PostSaveRoot(bool bCleanupIsRequired)
=> E__Supper__AGameStateBase_PostSaveRoot(this, bCleanupIsRequired);
/// <summary>
/// Called right before being marked for destruction due to network replication
/// </summary>
public override void PreDestroyFromReplication()
=> E__Supper__AGameStateBase_PreDestroyFromReplication(this);
/// <summary>
/// Called right before receiving a bunch
/// </summary>
public override void PreNetReceive()
=> E__Supper__AGameStateBase_PreNetReceive(this);
/// <summary>
/// After a critical error, perform any mission-critical cleanup, such as restoring the video mode orreleasing hardware resources.
/// </summary>
public override void ShutdownAfterError()
=> E__Supper__AGameStateBase_ShutdownAfterError(this);
/// <summary>
/// Called after PostLoad to create UObject cluster
/// </summary>
public override void CreateCluster()
=> E__Supper__AGameStateBase_CreateCluster(this);
/// <summary>
/// Called during Garbage Collection to perform additional cleanup when the cluster is about to be destroyed due to PendingKill flag being set on it.
/// </summary>
public override void OnClusterMarkedAsPendingKill()
=> E__Supper__AGameStateBase_OnClusterMarkedAsPendingKill(this);
#endregion
public static implicit operator IntPtr(ManageGameStateBase self)
{
return self?.NativePointer ?? IntPtr.Zero;
}
public static implicit operator ManageGameStateBase(ObjectPointerDescription PtrDesc)
{
return NativeManager.GetWrapper<ManageGameStateBase>(PtrDesc);
}
}
}
| |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="PaymentRunner.cs" company="Rare Crowds Inc">
// Copyright 2012-2013 Rare Crowds, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using Activities;
using BillingActivities;
using DataAccessLayer;
using Diagnostics;
using EntityUtilities;
using Microsoft.Practices.Unity;
using PaymentProcessor;
using RuntimeIoc.WorkerRole;
using Utilities.Serialization;
namespace ProcessPayment
{
/// <summary>Class to run payment processing.</summary>
public class PaymentRunner
{
/// <summary>Gets or sets Repository.</summary>
private IEntityRepository Repository { get; set; }
/// <summary>Gets or sets Payment Processor.</summary>
private IPaymentProcessor PaymentProcessor { get; set; }
/// <summary>Gets or sets User Access Repository.</summary>
private IUserAccessRepository UserAccessRepository { get; set; }
/// <summary>Main run method.</summary>
/// <param name="arguments">The command-line arguments.</param>
public void Run(ProcessPaymentArgs arguments)
{
this.Initialize(arguments);
var campaignId = arguments.CampaignEntityId;
var userId = arguments.UserId;
var companyId = arguments.CompanyEntityId;
if (arguments.IsForceTestApprove)
{
this.ForceTestApproval(campaignId);
return;
}
// Get the entities to make sure we can - fail early if not.
// User id in request context for auditing trail only.
var context = new RequestContext
{
EntityFilter = new RepositoryEntityFilter(true, false, true, false),
UserId = userId
};
var campaign = this.Repository.GetEntity(context, campaignId);
this.Repository.GetUser(context, userId);
if (arguments.IsForceApprove)
{
this.ForceApproval(context, campaign.ExternalEntityId, campaign.ExternalName);
return;
}
var company = this.Repository.GetEntity(context, companyId);
if (arguments.IsHistoryDump)
{
DumpBillingHistory(campaign, company, true);
return;
}
// Setup activity request
var request = new ActivityRequest
{
Task = EntityActivityTasks.ChargeBillingAccount,
Values =
{
{ EntityActivityValues.AuthUserId, userId },
{ EntityActivityValues.EntityId, companyId },
{ EntityActivityValues.CampaignEntityId, campaignId },
{ EntityActivityValues.ChargeAmount, arguments.Amount },
}
};
if (arguments.IsRefund)
{
request.Values.Add(EntityActivityValues.ChargeId, arguments.ChargeId);
}
if (arguments.IsCheck)
{
request.Values.Add(EntityActivityValues.IsChargeCheck, true.ToString());
}
// Run the activity
// Set up our activity
var activityContext = new Dictionary<Type, object>
{
{ typeof(IEntityRepository), this.Repository },
{ typeof(IUserAccessRepository), this.UserAccessRepository },
{ typeof(IPaymentProcessor), this.PaymentProcessor },
};
var activity = Activity.CreateActivity(
typeof(ChargeBillingAccountActivity),
activityContext,
SubmitActivityRequest) as ChargeBillingAccountActivity;
var result = activity.Run(request);
if (!result.Succeeded)
{
throw new InvalidOperationException(
"ChargeBillingAccountActivity failed. {0}".FormatInvariant(result.Error.Message));
}
DumpBillingHistory(this.Repository.GetEntity(context, campaignId), company, false);
}
/// <summary>Dummy method for activity call</summary>
/// <param name="request">The activity request.</param>
/// <param name="sourceName">The source name.</param>
/// <returns>always true</returns>
private static bool SubmitActivityRequest(ActivityRequest request, string sourceName)
{
return true;
}
/// <summary>Get the billing history off the campaign and dump to output.</summary>
/// <param name="campaign">Campaign entity.</param>
/// <param name="company">Company entity.</param>
/// <param name="isFullHistory">True for full history.</param>
private static void DumpBillingHistory(IEntity campaign, IEntity company, bool isFullHistory)
{
var billingId = company.TryGetPropertyByName<string>(BillingActivityNames.CustomerBillingId, "Could not find customer billing id.");
var name = (string)company.ExternalName;
Console.WriteLine("History for Customer. Name: {0}, Billing Id: {1}".FormatInvariant(name, billingId));
var billingHistoryJson = campaign.TryGetPropertyByName<string>(
BillingActivityNames.BillingHistory, "Could not retrieve billing history.");
var history = AppsJsonSerializer.DeserializeObject<List<Dictionary<string, object>>>(billingHistoryJson);
if (!isFullHistory)
{
history = history.Take(5).ToList();
}
foreach (var historyItem in history)
{
Console.WriteLine(
string.Join(", ", historyItem.Select(kvp => "{0}: {1}".FormatInvariant(kvp.Key, kvp.Value.ToString()))));
}
}
/// <summary>Force billing approval of the campaign without going through the billing activies.</summary>
/// <param name="context">Repository request context for saving.</param>
/// <param name="campaignId">Campaign entity Id.</param>
/// <param name="campaignName">Campaign entity Name.</param>
private void ForceApproval(RequestContext context, EntityId campaignId, string campaignName)
{
this.Repository.TryUpdateEntity(
context,
campaignId,
new List<EntityProperty> { new EntityProperty(BillingActivityNames.IsBillingApproved, true, PropertyFilter.Extended) });
Console.WriteLine(
"Billing approval forced for Campaign Name: {0}. Warning - customer billing information has not been verified.".FormatInvariant(
(string)campaignName));
}
/// <summary>Force test billing approval of the campaign without going through the billing activies.</summary>
/// <param name="campaignId">Campaign entity Id.</param>
private void ForceTestApproval(EntityId campaignId)
{
var context = new RequestContext
{
EntityFilter = new RepositoryEntityFilter(true, false, true, false),
};
this.ForceApproval(context, campaignId, "Not Supplied");
}
/// <summary>Initialize runtime dependencies.</summary>
/// <param name="arguments">The command-line arguments.</param>
private void Initialize(ProcessPaymentArgs arguments)
{
var logFilePath = @"C:\logs\ReportRuns.log";
if (arguments.LogFile != null)
{
logFilePath = arguments.LogFile.FullName;
}
LogManager.Initialize(new[]
{
new FileLogger(logFilePath)
});
this.Repository = RuntimeIocContainer.Instance.Resolve<IEntityRepository>();
this.PaymentProcessor = RuntimeIocContainer.Instance.Resolve<IPaymentProcessor>();
this.UserAccessRepository = RuntimeIocContainer.Instance.Resolve<IUserAccessRepository>();
}
}
}
| |
using System;
using System.Globalization;
namespace Eto.Drawing
{
/// <summary>
/// Enumeration of the different system fonts for a <see cref="Font"/>
/// </summary>
/// <remarks>
/// This is useful when you want to use a font that is the same as standard UI elements.
/// </remarks>
/// <copyright>(c) 2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
public enum SystemFont
{
/// <summary>
/// Default system font
/// </summary>
Default,
/// <summary>
/// Default system font in BOLD
/// </summary>
Bold,
/// <summary>
/// Default label font
/// </summary>
Label,
/// <summary>
/// Default title bar font (window title)
/// </summary>
TitleBar,
/// <summary>
/// Default tool top font
/// </summary>
ToolTip,
/// <summary>
/// Default menu bar font
/// </summary>
MenuBar,
/// <summary>
/// Default font for items in a menu
/// </summary>
Menu,
/// <summary>
/// Default font for message boxes
/// </summary>
Message,
/// <summary>
/// Default font for palette dialogs
/// </summary>
Palette,
/// <summary>
/// Default font for status bars
/// </summary>
StatusBar
}
/// <summary>
/// Syles for a <see cref="Font"/>
/// </summary>
/// <copyright>(c) 2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
[Flags]
public enum FontStyle
{
/// <summary>
/// No extra font style applied
/// </summary>
None = 0,
/// <summary>
/// Bold font style
/// </summary>
Bold = 1 << 0,
/// <summary>
/// Italic font style
/// </summary>
Italic = 1 << 1,
}
/// <summary>
/// Decorations for a <see cref="Font"/>
/// </summary>
/// <remarks>
/// These specify the different decorations to apply to a font, and are not related to the style.
/// </remarks>
/// <copyright>(c) 2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
[Flags]
public enum FontDecoration
{
/// <summary>
/// No decorations
/// </summary>
None = 0,
/// <summary>
/// Underline font decoration
/// </summary>
Underline = 1 << 0,
/// <summary>
/// Strikethrough font decoration
/// </summary>
Strikethrough = 1 << 1,
}
/// <summary>
/// Defines a format for text
/// </summary>
/// <remarks>
/// A font is typically defined with a specified font family, with a given typeface. Each typeface has certain characteristics
/// that define the variation of the font family, for example Bold, or Italic.
///
/// You can get a list of <see cref="FontFamily"/> objects available in the current system using
/// <see cref="Fonts.AvailableFontFamilies"/>, which can then be used to create an instance of a font.
/// </remarks>
/// <copyright>(c) 2014 by Curtis Wensley</copyright>
/// <license type="BSD-3">See LICENSE for full terms</license>
[Handler(typeof(Font.IHandler))]
public class Font : Widget
{
new IHandler Handler { get { return (IHandler)base.Handler; } }
/// <summary>
/// Creates a new instance of the Font class with a specified <paramref name="family"/>, <paramref name="size"/>, and <paramref name="style"/>
/// </summary>
/// <param name="family">Family of font to use</param>
/// <param name="size">Size of the font, in points</param>
/// <param name="style">Style of the font</param>
/// <param name="decoration">Decorations to apply to the font</param>
public Font(string family, float size, FontStyle style = FontStyle.None, FontDecoration decoration = FontDecoration.None)
{
Handler.Create(new FontFamily(family), size, style, decoration);
Initialize();
}
/// <summary>
/// Creates a new instance of the Font class with a specified <paramref name="family"/>, <paramref name="size"/>, and <paramref name="style"/>
/// </summary>
/// <param name="family">Family of font to use</param>
/// <param name="size">Size of the font, in points</param>
/// <param name="style">Style of the font</param>
/// <param name="decoration">Decorations to apply to the font</param>
public Font(FontFamily family, float size, FontStyle style = FontStyle.None, FontDecoration decoration = FontDecoration.None)
{
Handler.Create(family, size, style, decoration);
Initialize();
}
/// <summary>
/// Creates a new instance of the Font class with a specified <paramref name="systemFont"/> and optional custom <paramref name="size"/>
/// </summary>
/// <remarks>
/// The system fonts are the same fonts that the standard UI of each platform use for particular areas
/// given the <see cref="SystemFont"/> enumeration.
/// </remarks>
/// <param name="systemFont">Type of system font to create</param>
/// <param name="size">Optional size of the font, in points. If not specified, the default size of the system font is used</param>
/// <param name="decoration">Decorations to apply to the font</param>
public Font(SystemFont systemFont, float? size = null, FontDecoration decoration = FontDecoration.None)
{
Handler.Create(systemFont, size, decoration);
Initialize();
}
/// <summary>
/// Initializes a new instance of the Font class with the specified <paramref name="typeface"/> and <paramref name="size"/>
/// </summary>
/// <param name="typeface">Typeface of the font to create</param>
/// <param name="size">Size of the font in points</param>
/// <param name="decoration">Decorations to apply to the font</param>
public Font(FontTypeface typeface, float size, FontDecoration decoration = FontDecoration.None)
{
Handler.Create(typeface, size, decoration);
Initialize();
}
/// <summary>
/// Initializes a new instance of the Font class with the specified font <paramref name="handler"/>
/// </summary>
/// <remarks>
/// Not intended to be used directly, this is used by each platform to pass back a font instance with a specific handler
/// </remarks>
/// <param name="handler">Handler for the font</param>
public Font(IHandler handler)
: base(handler)
{
}
/// <summary>
/// Gets the name of the family of this font
/// </summary>
public string FamilyName
{
get { return Handler.FamilyName; }
}
/// <summary>
/// Gets the style flags for this font
/// </summary>
/// <remarks>
/// This does not represent all of the style properties of the font. Each <see cref="Typeface"/>
/// has its own style relative to the font family.
/// </remarks>
public FontStyle FontStyle
{
get { return Handler.FontStyle; }
}
/// <summary>
/// Gets the decorations applied to the font
/// </summary>
/// <remarks>
/// Decorations can be applied to any typeface/style of font.
/// </remarks>
/// <value>The font decoration.</value>
public FontDecoration FontDecoration
{
get { return Handler.FontDecoration; }
}
/// <summary>
/// Gets the family information for this font
/// </summary>
public FontFamily Family
{
get { return Handler.Family; }
}
/// <summary>
/// Gets the typeface information for this font
/// </summary>
public FontTypeface Typeface
{
get { return Handler.Typeface; }
}
/// <summary>
/// Gets the height of the lower case 'x' character
/// </summary>
/// <value>The height of the x character</value>
public float XHeight
{
get { return Handler.XHeight; }
}
/// <summary>
/// Gets the top y co-ordinate from the baseline to the tallest character ascent
/// </summary>
/// <value>The tallest ascent of the font</value>
public float Ascent
{
get { return Handler.Ascent; }
}
/// <summary>
/// Gets the bottom y co-ordinate from the baseline to the longest character descent
/// </summary>
/// <value>The longest descent of the font</value>
public float Descent
{
get { return Handler.Descent; }
}
/// <summary>
/// Gets the height of a single line of the font
/// </summary>
/// <value>The height of a single line</value>
public float LineHeight
{
get { return Handler.LineHeight; }
}
/// <summary>
/// Gets the leading space between each line
/// </summary>
/// <value>The leading.</value>
public float Leading
{
get { return Handler.Leading; }
}
/// <summary>
/// Gets the offset of the baseline from the drawing point
/// </summary>
/// <value>The baseline offset from the drawing point</value>
public float Baseline
{
get { return Handler.Baseline; }
}
/// <summary>
/// Gets the size, in points, of this font
/// </summary>
public float Size
{
get { return Handler.Size; }
}
/// <summary>
/// Gets a value indicating that this font has a bold style
/// </summary>
public bool Bold
{
get { return FontStyle.HasFlag(FontStyle.Bold); }
}
/// <summary>
/// Gets a value indicating that this font has an italic style
/// </summary>
public bool Italic
{
get { return FontStyle.HasFlag(FontStyle.Italic); }
}
/// <summary>
/// Gets a value indicating that this font has an underline decoration
/// </summary>
public bool Underline
{
get { return FontDecoration.HasFlag(FontDecoration.Underline); }
}
/// <summary>
/// Gets a value indicating that this font has a strikethrough decoration
/// </summary>
public bool Strikethrough
{
get { return FontDecoration.HasFlag(FontDecoration.Strikethrough); }
}
/// <summary>
/// Gets a string representation of the font object
/// </summary>
/// <returns>String representation of the font object</returns>
public override string ToString()
{
return string.Format(CultureInfo.InvariantCulture, "Family={0}, Typeface={1}, Size={2}pt, Style={3}", Family, Typeface, Size, FontStyle);
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to the current <see cref="Eto.Drawing.Font"/>.
/// </summary>
/// <param name="obj">The <see cref="System.Object"/> to compare with the current <see cref="Eto.Drawing.Font"/>.</param>
/// <returns><c>true</c> if the specified <see cref="System.Object"/> is equal to the current <see cref="Eto.Drawing.Font"/>;
/// otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
var font = obj as Font;
return font != null
&& object.ReferenceEquals(Platform, font.Platform)
&& Family.Equals(font.Family)
&& Size.Equals(font.Size)
&& FontStyle.Equals(font.FontStyle);
}
/// <summary>
/// Serves as a hash function for a <see cref="Eto.Drawing.Font"/> object.
/// </summary>
/// <returns>A hash code for this instance that is suitable for use in hashing algorithms and data structures such as a hash table.</returns>
public override int GetHashCode()
{
return FamilyName.GetHashCode() ^ Platform.GetHashCode() ^ Size.GetHashCode() ^ FontStyle.GetHashCode();
}
#region Handler
/// <summary>
/// Platform handler for the <see cref="Font"/> class
/// </summary>
[AutoInitialize(false)]
public new interface IHandler : Widget.IHandler
{
/// <summary>
/// Creates a new font object
/// </summary>
/// <param name="family">Type of font family</param>
/// <param name="size">Size of the font (in points)</param>
/// <param name="style">Style of the font</param>
/// <param name="decoration">Decorations to apply to the font</param>
void Create(FontFamily family, float size, FontStyle style, FontDecoration decoration);
/// <summary>
/// Creates a new font object with the specified <paramref name="systemFont"/> and optional size
/// </summary>
/// <param name="systemFont">System font to create</param>
/// <param name="size">Size of font to use, or null to use the system font's default size</param>
/// <param name="decoration">Decorations to apply to the font</param>
void Create(SystemFont systemFont, float? size, FontDecoration decoration);
/// <summary>
/// Creates a new font object with the specified <paramref name="typeface"/> and <paramref name="size"/>
/// </summary>
/// <param name="typeface">Typeface to specify the style (and family) of the font</param>
/// <param name="size">Size of the font to create</param>
/// <param name="decoration">Decorations to apply to the font</param>
void Create(FontTypeface typeface, float size, FontDecoration decoration);
/// <summary>
/// Gets the height of the lower case 'x' character
/// </summary>
/// <value>The height of the x character</value>
float XHeight { get; }
/// <summary>
/// Gets the top y co-ordinate from the baseline to the tallest character ascent
/// </summary>
/// <value>The tallest ascent of the font</value>
float Ascent { get; }
/// <summary>
/// Gets the bottom y co-ordinate from the baseline to the longest character descent
/// </summary>
/// <value>The longest descent of the font</value>
float Descent { get; }
/// <summary>
/// Gets the height of a single line of the font
/// </summary>
/// <value>The height of a single line</value>
float LineHeight { get; }
/// <summary>
/// Gets the leading space between each line
/// </summary>
/// <value>The leading.</value>
float Leading { get; }
/// <summary>
/// Gets the offset of the baseline from the drawing point
/// </summary>
/// <value>The baseline offset from the drawing point</value>
float Baseline { get; }
/// <summary>
/// Gets the size of the font in points
/// </summary>
float Size { get; }
/// <summary>
/// Gets the name of the family of this font
/// </summary>
string FamilyName { get; }
/// <summary>
/// Gets the style flags for this font
/// </summary>
/// <remarks>
/// This does not necessarily represent all of the style properties of the font.
/// Each <see cref="Typeface"/> has its own style relative to the font family. This is meerely a
/// convenience to get the common properties of a font's typeface style
/// </remarks>
FontStyle FontStyle { get; }
/// <summary>
/// Gets the decorations applied to the font
/// </summary>
/// <remarks>
/// Decorations can be applied to any typeface/style of font.
/// </remarks>
/// <value>The font decoration.</value>
FontDecoration FontDecoration { get; }
/// <summary>
/// Gets the family information for this font
/// </summary>
/// <remarks>
/// This should always return an instance that represents the family of this font
/// </remarks>
FontFamily Family { get; }
/// <summary>
/// Gets the typeface information for this font
/// </summary>
/// <remarks>
/// This should always return an instance that represents the typeface of this font
/// </remarks>
FontTypeface Typeface { get; }
}
#endregion
}
}
| |
using YAF.Lucene.Net.Support;
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace YAF.Lucene.Net.Util.Fst
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
//using INPUT_TYPE = YAF.Lucene.Net.Util.Fst.FST.INPUT_TYPE; // javadoc
using PackedInt32s = YAF.Lucene.Net.Util.Packed.PackedInt32s;
// TODO: could we somehow stream an FST to disk while we
// build it?
/// <summary>
/// Builds a minimal FST (maps an <see cref="Int32sRef"/> term to an arbitrary
/// output) from pre-sorted terms with outputs. The FST
/// becomes an FSA if you use NoOutputs. The FST is written
/// on-the-fly into a compact serialized format byte array, which can
/// be saved to / loaded from a Directory or used directly
/// for traversal. The FST is always finite (no cycles).
///
/// <para/>NOTE: The algorithm is described at
/// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.24.3698
///
/// <para/>The parameterized type <typeparam name="T"/> is the output type. See the
/// subclasses of <see cref="Outputs{T}"/>.
///
/// <para/>FSTs larger than 2.1GB are now possible (as of Lucene
/// 4.2). FSTs containing more than 2.1B nodes are also now
/// possible, however they cannot be packed.
/// <para/>
/// @lucene.experimental
/// </summary>
public class Builder<T> : Builder
{
private readonly NodeHash<T> dedupHash;
private readonly FST<T> fst;
private readonly T NO_OUTPUT;
// private static final boolean DEBUG = true;
// simplistic pruning: we prune node (and all following
// nodes) if less than this number of terms go through it:
private readonly int minSuffixCount1;
// better pruning: we prune node (and all following
// nodes) if the prior node has less than this number of
// terms go through it:
private readonly int minSuffixCount2;
private readonly bool doShareNonSingletonNodes;
private readonly int shareMaxTailLength;
private readonly Int32sRef lastInput = new Int32sRef();
// for packing
private readonly bool doPackFST;
private readonly float acceptableOverheadRatio;
// NOTE: cutting this over to ArrayList instead loses ~6%
// in build performance on 9.8M Wikipedia terms; so we
// left this as an array:
// current "frontier"
private UnCompiledNode<T>[] frontier;
// LUCENENET specific - FreezeTail class moved to non-generic type Builder
private readonly FreezeTail<T> freezeTail;
// LUCENENET specific - allow external access through property
internal FST<T> Fst
{
get { return fst; }
}
internal T NoOutput
{
get { return NO_OUTPUT; }
}
/// <summary>
/// Instantiates an FST/FSA builder without any pruning. A shortcut
/// to <see cref="Builder{T}.Builder(FST.INPUT_TYPE, int, int, bool, bool, int, Outputs{T}, FreezeTail{T}, bool, float, bool, int)"/>
/// with pruning options turned off.
/// </summary>
public Builder(FST.INPUT_TYPE inputType, Outputs<T> outputs)
: this(inputType, 0, 0, true, true, int.MaxValue, outputs, null, false, PackedInt32s.COMPACT, true, 15)
{
var x = new System.Text.StringBuilder();
}
/// <summary>
/// Instantiates an FST/FSA builder with all the possible tuning and construction
/// tweaks. Read parameter documentation carefully.
/// </summary>
/// <param name="inputType">
/// The input type (transition labels). Can be anything from <see cref="Lucene.Net.Util.Fst.FST.INPUT_TYPE"/>
/// enumeration. Shorter types will consume less memory. Strings (character sequences) are
/// represented as <see cref="Lucene.Net.Util.Fst.FST.INPUT_TYPE.BYTE4"/> (full unicode codepoints).
/// </param>
/// <param name="minSuffixCount1">
/// If pruning the input graph during construction, this threshold is used for telling
/// if a node is kept or pruned. If transition_count(node) >= minSuffixCount1, the node
/// is kept.
/// </param>
/// <param name="minSuffixCount2">
/// (Note: only Mike McCandless knows what this one is really doing...)
/// </param>
/// <param name="doShareSuffix">
/// If <c>true</c>, the shared suffixes will be compacted into unique paths.
/// this requires an additional RAM-intensive hash map for lookups in memory. Setting this parameter to
/// <c>false</c> creates a single suffix path for all input sequences. this will result in a larger
/// FST, but requires substantially less memory and CPU during building.
/// </param>
/// <param name="doShareNonSingletonNodes">
/// Only used if <paramref name="doShareSuffix"/> is <c>true</c>. Set this to
/// true to ensure FST is fully minimal, at cost of more
/// CPU and more RAM during building.
/// </param>
/// <param name="shareMaxTailLength">
/// Only used if <paramref name="doShareSuffix"/> is <c>true</c>. Set this to
/// <see cref="int.MaxValue"/> to ensure FST is fully minimal, at cost of more
/// CPU and more RAM during building.
/// </param>
/// <param name="outputs"> The output type for each input sequence. Applies only if building an FST. For
/// FSA, use <see cref="NoOutputs.Singleton"/> and <see cref="NoOutputs.NoOutput"/> as the
/// singleton output object.
/// </param>
/// <param name="doPackFST"> Pass <c>true</c> to create a packed FST.
/// </param>
/// <param name="acceptableOverheadRatio"> How to trade speed for space when building the FST. this option
/// is only relevant when doPackFST is true. <see cref="PackedInt32s.GetMutable(int, int, float)"/>
/// </param>
/// <param name="allowArrayArcs"> Pass false to disable the array arc optimization
/// while building the FST; this will make the resulting
/// FST smaller but slower to traverse.
/// </param>
/// <param name="bytesPageBits"> How many bits wide to make each
/// <see cref="T:byte[]"/> block in the <see cref="BytesStore"/>; if you know the FST
/// will be large then make this larger. For example 15
/// bits = 32768 byte pages. </param>
public Builder(FST.INPUT_TYPE inputType, int minSuffixCount1, int minSuffixCount2, bool doShareSuffix,
bool doShareNonSingletonNodes, int shareMaxTailLength, Outputs<T> outputs,
FreezeTail<T> freezeTail, bool doPackFST, float acceptableOverheadRatio, bool allowArrayArcs,
int bytesPageBits)
{
this.minSuffixCount1 = minSuffixCount1;
this.minSuffixCount2 = minSuffixCount2;
this.freezeTail = freezeTail;
this.doShareNonSingletonNodes = doShareNonSingletonNodes;
this.shareMaxTailLength = shareMaxTailLength;
this.doPackFST = doPackFST;
this.acceptableOverheadRatio = acceptableOverheadRatio;
fst = new FST<T>(inputType, outputs, doPackFST, acceptableOverheadRatio, allowArrayArcs, bytesPageBits);
if (doShareSuffix)
{
dedupHash = new NodeHash<T>(fst, fst.bytes.GetReverseReader(false));
}
else
{
dedupHash = null;
}
NO_OUTPUT = outputs.NoOutput;
UnCompiledNode<T>[] f = (UnCompiledNode<T>[])new UnCompiledNode<T>[10];
frontier = f;
for (int idx = 0; idx < frontier.Length; idx++)
{
frontier[idx] = new UnCompiledNode<T>(this, idx);
}
}
public virtual long TotStateCount
{
get
{
return fst.nodeCount;
}
}
public virtual long TermCount
{
get
{
return frontier[0].InputCount;
}
}
public virtual long MappedStateCount
{
get
{
return dedupHash == null ? 0 : fst.nodeCount;
}
}
private CompiledNode CompileNode(UnCompiledNode<T> nodeIn, int tailLength)
{
long node;
if (dedupHash != null && (doShareNonSingletonNodes || nodeIn.NumArcs <= 1) && tailLength <= shareMaxTailLength)
{
if (nodeIn.NumArcs == 0)
{
node = fst.AddNode(nodeIn);
}
else
{
node = dedupHash.Add(nodeIn);
}
}
else
{
node = fst.AddNode(nodeIn);
}
Debug.Assert(node != -2);
nodeIn.Clear();
CompiledNode fn = new CompiledNode();
fn.Node = node;
return fn;
}
private void DoFreezeTail(int prefixLenPlus1)
{
if (freezeTail != null)
{
// Custom plugin:
freezeTail.Freeze(frontier, prefixLenPlus1, lastInput);
}
else
{
//System.out.println(" compileTail " + prefixLenPlus1);
int downTo = Math.Max(1, prefixLenPlus1);
for (int idx = lastInput.Length; idx >= downTo; idx--)
{
bool doPrune = false;
bool doCompile = false;
UnCompiledNode<T> node = frontier[idx];
UnCompiledNode<T> parent = frontier[idx - 1];
if (node.InputCount < minSuffixCount1)
{
doPrune = true;
doCompile = true;
}
else if (idx > prefixLenPlus1)
{
// prune if parent's inputCount is less than suffixMinCount2
if (parent.InputCount < minSuffixCount2 || (minSuffixCount2 == 1 && parent.InputCount == 1 && idx > 1))
{
// my parent, about to be compiled, doesn't make the cut, so
// I'm definitely pruned
// if minSuffixCount2 is 1, we keep only up
// until the 'distinguished edge', ie we keep only the
// 'divergent' part of the FST. if my parent, about to be
// compiled, has inputCount 1 then we are already past the
// distinguished edge. NOTE: this only works if
// the FST outputs are not "compressible" (simple
// ords ARE compressible).
doPrune = true;
}
else
{
// my parent, about to be compiled, does make the cut, so
// I'm definitely not pruned
doPrune = false;
}
doCompile = true;
}
else
{
// if pruning is disabled (count is 0) we can always
// compile current node
doCompile = minSuffixCount2 == 0;
}
//System.out.println(" label=" + ((char) lastInput.ints[lastInput.offset+idx-1]) + " idx=" + idx + " inputCount=" + frontier[idx].inputCount + " doCompile=" + doCompile + " doPrune=" + doPrune);
if (node.InputCount < minSuffixCount2 || (minSuffixCount2 == 1 && node.InputCount == 1 && idx > 1))
{
// drop all arcs
for (int arcIdx = 0; arcIdx < node.NumArcs; arcIdx++)
{
UnCompiledNode<T> target = (UnCompiledNode<T>)node.Arcs[arcIdx].Target;
target.Clear();
}
node.NumArcs = 0;
}
if (doPrune)
{
// this node doesn't make it -- deref it
node.Clear();
parent.DeleteLast(lastInput.Int32s[lastInput.Offset + idx - 1], node);
}
else
{
if (minSuffixCount2 != 0)
{
CompileAllTargets(node, lastInput.Length - idx);
}
T nextFinalOutput = node.Output;
// We "fake" the node as being final if it has no
// outgoing arcs; in theory we could leave it
// as non-final (the FST can represent this), but
// FSTEnum, Util, etc., have trouble w/ non-final
// dead-end states:
bool isFinal = node.IsFinal || node.NumArcs == 0;
if (doCompile)
{
// this node makes it and we now compile it. first,
// compile any targets that were previously
// undecided:
parent.ReplaceLast(lastInput.Int32s[lastInput.Offset + idx - 1], CompileNode(node, 1 + lastInput.Length - idx), nextFinalOutput, isFinal);
}
else
{
// replaceLast just to install
// nextFinalOutput/isFinal onto the arc
parent.ReplaceLast(lastInput.Int32s[lastInput.Offset + idx - 1], node, nextFinalOutput, isFinal);
// this node will stay in play for now, since we are
// undecided on whether to prune it. later, it
// will be either compiled or pruned, so we must
// allocate a new node:
frontier[idx] = new UnCompiledNode<T>(this, idx);
}
}
}
}
}
// for debugging
/*
private String toString(BytesRef b) {
try {
return b.utf8ToString() + " " + b;
} catch (Throwable t) {
return b.toString();
}
}
*/
/// <summary>
/// It's OK to add the same input twice in a row with
/// different outputs, as long as outputs impls the merge
/// method. Note that input is fully consumed after this
/// method is returned (so caller is free to reuse), but
/// output is not. So if your outputs are changeable (eg
/// <see cref="ByteSequenceOutputs"/> or
/// <see cref="Int32SequenceOutputs"/>) then you cannot reuse across
/// calls.
/// </summary>
public virtual void Add(Int32sRef input, T output)
{
/*
if (DEBUG) {
BytesRef b = new BytesRef(input.length);
for(int x=0;x<input.length;x++) {
b.bytes[x] = (byte) input.ints[x];
}
b.length = input.length;
if (output == NO_OUTPUT) {
System.out.println("\nFST ADD: input=" + toString(b) + " " + b);
} else {
System.out.println("\nFST ADD: input=" + toString(b) + " " + b + " output=" + fst.outputs.outputToString(output));
}
}
*/
// De-dup NO_OUTPUT since it must be a singleton:
if (output.Equals(NO_OUTPUT))
{
output = NO_OUTPUT;
}
Debug.Assert(lastInput.Length == 0 || input.CompareTo(lastInput) >= 0, "inputs are added out of order lastInput=" + lastInput + " vs input=" + input);
Debug.Assert(ValidOutput(output));
//System.out.println("\nadd: " + input);
if (input.Length == 0)
{
// empty input: only allowed as first input. we have
// to special case this because the packed FST
// format cannot represent the empty input since
// 'finalness' is stored on the incoming arc, not on
// the node
frontier[0].InputCount++;
frontier[0].IsFinal = true;
fst.EmptyOutput = output;
return;
}
// compare shared prefix length
int pos1 = 0;
int pos2 = input.Offset;
int pos1Stop = Math.Min(lastInput.Length, input.Length);
while (true)
{
frontier[pos1].InputCount++;
//System.out.println(" incr " + pos1 + " ct=" + frontier[pos1].inputCount + " n=" + frontier[pos1]);
if (pos1 >= pos1Stop || lastInput.Int32s[pos1] != input.Int32s[pos2])
{
break;
}
pos1++;
pos2++;
}
int prefixLenPlus1 = pos1 + 1;
if (frontier.Length < input.Length + 1)
{
UnCompiledNode<T>[] next = new UnCompiledNode<T>[ArrayUtil.Oversize(input.Length + 1, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
Array.Copy(frontier, 0, next, 0, frontier.Length);
for (int idx = frontier.Length; idx < next.Length; idx++)
{
next[idx] = new UnCompiledNode<T>(this, idx);
}
frontier = next;
}
// minimize/compile states from previous input's
// orphan'd suffix
DoFreezeTail(prefixLenPlus1);
// init tail states for current input
for (int idx = prefixLenPlus1; idx <= input.Length; idx++)
{
frontier[idx - 1].AddArc(input.Int32s[input.Offset + idx - 1], frontier[idx]);
frontier[idx].InputCount++;
}
UnCompiledNode<T> lastNode = frontier[input.Length];
if (lastInput.Length != input.Length || prefixLenPlus1 != input.Length + 1)
{
lastNode.IsFinal = true;
lastNode.Output = NO_OUTPUT;
}
// push conflicting outputs forward, only as far as
// needed
for (int idx = 1; idx < prefixLenPlus1; idx++)
{
UnCompiledNode<T> node = frontier[idx];
UnCompiledNode<T> parentNode = frontier[idx - 1];
T lastOutput = parentNode.GetLastOutput(input.Int32s[input.Offset + idx - 1]);
Debug.Assert(ValidOutput(lastOutput));
T commonOutputPrefix;
T wordSuffix;
if (!lastOutput.Equals(NO_OUTPUT))
{
commonOutputPrefix = fst.Outputs.Common(output, lastOutput);
Debug.Assert(ValidOutput(commonOutputPrefix));
wordSuffix = fst.Outputs.Subtract(lastOutput, commonOutputPrefix);
Debug.Assert(ValidOutput(wordSuffix));
parentNode.SetLastOutput(input.Int32s[input.Offset + idx - 1], commonOutputPrefix);
node.PrependOutput(wordSuffix);
}
else
{
commonOutputPrefix = wordSuffix = NO_OUTPUT;
}
output = fst.Outputs.Subtract(output, commonOutputPrefix);
Debug.Assert(ValidOutput(output));
}
if (lastInput.Length == input.Length && prefixLenPlus1 == 1 + input.Length)
{
// same input more than 1 time in a row, mapping to
// multiple outputs
lastNode.Output = fst.Outputs.Merge(lastNode.Output, output);
}
else
{
// this new arc is private to this new input; set its
// arc output to the leftover output:
frontier[prefixLenPlus1 - 1].SetLastOutput(input.Int32s[input.Offset + prefixLenPlus1 - 1], output);
}
// save last input
lastInput.CopyInt32s(input);
//System.out.println(" count[0]=" + frontier[0].inputCount);
}
internal bool ValidOutput(T output)
{
return output.Equals(NO_OUTPUT) || !output.Equals(NO_OUTPUT);
}
/// <summary>
/// Returns final FST. NOTE: this will return null if
/// nothing is accepted by the FST.
/// </summary>
public virtual FST<T> Finish()
{
UnCompiledNode<T> root = frontier[0];
// minimize nodes in the last word's suffix
DoFreezeTail(0);
if (root.InputCount < minSuffixCount1 || root.InputCount < minSuffixCount2 || root.NumArcs == 0)
{
if (fst.emptyOutput == null)
{
return null;
}
else if (minSuffixCount1 > 0 || minSuffixCount2 > 0)
{
// empty string got pruned
return null;
}
}
else
{
if (minSuffixCount2 != 0)
{
CompileAllTargets(root, lastInput.Length);
}
}
//if (DEBUG) System.out.println(" builder.finish root.isFinal=" + root.isFinal + " root.Output=" + root.Output);
fst.Finish(CompileNode(root, lastInput.Length).Node);
if (doPackFST)
{
return fst.Pack(3, Math.Max(10, (int)(fst.NodeCount / 4)), acceptableOverheadRatio);
}
else
{
return fst;
}
}
private void CompileAllTargets(UnCompiledNode<T> node, int tailLength)
{
for (int arcIdx = 0; arcIdx < node.NumArcs; arcIdx++)
{
Arc<T> arc = node.Arcs[arcIdx];
if (!arc.Target.IsCompiled)
{
// not yet compiled
UnCompiledNode<T> n = (UnCompiledNode<T>)arc.Target;
if (n.NumArcs == 0)
{
//System.out.println("seg=" + segment + " FORCE final arc=" + (char) arc.Label);
arc.IsFinal = n.IsFinal = true;
}
arc.Target = CompileNode(n, tailLength - 1);
}
}
}
// LUCENENET specific: moved Arc<S> to Builder type
// NOTE: not many instances of Node or CompiledNode are in
// memory while the FST is being built; it's only the
// current "frontier":
// LUCENENET specific: moved INode to Builder type
public virtual long GetFstSizeInBytes()
{
return fst.GetSizeInBytes();
}
// LUCENENET specific: Moved CompiledNode and UncompiledNode to Builder class
}
/// <summary>
/// LUCENENET specific type used to access nested types of <see cref="Builder{T}"/>
/// without referring to its generic closing type.
/// </summary>
public abstract class Builder
{
internal Builder() { } // Disallow external creation
/// <summary>
/// Expert: this is invoked by Builder whenever a suffix
/// is serialized.
/// </summary>
public abstract class FreezeTail<S>
{
public abstract void Freeze(UnCompiledNode<S>[] frontier, int prefixLenPlus1, Int32sRef prevInput);
}
public interface INode // LUCENENET NOTE: made public rather than internal because it is returned in public types
{
bool IsCompiled { get; }
}
/// <summary>
/// Expert: holds a pending (seen but not yet serialized) arc. </summary>
public class Arc<S>
{
public int Label { get; set; } // really an "unsigned" byte
public INode Target { get; set; }
public bool IsFinal { get; set; }
public S Output { get; set; }
public S NextFinalOutput { get; set; }
}
public sealed class CompiledNode : INode
{
public long Node { get; set; }
public bool IsCompiled
{
get
{
return true;
}
}
}
/// <summary>
/// Expert: holds a pending (seen but not yet serialized) Node. </summary>
public sealed class UnCompiledNode<S> : INode
{
internal Builder<S> Owner { get; private set; }
public int NumArcs { get; set; }
[WritableArray]
[SuppressMessage("Microsoft.Performance", "CA1819", Justification = "Lucene's design requires some writable array properties")]
public Arc<S>[] Arcs { get; set; }
// TODO: instead of recording isFinal/output on the
// node, maybe we should use -1 arc to mean "end" (like
// we do when reading the FST). Would simplify much
// code here...
public S Output { get; set; }
public bool IsFinal { get; set; }
public long InputCount { get; set; }
/// <summary>
/// this node's depth, starting from the automaton root. </summary>
public int Depth { get; private set; }
/// <param name="depth">
/// The node's depth starting from the automaton root. Needed for
/// LUCENE-2934 (node expansion based on conditions other than the
/// fanout size). </param>
public UnCompiledNode(Builder<S> owner, int depth)
{
this.Owner = owner;
Arcs = (Arc<S>[])new Arc<S>[1];
Arcs[0] = new Arc<S>();
Output = owner.NoOutput;
this.Depth = depth;
}
public bool IsCompiled
{
get
{
return false;
}
}
public void Clear()
{
NumArcs = 0;
IsFinal = false;
Output = Owner.NoOutput;
InputCount = 0;
// We don't clear the depth here because it never changes
// for nodes on the frontier (even when reused).
}
public S GetLastOutput(int labelToMatch)
{
Debug.Assert(NumArcs > 0);
Debug.Assert(Arcs[NumArcs - 1].Label == labelToMatch);
return Arcs[NumArcs - 1].Output;
}
public void AddArc(int label, INode target)
{
Debug.Assert(label >= 0);
if (NumArcs != 0)
{
Debug.Assert(label > Arcs[NumArcs - 1].Label, "arc[-1].Label=" + Arcs[NumArcs - 1].Label + " new label=" + label + " numArcs=" + NumArcs);
}
if (NumArcs == Arcs.Length)
{
Arc<S>[] newArcs = new Arc<S>[ArrayUtil.Oversize(NumArcs + 1, RamUsageEstimator.NUM_BYTES_OBJECT_REF)];
Array.Copy(Arcs, 0, newArcs, 0, Arcs.Length);
for (int arcIdx = NumArcs; arcIdx < newArcs.Length; arcIdx++)
{
newArcs[arcIdx] = new Arc<S>();
}
Arcs = newArcs;
}
Arc<S> arc = Arcs[NumArcs++];
arc.Label = label;
arc.Target = target;
arc.Output = arc.NextFinalOutput = Owner.NoOutput;
arc.IsFinal = false;
}
public void ReplaceLast(int labelToMatch, INode target, S nextFinalOutput, bool isFinal)
{
Debug.Assert(NumArcs > 0);
Arc<S> arc = Arcs[NumArcs - 1];
Debug.Assert(arc.Label == labelToMatch, "arc.Label=" + arc.Label + " vs " + labelToMatch);
arc.Target = target;
//assert target.Node != -2;
arc.NextFinalOutput = nextFinalOutput;
arc.IsFinal = isFinal;
}
public void DeleteLast(int label, INode target)
{
Debug.Assert(NumArcs > 0);
Debug.Assert(label == Arcs[NumArcs - 1].Label);
Debug.Assert(target == Arcs[NumArcs - 1].Target);
NumArcs--;
}
public void SetLastOutput(int labelToMatch, S newOutput)
{
Debug.Assert(Owner.ValidOutput(newOutput));
Debug.Assert(NumArcs > 0);
Arc<S> arc = Arcs[NumArcs - 1];
Debug.Assert(arc.Label == labelToMatch);
arc.Output = newOutput;
}
// pushes an output prefix forward onto all arcs
public void PrependOutput(S outputPrefix)
{
Debug.Assert(Owner.ValidOutput(outputPrefix));
for (int arcIdx = 0; arcIdx < NumArcs; arcIdx++)
{
Arcs[arcIdx].Output = Owner.Fst.Outputs.Add(outputPrefix, Arcs[arcIdx].Output);
Debug.Assert(Owner.ValidOutput(Arcs[arcIdx].Output));
}
if (IsFinal)
{
Output = Owner.Fst.Outputs.Add(outputPrefix, Output);
Debug.Assert(Owner.ValidOutput(Output));
}
}
}
}
}
| |
/*
| Version 10.1.1
| Copyright 2012 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.Collections.Generic;
using System.Text;
using ESRI.ArcGIS.Geodatabase;
using Esri_Telecom_Tools.Core.Wrappers;
using Esri_Telecom_Tools.Core;
using Esri_Telecom_Tools.Core.Utils;
using ESRI.ArcGIS.Editor;
namespace Esri_Telecom_Tools.Helpers
{
/// <summary>
/// This class does all the real work so that we can change the UI more easily if necessary
/// </summary>
public class FiberSpliceHelper
{
private static FiberSpliceHelper _instance = null;
private LogHelper _logHelper = LogHelper.Instance();
private TelecomWorkspaceHelper _wkspHelper = TelecomWorkspaceHelper.Instance();
private HookHelperExt _hookHelper = null;
private IEditor3 _editor = null;
/// <summary>
/// Constructs a new FiberSpliceConfigHelper
/// </summary>
/// <param name="hook">Hook</param>
/// <param name="editor">Editor</param>
public FiberSpliceHelper(HookHelperExt hookHelper, IEditor3 editor)
// : base(hook)
// : base(hook, editor)
{
_hookHelper = hookHelper;
_editor = editor;
}
//public static FiberSpliceConnectionHelper Instance(object hook, ESRI.ArcGIS.Editor.IEditor editor)
//{
// if (_instance != null)
// {
// return _instance;
// }
// else
// {
// _instance = new FiberSpliceConnectionHelper(hook, editor);
// return _instance;
// }
//}
/// <summary>
/// Gets a list of cable features that are connected to the splice closure in the geometric network
/// </summary>
/// <param name="spliceClosure">Splice to check</param>
/// <returns>List of IFeature</returns>
public List<ESRI.ArcGIS.Geodatabase.IFeature> GetConnectedCables(SpliceClosureWrapper spliceClosure)
{
// At the time of this comment, splicable means they are connected in the
// geometric network and the splice closure "touches" one of the ends of the cable
List<ESRI.ArcGIS.Geodatabase.IFeature> result = new List<ESRI.ArcGIS.Geodatabase.IFeature>();
if (null == spliceClosure)
{
throw new ArgumentNullException("spliceClosure");
}
ESRI.ArcGIS.Geometry.IRelationalOperator relOp = spliceClosure.Feature.Shape as ESRI.ArcGIS.Geometry.IRelationalOperator;
if (relOp == null)
throw new ArgumentNullException("spliceClosure");
ESRI.ArcGIS.Geodatabase.ISimpleJunctionFeature junction = spliceClosure.Feature as ESRI.ArcGIS.Geodatabase.ISimpleJunctionFeature;
if (null != junction)
{
for (int i = 0; i < junction.EdgeFeatureCount; i++)
{
ESRI.ArcGIS.Geodatabase.IFeature connectedEdge = junction.get_EdgeFeature(i) as ESRI.ArcGIS.Geodatabase.IFeature;
ESRI.ArcGIS.Geodatabase.IDataset dataset = connectedEdge.Class as ESRI.ArcGIS.Geodatabase.IDataset;
string ftClassName = GdbUtils.ParseTableName(dataset);
if (0 == string.Compare(ftClassName, ConfigUtil.FiberCableFtClassName, true))
{
// Test feature edge is coincident with splice closure. Cables are
// complex features so splice might lie half way along some cables
// but will not be providing any splice connectivity to them.
if (relOp.Touches(connectedEdge.Shape)) // only true if point at either end of a line
result.Add(connectedEdge);
}
}
}
return result;
}
/// <summary>
/// Gets all cables that are considered splicable to another cable at a given splice closure.
/// </summary>
/// <param name="cable">Cable to splice with</param>
/// <param name="spliceClosure">Splice Closure to splice at</param>
/// <returns>List of SpliceableCableWrapper</returns>
public List<SpliceableCableWrapper> GetSpliceableCables(FiberCableWrapper cable, SpliceClosureWrapper spliceClosure)
{
// At the time of this comment, splicable means they are connected in the geometric network
List<SpliceableCableWrapper> result = new List<SpliceableCableWrapper>();
if (null == cable)
{
throw new ArgumentNullException("cable");
}
if (null == spliceClosure)
{
throw new ArgumentNullException("spliceClosure");
}
int searchOid = cable.Feature.OID;
ESRI.ArcGIS.Geodatabase.IEdgeFeature cableFt = cable.Feature as ESRI.ArcGIS.Geodatabase.IEdgeFeature;
ESRI.ArcGIS.Carto.IFeatureLayer ftLayer = _hookHelper.FindFeatureLayer(ConfigUtil.FiberCableFtClassName);
int displayIdx = ftLayer.FeatureClass.FindField(ftLayer.DisplayField);
if (null != cableFt)
{
// We assume it is simple. Complex junctions are not supported for splicing cables
ESRI.ArcGIS.Geodatabase.ISimpleJunctionFeature junction = spliceClosure.Feature as ESRI.ArcGIS.Geodatabase.ISimpleJunctionFeature;
if (null != junction)
{
bool isAFromEnd = false; // would be in the case that junction.EID == cableFt.ToJunctionEID
if (junction.EID == cableFt.FromJunctionEID)
{
isAFromEnd = true;
}
else if (junction.EID != cableFt.ToJunctionEID)
{
// It isn't the from or the two? It shouldn't have been passed in as if it was coincident with the cable
return result;
// throw new InvalidOperationException("Given splice closure is not the junction for the given cable.");
}
int edgeCount = junction.EdgeFeatureCount;
for (int i = 0; i < edgeCount; i++)
{
ESRI.ArcGIS.Geodatabase.IEdgeFeature connectedEdge = junction.get_EdgeFeature(i);
ESRI.ArcGIS.Geodatabase.IFeature feature = (ESRI.ArcGIS.Geodatabase.IFeature)connectedEdge;
ESRI.ArcGIS.Geodatabase.IDataset dataset = feature.Class as ESRI.ArcGIS.Geodatabase.IDataset;
string featureClassName = GdbUtils.ParseTableName(dataset);
if (0 == string.Compare(featureClassName, ConfigUtil.FiberCableFtClassName)
&& feature.OID != searchOid)
{
if (junction.EID == connectedEdge.FromJunctionEID)
{
result.Add(new SpliceableCableWrapper(feature, true, isAFromEnd, displayIdx));
}
else if (junction.EID == connectedEdge.ToJunctionEID)
{
result.Add(new SpliceableCableWrapper(feature, false, isAFromEnd, displayIdx));
}
}
}
}
}
return result;
}
/// <summary>
/// Deletes all splices for a cable to any other at any splice closure
/// </summary>
/// <param name="cable">Cable</param>
/// <param name="isExistingOperation">Are we already in an edit operation?</param>
/// <returns>Success</returns>
public bool BreakAllSplices(FiberCableWrapper cable, bool isExistingOperation)
{
bool success = false;
bool isOperationOpen = false;
#region Validation
if (null == cable)
{
throw new ArgumentNullException("cable");
}
if (ESRI.ArcGIS.Editor.esriEditState.esriStateNotEditing == _editor.EditState)
{
throw new InvalidOperationException("You must be editing to perform this operation");
}
#endregion
if (!isExistingOperation)
{
_editor.StartOperation();
isOperationOpen = true;
}
try
{
ESRI.ArcGIS.Geodatabase.ITable spliceTable = _wkspHelper.FindTable(ConfigUtil.FiberSpliceTableName);
// ESRI.ArcGIS.Geodatabase.ITable spliceTable = GdbUtils.GetTable(cable.Feature.Class, ConfigUtil.FiberSpliceTableName);
ESRI.ArcGIS.Geodatabase.IQueryFilter filter = new ESRI.ArcGIS.Geodatabase.QueryFilterClass();
// A and B is arbitrary, so we check the given combinations going both ways. The structure is:
// Where either the A or B cableID is our cable ID
filter.WhereClause = string.Format("{0}='{1}' OR {2}='{1}'",
ConfigUtil.ACableIdFieldName,
cable.IPID,
ConfigUtil.BCableIdFieldName);
spliceTable.DeleteSearchedRows(filter);
ESRI.ArcGIS.ADF.ComReleaser.ReleaseCOMObject(filter);
if (isOperationOpen)
{
_editor.StopOperation("Break Splices");
isOperationOpen = false;
}
success = true;
}
catch
{
if (isOperationOpen)
{
_editor.AbortOperation();
}
success = false;
}
return success;
}
/// <summary>
/// Deletes all splices at a splice closure
/// </summary>
/// <param name="splice">Splice</param>
/// <param name="isExistingOperation">Are we already in an edit operation?</param>
/// <returns>Success</returns>
public bool BreakAllSplices(SpliceClosureWrapper splice, bool isExistingOperation)
{
bool success = false;
bool isOperationOpen = false;
#region Validation
if (null == splice)
{
throw new ArgumentNullException("splice");
}
if (ESRI.ArcGIS.Editor.esriEditState.esriStateNotEditing == _editor.EditState)
{
throw new InvalidOperationException("You must be editing to perform this operation");
}
#endregion
if (!isExistingOperation)
{
_editor.StartOperation();
isOperationOpen = true;
}
try
{
ESRI.ArcGIS.Geodatabase.ITable spliceTable = _wkspHelper.FindTable(ConfigUtil.FiberSpliceTableName);
// ESRI.ArcGIS.Geodatabase.ITable spliceTable = GdbUtils.GetTable(splice.Feature.Class, ConfigUtil.FiberSpliceTableName);
ESRI.ArcGIS.Geodatabase.IQueryFilter filter = new ESRI.ArcGIS.Geodatabase.QueryFilterClass();
// A and B is arbitrary, so we check the given combinations going both ways. The structure is:
// Where either the A or B cableID is our cable ID
filter.WhereClause = string.Format("{0}='{1}'",
ConfigUtil.SpliceClosureIpidFieldName,
splice.IPID);
spliceTable.DeleteSearchedRows(filter);
ESRI.ArcGIS.ADF.ComReleaser.ReleaseCOMObject(filter);
if (isOperationOpen)
{
_editor.StopOperation("Break Splices");
isOperationOpen = false;
}
success = true;
}
catch
{
if (isOperationOpen)
{
_editor.AbortOperation();
}
success = false;
}
return success;
}
/// <summary>
/// Deletes given splices from one cable to the other, at a given splice closure
/// </summary>
/// <param name="cableA">Cable A</param>
/// <param name="cableB">Cable B</param>
/// <param name="splice">Splice Closure</param>
/// <param name="strands">Strands to remove</param>
/// <param name="isExistingOperation">Flag to control whether we need to wrap this in an edit operation</param>
/// <returns>Success</returns>
public bool BreakSplices(FiberCableWrapper cableA, SpliceableCableWrapper cableB, SpliceClosureWrapper splice, Dictionary<int,FiberSplice> strands, bool isExistingOperation)
{
bool success = false;
bool isOperationOpen = false;
#region Validation
if (null == cableA)
{
throw new ArgumentNullException("cableA");
}
if (null == cableB)
{
throw new ArgumentNullException("cableB");
}
if (null == splice)
{
throw new ArgumentNullException("splice");
}
if (ESRI.ArcGIS.Editor.esriEditState.esriStateNotEditing == _editor.EditState)
{
throw new InvalidOperationException("You must be editing to perform this operation");
}
#endregion
if (!isExistingOperation)
{
_editor.StartOperation();
isOperationOpen = true;
}
try
{
ESRI.ArcGIS.Geodatabase.ITable spliceTable = _wkspHelper.FindTable(ConfigUtil.FiberSpliceTableName);
// ESRI.ArcGIS.Geodatabase.ITable spliceTable = GdbUtils.GetTable(splice.Feature.Class, ConfigUtil.FiberSpliceTableName);
using (ESRI.ArcGIS.ADF.ComReleaser releaser = new ESRI.ArcGIS.ADF.ComReleaser())
{
ESRI.ArcGIS.Geodatabase.IQueryFilter filter = new ESRI.ArcGIS.Geodatabase.QueryFilterClass();
releaser.ManageLifetime(filter);
// A and B is arbitrary, so we check the given combinations going both ways. The structure is:
// Where the splice closure IPID is ours and
// ((the A Cable/Fiber matches our A cable and B Cable/Fiber matches our B)
// OR (the A Cable/Fiber matches our B cable and B Cable/Fiber matches our A))
string format = "{0}='{1}' AND (({2}='{3}' AND {4}={5} AND {6}='{7}' AND {8}={9})" +
" OR ({2}='{7}' AND {4}={9} AND {6}='{3}' AND {8}={5}))";
foreach (KeyValuePair<int, FiberSplice> pair in strands)
{
filter.WhereClause = string.Format(format,
ConfigUtil.SpliceClosureIpidFieldName,
splice.IPID,
ConfigUtil.ACableIdFieldName,
cableA.IPID,
ConfigUtil.AFiberNumberFieldName,
pair.Key,
ConfigUtil.BCableIdFieldName,
cableB.IPID,
ConfigUtil.BFiberNumberFieldName,
pair.Value.BRange.Low);
spliceTable.DeleteSearchedRows(filter);
}
if (isOperationOpen)
{
_editor.StopOperation("Break Splices");
isOperationOpen = false;
}
success = true;
}
}
catch
{
if (isOperationOpen)
{
_editor.AbortOperation();
}
success = false;
}
return success;
}
/// <summary>
/// Splices all available strands from one cable to the other, at a given splice closure
/// </summary>
/// <param name="cableA">Cable A</param>
/// <param name="cableB">Cable B</param>
/// <param name="splice">Splice Closure</param>
/// <param name="strands">Strands to splice together</param>
/// <param name="isExistingOperation">Flag to control whether we need to wrap this in an edit operation</param>
/// <returns>Success</returns>
public bool CreateSplices(FiberCableWrapper cableA, SpliceableCableWrapper cableB, SpliceClosureWrapper splice, Dictionary<int,FiberSplice> strands, bool isExistingOperation)
{
bool success = false;
bool isOperationOpen = false;
#region Validation
if (null == cableA)
{
throw new ArgumentNullException("cableA");
}
if (null == cableB)
{
throw new ArgumentNullException("cableB");
}
if (ESRI.ArcGIS.Editor.esriEditState.esriStateNotEditing == _editor.EditState)
{
throw new InvalidOperationException("You must be editing to perform this operation");
}
#endregion
if (!isExistingOperation)
{
_editor.StartOperation();
isOperationOpen = true;
}
if (null == splice)
{
splice = GenerateSpliceClosure(cableA, cableB);
}
else if (0 == splice.IPID.Length)
{
// Populate an IPID; we will need it
ESRI.ArcGIS.Geodatabase.IFeature spliceFt = splice.Feature;
Guid g = Guid.NewGuid();
spliceFt.set_Value(spliceFt.Fields.FindField(ConfigUtil.IpidFieldName), g.ToString("B").ToUpper());
spliceFt.Store();
}
try
{
ESRI.ArcGIS.Geodatabase.ITable fiberSpliceTable = _wkspHelper.FindTable(ConfigUtil.FiberSpliceTableName);
// ESRI.ArcGIS.Geodatabase.ITable fiberSpliceTable = GdbUtils.GetTable(cableA.Feature.Class, ConfigUtil.FiberSpliceTableName);
int aCableIdx = fiberSpliceTable.FindField(ConfigUtil.ACableIdFieldName);
int bCableIdx = fiberSpliceTable.FindField(ConfigUtil.BCableIdFieldName);
int aFiberNumIdx = fiberSpliceTable.FindField(ConfigUtil.AFiberNumberFieldName);
int bFiberNumIdx = fiberSpliceTable.FindField(ConfigUtil.BFiberNumberFieldName);
int spliceIpidIdx = fiberSpliceTable.FindField(ConfigUtil.SpliceClosureIpidFieldName);
int isAFromIdx = fiberSpliceTable.FindField(ConfigUtil.IsAFromEndFieldName);
int isBFromIdx = fiberSpliceTable.FindField(ConfigUtil.IsBFromEndFieldName);
int lossIdx = fiberSpliceTable.FindField(ConfigUtil.LossFieldName);
int typeIdx = fiberSpliceTable.FindField(ConfigUtil.TypeFieldName);
ESRI.ArcGIS.Geodatabase.IField typeField = fiberSpliceTable.Fields.get_Field(typeIdx);
string aCableId = cableA.IPID;
string bCableId = cableB.IPID;
string isAFromEnd = cableB.IsOtherFromEnd ? "T" : "F";
string isBFromEnd = cableB.IsThisFromEnd ? "T" : "F";
string spliceIpid = splice.IPID;
using (ESRI.ArcGIS.ADF.ComReleaser releaser = new ESRI.ArcGIS.ADF.ComReleaser())
{
// TODO cant use insert cursor since edit events wont fire.
// We need evetns to fire for dynamic values to get populated.
// ESRI.ArcGIS.Geodatabase.ICursor insertCursor = fiberSpliceTable.Insert(true);
// releaser.ManageLifetime(insertCursor);
foreach (KeyValuePair<int, FiberSplice> pair in strands)
{
IRow row = fiberSpliceTable.CreateRow();
releaser.ManageLifetime(row);
FiberSplice fiberSplice = pair.Value;
row.set_Value(aCableIdx, aCableId);
row.set_Value(bCableIdx, bCableId);
row.set_Value(aFiberNumIdx, pair.Key);
row.set_Value(bFiberNumIdx, fiberSplice.BRange.Low);
row.set_Value(spliceIpidIdx, spliceIpid);
row.set_Value(isAFromIdx, isAFromEnd);
row.set_Value(isBFromIdx, isBFromEnd);
if (null == fiberSplice.Loss)
{
row.set_Value(lossIdx, DBNull.Value);
}
else
{
row.set_Value(lossIdx, fiberSplice.Loss);
}
object typeValue = DBNull.Value;
if (null != fiberSplice.Type)
{
try
{
typeValue = GdbUtils.CheckForCodedValue(typeField, fiberSplice.Type);
}
catch
{
// TODO: Log a warning about why we can't set the default split splice type?
}
}
row.set_Value(typeIdx, typeValue);
row.Store();
}
}
if (isOperationOpen)
{
_editor.StopOperation("Edit Splices");
}
success = true;
}
catch
{
if (isOperationOpen)
{
_editor.AbortOperation();
}
success = false;
}
return success;
}
/// <summary>
/// Generates a splice closure at the coincident endpoint. Does not start an edit operation.
/// </summary>
/// <param name="cableA">Cable A</param>
/// <param name="cableB">Cable B</param>
/// <returns>SpliceClosureWRapper based on new feature</returns>
private SpliceClosureWrapper GenerateSpliceClosure(FiberCableWrapper cableA, SpliceableCableWrapper cableB)
{
SpliceClosureWrapper wrapper = null;
#region Validation
if (null == cableA)
{
throw new ArgumentNullException("cableA");
}
if (null == cableB)
{
throw new ArgumentNullException("cableB");
}
if (ESRI.ArcGIS.Editor.esriEditState.esriStateNotEditing == _editor.EditState)
{
throw new InvalidOperationException("You must be editing to perform this operation");
}
#endregion
// Populate an IPID; we will need it
Guid g = Guid.NewGuid();
string spliceIpid = g.ToString("B").ToUpper();
try
{
ESRI.ArcGIS.Geometry.IPolyline line = cableB.Feature.Shape as ESRI.ArcGIS.Geometry.IPolyline;
if (null != line)
{
ESRI.ArcGIS.Geometry.IPoint splicePoint = null;
if (cableB.IsThisFromEnd)
{
splicePoint = line.FromPoint;
}
else
{
splicePoint = line.ToPoint;
}
ESRI.ArcGIS.Geodatabase.IFeatureClass spliceClosureFtClass = _wkspHelper.FindFeatureClass(ConfigUtil.SpliceClosureFtClassName);
// ESRI.ArcGIS.Geodatabase.IFeatureClass spliceClosureFtClass = GdbUtils.GetFeatureClass(cableA.Feature.Class, ConfigUtil.SpliceClosureFtClassName);
ESRI.ArcGIS.Geodatabase.IFeature spliceFt = spliceClosureFtClass.CreateFeature();
spliceFt.Shape = splicePoint;
spliceFt.set_Value(spliceClosureFtClass.Fields.FindField(ConfigUtil.IpidFieldName), spliceIpid);
spliceFt.Store();
wrapper = new SpliceClosureWrapper(spliceFt);
}
}
catch
{
wrapper = null;
}
return wrapper;
}
}
}
| |
using System;
using System.IO;
using System.Linq;
using System.Threading;
using NUnit.Framework;
using SIL.TestUtilities;
using Is = SIL.TestUtilities.NUnitExtensions.Is;
namespace SIL.WritingSystems.Tests
{
[TestFixture]
public class GlobalWritingSystemRepositoryTests
{
private static TemporaryFolder CreateTemporaryFolder(string testName)
{
return new TemporaryFolder($"{testName}_{Path.GetRandomFileName()}");
}
[Test]
public void DefaultInitializer_HasCorrectPath()
{
GlobalWritingSystemRepository repo = GlobalWritingSystemRepository.Initialize();
string expectedPath = string.Format(".*SIL.WritingSystemRepository.{0}",
LdmlDataMapper.CurrentLdmlLibraryVersion);
Assert.That(repo.PathToWritingSystems, Does.Match(expectedPath));
}
[Test]
public void Initialize_SkipsBadFile()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
string versionPath = Path.Combine(e.Path, LdmlDataMapper.CurrentLdmlLibraryVersion.ToString());
Directory.CreateDirectory(versionPath);
string badFile = Path.Combine(versionPath, "en.ldml");
File.WriteAllBytes(badFile, new byte[100]); // 100 nulls
var repo = GlobalWritingSystemRepository.InitializeWithBasePath(e.Path, null);
// main part of test is that we don't get any exception.
Assert.That(repo.Count, Is.EqualTo(1));
// original .ldml file should have been renamed
Assert.That(File.Exists(badFile), Is.False);
Assert.That(File.Exists(badFile + ".bad"), Is.True);
}
}
[Test]
public void Initialize_SkipsBadFile_DataProblemInLDMLIdentity()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var versionPath = Path.Combine(e.Path, LdmlDataMapper.CurrentLdmlLibraryVersion.ToString());
Directory.CreateDirectory(versionPath);
var badFile = Path.Combine(versionPath, "en.ldml");
const string ldmlData = @"<?xml version='1.0' encoding='utf-8'?>
<ldml>
<identity>
<version number=''/>
<generation date='2020-02-28T18:43:36Z'/>
<language type=''/>
<special xmlns:sil='urn://www.sil.org/ldml/0.1'>
<sil:identity windowsLCID='1033'/>
</special>
</identity>
</ldml>";
File.WriteAllText(badFile, ldmlData);
var repo = GlobalWritingSystemRepository.InitializeWithBasePath(e.Path, null);
// main part of test is that we don't get any exception.
Assert.That(repo.Count, Is.EqualTo(1));
// original .ldml file should have been renamed
Assert.That(File.Exists(badFile), Is.False);
Assert.That(File.Exists(badFile + ".bad"), Is.True);
Assert.That(File.Exists(Path.Combine(versionPath, "badldml.log")), Is.True);
}
}
[Test]
public void Initialize_SkipsBadFile_DataProblemInLDMLFont()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var versionPath = Path.Combine(e.Path, LdmlDataMapper.CurrentLdmlLibraryVersion.ToString());
Directory.CreateDirectory(versionPath);
var badFile = Path.Combine(versionPath, "en.ldml");
const string ldmlData = @"<?xml version='1.0' encoding='utf-8'?>
<ldml>
<identity>
<version number=''/>
<generation date='2020-02-28T18:43:36Z'/>
<language type='en'/>
<special xmlns:sil='urn://www.sil.org/ldml/0.1'>
<sil:identity windowsLCID='1033'/>
</special>
</identity>
<special xmlns:sil='urn://www.sil.org/ldml/0.1'>
<sil:external-resources>
<sil:font name='Amdo Classic 1' types='kaboom' />
</sil:external-resources>
</special>
</ldml>";
File.WriteAllText(badFile, ldmlData);
var repo = GlobalWritingSystemRepository.InitializeWithBasePath(e.Path, null);
// main part of test is that we don't get any exception.
Assert.That(repo.Count, Is.EqualTo(0));
// original .ldml file should have been renamed
Assert.That(File.Exists(badFile), Is.False);
Assert.That(File.Exists(badFile + ".bad"), Is.True);
Assert.That(File.Exists(Path.Combine(versionPath, "badldml.log")), Is.True);
}
}
[Test]
public void PathConstructor_HasCorrectPath()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo = new GlobalWritingSystemRepository(e.Path);
Assert.That(repo.PathToWritingSystems,
Does.Match($".*PathConstructor_HasCorrectPath.*{LdmlDataMapper.CurrentLdmlLibraryVersion}"));
}
}
[Test]
public void Constructor_CreatesFolders()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo = new GlobalWritingSystemRepository(e.Path);
Assert.That(Directory.Exists(repo.PathToWritingSystems), Is.True);
}
}
[Test]
public void Constructor_WithExistingFolders_NoThrow()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
new GlobalWritingSystemRepository(e.Path);
var repo2 = new GlobalWritingSystemRepository(e.Path);
Assert.That(Directory.Exists(repo2.PathToWritingSystems), Is.True);
}
}
[Test]
public void Set_NewWritingSystem_SetsId()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo = new GlobalWritingSystemRepository(e.Path);
var ws = new WritingSystemDefinition("en-US");
Assert.That(ws.Id, Is.Null);
repo.Set(ws);
Assert.That(ws.Id, Is.EqualTo("en-US"));
}
}
[Test]
public void Save_NewWritingSystem_CreatesLdmlFile()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo = new GlobalWritingSystemRepository(e.Path);
var ws = new WritingSystemDefinition("en-US");
repo.Set(ws);
repo.Save();
Assert.That(File.Exists(repo.GetFilePathFromLanguageTag("en-US")), Is.True);
}
}
[Test]
public void Save_DeletedWritingSystem_RemovesLdmlFile()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo = new GlobalWritingSystemRepository(e.Path);
var ws = new WritingSystemDefinition("en-US");
repo.Set(ws);
repo.Save();
Assert.That(File.Exists(repo.GetFilePathFromLanguageTag("en-US")), Is.True);
ws.MarkedForDeletion = true;
repo.Save();
Assert.That(File.Exists(repo.GetFilePathFromLanguageTag("en-US")), Is.False);
}
}
[Test]
public void Save_UpdatedWritingSystem_UpdatesLdmlFile()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo = new GlobalWritingSystemRepository(e.Path);
var ws = new WritingSystemDefinition("en-US");
repo.Set(ws);
repo.Save();
DateTime modified = File.GetLastWriteTime(repo.GetFilePathFromLanguageTag("en-US"));
// ensure that last modified timestamp changes
Thread.Sleep(1000);
ws.WindowsLcid = "test";
repo.Save();
Assert.That(File.GetLastWriteTime(repo.GetFilePathFromLanguageTag("en-US")), Is.Not.EqualTo(modified));
}
}
[Test]
public void Save_ChangingIcuSort_DoesNotDuplicateInLdmlFile()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo = new GlobalWritingSystemRepository(e.Path);
var ws = new WritingSystemDefinition("en-US");
ws.Collations.Add(new IcuRulesCollationDefinition("standard") { IcuRules = "&b < a" });
repo.Set(ws);
repo.Save();
// ensure that last modified timestamp changes
Thread.Sleep(1000);
ws.WindowsLcid = "test";
repo.Save();
AssertThatXmlIn.File(repo.GetFilePathFromLanguageTag("en-US")).HasSpecifiedNumberOfMatchesForXpath("/ldml/collations/collation", 1);
}
}
[Test]
public void Get_LdmlAddedByAnotherRepo_ReturnsDefinition()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo1 = new GlobalWritingSystemRepository(e.Path);
var repo2 = new GlobalWritingSystemRepository(e.Path);
Assert.That(() => repo2.Get("en-US"), Throws.TypeOf<ArgumentOutOfRangeException>());
var ws = new WritingSystemDefinition("en-US");
repo1.Set(ws);
repo1.Save();
Assert.That(File.Exists(repo1.GetFilePathFromLanguageTag("en-US")), Is.True);
Assert.That(repo2.Get("en-US").LanguageTag, Is.EqualTo("en-US"));
}
}
[Test]
public void Get_LdmlRemovedByAnotherRepo_Throws()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo1 = new GlobalWritingSystemRepository(e.Path);
var repo2 = new GlobalWritingSystemRepository(e.Path);
var ws = new WritingSystemDefinition("en-US");
repo1.Set(ws);
repo1.Save();
Assert.That(repo1.Get("en-US").LanguageTag, Is.EqualTo("en-US"));
repo2.Remove("en-US");
Assert.That(() => repo1.Get("en-US"), Throws.TypeOf<ArgumentOutOfRangeException>());
}
}
[Test]
public void Get_LdmlUpdatedByAnotherRepo_ReturnsUpdatedDefinition()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo1 = new GlobalWritingSystemRepository(e.Path);
var repo2 = new GlobalWritingSystemRepository(e.Path);
var ws = new WritingSystemDefinition("en-US");
repo1.Set(ws);
repo1.Save();
Assert.That(ws.WindowsLcid, Is.Empty);
// ensure that last modified timestamp changes
Thread.Sleep(1000);
ws = repo2.Get("en-US");
ws.WindowsLcid = "test";
repo2.Save();
Assert.That(repo1.Get("en-US").WindowsLcid, Is.EqualTo("test"));
}
}
[Test]
public void Get_UpdatedLdmlRemovedByAnotherRepo_ReturnUpdatedDefinition()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo1 = new GlobalWritingSystemRepository(e.Path);
var repo2 = new GlobalWritingSystemRepository(e.Path);
var ws = new WritingSystemDefinition("en-US");
repo1.Set(ws);
repo1.Save();
Assert.That(repo1.Get("en-US").LanguageTag, Is.EqualTo("en-US"));
repo2.Remove("en-US");
ws.WindowsLcid = "test";
Assert.That(repo1.Get("en-US").WindowsLcid, Is.EqualTo("test"));
}
}
[Test]
public void Get_UpdatedLdmlUpdatedByAnotherRepo_ReturnLastUpdatedDefinition()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo1 = new GlobalWritingSystemRepository(e.Path);
var repo2 = new GlobalWritingSystemRepository(e.Path);
var ws = new WritingSystemDefinition("en-US");
repo1.Set(ws);
repo1.Save();
Assert.That(repo1.Get("en-US").LanguageTag, Is.EqualTo("en-US"));
WritingSystemDefinition ws2 = repo2.Get("en-US");
ws2.WindowsLcid = "test2";
repo2.Save();
ws.WindowsLcid = "test1";
Assert.That(repo1.Get("en-US").WindowsLcid, Is.EqualTo("test1"));
}
}
// LF-297
[TestCase("en-US")]
[TestCase("en-us")]
[Platform(Include = "Linux", Reason = "Requires a case-sensitive file system")]
public void Get_CaseDifferingWritingSystems_DoesNotThrow(string id)
{
using (var temporaryFolder = CreateTemporaryFolder("Get_CaseDifferingWritingSystems_DoesNotThrow"))
{
// Setup
var repo = new GlobalWritingSystemRepository(temporaryFolder.Path);
var ws = new WritingSystemDefinition("en-US");
repo.Set(ws);
repo.Save();
// Now we simulate that the user did a S/R which added a WS that differs by case
File.Copy(Path.Combine(temporaryFolder.Path, "3", ws.Id + ".ldml"),
Path.Combine(temporaryFolder.Path, "3", ws.Id.ToLower() + ".ldml"));
// SUT/Verify
Assert.That(() => repo.Get(id), Throws.Nothing);
}
}
[TestCase("en-US")]
[TestCase("en-us")]
public void Remove_CaseDifferingWritingSystems_DoesNotThrow(string id)
{
using (var temporaryFolder = CreateTemporaryFolder("Remove_CaseDifferingWritingSystems_DoesNotThrow"))
{
// Setup
var repo = new GlobalWritingSystemRepository(temporaryFolder.Path);
var ws = new WritingSystemDefinition("en-US");
repo.Set(ws);
repo.Save();
// SUT
Assert.That(() => repo.Remove(id), Throws.Nothing);
// Verify
Assert.That(repo.Contains("en-US"), Is.False);
Assert.That(repo.Contains("en-us"), Is.False);
Assert.That(File.Exists(Path.Combine(temporaryFolder.Path, "3", "en-US.ldml")),
Is.False);
Assert.That(File.Exists(Path.Combine(temporaryFolder.Path, "3", "en-us.ldml")),
Is.False);
}
}
[Test]
public void AllWritingSystems_LdmlAddedByAnotherRepo_ReturnsDefinition()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo1 = new GlobalWritingSystemRepository(e.Path);
var repo2 = new GlobalWritingSystemRepository(e.Path);
Assert.That(repo2.AllWritingSystems, Is.Empty);
var ws = new WritingSystemDefinition("en-US");
repo1.Set(ws);
repo1.Save();
Assert.That(File.Exists(repo1.GetFilePathFromLanguageTag("en-US")), Is.True);
Assert.That(repo2.AllWritingSystems.First().LanguageTag, Is.EqualTo("en-US"));
}
}
[Test]
public void AllWritingSystems_LdmlRemovedByAnotherRepo_ReturnsEmpty()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo1 = new GlobalWritingSystemRepository(e.Path);
var repo2 = new GlobalWritingSystemRepository(e.Path);
var ws = new WritingSystemDefinition("en-US");
repo1.Set(ws);
repo1.Save();
Assert.That(repo1.AllWritingSystems, Is.Not.Empty);
repo2.Remove("en-US");
Assert.That(repo1.AllWritingSystems, Is.Empty);
}
}
[Test]
public void AllWritingSystems_LdmlUpdatedByAnotherRepo_ReturnsUpdatedDefinition()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo1 = new GlobalWritingSystemRepository(e.Path);
var repo2 = new GlobalWritingSystemRepository(e.Path);
var ws = new WritingSystemDefinition("en-US");
repo1.Set(ws);
repo1.Save();
Assert.That(ws.WindowsLcid, Is.Empty);
ws = repo2.Get("en-US");
ws.WindowsLcid = "test";
repo2.Save();
Assert.That(repo2.AllWritingSystems.First().WindowsLcid, Is.EqualTo("test"));
}
}
[Test]
public void Count_LdmlAddedByAnotherRepo_ReturnsOne()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo1 = new GlobalWritingSystemRepository(e.Path);
var repo2 = new GlobalWritingSystemRepository(e.Path);
Assert.That(repo2.Count, Is.EqualTo(0));
var ws = new WritingSystemDefinition("en-US");
repo1.Set(ws);
repo1.Save();
Assert.That(File.Exists(repo1.GetFilePathFromLanguageTag("en-US")), Is.True);
Assert.That(repo2.Count, Is.EqualTo(1));
}
}
[Test]
public void Count_LdmlRemovedByAnotherRepo_ReturnsZero()
{
using (var e = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo1 = new GlobalWritingSystemRepository(e.Path);
var repo2 = new GlobalWritingSystemRepository(e.Path);
var ws = new WritingSystemDefinition("en-US");
repo1.Set(ws);
repo1.Save();
Assert.That(repo1.Count, Is.EqualTo(1));
repo2.Remove("en-US");
Assert.That(repo1.Count, Is.EqualTo(0));
}
}
[Test]
public void AllWritingSystems_LdmlCheckingSetEmptyCanNotSave()
{
using (var tf = CreateTemporaryFolder(TestContext.CurrentContext.Test.Name))
{
var repo1 = new GlobalWritingSystemRepository(tf.Path);
var repo2 = new GlobalWritingSystemRepository(tf.Path);
var ws = new WritingSystemDefinition("en-US");
repo1.Set(ws);
repo1.Save();
Assert.That(ws.WindowsLcid, Is.Empty);
// ensure that last modified timestamp changes
Thread.Sleep(1000);
ws = repo2.Get("en-US");
ws.WindowsLcid = "test";
// a ws with an empty Id is assumed to be new, we can't save it if the LanguageTag is already found
// in the repo.
ws.Id = string.Empty;
Assert.That(repo2.CanSet(ws), Is.False, "A ws with an empty ID will not save if the LanguageTag matches an existing ws");
repo2.Save();
Assert.That(repo1.Get("en-US").WindowsLcid, Is.Not.EqualTo("test"), "Changes should not have been saved.");
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reactive.Threading.Tasks;
using System.Runtime.CompilerServices;
using MS.Core;
namespace System.Threading.Tasks
{
public static class __Task1
{
public static IObservable<TaskAwaiter<TResult>> GetAwaiter<TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue)
{
return Observable.Select(TaskValue, (TaskValueLambda) => TaskValueLambda.GetAwaiter());
}
public static IObservable<ConfiguredTaskAwaitable<TResult>> ConfigureAwait<TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<System.Boolean> continueOnCapturedContext)
{
return Observable.Zip(TaskValue, continueOnCapturedContext,
(TaskValueLambda, continueOnCapturedContextLambda) =>
TaskValueLambda.ConfigureAwait(continueOnCapturedContextLambda));
}
public static IObservable<System.Reactive.Unit> ContinueWith<TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Action<System.Threading.Tasks.Task<TResult>>> continuationAction)
{
return
Observable.Zip(TaskValue, continuationAction,
(TaskValueLambda, continuationActionLambda) =>
TaskValueLambda.ContinueWith(continuationActionLambda).ToObservable()).Flatten();
}
public static IObservable<System.Reactive.Unit> ContinueWith<TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Action<System.Threading.Tasks.Task<TResult>>> continuationAction,
IObservable<System.Threading.CancellationToken> cancellationToken)
{
return
Observable.Zip(TaskValue, continuationAction, cancellationToken,
(TaskValueLambda, continuationActionLambda, cancellationTokenLambda) =>
TaskValueLambda.ContinueWith(continuationActionLambda, cancellationTokenLambda).ToObservable())
.Flatten();
}
public static IObservable<System.Reactive.Unit> ContinueWith<TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Action<System.Threading.Tasks.Task<TResult>>> continuationAction,
IObservable<System.Threading.Tasks.TaskScheduler> scheduler)
{
return
Observable.Zip(TaskValue, continuationAction, scheduler,
(TaskValueLambda, continuationActionLambda, schedulerLambda) =>
TaskValueLambda.ContinueWith(continuationActionLambda, schedulerLambda).ToObservable())
.Flatten();
}
public static IObservable<System.Reactive.Unit> ContinueWith<TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Action<System.Threading.Tasks.Task<TResult>>> continuationAction,
IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions)
{
return
Observable.Zip(TaskValue, continuationAction, continuationOptions,
(TaskValueLambda, continuationActionLambda, continuationOptionsLambda) =>
TaskValueLambda.ContinueWith(continuationActionLambda, continuationOptionsLambda).ToObservable())
.Flatten();
}
public static IObservable<System.Reactive.Unit> ContinueWith<TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Action<System.Threading.Tasks.Task<TResult>>> continuationAction,
IObservable<System.Threading.CancellationToken> cancellationToken,
IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions,
IObservable<System.Threading.Tasks.TaskScheduler> scheduler)
{
return
Observable.Zip(TaskValue, continuationAction, cancellationToken, continuationOptions, scheduler,
(TaskValueLambda, continuationActionLambda, cancellationTokenLambda, continuationOptionsLambda,
schedulerLambda) =>
TaskValueLambda.ContinueWith(continuationActionLambda, cancellationTokenLambda,
continuationOptionsLambda, schedulerLambda).ToObservable()).Flatten();
}
public static IObservable<System.Reactive.Unit> ContinueWith<TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Action<System.Threading.Tasks.Task<TResult>, System.Object>> continuationAction,
IObservable<System.Object> state)
{
return
Observable.Zip(TaskValue, continuationAction, state,
(TaskValueLambda, continuationActionLambda, stateLambda) =>
TaskValueLambda.ContinueWith(continuationActionLambda, stateLambda).ToObservable()).Flatten();
}
public static IObservable<System.Reactive.Unit> ContinueWith<TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Action<System.Threading.Tasks.Task<TResult>, System.Object>> continuationAction,
IObservable<System.Object> state, IObservable<System.Threading.CancellationToken> cancellationToken)
{
return
Observable.Zip(TaskValue, continuationAction, state, cancellationToken,
(TaskValueLambda, continuationActionLambda, stateLambda, cancellationTokenLambda) =>
TaskValueLambda.ContinueWith(continuationActionLambda, stateLambda, cancellationTokenLambda)
.ToObservable()).Flatten();
}
public static IObservable<System.Reactive.Unit> ContinueWith<TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Action<System.Threading.Tasks.Task<TResult>, System.Object>> continuationAction,
IObservable<System.Object> state, IObservable<System.Threading.Tasks.TaskScheduler> scheduler)
{
return
Observable.Zip(TaskValue, continuationAction, state, scheduler,
(TaskValueLambda, continuationActionLambda, stateLambda, schedulerLambda) =>
TaskValueLambda.ContinueWith(continuationActionLambda, stateLambda, schedulerLambda)
.ToObservable()).Flatten();
}
public static IObservable<System.Reactive.Unit> ContinueWith<TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Action<System.Threading.Tasks.Task<TResult>, System.Object>> continuationAction,
IObservable<System.Object> state,
IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions)
{
return
Observable.Zip(TaskValue, continuationAction, state, continuationOptions,
(TaskValueLambda, continuationActionLambda, stateLambda, continuationOptionsLambda) =>
TaskValueLambda.ContinueWith(continuationActionLambda, stateLambda, continuationOptionsLambda)
.ToObservable()).Flatten();
}
public static IObservable<System.Reactive.Unit> ContinueWith<TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Action<System.Threading.Tasks.Task<TResult>, System.Object>> continuationAction,
IObservable<System.Object> state, IObservable<System.Threading.CancellationToken> cancellationToken,
IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions,
IObservable<System.Threading.Tasks.TaskScheduler> scheduler)
{
return
Observable.Zip(TaskValue, continuationAction, state, cancellationToken, continuationOptions, scheduler,
(TaskValueLambda, continuationActionLambda, stateLambda, cancellationTokenLambda,
continuationOptionsLambda, schedulerLambda) =>
TaskValueLambda.ContinueWith(continuationActionLambda, stateLambda, cancellationTokenLambda,
continuationOptionsLambda, schedulerLambda).ToObservable()).Flatten();
}
public static IObservable<TNewResult> ContinueWith<TNewResult, TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Func<System.Threading.Tasks.Task<TResult>, TNewResult>> continuationFunction)
{
return
Observable.Zip(TaskValue, continuationFunction,
(TaskValueLambda, continuationFunctionLambda) =>
TaskValueLambda.ContinueWith(continuationFunctionLambda).ToObservable()).Flatten();
}
public static IObservable<TNewResult> ContinueWith<TNewResult, TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Func<System.Threading.Tasks.Task<TResult>, TNewResult>> continuationFunction,
IObservable<System.Threading.CancellationToken> cancellationToken)
{
return
Observable.Zip(TaskValue, continuationFunction, cancellationToken,
(TaskValueLambda, continuationFunctionLambda, cancellationTokenLambda) =>
TaskValueLambda.ContinueWith(continuationFunctionLambda, cancellationTokenLambda).ToObservable())
.Flatten();
}
public static IObservable<TNewResult> ContinueWith<TNewResult, TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Func<System.Threading.Tasks.Task<TResult>, TNewResult>> continuationFunction,
IObservable<System.Threading.Tasks.TaskScheduler> scheduler)
{
return
Observable.Zip(TaskValue, continuationFunction, scheduler,
(TaskValueLambda, continuationFunctionLambda, schedulerLambda) =>
TaskValueLambda.ContinueWith(continuationFunctionLambda, schedulerLambda).ToObservable())
.Flatten();
}
public static IObservable<TNewResult> ContinueWith<TNewResult, TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Func<System.Threading.Tasks.Task<TResult>, TNewResult>> continuationFunction,
IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions)
{
return
Observable.Zip(TaskValue, continuationFunction, continuationOptions,
(TaskValueLambda, continuationFunctionLambda, continuationOptionsLambda) =>
TaskValueLambda.ContinueWith(continuationFunctionLambda, continuationOptionsLambda)
.ToObservable()).Flatten();
}
public static IObservable<TNewResult> ContinueWith<TNewResult, TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Func<System.Threading.Tasks.Task<TResult>, TNewResult>> continuationFunction,
IObservable<System.Threading.CancellationToken> cancellationToken,
IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions,
IObservable<System.Threading.Tasks.TaskScheduler> scheduler)
{
return
Observable.Zip(TaskValue, continuationFunction, cancellationToken, continuationOptions, scheduler,
(TaskValueLambda, continuationFunctionLambda, cancellationTokenLambda, continuationOptionsLambda,
schedulerLambda) =>
TaskValueLambda.ContinueWith(continuationFunctionLambda, cancellationTokenLambda,
continuationOptionsLambda, schedulerLambda).ToObservable()).Flatten();
}
public static IObservable<TNewResult> ContinueWith<TNewResult, TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Func<System.Threading.Tasks.Task<TResult>, System.Object, TNewResult>> continuationFunction,
IObservable<System.Object> state)
{
return
Observable.Zip(TaskValue, continuationFunction, state,
(TaskValueLambda, continuationFunctionLambda, stateLambda) =>
TaskValueLambda.ContinueWith(continuationFunctionLambda, stateLambda).ToObservable()).Flatten();
}
public static IObservable<TNewResult> ContinueWith<TNewResult, TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Func<System.Threading.Tasks.Task<TResult>, System.Object, TNewResult>> continuationFunction,
IObservable<System.Object> state, IObservable<System.Threading.CancellationToken> cancellationToken)
{
return
Observable.Zip(TaskValue, continuationFunction, state, cancellationToken,
(TaskValueLambda, continuationFunctionLambda, stateLambda, cancellationTokenLambda) =>
TaskValueLambda.ContinueWith(continuationFunctionLambda, stateLambda, cancellationTokenLambda)
.ToObservable()).Flatten();
}
public static IObservable<TNewResult> ContinueWith<TNewResult, TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Func<System.Threading.Tasks.Task<TResult>, System.Object, TNewResult>> continuationFunction,
IObservable<System.Object> state, IObservable<System.Threading.Tasks.TaskScheduler> scheduler)
{
return
Observable.Zip(TaskValue, continuationFunction, state, scheduler,
(TaskValueLambda, continuationFunctionLambda, stateLambda, schedulerLambda) =>
TaskValueLambda.ContinueWith(continuationFunctionLambda, stateLambda, schedulerLambda)
.ToObservable()).Flatten();
}
public static IObservable<TNewResult> ContinueWith<TNewResult, TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Func<System.Threading.Tasks.Task<TResult>, System.Object, TNewResult>> continuationFunction,
IObservable<System.Object> state,
IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions)
{
return
Observable.Zip(TaskValue, continuationFunction, state, continuationOptions,
(TaskValueLambda, continuationFunctionLambda, stateLambda, continuationOptionsLambda) =>
TaskValueLambda.ContinueWith(continuationFunctionLambda, stateLambda, continuationOptionsLambda)
.ToObservable()).Flatten();
}
public static IObservable<TNewResult> ContinueWith<TNewResult, TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue,
IObservable<Func<System.Threading.Tasks.Task<TResult>, System.Object, TNewResult>> continuationFunction,
IObservable<System.Object> state, IObservable<System.Threading.CancellationToken> cancellationToken,
IObservable<System.Threading.Tasks.TaskContinuationOptions> continuationOptions,
IObservable<System.Threading.Tasks.TaskScheduler> scheduler)
{
return
Observable.Zip(TaskValue, continuationFunction, state, cancellationToken, continuationOptions, scheduler,
(TaskValueLambda, continuationFunctionLambda, stateLambda, cancellationTokenLambda,
continuationOptionsLambda, schedulerLambda) =>
TaskValueLambda.ContinueWith(continuationFunctionLambda, stateLambda, cancellationTokenLambda,
continuationOptionsLambda, schedulerLambda).ToObservable()).Flatten();
}
public static IObservable<TResult> get_Result<TResult>(
this IObservable<System.Threading.Tasks.Task<TResult>> TaskValue)
{
return Observable.Select(TaskValue, (TaskValueLambda) => TaskValueLambda.Result);
}
public static IObservable<TaskFactory<TResult>> get_Factory<TResult>()
{
return ObservableExt.Factory(() => System.Threading.Tasks.Task<TResult>.Factory);
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Hydra.Framework;
using Hydra.Framework.Helpers;
using Hydra.Framework.Java;
using Hydra.Framework.Mapping.CoordinateSystems;
using Hydra.Framework.Conversions;
namespace Hydra.DomainModel
{
//
//**********************************************************************
/// <summary>
/// Network Design (Point) Information Details
/// </summary>
//**********************************************************************
//
[Serializable]
[DataContract(Namespace = CommonConstants.DATA_NAMESPACE)]
[KnownType(typeof(InternalOrganisation))]
[KnownType(typeof(InternalImage))]
public class InternalPoint
: AbstractInternalData
{
#region Member Variables
//
// **********************************************************************
/// <summary>
/// Location Identifier
/// </summary>
// **********************************************************************
//
[DataMember(Name = "LocationId")]
public int LocationId
{
get;
set;
}
//
// **********************************************************************
/// <summary>
/// Image Reference ID
/// </summary>
// **********************************************************************
//
[DataMember(Name = "ImageId")]
public int ImageId
{
get;
set;
}
//
// **********************************************************************
/// <summary>
/// Internal Image
/// </summary>
// **********************************************************************
//
[DataMember(Name = "Image")]
public InternalImage Image
{
get;
set;
}
#endregion
#region Constructors
//
//**********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="T:InternalPoint"/> class.
/// </summary>
//**********************************************************************
//
public InternalPoint()
: base(InternalLocationServiceType.Internal)
{
Log.Entry();
Log.Exit();
}
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="InternalPoint"/> class.
/// </summary>
/// <param name="locationId">The location id.</param>
/// <param name="changedOn">The changed on.</param>
/// <param name="name">The name.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="z">The z.</param>
// **********************************************************************
//
public InternalPoint(int locationId, DateTime changedOn, string name, float x, float y, float z)
: base(InternalLocationServiceType.Internal, 0, 0, changedOn, name, string.Empty, x, y, z)
{
Log.Entry();
LocationId = locationId;
Description = name;
Log.Exit();
}
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="InternalPoint"/> class.
/// </summary>
/// <param name="locationId">The location id.</param>
/// <param name="changedOn">The changed on.</param>
/// <param name="name">The name.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="z">The z.</param>
/// <param name="image">The image.</param>
// **********************************************************************
//
public InternalPoint(int locationId, DateTime changedOn, string name, float x, float y, float z, InternalImage image)
: base(InternalLocationServiceType.Internal, 0, 0, changedOn, name, string.Empty, x, y, z)
{
Log.Entry();
LocationId = locationId;
Description = name;
Image = image;
Log.Exit();
}
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="InternalPoint"/> class.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="locationId">The location id.</param>
/// <param name="changedOn">The changed on.</param>
/// <param name="name">The name.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="z">The z.</param>
// **********************************************************************
//
public InternalPoint(int id, int locationId, DateTime changedOn, string name, float x, float y, float z)
: base(InternalLocationServiceType.Internal, 0, 0, changedOn, name, string.Empty, x, y, z)
{
Log.Entry();
ID = id;
LocationId = locationId;
Description = name;
Log.Exit();
}
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="InternalPoint"/> class.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="locationId">The location id.</param>
/// <param name="changedOn">The changed on.</param>
/// <param name="name">The name.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="z">The z.</param>
/// <param name="image">The image.</param>
// **********************************************************************
//
public InternalPoint(int id, int locationId, DateTime changedOn, string name, float x, float y, float z, InternalImage image)
: base(InternalLocationServiceType.Internal, 0, 0, changedOn, name, string.Empty, x, y, z)
{
Log.Entry();
ID = id;
LocationId = locationId;
Description = name;
Image = image;
Log.Exit();
}
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="InternalPoint"/> class.
/// </summary>
/// <param name="locationId">The location id.</param>
/// <param name="objectId">The object id.</param>
/// <param name="parentId">The parent id.</param>
/// <param name="changedOn">The changed on.</param>
/// <param name="name">The name.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="z">The z.</param>
// **********************************************************************
//
public InternalPoint(int locationId, int objectId, int parentId, DateTime changedOn, string name, float x, float y, float z)
: base(InternalLocationServiceType.Internal, objectId, parentId, changedOn, name, string.Empty, x, y, z)
{
Log.Entry();
LocationId = locationId;
Description = name;
Log.Exit();
}
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="InternalPoint"/> class.
/// </summary>
/// <param name="locationId">The location id.</param>
/// <param name="objectId">The object id.</param>
/// <param name="parentId">The parent id.</param>
/// <param name="changedOn">The changed on.</param>
/// <param name="name">The name.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="z">The z.</param>
/// <param name="image">The image.</param>
// **********************************************************************
//
public InternalPoint(int locationId, int objectId, int parentId, DateTime changedOn, string name, float x, float y, float z, InternalImage image)
: base(InternalLocationServiceType.Internal, objectId, parentId, changedOn, name, string.Empty, x, y, z)
{
Log.Entry();
LocationId = locationId;
Description = name;
Image = image;
Log.Exit();
}
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="InternalPoint"/> class.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="locationId">The location id.</param>
/// <param name="objectId">The object id.</param>
/// <param name="parentId">The parent id.</param>
/// <param name="changedOn">The changed on.</param>
/// <param name="name">The name.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="z">The z.</param>
// **********************************************************************
//
public InternalPoint(int id, int locationId, int objectId, int parentId, DateTime changedOn, string name, float x, float y, float z)
: base(InternalLocationServiceType.Internal, objectId, parentId, changedOn, name, string.Empty, x, y, z)
{
Log.Entry();
ID = id;
LocationId = locationId;
Description = name;
Log.Exit();
}
//
// **********************************************************************
/// <summary>
/// Initializes a new instance of the <see cref="InternalPoint"/> class.
/// </summary>
/// <param name="id">The id.</param>
/// <param name="locationId">The location id.</param>
/// <param name="objectId">The object id.</param>
/// <param name="parentId">The parent id.</param>
/// <param name="changedOn">The changed on.</param>
/// <param name="name">The name.</param>
/// <param name="x">The x.</param>
/// <param name="y">The y.</param>
/// <param name="z">The z.</param>
/// <param name="image">The image.</param>
// **********************************************************************
//
public InternalPoint(int id, int locationId, int objectId, int parentId, DateTime changedOn, string name, float x, float y, float z, InternalImage image)
: base(InternalLocationServiceType.Internal, objectId, parentId, changedOn, name, string.Empty, x, y, z)
{
Log.Entry();
ID = id;
LocationId = locationId;
Description = name;
Image = image;
Log.Exit();
}
#endregion
#region Properties
#endregion
#region Private Methods
#endregion
#region Static Methods
#endregion
}
}
| |
/*
* Copyright 2002 Fluent Consulting, Inc. All rights reserved.
* PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using NUnit.Framework;
using Inform;
namespace Inform.Tests.Common
{
/// <summary>
/// Summary description for SqlFindObjectCommandTest.
/// </summary>
[TestFixture]
public abstract class FindObjectCommandTest {
DataStore dataStore;
public abstract DataStore CreateDataStore();
[SetUp]
public void InitializeConnection() {
dataStore = CreateDataStore();
dataStore.Settings.AutoGenerate = true;
dataStore.CreateStorage(typeof(Manager));
dataStore.CreateStorage(typeof(Employee));
dataStore.CreateStorage(typeof(Project));
dataStore.CreateStorage(typeof(Task));
dataStore.CreateStorage(typeof(Posting));
InsertTestData();
}
private void InsertTestData(){
Employee e = new Employee();
e.EmployeeID = "2";
e.FirstName = "Sam";
e.LastName = "Donaldson";
e.Title = "Director";
e.Salary = 70000;
dataStore.Insert(e);
e = new Employee();
e.EmployeeID = "3";
e.FirstName = "Dave";
e.LastName = "Donner";
e.Title = "Engineer";
e.Salary = 50000;
dataStore.Insert(e);
e = new Employee();
e.EmployeeID = "4";
e.FirstName = "Bill";
e.LastName = "Stevenson";
e.Title = "Analyst";
e.Salary = 40000;
dataStore.Insert(e);
Manager m = new Manager();
m.EmployeeID = "5";
m.FirstName = "Sam";
m.LastName = "Smith";
m.Certified = true;
m.Title = "Director";
m.Salary = 90000;
dataStore.Insert(m);
Project p = new Project();
p.Name = "ProjectX";
p.ProjectID = "1";
p.ManagerID = "5";
dataStore.Insert(p);
Task t = new Task();
t.ProjectID = p.ProjectID;
t.Description = "Task 1";
dataStore.Insert(t);
t.Description = "Task 2";
dataStore.Insert(t);
Posting ps = new Posting();
ps.Topic = "Topic 1";
ps.Details = "Some details.";
dataStore.Insert(ps);
ps = new Posting();
ps.Topic = "Topic w";
ps.Details = "Some details.";
dataStore.Insert(ps);
}
[TearDown]
public void DeleteStorage() {
try{
dataStore.DeleteStorage(typeof(Task));
} catch(Exception e){
Console.Write(e.Message);
}
try{
dataStore.DeleteStorage(typeof(Project));
} catch(Exception e){
Console.Write(e.Message);
}
try{
dataStore.DeleteStorage(typeof(Manager)); //TODO? Constraint on employee here?
} catch(Exception e){
Console.Write(e.Message);
}
try{
dataStore.DeleteStorage(typeof(Employee));
} catch(Exception e){
Console.Write(e.Message);
}
try{
dataStore.DeleteStorage(typeof(Posting));
} catch(Exception e){
Console.Write(e.Message);
}
}
//
// [Test]
// public void FindEmployeeCustomPopulate(){
//
// IFindObjectCommand command = dataStore.CreateFindObjectCommand(
// typeof(Employee), "WHERE EmployeeID = '2'");
// command.CustomPopulate = new CustomPopulate(PopulateEmployee);
// Employee e = (Employee)command.Execute();
//
// //test
// Assert.AreEqual("Donaldson", e.LastName,"Verify LastName");
// }
[Test]
public void FindEmployeeFullSelect(){
IFindObjectCommand command = dataStore.CreateFindObjectCommand(
typeof(Employee), "SELECT * FROM Employees WHERE EmployeeID = '4'");
Employee e = (Employee)command.Execute();
//test
Assert.AreEqual("Stevenson", e.LastName, "Verify LastName");
command = dataStore.CreateFindObjectCommand(
typeof(Employee), " SELECT * FROM Employees WHERE EmployeeID = '4'");
e = (Employee)command.Execute();
//test
Assert.AreEqual("Stevenson", e.LastName, "Verify LastName");
}
[Test]
public void UpdateEmployee(){
IFindObjectCommand command = dataStore.CreateFindObjectCommand(
typeof(Employee), "WHERE EmployeeID = @EmployeeID");
command.CreateInputParameter("@EmployeeID", "2");
Employee e = (Employee)command.Execute();
e.Salary = 120000;
dataStore.Update(e);
command = dataStore.CreateFindObjectCommand( typeof(Employee), "WHERE EmployeeID = @EmployeeID");
command.CreateInputParameter("@EmployeeID", "2");
e = (Employee)command.Execute();
//test
Assert.AreEqual(120000, e.Salary,"Verify LastName");
}
// /// <summary>
// /// Custom population method for tests.
// /// </summary>
// private object PopulateEmployee(IDataReader reader){
//
// Employee e = new Employee();
// e.FirstName = (string)reader["FirstName"];
// e.LastName = (string)reader["LastName"];
// e.Title = (string)reader["Title"];
// e.Salary = (int)reader["Salary"];
// return e;
// }
[Test]
public void ObjectNotFound(){
dataStore.Settings.FindObjectReturnsNull = false;
IFindObjectCommand command = dataStore.CreateFindObjectCommand( typeof(Employee), "WHERE EmployeeID = '0'");
//test command
try {
Employee e = (Employee)command.Execute();
Assert.Fail("Should have thrown Exception");
} catch (ObjectNotFoundException ofne) {
//test passed
} finally {
dataStore.Settings.FindObjectReturnsNull = true;
}
}
[Test]
public void FindEmployee(){
IFindObjectCommand command = dataStore.CreateFindObjectCommand( typeof(Employee), "WHERE EmployeeID = '2'");
Employee e = (Employee)command.Execute();
//test command
Assert.AreEqual("Donaldson", e.LastName, "Verify LastName");
}
[Test]
public void EmployeeReader(){
IObjectAccessCommand cmd = dataStore.CreateObjectAccessCommand( typeof(Employee), "");
IObjectReader reader = cmd.ExecuteObjectReader();
Employee e;
int count = 0;
while(reader.Read()){
e = (Employee)reader.GetObject();
Console.WriteLine(e.LastName);
count++;
}
reader.Close();
Assert.AreEqual( 3, count,"Empoyees found");
}
[Test]
public void EmployeeReaderEnumeration(){
IObjectAccessCommand cmd = dataStore.CreateObjectAccessCommand( typeof(Employee), "");
IObjectReader reader = cmd.ExecuteObjectReader();
int count = 0;
foreach(Employee e in reader){
Console.WriteLine(e.LastName);
count++;
}
Assert.AreEqual( 3, count,"Empoyees found");
Assert.IsTrue(reader.IsClosed);
}
[Test]
public void FindSimpleObject(){
IFindObjectCommand command = dataStore.CreateFindObjectCommand(
typeof(Posting), "WHERE ID = 1");
Posting p = (Posting)command.Execute();
//test
Assert.AreEqual("Topic 1", p.Topic, "Verify Topic");
}
[Test]
public void FindObjectPolymorphic(){
try {
dataStore.DeleteStorage(typeof(Circle));
} catch {}
dataStore.CreateStorage(typeof(Circle));
try {
dataStore.DeleteStorage(typeof(Rectangle));
} catch {}
dataStore.CreateStorage(typeof(Rectangle));
try{
dataStore.DeleteStorage(typeof(Shape));
} catch {}
Circle c = new Circle();
c.Color = "Green";
c.Radius = 5;
dataStore.Insert(c);
int shapeID = c.ShapeID;
IFindObjectCommand cmd;
cmd = dataStore.CreateFindObjectCommand( typeof(Shape), "WHERE Shapes.Color = @Color", true);
cmd.CreateInputParameter("@Color", c.Color);
c = (Circle)cmd.Execute();
Assert.IsTrue( c.Color == "Green" && c.ShapeID == shapeID, "Checking Shape: {0}, {1} ",c.Color, c.ShapeID);
cmd = dataStore.CreateFindObjectCommand(typeof(Circle), "WHERE Shapes.Color = @Color", true);
cmd.CreateInputParameter("@Color", c.Color);
c = (Circle)cmd.Execute();
Assert.IsTrue( c.Color == "Green" && c.ShapeID == shapeID, "Checking Shape: {0}, {1} ",c.Color, c.ShapeID);
dataStore.DeleteStorage(typeof(Circle));
dataStore.DeleteStorage(typeof(Rectangle));
dataStore.DeleteStorage(typeof(Shape));
Console.WriteLine("Storage Deleted");
}
[Test]
public void FindPrivateConstructor(){
try{
dataStore.DeleteStorage(typeof(Comment));
} catch {}
dataStore.CreateStorage(typeof(Comment));
Comment c1 = new Comment("Test Comment");
dataStore.Insert(c1);
IFindObjectCommand command = dataStore.CreateFindObjectCommand( typeof(Comment), "WHERE Text LIKE @Text");
command.CreateInputParameter("@Text",c1.Text);
Comment c2 = (Comment)command.Execute();
//test command
Assert.AreEqual(c1.Text, c2.Text, "Verify Text");
dataStore.DeleteStorage(typeof(Comment));
}
}
}
| |
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 PyriteCloudAdmin.Areas.HelpPage
{
/// <summary>
/// This class will generate the samples for the help page.
/// </summary>
public class HelpPageSampleGenerator
{
/// <summary>
/// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class.
/// </summary>
public HelpPageSampleGenerator()
{
ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>();
ActionSamples = new Dictionary<HelpPageSampleKey, object>();
SampleObjects = new Dictionary<Type, object>();
SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>>
{
DefaultSampleObjectFactory,
};
}
/// <summary>
/// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>.
/// </summary>
public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; }
/// <summary>
/// Gets the objects that are used directly as samples for certain actions.
/// </summary>
public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; }
/// <summary>
/// Gets the objects that are serialized as samples by the supported formatters.
/// </summary>
public IDictionary<Type, object> SampleObjects { get; internal set; }
/// <summary>
/// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order,
/// stopping when the factory successfully returns a non-<see langref="null"/> object.
/// </summary>
/// <remarks>
/// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use
/// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and
/// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks>
[SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures",
Justification = "This is an appropriate nesting of generic types")]
public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; }
/// <summary>
/// Gets the request body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api)
{
return GetSample(api, SampleDirection.Request);
}
/// <summary>
/// Gets the response body samples for a given <see cref="ApiDescription"/>.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The samples keyed by media type.</returns>
public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api)
{
return GetSample(api, SampleDirection.Response);
}
/// <summary>
/// Gets the request or response body samples.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The samples keyed by media type.</returns>
public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection)
{
if (api == null)
{
throw new ArgumentNullException("api");
}
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters);
var samples = new Dictionary<MediaTypeHeaderValue, object>();
// Use the samples provided directly for actions
var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection);
foreach (var actionSample in actionSamples)
{
samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value));
}
// Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage.
// Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters.
if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type))
{
object sampleObject = GetSampleObject(type);
foreach (var formatter in formatters)
{
foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes)
{
if (!samples.ContainsKey(mediaType))
{
object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection);
// If no sample found, try generate sample using formatter and sample object
if (sample == null && sampleObject != null)
{
sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType);
}
samples.Add(mediaType, WrapSampleIfString(sample));
}
}
}
}
return samples;
}
/// <summary>
/// Search for samples that are provided directly through <see cref="ActionSamples"/>.
/// </summary>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="type">The CLR type.</param>
/// <param name="formatter">The formatter.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param>
/// <returns>The sample that matches the parameters.</returns>
public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection)
{
object sample;
// First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames.
// If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames.
// If still not found, try to get the sample provided for the specified mediaType and type.
// Finally, try to get the sample provided for the specified mediaType.
if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) ||
ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample))
{
return sample;
}
return null;
}
/// <summary>
/// Gets the sample object that will be serialized by the formatters.
/// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create
/// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other
/// factories in <see cref="SampleObjectFactories"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>The sample object.</returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes",
Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")]
public virtual object GetSampleObject(Type type)
{
object sampleObject;
if (!SampleObjects.TryGetValue(type, out sampleObject))
{
// No specific object available, try our factories.
foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories)
{
if (factory == null)
{
continue;
}
try
{
sampleObject = factory(this, type);
if (sampleObject != null)
{
break;
}
}
catch
{
// Ignore any problems encountered in the factory; go on to the next one (if any).
}
}
}
return sampleObject;
}
/// <summary>
/// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <returns>The type.</returns>
public virtual Type ResolveHttpRequestMessageType(ApiDescription api)
{
string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName;
string actionName = api.ActionDescriptor.ActionName;
IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name);
Collection<MediaTypeFormatter> formatters;
return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters);
}
/// <summary>
/// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used.
/// </summary>
/// <param name="api">The <see cref="ApiDescription"/>.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
/// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param>
/// <param name="formatters">The formatters.</param>
[SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")]
public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters)
{
if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection))
{
throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection));
}
if (api == null)
{
throw new ArgumentNullException("api");
}
Type type;
if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) ||
ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type))
{
// Re-compute the supported formatters based on type
Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>();
foreach (var formatter in api.ActionDescriptor.Configuration.Formatters)
{
if (IsFormatSupported(sampleDirection, formatter, type))
{
newFormatters.Add(formatter);
}
}
formatters = newFormatters;
}
else
{
switch (sampleDirection)
{
case SampleDirection.Request:
ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody);
type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType;
formatters = api.SupportedRequestBodyFormatters;
break;
case SampleDirection.Response:
default:
type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType;
formatters = api.SupportedResponseFormatters;
break;
}
}
return type;
}
/// <summary>
/// Writes the sample object using formatter.
/// </summary>
/// <param name="formatter">The formatter.</param>
/// <param name="value">The value.</param>
/// <param name="type">The type.</param>
/// <param name="mediaType">Type of the media.</param>
/// <returns></returns>
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
}
object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = 0;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
}
sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().Name,
type.Name));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().Name,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
}
return sample;
}
internal static Exception UnwrapException(Exception exception)
{
AggregateException aggregateException = exception as AggregateException;
if (aggregateException != null)
{
return aggregateException.Flatten().InnerException;
}
return exception;
}
// Default factory for sample objects
private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type)
{
// Try to create a default sample object
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type);
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatJson(string str)
{
try
{
object parsedJson = JsonConvert.DeserializeObject(str);
return JsonConvert.SerializeObject(parsedJson, Formatting.Indented);
}
catch
{
// can't parse JSON, return the original string
return str;
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")]
private static string TryFormatXml(string str)
{
try
{
XDocument xml = XDocument.Parse(str);
return xml.ToString();
}
catch
{
// can't parse XML, return the original string
return str;
}
}
private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type)
{
switch (sampleDirection)
{
case SampleDirection.Request:
return formatter.CanReadType(type);
case SampleDirection.Response:
return formatter.CanWriteType(type);
}
return false;
}
private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection)
{
HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase);
foreach (var sample in ActionSamples)
{
HelpPageSampleKey sampleKey = sample.Key;
if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) &&
String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) &&
(sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) &&
sampleDirection == sampleKey.SampleDirection)
{
yield return sample;
}
}
}
private static object WrapSampleIfString(object sample)
{
string stringSample = sample as string;
if (stringSample != null)
{
return new TextSample(stringSample);
}
return sample;
}
}
}
| |
using System;
using System.Collections;
namespace Andi.Libs.HexBox
{
internal class DataMap : ICollection, IEnumerable
{
readonly object _syncRoot = new object();
internal int _count;
internal DataBlock _firstBlock;
internal int _version;
public DataMap()
{
}
public DataMap(IEnumerable collection)
{
if (collection == null)
{
throw new ArgumentNullException("collection");
}
foreach (DataBlock item in collection)
{
AddLast(item);
}
}
public DataBlock FirstBlock
{
get
{
return _firstBlock;
}
}
public void AddAfter(DataBlock block, DataBlock newBlock)
{
AddAfterInternal(block, newBlock);
}
public void AddBefore(DataBlock block, DataBlock newBlock)
{
AddBeforeInternal(block, newBlock);
}
public void AddFirst(DataBlock block)
{
if (_firstBlock == null)
{
AddBlockToEmptyMap(block);
}
else
{
AddBeforeInternal(_firstBlock, block);
}
}
public void AddLast(DataBlock block)
{
if (_firstBlock == null)
{
AddBlockToEmptyMap(block);
}
else
{
AddAfterInternal(GetLastBlock(), block);
}
}
public void Remove(DataBlock block)
{
RemoveInternal(block);
}
public void RemoveFirst()
{
if (_firstBlock == null)
{
throw new InvalidOperationException("The collection is empty.");
}
RemoveInternal(_firstBlock);
}
public void RemoveLast()
{
if (_firstBlock == null)
{
throw new InvalidOperationException("The collection is empty.");
}
RemoveInternal(GetLastBlock());
}
public DataBlock Replace(DataBlock block, DataBlock newBlock)
{
AddAfterInternal(block, newBlock);
RemoveInternal(block);
return newBlock;
}
public void Clear()
{
DataBlock block = FirstBlock;
while (block != null)
{
DataBlock nextBlock = block.NextBlock;
InvalidateBlock(block);
block = nextBlock;
}
_firstBlock = null;
_count = 0;
_version++;
}
void AddAfterInternal(DataBlock block, DataBlock newBlock)
{
newBlock._previousBlock = block;
newBlock._nextBlock = block._nextBlock;
newBlock._map = this;
if (block._nextBlock != null)
{
block._nextBlock._previousBlock = newBlock;
}
block._nextBlock = newBlock;
this._version++;
this._count++;
}
void AddBeforeInternal(DataBlock block, DataBlock newBlock)
{
newBlock._nextBlock = block;
newBlock._previousBlock = block._previousBlock;
newBlock._map = this;
if (block._previousBlock != null)
{
block._previousBlock._nextBlock = newBlock;
}
block._previousBlock = newBlock;
if (_firstBlock == block)
{
_firstBlock = newBlock;
}
this._version++;
this._count++;
}
void RemoveInternal(DataBlock block)
{
DataBlock previousBlock = block._previousBlock;
DataBlock nextBlock = block._nextBlock;
if (previousBlock != null)
{
previousBlock._nextBlock = nextBlock;
}
if (nextBlock != null)
{
nextBlock._previousBlock = previousBlock;
}
if (_firstBlock == block)
{
_firstBlock = nextBlock;
}
InvalidateBlock(block);
_count--;
_version++;
}
DataBlock GetLastBlock()
{
DataBlock lastBlock = null;
for (DataBlock block = FirstBlock; block != null; block = block.NextBlock)
{
lastBlock = block;
}
return lastBlock;
}
void InvalidateBlock(DataBlock block)
{
block._map = null;
block._nextBlock = null;
block._previousBlock = null;
}
void AddBlockToEmptyMap(DataBlock block)
{
block._map = this;
block._nextBlock = null;
block._previousBlock = null;
_firstBlock = block;
_version++;
_count++;
}
#region ICollection Members
public void CopyTo(Array array, int index)
{
DataBlock[] blockArray = array as DataBlock[];
for (DataBlock block = FirstBlock; block != null; block = block.NextBlock)
{
blockArray[index++] = block;
}
}
public int Count
{
get
{
return _count;
}
}
public bool IsSynchronized
{
get
{
return false;
}
}
public object SyncRoot
{
get
{
return _syncRoot;
}
}
#endregion
#region IEnumerable Members
public IEnumerator GetEnumerator()
{
return new Enumerator(this);
}
#endregion
#region Enumerator Nested Type
internal class Enumerator : IEnumerator, IDisposable
{
DataMap _map;
DataBlock _current;
int _index;
int _version;
internal Enumerator(DataMap map)
{
_map = map;
_version = map._version;
_current = null;
_index = -1;
}
object IEnumerator.Current
{
get
{
if (_index < 0 || _index > _map.Count)
{
throw new InvalidOperationException("Enumerator is positioned before the first element or after the last element of the collection.");
}
return _current;
}
}
public bool MoveNext()
{
if (this._version != _map._version)
{
throw new InvalidOperationException("Collection was modified after the enumerator was instantiated.");
}
if (_index >= _map.Count)
{
return false;
}
if (++_index == 0)
{
_current = _map.FirstBlock;
}
else
{
_current = _current.NextBlock;
}
return (_index < _map.Count);
}
void IEnumerator.Reset()
{
if (this._version != this._map._version)
{
throw new InvalidOperationException("Collection was modified after the enumerator was instantiated.");
}
this._index = -1;
this._current = null;
}
public void Dispose()
{
}
}
#endregion
}
}
| |
/*
* DocuSign REST API
*
* The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign.
*
* OpenAPI spec version: v2
* Contact: devcenter@docusign.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
namespace DocuSign.eSign.Model
{
/// <summary>
/// Group
/// </summary>
[DataContract]
public partial class Group : IEquatable<Group>, IValidatableObject
{
public Group()
{
// Empty Constructor
}
/// <summary>
/// Initializes a new instance of the <see cref="Group" /> class.
/// </summary>
/// <param name="ErrorDetails">ErrorDetails.</param>
/// <param name="GroupId">The DocuSign group ID for the group..</param>
/// <param name="GroupName">The name of the group..</param>
/// <param name="GroupType">The group type..</param>
/// <param name="PermissionProfileId">The ID of the permission profile associated with the group..</param>
/// <param name="Users">.</param>
public Group(ErrorDetails ErrorDetails = default(ErrorDetails), string GroupId = default(string), string GroupName = default(string), string GroupType = default(string), string PermissionProfileId = default(string), List<UserInfo> Users = default(List<UserInfo>))
{
this.ErrorDetails = ErrorDetails;
this.GroupId = GroupId;
this.GroupName = GroupName;
this.GroupType = GroupType;
this.PermissionProfileId = PermissionProfileId;
this.Users = Users;
}
/// <summary>
/// Gets or Sets ErrorDetails
/// </summary>
[DataMember(Name="errorDetails", EmitDefaultValue=false)]
public ErrorDetails ErrorDetails { get; set; }
/// <summary>
/// The DocuSign group ID for the group.
/// </summary>
/// <value>The DocuSign group ID for the group.</value>
[DataMember(Name="groupId", EmitDefaultValue=false)]
public string GroupId { get; set; }
/// <summary>
/// The name of the group.
/// </summary>
/// <value>The name of the group.</value>
[DataMember(Name="groupName", EmitDefaultValue=false)]
public string GroupName { get; set; }
/// <summary>
/// The group type.
/// </summary>
/// <value>The group type.</value>
[DataMember(Name="groupType", EmitDefaultValue=false)]
public string GroupType { get; set; }
/// <summary>
/// The ID of the permission profile associated with the group.
/// </summary>
/// <value>The ID of the permission profile associated with the group.</value>
[DataMember(Name="permissionProfileId", EmitDefaultValue=false)]
public string PermissionProfileId { get; set; }
/// <summary>
///
/// </summary>
/// <value></value>
[DataMember(Name="users", EmitDefaultValue=false)]
public List<UserInfo> Users { 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 Group {\n");
sb.Append(" ErrorDetails: ").Append(ErrorDetails).Append("\n");
sb.Append(" GroupId: ").Append(GroupId).Append("\n");
sb.Append(" GroupName: ").Append(GroupName).Append("\n");
sb.Append(" GroupType: ").Append(GroupType).Append("\n");
sb.Append(" PermissionProfileId: ").Append(PermissionProfileId).Append("\n");
sb.Append(" Users: ").Append(Users).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="obj">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object obj)
{
// credit: http://stackoverflow.com/a/10454552/677735
return this.Equals(obj as Group);
}
/// <summary>
/// Returns true if Group instances are equal
/// </summary>
/// <param name="other">Instance of Group to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(Group other)
{
// credit: http://stackoverflow.com/a/10454552/677735
if (other == null)
return false;
return
(
this.ErrorDetails == other.ErrorDetails ||
this.ErrorDetails != null &&
this.ErrorDetails.Equals(other.ErrorDetails)
) &&
(
this.GroupId == other.GroupId ||
this.GroupId != null &&
this.GroupId.Equals(other.GroupId)
) &&
(
this.GroupName == other.GroupName ||
this.GroupName != null &&
this.GroupName.Equals(other.GroupName)
) &&
(
this.GroupType == other.GroupType ||
this.GroupType != null &&
this.GroupType.Equals(other.GroupType)
) &&
(
this.PermissionProfileId == other.PermissionProfileId ||
this.PermissionProfileId != null &&
this.PermissionProfileId.Equals(other.PermissionProfileId)
) &&
(
this.Users == other.Users ||
this.Users != null &&
this.Users.SequenceEqual(other.Users)
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
// credit: http://stackoverflow.com/a/263416/677735
unchecked // Overflow is fine, just wrap
{
int hash = 41;
// Suitable nullity checks etc, of course :)
if (this.ErrorDetails != null)
hash = hash * 59 + this.ErrorDetails.GetHashCode();
if (this.GroupId != null)
hash = hash * 59 + this.GroupId.GetHashCode();
if (this.GroupName != null)
hash = hash * 59 + this.GroupName.GetHashCode();
if (this.GroupType != null)
hash = hash * 59 + this.GroupType.GetHashCode();
if (this.PermissionProfileId != null)
hash = hash * 59 + this.PermissionProfileId.GetHashCode();
if (this.Users != null)
hash = hash * 59 + this.Users.GetHashCode();
return hash;
}
}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| |
/*
* CP866.cs - Russian (DOS) code page.
*
* Copyright (c) 2002 Southern Storm Software, Pty Ltd
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// Generated from "ibm-866.ucm".
namespace I18N.Rare
{
using System;
using I18N.Common;
public class CP866 : ByteEncoding
{
public CP866()
: base(866, ToChars, "Russian (DOS)",
"ibm866", "ibm866", "ibm866",
false, false, false, false, 1251)
{}
private static readonly char[] ToChars = {
'\u0000', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005',
'\u0006', '\u0007', '\u0008', '\u0009', '\u000A', '\u000B',
'\u000C', '\u000D', '\u000E', '\u000F', '\u0010', '\u0011',
'\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017',
'\u0018', '\u0019', '\u001C', '\u001B', '\u007F', '\u001D',
'\u001E', '\u001F', '\u0020', '\u0021', '\u0022', '\u0023',
'\u0024', '\u0025', '\u0026', '\u0027', '\u0028', '\u0029',
'\u002A', '\u002B', '\u002C', '\u002D', '\u002E', '\u002F',
'\u0030', '\u0031', '\u0032', '\u0033', '\u0034', '\u0035',
'\u0036', '\u0037', '\u0038', '\u0039', '\u003A', '\u003B',
'\u003C', '\u003D', '\u003E', '\u003F', '\u0040', '\u0041',
'\u0042', '\u0043', '\u0044', '\u0045', '\u0046', '\u0047',
'\u0048', '\u0049', '\u004A', '\u004B', '\u004C', '\u004D',
'\u004E', '\u004F', '\u0050', '\u0051', '\u0052', '\u0053',
'\u0054', '\u0055', '\u0056', '\u0057', '\u0058', '\u0059',
'\u005A', '\u005B', '\u005C', '\u005D', '\u005E', '\u005F',
'\u0060', '\u0061', '\u0062', '\u0063', '\u0064', '\u0065',
'\u0066', '\u0067', '\u0068', '\u0069', '\u006A', '\u006B',
'\u006C', '\u006D', '\u006E', '\u006F', '\u0070', '\u0071',
'\u0072', '\u0073', '\u0074', '\u0075', '\u0076', '\u0077',
'\u0078', '\u0079', '\u007A', '\u007B', '\u007C', '\u007D',
'\u007E', '\u001A', '\u0410', '\u0411', '\u0412', '\u0413',
'\u0414', '\u0415', '\u0416', '\u0417', '\u0418', '\u0419',
'\u041A', '\u041B', '\u041C', '\u041D', '\u041E', '\u041F',
'\u0420', '\u0421', '\u0422', '\u0423', '\u0424', '\u0425',
'\u0426', '\u0427', '\u0428', '\u0429', '\u042A', '\u042B',
'\u042C', '\u042D', '\u042E', '\u042F', '\u0430', '\u0431',
'\u0432', '\u0433', '\u0434', '\u0435', '\u0436', '\u0437',
'\u0438', '\u0439', '\u043A', '\u043B', '\u043C', '\u043D',
'\u043E', '\u043F', '\u2591', '\u2592', '\u2593', '\u2502',
'\u2524', '\u2561', '\u2562', '\u2556', '\u2555', '\u2563',
'\u2551', '\u2557', '\u255D', '\u255C', '\u255B', '\u2510',
'\u2514', '\u2534', '\u252C', '\u251C', '\u2500', '\u253C',
'\u255E', '\u255F', '\u255A', '\u2554', '\u2569', '\u2566',
'\u2560', '\u2550', '\u256C', '\u2567', '\u2568', '\u2564',
'\u2565', '\u2559', '\u2558', '\u2552', '\u2553', '\u256B',
'\u256A', '\u2518', '\u250C', '\u2588', '\u2584', '\u258C',
'\u2590', '\u2580', '\u0440', '\u0441', '\u0442', '\u0443',
'\u0444', '\u0445', '\u0446', '\u0447', '\u0448', '\u0449',
'\u044A', '\u044B', '\u044C', '\u044D', '\u044E', '\u044F',
'\u0401', '\u0451', '\u0404', '\u0454', '\u0407', '\u0457',
'\u040E', '\u045E', '\u00B0', '\u2219', '\u00B7', '\u221A',
'\u2116', '\u00A4', '\u25A0', '\u00A0',
};
protected override void ToBytes(char[] chars, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(chars[charIndex++]);
if(ch >= 26) switch(ch)
{
case 0x001B:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x0020:
case 0x0021:
case 0x0022:
case 0x0023:
case 0x0024:
case 0x0025:
case 0x0026:
case 0x0027:
case 0x0028:
case 0x0029:
case 0x002A:
case 0x002B:
case 0x002C:
case 0x002D:
case 0x002E:
case 0x002F:
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
case 0x003A:
case 0x003B:
case 0x003C:
case 0x003D:
case 0x003E:
case 0x003F:
case 0x0040:
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
case 0x005B:
case 0x005C:
case 0x005D:
case 0x005E:
case 0x005F:
case 0x0060:
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
case 0x007B:
case 0x007C:
case 0x007D:
case 0x007E:
break;
case 0x001A: ch = 0x7F; break;
case 0x001C: ch = 0x1A; break;
case 0x007F: ch = 0x1C; break;
case 0x00A0: ch = 0xFF; break;
case 0x00A4: ch = 0xFD; break;
case 0x00A7: ch = 0x15; break;
case 0x00B0: ch = 0xF8; break;
case 0x00B6: ch = 0x14; break;
case 0x00B7: ch = 0xFA; break;
case 0x0401: ch = 0xF0; break;
case 0x0404: ch = 0xF2; break;
case 0x0407: ch = 0xF4; break;
case 0x040E: ch = 0xF6; break;
case 0x0410:
case 0x0411:
case 0x0412:
case 0x0413:
case 0x0414:
case 0x0415:
case 0x0416:
case 0x0417:
case 0x0418:
case 0x0419:
case 0x041A:
case 0x041B:
case 0x041C:
case 0x041D:
case 0x041E:
case 0x041F:
case 0x0420:
case 0x0421:
case 0x0422:
case 0x0423:
case 0x0424:
case 0x0425:
case 0x0426:
case 0x0427:
case 0x0428:
case 0x0429:
case 0x042A:
case 0x042B:
case 0x042C:
case 0x042D:
case 0x042E:
case 0x042F:
case 0x0430:
case 0x0431:
case 0x0432:
case 0x0433:
case 0x0434:
case 0x0435:
case 0x0436:
case 0x0437:
case 0x0438:
case 0x0439:
case 0x043A:
case 0x043B:
case 0x043C:
case 0x043D:
case 0x043E:
case 0x043F:
ch -= 0x0390;
break;
case 0x0440:
case 0x0441:
case 0x0442:
case 0x0443:
case 0x0444:
case 0x0445:
case 0x0446:
case 0x0447:
case 0x0448:
case 0x0449:
case 0x044A:
case 0x044B:
case 0x044C:
case 0x044D:
case 0x044E:
case 0x044F:
ch -= 0x0360;
break;
case 0x0451: ch = 0xF1; break;
case 0x0454: ch = 0xF3; break;
case 0x0457: ch = 0xF5; break;
case 0x045E: ch = 0xF7; break;
case 0x2022: ch = 0x07; break;
case 0x203C: ch = 0x13; break;
case 0x2116: ch = 0xFC; break;
case 0x2190: ch = 0x1B; break;
case 0x2191: ch = 0x18; break;
case 0x2192: ch = 0x1A; break;
case 0x2193: ch = 0x19; break;
case 0x2194: ch = 0x1D; break;
case 0x2195: ch = 0x12; break;
case 0x21A8: ch = 0x17; break;
case 0x2219: ch = 0xF9; break;
case 0x221A: ch = 0xFB; break;
case 0x221F: ch = 0x1C; break;
case 0x2302: ch = 0x7F; break;
case 0x2500: ch = 0xC4; break;
case 0x2502: ch = 0xB3; break;
case 0x250C: ch = 0xDA; break;
case 0x2510: ch = 0xBF; break;
case 0x2514: ch = 0xC0; break;
case 0x2518: ch = 0xD9; break;
case 0x251C: ch = 0xC3; break;
case 0x2524: ch = 0xB4; break;
case 0x252C: ch = 0xC2; break;
case 0x2534: ch = 0xC1; break;
case 0x253C: ch = 0xC5; break;
case 0x2550: ch = 0xCD; break;
case 0x2551: ch = 0xBA; break;
case 0x2552: ch = 0xD5; break;
case 0x2553: ch = 0xD6; break;
case 0x2554: ch = 0xC9; break;
case 0x2555: ch = 0xB8; break;
case 0x2556: ch = 0xB7; break;
case 0x2557: ch = 0xBB; break;
case 0x2558: ch = 0xD4; break;
case 0x2559: ch = 0xD3; break;
case 0x255A: ch = 0xC8; break;
case 0x255B: ch = 0xBE; break;
case 0x255C: ch = 0xBD; break;
case 0x255D: ch = 0xBC; break;
case 0x255E: ch = 0xC6; break;
case 0x255F: ch = 0xC7; break;
case 0x2560: ch = 0xCC; break;
case 0x2561: ch = 0xB5; break;
case 0x2562: ch = 0xB6; break;
case 0x2563: ch = 0xB9; break;
case 0x2564: ch = 0xD1; break;
case 0x2565: ch = 0xD2; break;
case 0x2566: ch = 0xCB; break;
case 0x2567: ch = 0xCF; break;
case 0x2568: ch = 0xD0; break;
case 0x2569: ch = 0xCA; break;
case 0x256A: ch = 0xD8; break;
case 0x256B: ch = 0xD7; break;
case 0x256C: ch = 0xCE; break;
case 0x2580: ch = 0xDF; break;
case 0x2584: ch = 0xDC; break;
case 0x2588: ch = 0xDB; break;
case 0x258C: ch = 0xDD; break;
case 0x2590: ch = 0xDE; break;
case 0x2591: ch = 0xB0; break;
case 0x2592: ch = 0xB1; break;
case 0x2593: ch = 0xB2; break;
case 0x25A0: ch = 0xFE; break;
case 0x25AC: ch = 0x16; break;
case 0x25B2: ch = 0x1E; break;
case 0x25BA: ch = 0x10; break;
case 0x25BC: ch = 0x1F; break;
case 0x25C4: ch = 0x11; break;
case 0x25CB: ch = 0x09; break;
case 0x25D8: ch = 0x08; break;
case 0x25D9: ch = 0x0A; break;
case 0x263A: ch = 0x01; break;
case 0x263B: ch = 0x02; break;
case 0x263C: ch = 0x0F; break;
case 0x2640: ch = 0x0C; break;
case 0x2642: ch = 0x0B; break;
case 0x2660: ch = 0x06; break;
case 0x2663: ch = 0x05; break;
case 0x2665: ch = 0x03; break;
case 0x2666: ch = 0x04; break;
case 0x266A: ch = 0x0D; break;
case 0x266B: ch = 0x0E; break;
case 0xFFE8: ch = 0xB3; break;
case 0xFFE9: ch = 0x1B; break;
case 0xFFEA: ch = 0x18; break;
case 0xFFEB: ch = 0x1A; break;
case 0xFFEC: ch = 0x19; break;
case 0xFFED: ch = 0xFE; break;
case 0xFFEE: ch = 0x09; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
protected override void ToBytes(String s, int charIndex, int charCount,
byte[] bytes, int byteIndex)
{
int ch;
while(charCount > 0)
{
ch = (int)(s[charIndex++]);
if(ch >= 26) switch(ch)
{
case 0x001B:
case 0x001D:
case 0x001E:
case 0x001F:
case 0x0020:
case 0x0021:
case 0x0022:
case 0x0023:
case 0x0024:
case 0x0025:
case 0x0026:
case 0x0027:
case 0x0028:
case 0x0029:
case 0x002A:
case 0x002B:
case 0x002C:
case 0x002D:
case 0x002E:
case 0x002F:
case 0x0030:
case 0x0031:
case 0x0032:
case 0x0033:
case 0x0034:
case 0x0035:
case 0x0036:
case 0x0037:
case 0x0038:
case 0x0039:
case 0x003A:
case 0x003B:
case 0x003C:
case 0x003D:
case 0x003E:
case 0x003F:
case 0x0040:
case 0x0041:
case 0x0042:
case 0x0043:
case 0x0044:
case 0x0045:
case 0x0046:
case 0x0047:
case 0x0048:
case 0x0049:
case 0x004A:
case 0x004B:
case 0x004C:
case 0x004D:
case 0x004E:
case 0x004F:
case 0x0050:
case 0x0051:
case 0x0052:
case 0x0053:
case 0x0054:
case 0x0055:
case 0x0056:
case 0x0057:
case 0x0058:
case 0x0059:
case 0x005A:
case 0x005B:
case 0x005C:
case 0x005D:
case 0x005E:
case 0x005F:
case 0x0060:
case 0x0061:
case 0x0062:
case 0x0063:
case 0x0064:
case 0x0065:
case 0x0066:
case 0x0067:
case 0x0068:
case 0x0069:
case 0x006A:
case 0x006B:
case 0x006C:
case 0x006D:
case 0x006E:
case 0x006F:
case 0x0070:
case 0x0071:
case 0x0072:
case 0x0073:
case 0x0074:
case 0x0075:
case 0x0076:
case 0x0077:
case 0x0078:
case 0x0079:
case 0x007A:
case 0x007B:
case 0x007C:
case 0x007D:
case 0x007E:
break;
case 0x001A: ch = 0x7F; break;
case 0x001C: ch = 0x1A; break;
case 0x007F: ch = 0x1C; break;
case 0x00A0: ch = 0xFF; break;
case 0x00A4: ch = 0xFD; break;
case 0x00A7: ch = 0x15; break;
case 0x00B0: ch = 0xF8; break;
case 0x00B6: ch = 0x14; break;
case 0x00B7: ch = 0xFA; break;
case 0x0401: ch = 0xF0; break;
case 0x0404: ch = 0xF2; break;
case 0x0407: ch = 0xF4; break;
case 0x040E: ch = 0xF6; break;
case 0x0410:
case 0x0411:
case 0x0412:
case 0x0413:
case 0x0414:
case 0x0415:
case 0x0416:
case 0x0417:
case 0x0418:
case 0x0419:
case 0x041A:
case 0x041B:
case 0x041C:
case 0x041D:
case 0x041E:
case 0x041F:
case 0x0420:
case 0x0421:
case 0x0422:
case 0x0423:
case 0x0424:
case 0x0425:
case 0x0426:
case 0x0427:
case 0x0428:
case 0x0429:
case 0x042A:
case 0x042B:
case 0x042C:
case 0x042D:
case 0x042E:
case 0x042F:
case 0x0430:
case 0x0431:
case 0x0432:
case 0x0433:
case 0x0434:
case 0x0435:
case 0x0436:
case 0x0437:
case 0x0438:
case 0x0439:
case 0x043A:
case 0x043B:
case 0x043C:
case 0x043D:
case 0x043E:
case 0x043F:
ch -= 0x0390;
break;
case 0x0440:
case 0x0441:
case 0x0442:
case 0x0443:
case 0x0444:
case 0x0445:
case 0x0446:
case 0x0447:
case 0x0448:
case 0x0449:
case 0x044A:
case 0x044B:
case 0x044C:
case 0x044D:
case 0x044E:
case 0x044F:
ch -= 0x0360;
break;
case 0x0451: ch = 0xF1; break;
case 0x0454: ch = 0xF3; break;
case 0x0457: ch = 0xF5; break;
case 0x045E: ch = 0xF7; break;
case 0x2022: ch = 0x07; break;
case 0x203C: ch = 0x13; break;
case 0x2116: ch = 0xFC; break;
case 0x2190: ch = 0x1B; break;
case 0x2191: ch = 0x18; break;
case 0x2192: ch = 0x1A; break;
case 0x2193: ch = 0x19; break;
case 0x2194: ch = 0x1D; break;
case 0x2195: ch = 0x12; break;
case 0x21A8: ch = 0x17; break;
case 0x2219: ch = 0xF9; break;
case 0x221A: ch = 0xFB; break;
case 0x221F: ch = 0x1C; break;
case 0x2302: ch = 0x7F; break;
case 0x2500: ch = 0xC4; break;
case 0x2502: ch = 0xB3; break;
case 0x250C: ch = 0xDA; break;
case 0x2510: ch = 0xBF; break;
case 0x2514: ch = 0xC0; break;
case 0x2518: ch = 0xD9; break;
case 0x251C: ch = 0xC3; break;
case 0x2524: ch = 0xB4; break;
case 0x252C: ch = 0xC2; break;
case 0x2534: ch = 0xC1; break;
case 0x253C: ch = 0xC5; break;
case 0x2550: ch = 0xCD; break;
case 0x2551: ch = 0xBA; break;
case 0x2552: ch = 0xD5; break;
case 0x2553: ch = 0xD6; break;
case 0x2554: ch = 0xC9; break;
case 0x2555: ch = 0xB8; break;
case 0x2556: ch = 0xB7; break;
case 0x2557: ch = 0xBB; break;
case 0x2558: ch = 0xD4; break;
case 0x2559: ch = 0xD3; break;
case 0x255A: ch = 0xC8; break;
case 0x255B: ch = 0xBE; break;
case 0x255C: ch = 0xBD; break;
case 0x255D: ch = 0xBC; break;
case 0x255E: ch = 0xC6; break;
case 0x255F: ch = 0xC7; break;
case 0x2560: ch = 0xCC; break;
case 0x2561: ch = 0xB5; break;
case 0x2562: ch = 0xB6; break;
case 0x2563: ch = 0xB9; break;
case 0x2564: ch = 0xD1; break;
case 0x2565: ch = 0xD2; break;
case 0x2566: ch = 0xCB; break;
case 0x2567: ch = 0xCF; break;
case 0x2568: ch = 0xD0; break;
case 0x2569: ch = 0xCA; break;
case 0x256A: ch = 0xD8; break;
case 0x256B: ch = 0xD7; break;
case 0x256C: ch = 0xCE; break;
case 0x2580: ch = 0xDF; break;
case 0x2584: ch = 0xDC; break;
case 0x2588: ch = 0xDB; break;
case 0x258C: ch = 0xDD; break;
case 0x2590: ch = 0xDE; break;
case 0x2591: ch = 0xB0; break;
case 0x2592: ch = 0xB1; break;
case 0x2593: ch = 0xB2; break;
case 0x25A0: ch = 0xFE; break;
case 0x25AC: ch = 0x16; break;
case 0x25B2: ch = 0x1E; break;
case 0x25BA: ch = 0x10; break;
case 0x25BC: ch = 0x1F; break;
case 0x25C4: ch = 0x11; break;
case 0x25CB: ch = 0x09; break;
case 0x25D8: ch = 0x08; break;
case 0x25D9: ch = 0x0A; break;
case 0x263A: ch = 0x01; break;
case 0x263B: ch = 0x02; break;
case 0x263C: ch = 0x0F; break;
case 0x2640: ch = 0x0C; break;
case 0x2642: ch = 0x0B; break;
case 0x2660: ch = 0x06; break;
case 0x2663: ch = 0x05; break;
case 0x2665: ch = 0x03; break;
case 0x2666: ch = 0x04; break;
case 0x266A: ch = 0x0D; break;
case 0x266B: ch = 0x0E; break;
case 0xFFE8: ch = 0xB3; break;
case 0xFFE9: ch = 0x1B; break;
case 0xFFEA: ch = 0x18; break;
case 0xFFEB: ch = 0x1A; break;
case 0xFFEC: ch = 0x19; break;
case 0xFFED: ch = 0xFE; break;
case 0xFFEE: ch = 0x09; break;
default:
{
if(ch >= 0xFF01 && ch <= 0xFF5E)
ch -= 0xFEE0;
else
ch = 0x3F;
}
break;
}
bytes[byteIndex++] = (byte)ch;
--charCount;
}
}
}; // class CP866
public class ENCibm866 : CP866
{
public ENCibm866() : base() {}
}; // class ENCibm866
}; // namespace I18N.Rare
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
using Thrift.Transport;
using System.Globalization;
namespace Thrift.Protocol
{
/// <summary>
/// JSON protocol implementation for thrift.
///
/// This is a full-featured protocol supporting Write and Read.
///
/// Please see the C++ class header for a detailed description of the
/// protocol's wire format.
///
/// Adapted from the Java version.
/// </summary>
public class TJSONProtocol : TProtocol
{
/// <summary>
/// Factory for JSON protocol objects
/// </summary>
public class Factory : TProtocolFactory
{
public TProtocol GetProtocol(TTransport trans)
{
return new TJSONProtocol(trans);
}
}
private static byte[] COMMA = new byte[] { (byte)',' };
private static byte[] COLON = new byte[] { (byte)':' };
private static byte[] LBRACE = new byte[] { (byte)'{' };
private static byte[] RBRACE = new byte[] { (byte)'}' };
private static byte[] LBRACKET = new byte[] { (byte)'[' };
private static byte[] RBRACKET = new byte[] { (byte)']' };
private static byte[] QUOTE = new byte[] { (byte)'"' };
private static byte[] BACKSLASH = new byte[] { (byte)'\\' };
private byte[] ESCSEQ = new byte[] { (byte)'\\', (byte)'u', (byte)'0', (byte)'0' };
private const long VERSION = 1;
private byte[] JSON_CHAR_TABLE = {
0, 0, 0, 0, 0, 0, 0, 0,(byte)'b',(byte)'t',(byte)'n', 0,(byte)'f',(byte)'r', 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1, 1,(byte)'"', 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
};
private char[] ESCAPE_CHARS = "\"\\/bfnrt".ToCharArray();
private byte[] ESCAPE_CHAR_VALS = {
(byte)'"', (byte)'\\', (byte)'/', (byte)'\b', (byte)'\f', (byte)'\n', (byte)'\r', (byte)'\t',
};
private const int DEF_STRING_SIZE = 16;
private static byte[] NAME_BOOL = new byte[] { (byte)'t', (byte)'f' };
private static byte[] NAME_BYTE = new byte[] { (byte)'i', (byte)'8' };
private static byte[] NAME_I16 = new byte[] { (byte)'i', (byte)'1', (byte)'6' };
private static byte[] NAME_I32 = new byte[] { (byte)'i', (byte)'3', (byte)'2' };
private static byte[] NAME_I64 = new byte[] { (byte)'i', (byte)'6', (byte)'4' };
private static byte[] NAME_DOUBLE = new byte[] { (byte)'d', (byte)'b', (byte)'l' };
private static byte[] NAME_STRUCT = new byte[] { (byte)'r', (byte)'e', (byte)'c' };
private static byte[] NAME_STRING = new byte[] { (byte)'s', (byte)'t', (byte)'r' };
private static byte[] NAME_MAP = new byte[] { (byte)'m', (byte)'a', (byte)'p' };
private static byte[] NAME_LIST = new byte[] { (byte)'l', (byte)'s', (byte)'t' };
private static byte[] NAME_SET = new byte[] { (byte)'s', (byte)'e', (byte)'t' };
private static byte[] GetTypeNameForTypeID(TType typeID)
{
switch (typeID)
{
case TType.Bool:
return NAME_BOOL;
case TType.Byte:
return NAME_BYTE;
case TType.I16:
return NAME_I16;
case TType.I32:
return NAME_I32;
case TType.I64:
return NAME_I64;
case TType.Double:
return NAME_DOUBLE;
case TType.String:
return NAME_STRING;
case TType.Struct:
return NAME_STRUCT;
case TType.Map:
return NAME_MAP;
case TType.Set:
return NAME_SET;
case TType.List:
return NAME_LIST;
default:
throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED,
"Unrecognized type");
}
}
private static TType GetTypeIDForTypeName(byte[] name)
{
TType result = TType.Stop;
if (name.Length > 1)
{
switch (name[0])
{
case (byte)'d':
result = TType.Double;
break;
case (byte)'i':
switch (name[1])
{
case (byte)'8':
result = TType.Byte;
break;
case (byte)'1':
result = TType.I16;
break;
case (byte)'3':
result = TType.I32;
break;
case (byte)'6':
result = TType.I64;
break;
}
break;
case (byte)'l':
result = TType.List;
break;
case (byte)'m':
result = TType.Map;
break;
case (byte)'r':
result = TType.Struct;
break;
case (byte)'s':
if (name[1] == (byte)'t')
{
result = TType.String;
}
else if (name[1] == (byte)'e')
{
result = TType.Set;
}
break;
case (byte)'t':
result = TType.Bool;
break;
}
}
if (result == TType.Stop)
{
throw new TProtocolException(TProtocolException.NOT_IMPLEMENTED,
"Unrecognized type");
}
return result;
}
///<summary>
/// Base class for tracking JSON contexts that may require
/// inserting/Reading additional JSON syntax characters
/// This base context does nothing.
///</summary>
protected class JSONBaseContext
{
protected TJSONProtocol proto;
public JSONBaseContext(TJSONProtocol proto)
{
this.proto = proto;
}
public virtual void Write() { }
public virtual void Read() { }
public virtual bool EscapeNumbers() { return false; }
}
///<summary>
/// Context for JSON lists. Will insert/Read commas before each item except
/// for the first one
///</summary>
protected class JSONListContext : JSONBaseContext
{
public JSONListContext(TJSONProtocol protocol)
: base(protocol)
{
}
private bool first = true;
public override void Write()
{
if (first)
{
first = false;
}
else
{
proto.trans.Write(COMMA);
}
}
public override void Read()
{
if (first)
{
first = false;
}
else
{
proto.ReadJSONSyntaxChar(COMMA);
}
}
}
///<summary>
/// Context for JSON records. Will insert/Read colons before the value portion
/// of each record pair, and commas before each key except the first. In
/// addition, will indicate that numbers in the key position need to be
/// escaped in quotes (since JSON keys must be strings).
///</summary>
protected class JSONPairContext : JSONBaseContext
{
public JSONPairContext(TJSONProtocol proto)
: base(proto)
{
}
private bool first = true;
private bool colon = true;
public override void Write()
{
if (first)
{
first = false;
colon = true;
}
else
{
proto.trans.Write(colon ? COLON : COMMA);
colon = !colon;
}
}
public override void Read()
{
if (first)
{
first = false;
colon = true;
}
else
{
proto.ReadJSONSyntaxChar(colon ? COLON : COMMA);
colon = !colon;
}
}
public override bool EscapeNumbers()
{
return colon;
}
}
///<summary>
/// Holds up to one byte from the transport
///</summary>
protected class LookaheadReader
{
protected TJSONProtocol proto;
public LookaheadReader(TJSONProtocol proto)
{
this.proto = proto;
}
private bool hasData;
private byte[] data = new byte[1];
///<summary>
/// Return and consume the next byte to be Read, either taking it from the
/// data buffer if present or getting it from the transport otherwise.
///</summary>
public byte Read()
{
if (hasData)
{
hasData = false;
}
else
{
proto.trans.ReadAll(data, 0, 1);
}
return data[0];
}
///<summary>
/// Return the next byte to be Read without consuming, filling the data
/// buffer if it has not been filled alReady.
///</summary>
public byte Peek()
{
if (!hasData)
{
proto.trans.ReadAll(data, 0, 1);
}
hasData = true;
return data[0];
}
}
// Default encoding
protected Encoding utf8Encoding = UTF8Encoding.UTF8;
// Stack of nested contexts that we may be in
protected Stack<JSONBaseContext> contextStack = new Stack<JSONBaseContext>();
// Current context that we are in
protected JSONBaseContext context;
// Reader that manages a 1-byte buffer
protected LookaheadReader reader;
///<summary>
/// Push a new JSON context onto the stack.
///</summary>
protected void PushContext(JSONBaseContext c)
{
contextStack.Push(context);
context = c;
}
///<summary>
/// Pop the last JSON context off the stack
///</summary>
protected void PopContext()
{
context = contextStack.Pop();
}
///<summary>
/// TJSONProtocol Constructor
///</summary>
public TJSONProtocol(TTransport trans)
: base(trans)
{
context = new JSONBaseContext(this);
reader = new LookaheadReader(this);
}
// Temporary buffer used by several methods
private byte[] tempBuffer = new byte[4];
///<summary>
/// Read a byte that must match b[0]; otherwise an exception is thrown.
/// Marked protected to avoid synthetic accessor in JSONListContext.Read
/// and JSONPairContext.Read
///</summary>
protected void ReadJSONSyntaxChar(byte[] b)
{
byte ch = reader.Read();
if (ch != b[0])
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Unexpected character:" + (char)ch);
}
}
///<summary>
/// Convert a byte containing a hex char ('0'-'9' or 'a'-'f') into its
/// corresponding hex value
///</summary>
private static byte HexVal(byte ch)
{
if ((ch >= '0') && (ch <= '9'))
{
return (byte)((char)ch - '0');
}
else if ((ch >= 'a') && (ch <= 'f'))
{
ch += 10;
return (byte)((char)ch - 'a');
}
else
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Expected hex character");
}
}
///<summary>
/// Convert a byte containing a hex value to its corresponding hex character
///</summary>
private static byte HexChar(byte val)
{
val &= 0x0F;
if (val < 10)
{
return (byte)((char)val + '0');
}
else
{
val -= 10;
return (byte)((char)val + 'a');
}
}
///<summary>
/// Write the bytes in array buf as a JSON characters, escaping as needed
///</summary>
private void WriteJSONString(byte[] b)
{
context.Write();
trans.Write(QUOTE);
int len = b.Length;
for (int i = 0; i < len; i++)
{
if ((b[i] & 0x00FF) >= 0x30)
{
if (b[i] == BACKSLASH[0])
{
trans.Write(BACKSLASH);
trans.Write(BACKSLASH);
}
else
{
trans.Write(b, i, 1);
}
}
else
{
tempBuffer[0] = JSON_CHAR_TABLE[b[i]];
if (tempBuffer[0] == 1)
{
trans.Write(b, i, 1);
}
else if (tempBuffer[0] > 1)
{
trans.Write(BACKSLASH);
trans.Write(tempBuffer, 0, 1);
}
else
{
trans.Write(ESCSEQ);
tempBuffer[0] = HexChar((byte)(b[i] >> 4));
tempBuffer[1] = HexChar(b[i]);
trans.Write(tempBuffer, 0, 2);
}
}
}
trans.Write(QUOTE);
}
///<summary>
/// Write out number as a JSON value. If the context dictates so, it will be
/// wrapped in quotes to output as a JSON string.
///</summary>
private void WriteJSONInteger(long num)
{
context.Write();
String str = num.ToString();
bool escapeNum = context.EscapeNumbers();
if (escapeNum)
trans.Write(QUOTE);
trans.Write(utf8Encoding.GetBytes(str));
if (escapeNum)
trans.Write(QUOTE);
}
///<summary>
/// Write out a double as a JSON value. If it is NaN or infinity or if the
/// context dictates escaping, Write out as JSON string.
///</summary>
private void WriteJSONDouble(double num)
{
context.Write();
String str = num.ToString("G17", CultureInfo.InvariantCulture);
bool special = false;
switch (str[0])
{
case 'N': // NaN
case 'I': // Infinity
special = true;
break;
case '-':
if (str[1] == 'I')
{ // -Infinity
special = true;
}
break;
}
bool escapeNum = special || context.EscapeNumbers();
if (escapeNum)
trans.Write(QUOTE);
trans.Write(utf8Encoding.GetBytes(str));
if (escapeNum)
trans.Write(QUOTE);
}
///<summary>
/// Write out contents of byte array b as a JSON string with base-64 encoded
/// data
///</summary>
private void WriteJSONBase64(byte[] b)
{
context.Write();
trans.Write(QUOTE);
int len = b.Length;
int off = 0;
// Ignore padding
int bound = len >= 2 ? len - 2 : 0;
for (int i = len - 1; i >= bound && b[i] == '='; --i) {
--len;
}
while (len >= 3)
{
// Encode 3 bytes at a time
TBase64Utils.encode(b, off, 3, tempBuffer, 0);
trans.Write(tempBuffer, 0, 4);
off += 3;
len -= 3;
}
if (len > 0)
{
// Encode remainder
TBase64Utils.encode(b, off, len, tempBuffer, 0);
trans.Write(tempBuffer, 0, len + 1);
}
trans.Write(QUOTE);
}
private void WriteJSONObjectStart()
{
context.Write();
trans.Write(LBRACE);
PushContext(new JSONPairContext(this));
}
private void WriteJSONObjectEnd()
{
PopContext();
trans.Write(RBRACE);
}
private void WriteJSONArrayStart()
{
context.Write();
trans.Write(LBRACKET);
PushContext(new JSONListContext(this));
}
private void WriteJSONArrayEnd()
{
PopContext();
trans.Write(RBRACKET);
}
public override void WriteMessageBegin(TMessage message)
{
WriteJSONArrayStart();
WriteJSONInteger(VERSION);
byte[] b = utf8Encoding.GetBytes(message.Name);
WriteJSONString(b);
WriteJSONInteger((long)message.Type);
WriteJSONInteger(message.SeqID);
}
public override void WriteMessageEnd()
{
WriteJSONArrayEnd();
}
public override void WriteStructBegin(TStruct str)
{
WriteJSONObjectStart();
}
public override void WriteStructEnd()
{
WriteJSONObjectEnd();
}
public override void WriteFieldBegin(TField field)
{
WriteJSONInteger(field.ID);
WriteJSONObjectStart();
WriteJSONString(GetTypeNameForTypeID(field.Type));
}
public override void WriteFieldEnd()
{
WriteJSONObjectEnd();
}
public override void WriteFieldStop() { }
public override void WriteMapBegin(TMap map)
{
WriteJSONArrayStart();
WriteJSONString(GetTypeNameForTypeID(map.KeyType));
WriteJSONString(GetTypeNameForTypeID(map.ValueType));
WriteJSONInteger(map.Count);
WriteJSONObjectStart();
}
public override void WriteMapEnd()
{
WriteJSONObjectEnd();
WriteJSONArrayEnd();
}
public override void WriteListBegin(TList list)
{
WriteJSONArrayStart();
WriteJSONString(GetTypeNameForTypeID(list.ElementType));
WriteJSONInteger(list.Count);
}
public override void WriteListEnd()
{
WriteJSONArrayEnd();
}
public override void WriteSetBegin(TSet set)
{
WriteJSONArrayStart();
WriteJSONString(GetTypeNameForTypeID(set.ElementType));
WriteJSONInteger(set.Count);
}
public override void WriteSetEnd()
{
WriteJSONArrayEnd();
}
public override void WriteBool(bool b)
{
WriteJSONInteger(b ? (long)1 : (long)0);
}
public override void WriteByte(sbyte b)
{
WriteJSONInteger((long)b);
}
public override void WriteI16(short i16)
{
WriteJSONInteger((long)i16);
}
public override void WriteI32(int i32)
{
WriteJSONInteger((long)i32);
}
public override void WriteI64(long i64)
{
WriteJSONInteger(i64);
}
public override void WriteDouble(double dub)
{
WriteJSONDouble(dub);
}
public override void WriteString(String str)
{
byte[] b = utf8Encoding.GetBytes(str);
WriteJSONString(b);
}
public override void WriteBinary(byte[] bin)
{
WriteJSONBase64(bin);
}
/**
* Reading methods.
*/
///<summary>
/// Read in a JSON string, unescaping as appropriate.. Skip Reading from the
/// context if skipContext is true.
///</summary>
private byte[] ReadJSONString(bool skipContext)
{
MemoryStream buffer = new MemoryStream();
List<char> codeunits = new List<char>();
if (!skipContext)
{
context.Read();
}
ReadJSONSyntaxChar(QUOTE);
while (true)
{
byte ch = reader.Read();
if (ch == QUOTE[0])
{
break;
}
// escaped?
if (ch != ESCSEQ[0])
{
buffer.Write(new byte[] { (byte)ch }, 0, 1);
continue;
}
// distinguish between \uXXXX and \?
ch = reader.Read();
if (ch != ESCSEQ[1]) // control chars like \n
{
int off = Array.IndexOf(ESCAPE_CHARS, (char)ch);
if (off == -1)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Expected control char");
}
ch = ESCAPE_CHAR_VALS[off];
buffer.Write(new byte[] { (byte)ch }, 0, 1);
continue;
}
// it's \uXXXX
trans.ReadAll(tempBuffer, 0, 4);
var wch = (short)((HexVal((byte)tempBuffer[0]) << 12) +
(HexVal((byte)tempBuffer[1]) << 8) +
(HexVal((byte)tempBuffer[2]) << 4) +
HexVal(tempBuffer[3]));
if (Char.IsHighSurrogate((char)wch))
{
if (codeunits.Count > 0)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Expected low surrogate char");
}
codeunits.Add((char)wch);
}
else if (Char.IsLowSurrogate((char)wch))
{
if (codeunits.Count == 0)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Expected high surrogate char");
}
codeunits.Add((char)wch);
var tmp = utf8Encoding.GetBytes(codeunits.ToArray());
buffer.Write(tmp, 0, tmp.Length);
codeunits.Clear();
}
else
{
var tmp = utf8Encoding.GetBytes(new char[] { (char)wch });
buffer.Write(tmp, 0, tmp.Length);
}
}
if (codeunits.Count > 0)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Expected low surrogate char");
}
return buffer.ToArray();
}
///<summary>
/// Return true if the given byte could be a valid part of a JSON number.
///</summary>
private bool IsJSONNumeric(byte b)
{
switch (b)
{
case (byte)'+':
case (byte)'-':
case (byte)'.':
case (byte)'0':
case (byte)'1':
case (byte)'2':
case (byte)'3':
case (byte)'4':
case (byte)'5':
case (byte)'6':
case (byte)'7':
case (byte)'8':
case (byte)'9':
case (byte)'E':
case (byte)'e':
return true;
}
return false;
}
///<summary>
/// Read in a sequence of characters that are all valid in JSON numbers. Does
/// not do a complete regex check to validate that this is actually a number.
////</summary>
private String ReadJSONNumericChars()
{
StringBuilder strbld = new StringBuilder();
while (true)
{
byte ch = reader.Peek();
if (!IsJSONNumeric(ch))
{
break;
}
strbld.Append((char)reader.Read());
}
return strbld.ToString();
}
///<summary>
/// Read in a JSON number. If the context dictates, Read in enclosing quotes.
///</summary>
private long ReadJSONInteger()
{
context.Read();
if (context.EscapeNumbers())
{
ReadJSONSyntaxChar(QUOTE);
}
String str = ReadJSONNumericChars();
if (context.EscapeNumbers())
{
ReadJSONSyntaxChar(QUOTE);
}
try
{
return Int64.Parse(str);
}
catch (FormatException)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Bad data encounted in numeric data");
}
}
///<summary>
/// Read in a JSON double value. Throw if the value is not wrapped in quotes
/// when expected or if wrapped in quotes when not expected.
///</summary>
private double ReadJSONDouble()
{
context.Read();
if (reader.Peek() == QUOTE[0])
{
byte[] arr = ReadJSONString(true);
double dub = Double.Parse(utf8Encoding.GetString(arr,0,arr.Length), CultureInfo.InvariantCulture);
if (!context.EscapeNumbers() && !Double.IsNaN(dub) &&
!Double.IsInfinity(dub))
{
// Throw exception -- we should not be in a string in this case
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Numeric data unexpectedly quoted");
}
return dub;
}
else
{
if (context.EscapeNumbers())
{
// This will throw - we should have had a quote if escapeNum == true
ReadJSONSyntaxChar(QUOTE);
}
try
{
return Double.Parse(ReadJSONNumericChars(), CultureInfo.InvariantCulture);
}
catch (FormatException)
{
throw new TProtocolException(TProtocolException.INVALID_DATA,
"Bad data encounted in numeric data");
}
}
}
//<summary>
/// Read in a JSON string containing base-64 encoded data and decode it.
///</summary>
private byte[] ReadJSONBase64()
{
byte[] b = ReadJSONString(false);
int len = b.Length;
int off = 0;
int size = 0;
// reduce len to ignore fill bytes
while ((len > 0) && (b[len - 1] == '='))
{
--len;
}
// read & decode full byte triplets = 4 source bytes
while (len > 4)
{
// Decode 4 bytes at a time
TBase64Utils.decode(b, off, 4, b, size); // NB: decoded in place
off += 4;
len -= 4;
size += 3;
}
// Don't decode if we hit the end or got a single leftover byte (invalid
// base64 but legal for skip of regular string type)
if (len > 1)
{
// Decode remainder
TBase64Utils.decode(b, off, len, b, size); // NB: decoded in place
size += len - 1;
}
// Sadly we must copy the byte[] (any way around this?)
byte[] result = new byte[size];
Array.Copy(b, 0, result, 0, size);
return result;
}
private void ReadJSONObjectStart()
{
context.Read();
ReadJSONSyntaxChar(LBRACE);
PushContext(new JSONPairContext(this));
}
private void ReadJSONObjectEnd()
{
ReadJSONSyntaxChar(RBRACE);
PopContext();
}
private void ReadJSONArrayStart()
{
context.Read();
ReadJSONSyntaxChar(LBRACKET);
PushContext(new JSONListContext(this));
}
private void ReadJSONArrayEnd()
{
ReadJSONSyntaxChar(RBRACKET);
PopContext();
}
public override TMessage ReadMessageBegin()
{
TMessage message = new TMessage();
ReadJSONArrayStart();
if (ReadJSONInteger() != VERSION)
{
throw new TProtocolException(TProtocolException.BAD_VERSION,
"Message contained bad version.");
}
var buf = ReadJSONString(false);
message.Name = utf8Encoding.GetString(buf,0,buf.Length);
message.Type = (TMessageType)ReadJSONInteger();
message.SeqID = (int)ReadJSONInteger();
return message;
}
public override void ReadMessageEnd()
{
ReadJSONArrayEnd();
}
public override TStruct ReadStructBegin()
{
ReadJSONObjectStart();
return new TStruct();
}
public override void ReadStructEnd()
{
ReadJSONObjectEnd();
}
public override TField ReadFieldBegin()
{
TField field = new TField();
byte ch = reader.Peek();
if (ch == RBRACE[0])
{
field.Type = TType.Stop;
}
else
{
field.ID = (short)ReadJSONInteger();
ReadJSONObjectStart();
field.Type = GetTypeIDForTypeName(ReadJSONString(false));
}
return field;
}
public override void ReadFieldEnd()
{
ReadJSONObjectEnd();
}
public override TMap ReadMapBegin()
{
TMap map = new TMap();
ReadJSONArrayStart();
map.KeyType = GetTypeIDForTypeName(ReadJSONString(false));
map.ValueType = GetTypeIDForTypeName(ReadJSONString(false));
map.Count = (int)ReadJSONInteger();
ReadJSONObjectStart();
return map;
}
public override void ReadMapEnd()
{
ReadJSONObjectEnd();
ReadJSONArrayEnd();
}
public override TList ReadListBegin()
{
TList list = new TList();
ReadJSONArrayStart();
list.ElementType = GetTypeIDForTypeName(ReadJSONString(false));
list.Count = (int)ReadJSONInteger();
return list;
}
public override void ReadListEnd()
{
ReadJSONArrayEnd();
}
public override TSet ReadSetBegin()
{
TSet set = new TSet();
ReadJSONArrayStart();
set.ElementType = GetTypeIDForTypeName(ReadJSONString(false));
set.Count = (int)ReadJSONInteger();
return set;
}
public override void ReadSetEnd()
{
ReadJSONArrayEnd();
}
public override bool ReadBool()
{
return (ReadJSONInteger() == 0 ? false : true);
}
public override sbyte ReadByte()
{
return (sbyte)ReadJSONInteger();
}
public override short ReadI16()
{
return (short)ReadJSONInteger();
}
public override int ReadI32()
{
return (int)ReadJSONInteger();
}
public override long ReadI64()
{
return (long)ReadJSONInteger();
}
public override double ReadDouble()
{
return ReadJSONDouble();
}
public override String ReadString()
{
var buf = ReadJSONString(false);
return utf8Encoding.GetString(buf,0,buf.Length);
}
public override byte[] ReadBinary()
{
return ReadJSONBase64();
}
}
}
| |
// Helpers/Settings.cs
using System;
using Plugin.Settings;
using Plugin.Settings.Abstractions;
using RaceDay.Model;
using Xamarin.Forms;
namespace RaceDay.Helpers
{
/// <summary>
/// This is the Settings static class that can be used in your Core solution or in any
/// of your client applications. All settings are laid out the same exact way with getters
/// and setters.
/// </summary>
public static class Settings
{
public enum ApplicationRole
{
NotInGroup = -1,
Denied = 1,
Member = 5,
Admin = 10
};
private static ISettings AppSettings
{
get
{
return CrossSettings.Current;
}
}
#region Setting Constants
// User information obtained from Facebook
//
private const string ApiUrlKey = "apiurl_key";
private const string GroupNameKey = "groupname_key";
private const string GroupCodeKey = "groupcode_key";
private const string GroupApiKey = "groupapi_key";
private const string UserIdKey = "userid_key";
private const string UserNameKey = "username_key";
private const string UserFirstNameKey = "userfirstname_key";
private const string UserLastNameKey = "userlastname_key";
private const string UserEmailKey = "useremail_key";
private const string UserPasswordKey = "userpassword_key";
private const string AppThemeKey = "apptheme_key";
// Access Token authorizing REST client to the server API
//
private const string AccessTokenKey = "accesstoken_key";
private static readonly string AccessTokenDefault = string.Empty;
private const string AccessExpirationKey = "accessexpiration_key";
private static readonly DateTime AccessExpirationDefault = DateTime.MinValue;
private const string AccessRoleKey = "accessrole_key";
private static readonly int AccessRoleDefault = (int)ApplicationRole.Member;
// Application notification settings (future)
//
private const string NotifyNewRaceKey = "notifynewrace_key";
private static readonly bool NotifyNewRaceDefault = false;
private const string NotifyParticipantJoinsKey = "notifyparticipantjoins_key";
private static readonly bool NotifyParticipantJoinsDefault = false;
private const string HideInformationKey = "hideinformation_key";
private static readonly bool HideInformationDefault = false;
#endregion
public static string APIUrl
{
get
{
return AppSettings.GetValueOrDefault(ApiUrlKey, SettingsDefaults.ApiUrlDefault);
}
}
public static string GroupName
{
get
{
return AppSettings.GetValueOrDefault(GroupNameKey, SettingsDefaults.GroupNameDefault);
}
set
{
AppSettings.AddOrUpdateValue(GroupNameKey, value);
}
}
public static string GroupCode
{
get
{
return AppSettings.GetValueOrDefault(GroupCodeKey, SettingsDefaults.GroupCodeDefault);
}
set
{
AppSettings.AddOrUpdateValue(GroupCodeKey, value);
}
}
public static string GroupApi
{
get
{
return AppSettings.GetValueOrDefault(GroupApiKey, SettingsDefaults.GroupApiDefault);
}
set
{
AppSettings.AddOrUpdateValue(GroupApiKey, value);
}
}
public static string UserId
{
get
{
return AppSettings.GetValueOrDefault(UserIdKey, SettingsDefaults.UserIdDefault);
}
set
{
AppSettings.AddOrUpdateValue(UserIdKey, value);
}
}
public static string UserName
{
get
{
return AppSettings.GetValueOrDefault(UserNameKey, SettingsDefaults.UserNameDefault);
}
set
{
AppSettings.AddOrUpdateValue(UserNameKey, value);
}
}
public static string UserFirstName
{
get
{
return AppSettings.GetValueOrDefault(UserFirstNameKey, String.Empty);
}
set
{
AppSettings.AddOrUpdateValue(UserFirstNameKey, value);
}
}
public static string UserLastName
{
get
{
return AppSettings.GetValueOrDefault(UserLastNameKey, String.Empty);
}
set
{
AppSettings.AddOrUpdateValue(UserLastNameKey, value);
}
}
public static string UserEmail
{
get
{
return AppSettings.GetValueOrDefault(UserEmailKey, SettingsDefaults.UserEmailDefault);
}
set
{
AppSettings.AddOrUpdateValue(UserEmailKey, value);
}
}
public static string UserPassword
{
get
{
return AppSettings.GetValueOrDefault(UserPasswordKey, String.Empty);
}
set
{
AppSettings.AddOrUpdateValue(UserPasswordKey, value);
}
}
public static OSAppTheme AppTheme
{
get
{
var defaultTheme = Application.Current.RequestedTheme == OSAppTheme.Light ? 0 : 1;
var intTheme = AppSettings.GetValueOrDefault(AppThemeKey, defaultTheme);
return (intTheme == 0 ? OSAppTheme.Light : intTheme == 1 ? OSAppTheme.Dark : OSAppTheme.Unspecified);
}
set
{
if (value == OSAppTheme.Light)
AppSettings.AddOrUpdateValue(AppThemeKey, 0);
else if (value == OSAppTheme.Dark)
AppSettings.AddOrUpdateValue(AppThemeKey, 1);
else
AppSettings.AddOrUpdateValue(AppThemeKey, 2);
}
}
public static string AccessToken
{
get
{
return AppSettings.GetValueOrDefault(AccessTokenKey, AccessTokenDefault);
}
set
{
AppSettings.AddOrUpdateValue(AccessTokenKey, value);
}
}
public static DateTime AccessExpiration
{
get
{
return AppSettings.GetValueOrDefault(AccessExpirationKey, AccessExpirationDefault);
}
set
{
AppSettings.AddOrUpdateValue(AccessExpirationKey, value);
}
}
public static int AccessRole
{
get
{
return AppSettings.GetValueOrDefault(AccessRoleKey, AccessRoleDefault);
}
set
{
AppSettings.AddOrUpdateValue(AccessRoleKey, value);
}
}
public static Boolean IsAuthenticated
{
get
{
return !string.IsNullOrEmpty(UserEmail) && !string.IsNullOrEmpty(UserPassword);
}
}
public static bool NotifyNewRace
{
get
{
return AppSettings.GetValueOrDefault(NotifyNewRaceKey, NotifyNewRaceDefault);
}
set
{
AppSettings.AddOrUpdateValue(NotifyNewRaceKey, value);
}
}
public static bool NotifyParticipantJoins
{
get
{
return AppSettings.GetValueOrDefault(NotifyParticipantJoinsKey, NotifyParticipantJoinsDefault);
}
set
{
AppSettings.AddOrUpdateValue(NotifyParticipantJoinsKey, value);
}
}
public static bool HideInformation
{
get
{
return AppSettings.GetValueOrDefault(HideInformationKey, HideInformationDefault);
}
set
{
AppSettings.AddOrUpdateValue(HideInformationKey, value);
}
}
// Retrieve stored Access Token, if available. If no token stored or it has expired, then return null
//
public static AccessToken Token
{
get
{
AccessToken token = new AccessToken
{
Token = AccessToken,
Expiration = AccessExpiration,
Role = AccessRole,
};
if (string.IsNullOrEmpty(token.Token) || (token.Expiration < DateTime.Now))
return null;
return token;
}
set
{
if (value != null)
{
AccessToken = value.Token;
AccessExpiration = value.Expiration;
AccessRole = value.Role;
}
}
}
}
}
| |
// 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.Diagnostics;
using System.Net.Security;
using System.Runtime.InteropServices;
using System.Security.Authentication;
using System.Security.Authentication.ExtendedProtection;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using Microsoft.Win32.SafeHandles;
internal static partial class Interop
{
internal static partial class Ssl
{
internal delegate int SslCtxSetVerifyCallback(int preverify_ok, IntPtr x509_ctx);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_EnsureLibSslInitialized")]
internal static extern void EnsureLibSslInitialized();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV2_3Method")]
internal static extern IntPtr SslV2_3Method();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslV3Method")]
internal static extern IntPtr SslV3Method();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_TlsV1Method")]
internal static extern IntPtr TlsV1Method();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_TlsV1_1Method")]
internal static extern IntPtr TlsV1_1Method();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_TlsV1_2Method")]
internal static extern IntPtr TlsV1_2Method();
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslCreate")]
internal static extern SafeSslHandle SslCreate(SafeSslContextHandle ctx);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")]
internal static extern SslErrorCode SslGetError(SafeSslHandle ssl, int ret);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetError")]
internal static extern SslErrorCode SslGetError(IntPtr ssl, int ret);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDestroy")]
internal static extern void SslDestroy(IntPtr ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetConnectState")]
internal static extern void SslSetConnectState(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetAcceptState")]
internal static extern void SslSetAcceptState(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetVersion")]
private static extern IntPtr SslGetVersion(SafeSslHandle ssl);
internal static string GetProtocolVersion(SafeSslHandle ssl)
{
return Marshal.PtrToStringAnsi(SslGetVersion(ssl));
}
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_GetSslConnectionInfo")]
internal static extern bool GetSslConnectionInfo(
SafeSslHandle ssl,
out int dataCipherAlg,
out int keyExchangeAlg,
out int dataHashAlg,
out int dataKeySize,
out int hashKeySize);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslWrite")]
internal static unsafe extern int SslWrite(SafeSslHandle ssl, byte* buf, int num);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslRead")]
internal static extern int SslRead(SafeSslHandle ssl, byte[] buf, int num);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslRenegotiatePending")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsSslRenegotiatePending(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslShutdown")]
internal static extern int SslShutdown(IntPtr ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSetBio")]
internal static extern void SslSetBio(SafeSslHandle ssl, SafeBioHandle rbio, SafeBioHandle wbio);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslDoHandshake")]
internal static extern int SslDoHandshake(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_IsSslStateOK")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool IsSslStateOK(SafeSslHandle ssl);
// NOTE: this is just an (unsafe) overload to the BioWrite method from Interop.Bio.cs.
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_BioWrite")]
internal static unsafe extern int BioWrite(SafeBioHandle b, byte* data, int len);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertificate")]
internal static extern SafeX509Handle SslGetPeerCertificate(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerCertChain")]
internal static extern SafeSharedX509StackHandle SslGetPeerCertChain(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetPeerFinished")]
internal static extern int SslGetPeerFinished(SafeSslHandle ssl, IntPtr buf, int count);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetFinished")]
internal static extern int SslGetFinished(SafeSslHandle ssl, IntPtr buf, int count);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslSessionReused")]
internal static extern bool SslSessionReused(SafeSslHandle ssl);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslAddExtraChainCert")]
internal static extern bool SslAddExtraChainCert(SafeSslHandle ssl, SafeX509Handle x509);
[DllImport(Libraries.CryptoNative, EntryPoint = "CryptoNative_SslGetClientCAList")]
private static extern SafeSharedX509NameStackHandle SslGetClientCAList_private(SafeSslHandle ssl);
internal static SafeSharedX509NameStackHandle SslGetClientCAList(SafeSslHandle ssl)
{
Crypto.CheckValidOpenSslHandle(ssl);
SafeSharedX509NameStackHandle handle = SslGetClientCAList_private(ssl);
if (!handle.IsInvalid)
{
handle.SetParent(ssl);
}
return handle;
}
internal static bool AddExtraChainCertificates(SafeSslHandle sslContext, X509Chain chain)
{
Debug.Assert(chain != null, "X509Chain should not be null");
Debug.Assert(chain.ChainElements.Count > 0, "chain.Build should have already been called");
for (int i = chain.ChainElements.Count - 2; i > 0; i--)
{
SafeX509Handle dupCertHandle = Crypto.X509UpRef(chain.ChainElements[i].Certificate.Handle);
Crypto.CheckValidOpenSslHandle(dupCertHandle);
if (!SslAddExtraChainCert(sslContext, dupCertHandle))
{
dupCertHandle.Dispose(); // we still own the safe handle; clean it up
return false;
}
dupCertHandle.SetHandleAsInvalid(); // ownership has been transferred to sslHandle; do not free via this safe handle
}
return true;
}
internal static class SslMethods
{
internal static readonly IntPtr TLSv1_method = TlsV1Method();
internal static readonly IntPtr TLSv1_1_method = TlsV1_1Method();
internal static readonly IntPtr TLSv1_2_method = TlsV1_2Method();
internal static readonly IntPtr SSLv3_method = SslV3Method();
internal static readonly IntPtr SSLv23_method = SslV2_3Method();
}
internal enum SslErrorCode
{
SSL_ERROR_NONE = 0,
SSL_ERROR_SSL = 1,
SSL_ERROR_WANT_READ = 2,
SSL_ERROR_WANT_WRITE = 3,
SSL_ERROR_SYSCALL = 5,
SSL_ERROR_ZERO_RETURN = 6,
// NOTE: this SslErrorCode value doesn't exist in OpenSSL, but
// we use it to distinguish when a renegotiation is pending.
// Choosing an arbitrarily large value that shouldn't conflict
// with any actual OpenSSL error codes
SSL_ERROR_RENEGOTIATE = 29304
}
}
}
namespace Microsoft.Win32.SafeHandles
{
internal sealed class SafeSslHandle : SafeHandle
{
private SafeBioHandle _readBio;
private SafeBioHandle _writeBio;
private bool _isServer;
private bool _handshakeCompleted = false;
public bool IsServer
{
get { return _isServer; }
}
public SafeBioHandle InputBio
{
get
{
return _readBio;
}
}
public SafeBioHandle OutputBio
{
get
{
return _writeBio;
}
}
internal void MarkHandshakeCompleted()
{
_handshakeCompleted = true;
}
public static SafeSslHandle Create(SafeSslContextHandle context, bool isServer)
{
SafeBioHandle readBio = Interop.Crypto.CreateMemoryBio();
SafeBioHandle writeBio = Interop.Crypto.CreateMemoryBio();
SafeSslHandle handle = Interop.Ssl.SslCreate(context);
if (readBio.IsInvalid || writeBio.IsInvalid || handle.IsInvalid)
{
readBio.Dispose();
writeBio.Dispose();
handle.Dispose(); // will make IsInvalid==true if it's not already
return handle;
}
handle._isServer = isServer;
// SslSetBio will transfer ownership of the BIO handles to the SSL context
try
{
readBio.TransferOwnershipToParent(handle);
writeBio.TransferOwnershipToParent(handle);
handle._readBio = readBio;
handle._writeBio = writeBio;
Interop.Ssl.SslSetBio(handle, readBio, writeBio);
}
catch (Exception exc)
{
// The only way this should be able to happen without thread aborts is if we hit OOMs while
// manipulating the safe handles, in which case we may leak the bio handles.
Debug.Fail("Unexpected exception while transferring SafeBioHandle ownership to SafeSslHandle", exc.ToString());
throw;
}
if (isServer)
{
Interop.Ssl.SslSetAcceptState(handle);
}
else
{
Interop.Ssl.SslSetConnectState(handle);
}
return handle;
}
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_readBio?.Dispose();
_writeBio?.Dispose();
}
base.Dispose(disposing);
}
protected override bool ReleaseHandle()
{
if (_handshakeCompleted)
{
Disconnect();
}
IntPtr h = handle;
SetHandle(IntPtr.Zero);
Interop.Ssl.SslDestroy(h); // will free the handles underlying _readBio and _writeBio
return true;
}
private void Disconnect()
{
Debug.Assert(!IsInvalid, "Expected a valid context in Disconnect");
// Because we set "quiet shutdown" on the SSL_CTX, SslShutdown is supposed
// to always return 1 (completed success). In "close-notify" shutdown (the
// opposite of quiet) there's also 0 (incomplete success) and negative
// (probably async IO WANT_READ/WANT_WRITE, but need to check) return codes
// to handle.
//
// If quiet shutdown is ever not set, see
// https://www.openssl.org/docs/manmaster/ssl/SSL_shutdown.html
// for guidance on how to rewrite this method.
int retVal = Interop.Ssl.SslShutdown(handle);
Debug.Assert(retVal == 1);
}
private SafeSslHandle() : base(IntPtr.Zero, true)
{
}
internal SafeSslHandle(IntPtr validSslPointer, bool ownsHandle) : base(IntPtr.Zero, ownsHandle)
{
handle = validSslPointer;
}
}
internal sealed class SafeChannelBindingHandle : SafeHandle
{
[StructLayout(LayoutKind.Sequential)]
private struct SecChannelBindings
{
internal int InitiatorLength;
internal int InitiatorOffset;
internal int AcceptorAddrType;
internal int AcceptorLength;
internal int AcceptorOffset;
internal int ApplicationDataLength;
internal int ApplicationDataOffset;
}
private const int CertHashMaxSize = 128;
private static readonly byte[] s_tlsServerEndPointByteArray = Encoding.UTF8.GetBytes("tls-server-end-point:");
private static readonly byte[] s_tlsUniqueByteArray = Encoding.UTF8.GetBytes("tls-unique:");
private static readonly int s_secChannelBindingSize = Marshal.SizeOf<SecChannelBindings>();
private readonly int _cbtPrefixByteArraySize;
internal int Length { get; private set; }
internal IntPtr CertHashPtr { get; private set; }
internal void SetCertHash(byte[] certHashBytes)
{
Debug.Assert(certHashBytes != null, "check certHashBytes is not null");
Debug.Assert(certHashBytes.Length <= CertHashMaxSize);
int length = certHashBytes.Length;
Marshal.Copy(certHashBytes, 0, CertHashPtr, length);
SetCertHashLength(length);
}
private byte[] GetPrefixBytes(ChannelBindingKind kind)
{
Debug.Assert(kind == ChannelBindingKind.Endpoint || kind == ChannelBindingKind.Unique);
return kind == ChannelBindingKind.Endpoint ?
s_tlsServerEndPointByteArray :
s_tlsUniqueByteArray;
}
internal SafeChannelBindingHandle(ChannelBindingKind kind)
: base(IntPtr.Zero, true)
{
byte[] cbtPrefix = GetPrefixBytes(kind);
_cbtPrefixByteArraySize = cbtPrefix.Length;
handle = Marshal.AllocHGlobal(s_secChannelBindingSize + _cbtPrefixByteArraySize + CertHashMaxSize);
IntPtr cbtPrefixPtr = handle + s_secChannelBindingSize;
Marshal.Copy(cbtPrefix, 0, cbtPrefixPtr, _cbtPrefixByteArraySize);
CertHashPtr = cbtPrefixPtr + _cbtPrefixByteArraySize;
Length = CertHashMaxSize;
}
internal void SetCertHashLength(int certHashLength)
{
int cbtLength = _cbtPrefixByteArraySize + certHashLength;
Length = s_secChannelBindingSize + cbtLength;
SecChannelBindings channelBindings = new SecChannelBindings()
{
ApplicationDataLength = cbtLength,
ApplicationDataOffset = s_secChannelBindingSize
};
Marshal.StructureToPtr(channelBindings, handle, true);
}
public override bool IsInvalid => handle == IntPtr.Zero;
protected override bool ReleaseHandle()
{
Marshal.FreeHGlobal(handle);
SetHandle(IntPtr.Zero);
return true;
}
}
}
| |
// InflaterDynHeader.cs
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// 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.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
namespace ICSharpCode.SharpZipLib.Zip.Compression
{
class InflaterDynHeader
{
const int LNUM = 0;
const int DNUM = 1;
const int BLNUM = 2;
const int BLLENS = 3;
const int LENS = 4;
const int REPS = 5;
static readonly int[] repMin = { 3, 3, 11 };
static readonly int[] repBits = { 2, 3, 7 };
byte[] blLens;
byte[] litdistLens;
InflaterHuffmanTree blTree;
int mode;
int lnum, dnum, blnum, num;
int repSymbol;
byte lastLen;
int ptr;
static readonly int[] BL_ORDER =
{ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 };
public InflaterDynHeader()
{
}
public bool Decode(StreamManipulator input)
{
decode_loop:
for (;;) {
switch (mode) {
case LNUM:
lnum = input.PeekBits(5);
if (lnum < 0) {
return false;
}
lnum += 257;
input.DropBits(5);
// System.err.println("LNUM: "+lnum);
mode = DNUM;
goto case DNUM; // fall through
case DNUM:
dnum = input.PeekBits(5);
if (dnum < 0) {
return false;
}
dnum++;
input.DropBits(5);
// System.err.println("DNUM: "+dnum);
num = lnum+dnum;
litdistLens = new byte[num];
mode = BLNUM;
goto case BLNUM; // fall through
case BLNUM:
blnum = input.PeekBits(4);
if (blnum < 0) {
return false;
}
blnum += 4;
input.DropBits(4);
blLens = new byte[19];
ptr = 0;
// System.err.println("BLNUM: "+blnum);
mode = BLLENS;
goto case BLLENS; // fall through
case BLLENS:
while (ptr < blnum) {
int len = input.PeekBits(3);
if (len < 0) {
return false;
}
input.DropBits(3);
// System.err.println("blLens["+BL_ORDER[ptr]+"]: "+len);
blLens[BL_ORDER[ptr]] = (byte) len;
ptr++;
}
blTree = new InflaterHuffmanTree(blLens);
blLens = null;
ptr = 0;
mode = LENS;
goto case LENS; // fall through
case LENS:
{
int symbol;
while (((symbol = blTree.GetSymbol(input)) & ~15) == 0) {
/* Normal case: symbol in [0..15] */
// System.err.println("litdistLens["+ptr+"]: "+symbol);
litdistLens[ptr++] = lastLen = (byte)symbol;
if (ptr == num) {
/* Finished */
return true;
}
}
/* need more input ? */
if (symbol < 0) {
return false;
}
/* otherwise repeat code */
if (symbol >= 17) {
/* repeat zero */
// System.err.println("repeating zero");
lastLen = 0;
} else {
if (ptr == 0) {
throw new Exception();
}
}
repSymbol = symbol-16;
}
mode = REPS;
goto case REPS; // fall through
case REPS:
{
int bits = repBits[repSymbol];
int count = input.PeekBits(bits);
if (count < 0) {
return false;
}
input.DropBits(bits);
count += repMin[repSymbol];
// System.err.println("litdistLens repeated: "+count);
if (ptr + count > num) {
throw new Exception();
}
while (count-- > 0) {
litdistLens[ptr++] = lastLen;
}
if (ptr == num) {
/* Finished */
return true;
}
}
mode = LENS;
goto decode_loop;
}
}
}
public InflaterHuffmanTree BuildLitLenTree()
{
byte[] litlenLens = new byte[lnum];
Array.Copy(litdistLens, 0, litlenLens, 0, lnum);
return new InflaterHuffmanTree(litlenLens);
}
public InflaterHuffmanTree BuildDistTree()
{
byte[] distLens = new byte[dnum];
Array.Copy(litdistLens, lnum, distLens, 0, dnum);
return new InflaterHuffmanTree(distLens);
}
}
}
| |
// leveldb-sharp
//
// Copyright (c) 2011 The LevelDB Authors
// Copyright (c) 2012-2013, Mirco Bauer <meebey@meebey.net>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
using System.Collections;
using System.Collections.Generic;
namespace LevelDB
{
/// <remarks>
/// This type is thread safe.
///
/// Concurrency:
/// A database may only be opened by one process at a time. The leveldb
/// implementation acquires a lock from the operating system to prevent
/// misuse. Within a single process, the same DB object may be safely
/// shared by multiple concurrent threads. I.e., different threads may
/// write into or fetch iterators or call Get on the same database without
/// any external synchronization (the leveldb implementation will
/// automatically do the required synchronization). However other objects
/// (like Iterator and WriteBatch) may require external synchronization.
/// If two threads share such an object, they must protect access to it
/// using their own locking protocol.
/// </remarks>
public class DB : IDisposable, IEnumerable<KeyValuePair<string, string>>
{
/// <summary>
/// Native handle
/// </summary>
public IntPtr Handle { get; private set; }
Options Options { get; set; }
bool Disposed { get; set; }
public string this[string key] {
get {
return Get(null, key);
}
set {
Put(null, key, value);
}
}
public DB(Options options, string path)
{
if (options == null) {
options = new Options();
}
// keep a reference to options as it might contain a cache object
// which needs to stay alive as long as the DB is not closed
Options = options;
Handle = Native.leveldb_open(options.Handle, path);
}
~DB()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
var disposed = Disposed;
if (disposed) {
return;
}
Disposed = true;
if (disposing) {
// free managed
Options = null;
}
// free unmanaged
var handle = Handle;
if (handle != IntPtr.Zero) {
Handle = IntPtr.Zero;
Native.leveldb_close(handle);
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public static DB Open(Options options, string path)
{
return new DB(options, path);
}
public static void Repair(Options options, string path)
{
if (path == null) {
throw new ArgumentNullException("path");
}
if (options == null) {
options = new Options();
}
Native.leveldb_repair_db(options.Handle, path);
}
public static void Destroy(Options options, string path)
{
if (path == null) {
throw new ArgumentNullException("path");
}
if (options == null) {
options = new Options();
}
Native.leveldb_destroy_db(options.Handle, path);
}
public void Put(WriteOptions options, string key, string value)
{
CheckDisposed();
if (options == null) {
options = new WriteOptions();
}
Native.leveldb_put(Handle, options.Handle, key, value);
}
public void Put(string key, string value)
{
Put(null, key, value);
}
public void Delete(WriteOptions options, string key)
{
CheckDisposed();
if (options == null) {
options = new WriteOptions();
}
Native.leveldb_delete(Handle, options.Handle, key);
}
public void Delete(string key)
{
Delete(null, key);
}
public void Write(WriteOptions writeOptions, WriteBatch writeBatch)
{
CheckDisposed();
if (writeOptions == null) {
writeOptions = new WriteOptions();
}
if (writeBatch == null) {
throw new ArgumentNullException("writeBatch");
}
Native.leveldb_write(Handle, writeOptions.Handle, writeBatch.Handle);
}
public void Write(WriteBatch writeBatch)
{
Write(null, writeBatch);
}
public string Get(ReadOptions options, string key)
{
CheckDisposed();
if (options == null) {
options = new ReadOptions();
}
return Native.leveldb_get(Handle, options.Handle, key);
}
public string Get(string key)
{
return Get(null, key);
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator<KeyValuePair<string, string>> GetEnumerator()
{
CheckDisposed();
return new Iterator(this, null);
}
public Snapshot CreateSnapshot()
{
CheckDisposed();
return new Snapshot(this);
}
/// <summary>
/// Compacts the entire database.
/// </summary>
/// <seealso cref="M:DB.CompactRange"/>
public void Compact()
{
CompactRange(null, null);
}
/// <summary>
/// Compact the underlying storage for the key range [startKey,limitKey].
/// In particular, deleted and overwritten versions are discarded,
/// and the data is rearranged to reduce the cost of operations
/// needed to access the data. This operation should typically only
/// be invoked by users who understand the underlying implementation.
/// </summary>
/// <remarks>
/// CompactRange(null, null) will compact the entire database
/// </remarks>
/// <param name="startKey">
/// null is treated as a key before all keys in the database
/// </param>
/// <param name="limitKey">
/// null is treated as a key after all keys in the database
/// </param>
public void CompactRange(string startKey, string limitKey)
{
CheckDisposed();
Native.leveldb_compact_range(Handle, startKey, limitKey);
}
/// <summary>
/// DB implementations can export properties about their state via this
/// method. If "property" is a valid property understood by this DB
/// implementation, it returns its current value. Otherwise it returns
/// null.
///
/// Valid property names include:
/// "leveldb.num-files-at-level<N>" - return the number of files at level <N>,
/// where <N> is an ASCII representation of a level number (e.g. "0").
/// "leveldb.stats" - returns a multi-line string that describes statistics
/// about the internal operation of the DB.
/// "leveldb.sstables" - returns a multi-line string that describes all
/// of the sstables that make up the db contents.
/// </summary>
public string GetProperty(string property)
{
CheckDisposed();
if (property == null) {
throw new ArgumentNullException("property");
}
return Native.leveldb_property_value(Handle, property);
}
void CheckDisposed()
{
if (!Disposed) {
return;
}
throw new ObjectDisposedException(this.GetType().Name);
}
}
}
| |
// Copyright (C) 2015, Felix Kate; All rights reserved
//
// <Class content>
// Class for handling the generation of the arena and as interface between the different classes to
// communicate if there is an active running game etc.
//
using UnityEngine;
using System.Collections;
public class ProcedualArena : MonoBehaviour {
public struct PlayerData{
public Color Color;
public int Vertices;
}
public int TimeLimit = 60;
public float ChestSpawnChance = 0.5f;
public bool DoubleSpeed = false;
public bool GameStarted;
public PlayerData[] ColoredVertices = new PlayerData[4];
public GameObject PlayerPrefab;
public GameObject ChestPrefab;
public int SizeX, SizeY;
public Material FloorMaterial;
private Mesh mesh, edge;
private Vector3[] vertices;
private int[] triangles;
private Vector2[] uvs1;
private Vector2[] uvs2;
private Color[] colors;
private GameObject[] players = new GameObject[4];
private bool canClear;
private bool recalculateColors;
// Game related methods
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Get the mesh colors back to the color array
/// </summary>
void Start(){
mesh = GetComponent<MeshFilter>().mesh;
colors = mesh.colors;
GameStarted = false;
}
/// <summary>
/// Starts the game
/// </summary>
public void StartGame(){
if(GameStarted)return;
//Set up the players
for(int i = 0; i < players.Length; i++){
if(!players[i])continue;
players[i].GetComponent<CubeMovement>().OnStart();
ColoredVertices[i].Color = players[i].GetComponent<CubeMovement>().EntityColor;
}
//Set the game to be started
GameStarted = true;
canClear = true;
}
/// <summary>
/// Update method to watch over the color array
/// </summary>
void Update(){
//Recalculate all colors on the field
if(recalculateColors){
//Calculate the sum of the colors of the players and reset the colored vertices amount
float[] playerColorSum = new float[players.Length];
for(int i = 0; i < players.Length; i++){
playerColorSum[i] = ColoredVertices[i].Color.r + ColoredVertices[i].Color.g + ColoredVertices[i].Color.b;
ColoredVertices[i].Vertices = 0;
}
for(int i = 0; i < colors.Length; i++){
//Decrease the alpha to make a fade out effect
colors[i].a = Mathf.Clamp(colors[i].a - Time.deltaTime * 0.5f, 0, 1);
//Count how many tiles are set to the player colors
for(int j = 0; j < players.Length; j++){
//Only compare sums because it would be 3 checks otherwise
float tileColSum = colors[i].r + colors[i].g + colors[i].b;
if(playerColorSum[j] == tileColSum){
ColoredVertices[j].Vertices++;
}
}
}
recalculateColors = false;
//Only do the fade out
}else{
for(int i = 0; i < colors.Length; i++){
//Decrease the alpha to make a fade out effect
colors[i].a = Mathf.Clamp(colors[i].a - Time.deltaTime * 0.5f, 0, 1);
}
}
mesh.colors = colors;
}
/// <summary>
/// Spawns a player
/// </summary>
public void SpawnPlayer(int playerIndex, Color playerColor, CubeMovement.InputStruct keys){
if(GameStarted)return;
GameObject spawnedPlayer = (GameObject) GameObject.Instantiate(PlayerPrefab, Vector3.zero, Quaternion.identity);
players[playerIndex] = spawnedPlayer;
CubeMovement cMove = spawnedPlayer.GetComponent<CubeMovement>();
cMove.EntityColor = playerColor;
cMove.PlayerNumber = playerIndex;
cMove.InputKeys = keys;
cMove.UpdateColor();
cMove.setStartPosition(this);
}
/// <summary>
/// Remove player
/// </summary>
public void RemovePlayer(int playerIndex){
if(GameStarted)return;
Destroy(players[playerIndex]);
}
/// <summary>
/// Spawn a chest
/// </summary>
public void SpawnChest(){
//Spawn chest object with a chance
if(Random.Range(0.0f, 1.0f) <= ChestSpawnChance){
Vector3 spawnPos = new Vector3(Random.Range (0, SizeX), 0, Random.Range (0, SizeY));
GameObject.Instantiate(ChestPrefab, transform.position + spawnPos + Vector3.one * 0.5f, Quaternion.identity);
}
}
/// <summary>
/// Force an update on the player color
/// </summary>
public void UpdatePlayer(int playerIndex, Color playerColor, CubeMovement.InputStruct keys){
if(GameStarted)return;
CubeMovement cMove = players[playerIndex].GetComponent<CubeMovement>();
cMove.EntityColor = playerColor;
cMove.InputKeys = keys;
cMove.GetComponent<CubeMovement>().UpdateColor();
}
/// <summary>
/// Force all players into their start positions
/// </summary>
public void UpdatePlayerStartPosition(){
if(GameStarted)return;
for(int i = 0; i < players.Length; i++){
if(!players[i])continue;
players[i].GetComponent<CubeMovement>().setStartPosition(this);
}
}
// Coloring and collision checks
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Set color of specific tile
/// </summary>
public void setTile(Vector3 entityPosition, Color color){
Vector3 posOnGrid = entityPosition - transform.position;
int x = Mathf.FloorToInt (posOnGrid.x);
int y = Mathf.FloorToInt (posOnGrid.z);
setColor (x, y, color);
recalculateColors = true;
}
/// <summary>
/// Set colors in a radius
/// </summary>
public void setRadius(Vector3 entityPosition, int radius, Color color){
Vector3 posOnGrid = entityPosition - transform.position;
int x = Mathf.FloorToInt (posOnGrid.x);
int y = Mathf.FloorToInt (posOnGrid.z);
// Besham algorithm code taken from https://de.wikipedia.org/wiki/Bresenham-Algorithmus
while(radius > 0){
int f = 1 - radius;
int ddF_x = 0;
int ddF_y = -2 * radius;
int i = 0;
int j = radius;
while(i < j){
if(f >= 0){
j--;
ddF_y += 2;
f += ddF_y;
}
i++;
ddF_x += 2;
f += ddF_x + 1;
setColor (x + i, y + j, color);
setColor (x - i, y + j, color);
setColor (x + i, y - j, color);
setColor (x - i, y - j, color);
setColor (x + j, y + i, color);
setColor (x - j, y + i, color);
setColor (x + j, y - i, color);
setColor (x - j, y - i, color);
}
radius--;
}
recalculateColors = true;
}
/// <summary>
/// Clear all the tiles
/// </summary>
public void ClearArena(){
if(!canClear)return;
canClear = false;
//Destroy all one round objects and clear old tiles
foreach(GameObject obj in GameObject.FindGameObjectsWithTag("OneRound")){
Destroy(obj);
}
//Clear all tiles
for(int i = 0; i < colors.Length; i++){
colors[i] = new Color(0.05f, 0.05f, 0.05f, 1);
}
recalculateColors = true;
}
/// <summary>
/// Check if object is in bounds
/// </summary>
public bool inBounds(Vector3 entityPosition){
Vector3 posOnGrid = entityPosition - transform.position;
int x = Mathf.FloorToInt (posOnGrid.x);
int y = Mathf.FloorToInt (posOnGrid.z);
return (x >= 0 && x < SizeX && y >= 0 && y < SizeY);
}
/// <summary>
/// Check if object would hit another entity
/// </summary>
public bool wouldCollide(GameObject entity, Vector3 entityPosition){
for(int i = 0; i < players.Length; i++){
if(!players[i] || entity == players[i])continue;
if(players[i].GetComponent<CubeMovement>().BlocksTile(entityPosition))return true;
}
return false;
}
/// <summary>
/// Set the 4 vertex colors around a specific tile
/// </summary>
private void setColor(int x, int y, Color col){
if(x >= 0 && x < SizeX && y >= 0 && y < SizeY){
int vPos = (x + (SizeX * y));
vPos += Mathf.FloorToInt(vPos / SizeX);
colors[vPos] = col;
colors[vPos + 1] = col;
colors[vPos + SizeX + 1] = col;
colors[vPos + SizeX + 2] = col;
}
}
// Mesh Generation
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// <summary>
/// Generate the playground
/// </summary>
public void GenerateArena(){
//Set the camera
Camera.main.transform.position = transform.position + new Vector3(SizeX / 2.0f, 0, SizeY / 2.0f) + Camera.main.transform.forward * -(Mathf.Max(SizeX, SizeY) + 10);
Camera.main.orthographicSize = Mathf.Max(SizeX, SizeY) * 0.75f;
Camera.main.transform.GetChild(0).localScale = new Vector3(3.6f * Camera.main.orthographicSize, 2.025f * Camera.main.orthographicSize, 1);
//Clean old and set new mesh
mesh = new Mesh();
mesh.name = "Arena";
mesh.Clear();
//Set up the arrays
vertices = new Vector3[(SizeX + 1) * (SizeY + 1)];
triangles = new int[SizeX * SizeY * 6];
uvs1 = new Vector2[vertices.Length];
uvs2 = new Vector2[vertices.Length];
colors = new Color[vertices.Length];
//Set the vertices and vertex colors and uvs
for(int i = 0; i < vertices.Length; i++){
int x = i % (SizeX + 1);
int y = Mathf.FloorToInt(i / (SizeX + 1));
vertices[i] = new Vector3(x, 0, y);
colors[i] = new Color(0.05f, 0.05f, 0.05f, 1);
uvs1[i] = new Vector2((float) x / SizeX, (float) y / SizeY); //Main UV over the full mesh
uvs2[i] = new Vector2(x, y); //Sub uv over only one tile
}
//Set the triangles
for(int i = 0; i < triangles.Length / 6; i++){
int firstTri = i + Mathf.FloorToInt(i / SizeX); //Position of the first tri of the quad
triangles[i * 6] = firstTri;
triangles[i * 6 + 1] = firstTri + (SizeX + 1);
triangles[i * 6 + 2] = firstTri + 1;
triangles[i * 6 + 3] = firstTri + 1;
triangles[i * 6 + 4] = firstTri + (SizeX + 1);
triangles[i * 6 + 5] = firstTri + (SizeX + 2);
}
//Set mesh parts
mesh.vertices = vertices;
mesh.triangles = triangles;
mesh.uv = uvs1;
mesh.uv2 = uvs2;
mesh.colors = colors;
mesh.RecalculateBounds ();
mesh.RecalculateNormals ();
//Assign to components
GetComponent<MeshFilter>().mesh = mesh;
GetComponent<MeshRenderer>().material = FloorMaterial;
generateEdge();
Debug.Log("Arena generated");
}
/// <summary>
/// Generate a mesh for the edge to let the arena look like a board
/// </summary>
private void generateEdge(){
//Destroy old edge
if(transform.FindChild("Edge"))DestroyImmediate(transform.FindChild("Edge").gameObject);
GameObject edgeObj = new GameObject("Edge");
edgeObj.transform.SetParent(transform);
edgeObj.AddComponent<MeshFilter>();
edgeObj.AddComponent<MeshRenderer>();
//Clean old and set new mesh
edge = new Mesh();
edge.name = "ArenaEdge";
edge.Clear();
vertices = new Vector3[6];
vertices[0] = new Vector3(0, 0, SizeY);
vertices[1] = new Vector3(0, -0.5f, SizeY);
vertices[2] = new Vector3(0, 0, 0);
vertices[3] = new Vector3(0, -0.5f, 0);
vertices[4] = new Vector3(SizeX, 0, 0);
vertices[5] = new Vector3(SizeX, -0.5f, 0);
triangles = new int[12];
triangles[0] = 0;
triangles[1] = 2;
triangles[2] = 1;
triangles[3] = 2;
triangles[4] = 3;
triangles[5] = 1;
triangles[6] = 2;
triangles[7] = 4;
triangles[8] = 3;
triangles[9] = 4;
triangles[10] = 5;
triangles[11] = 3;
edge.vertices = vertices;
edge.triangles = triangles;
edge.RecalculateBounds ();
edge.RecalculateNormals ();
edgeObj.GetComponent<MeshFilter>().mesh = edge;
edgeObj.GetComponent<MeshRenderer>().material = new Material(Shader.Find ("Unlit/Color"));
edgeObj.GetComponent<MeshRenderer>().sharedMaterial.SetColor ("_Color", new Color(0.1f, 0.1f, 0.1f, 1));
}
}
| |
// 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.
using Microsoft.Research.DataStructures;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Microsoft.Research.CodeAnalysis
{
class Parallel<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly>
{
[ContractInvariantMethod]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Required for code contracts.")]
private void ObjectInvariant()
{
Contract.Invariant(this.metadataDecoder != null);
Contract.Invariant(this.methodNumbers != null);
}
private readonly IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> metadataDecoder;
private readonly MethodNumbers<Method, Type> methodNumbers;
private readonly int bucketSize;
public Parallel(IDecodeMetaData<Local, Parameter, Method, Field, Property, Event, Type, Attribute, Assembly> md, MethodNumbers<Method, Type> methodNumbers, int bucketSize)
{
Contract.Requires(md != null);
Contract.Requires(methodNumbers != null);
this.metadataDecoder = md;
this.methodNumbers = methodNumbers;
this.bucketSize = ComputeBucketSize(bucketSize, this.methodNumbers.Count);
}
/// <summary>
/// Buckets output
/// </summary>
public void RunWithBuckets(string[] args)
{
Contract.Requires(args != null);
args = RemoveArgs(args); // To make cccheck.exe happy
var watch = new Stopwatch();
watch.Start();
var executor = new BucketExecutor();
// var id = 0;
var temp = new ConcurrentBag<IEnumerable<int>>();
// foreach(var bucket in this.GenerateDisjointBuckets())
Parallel.ForEach(
this.GenerateDisjointBuckets(),
bucket =>
{
//PrintBucket(watch, bucket);
temp.Add(bucket);
// executor.AddJob(() => RunOneAnalysis(id++, args, ToSelectArgument(bucket)));
});
var array = temp.ToArray();
Console.WriteLine("Eventually we inferred {0} buckets", array.Count());
foreach(var b in array)
{
PrintBucket(watch, b);
}
//executor.DoAllTheRemainingJobs();
//executor.WaitForStillActiveJobs();
}
// TODO: this method is an hack, make it better using reflection, or probably pushing all to the GeneralOptions object
public static string[] RemoveArgs(string[] args)
{
Contract.Requires(args != null);
Contract.Ensures(Contract.Result<string[]>() != null);
var result = new List<string>(args.Length);
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg.Length > 0)
{
var option = arg.Substring(1).ToLower();
switch (option)
{
case "splitanalysis":
continue;
case "bucketsize":
i++;
continue;
}
// Case "bucketsize=3" or case "splitanalysis=true":
if (option.StartsWith("bucketsize") || option.StartsWith("splitanalysis"))
{
continue;
}
result.Add(arg);
}
}
return result.ToArray();
}
public IEnumerable<IEnumerable<int>> GenerateBucketsBasedOnVisibility()
{
var bucketsCounts = new int[this.methodNumbers.Count];
var methodsInABucket = new List<Method>();
foreach (var m in this.methodNumbers.OrderedMethods())
{
if (metadataDecoder.IsVisibleOutsideAssembly(m)&& metadataDecoder.HasBody(m))
{
var currentBucket = new Set<Method>();
var currentNumbers = new List<int>();
// Get the bucket containing the cone for this method
var bucket = methodNumbers.GetMethodBucket(m);
// Remember we saw those methods
methodsInABucket.AddRange(bucket);
// Add the method number to the current numbers
currentNumbers.Add(this.methodNumbers.GetMethodNumber(m));
// Add the bucket to the current methods
currentBucket.AddRange(bucket);
// If we passed the threshold, then schedule for analysis
if (currentBucket.Count >= this.bucketSize)
{
bucketsCounts[currentBucket.Count]++;
yield return currentNumbers;
}
}
else
{
// skip them for now...
}
}
var methodsNotInABucket = this.methodNumbers.OrderedMethods().Where(m => metadataDecoder.HasBody(m)).Except(methodsInABucket);
var count = methodsNotInABucket.Count();
if (count > 0)
{
Console.WriteLine("*** There are {0} methods not in a bucket from externally visible surface", count);
yield return methodsNotInABucket.Select(m => this.methodNumbers.GetMethodNumber(m));
}
else
{
Console.WriteLine("*** All the methods are reachable from the outside");
}
}
public IEnumerable<IEnumerable<int>> GenerateDisjointBuckets()
{
var bucketsCounts = new int[this.methodNumbers.Count];
var methodsInABucket = new List<Method>();
var concurrentbuckets = new ConcurrentBag<Tuple<int, Set<int>>>();
Console.WriteLine("Creating buckets");
//foreach (var m in this.methodNumbers.OrderedMethods())
Parallel.ForEach(
this.methodNumbers.OrderedMethods().Where(m => metadataDecoder.IsVisibleOutsideAssembly(m) && metadataDecoder.HasBody(m)),
m =>
{
// if (metadataDecoder.IsVisibleOutsideAssembly(m) && metadataDecoder.HasBody(m))
{
var methodNumber = this.methodNumbers.GetMethodNumber(m);
// Get the bucket containing the cone for this method
var bucket = methodNumbers.GetMethodBucket(m);
// Remember we saw those methods
methodsInABucket.AddRange(bucket);
concurrentbuckets.Add(new Tuple<int, Set<int>>(methodNumber, new Set<int>(bucket.Select(method => this.methodNumbers.GetMethodNumber(method)))));
}
});
var buckets = concurrentbuckets.ToArray();
var methodsNotInABucket = this.methodNumbers.OrderedMethods().Except(methodsInABucket);
var methodsWithFewSubsumed = new List<int>();
var count = methodsNotInABucket.Count();
if (count > 0)
{
Console.WriteLine("*** There are {0} methods not in a bucket from externally visible surface", count);
yield return methodsNotInABucket.Select(m => this.methodNumbers.GetMethodNumber(m));
}
else
{
Console.WriteLine("*** All the methods are reachable from the outside");
}
Console.WriteLine("Mergin buckets");
var methodsAlreadyInABucket = new List<int>();
for(var i = 0; i < buckets.Count(); i++)
{
var currentRepresentative = buckets[i].Item1;
if(methodsAlreadyInABucket.Contains(currentRepresentative))
{
continue;
}
var allRepresentativesInThisIteration = new List<int>() { currentRepresentative };
var allSubsumedMethodsInThisIteration = new Set<int>( buckets[i].Item2 );
for (var j = i + 1; j < buckets.Count(); j++)
{
var candidateRepresentative = buckets[j].Item1;
if (methodsAlreadyInABucket.Contains(candidateRepresentative))
{
continue;
}
var methodsSubsumedByTheCandidate = buckets[j].Item2;
if (allSubsumedMethodsInThisIteration.Intersect(methodsSubsumedByTheCandidate).Any())
{
{
Console.WriteLine(" Merging together the methods subsumed by {0} and {1} -- Method {1} subsumes other {2} methods", buckets[i].Item1, candidateRepresentative, buckets[j].Item2.Count);
}
// let's merge!
allRepresentativesInThisIteration.Add(candidateRepresentative);
allSubsumedMethodsInThisIteration.AddRange(methodsSubsumedByTheCandidate);
methodsAlreadyInABucket.Add(j);
methodsAlreadyInABucket.AddRange(methodsSubsumedByTheCandidate);
}
}
if (allSubsumedMethodsInThisIteration.Count == 1)
{
Console.WriteLine(" The method {0} has a trivial subsumption set, adding to the todo buckets", currentRepresentative);
methodsWithFewSubsumed.AddRange(allSubsumedMethodsInThisIteration);
continue;
}
Console.WriteLine(" Top level method(s) = {0}{1} Subsumed method = {2}", ToString(allRepresentativesInThisIteration), Environment.NewLine, ToString(allSubsumedMethodsInThisIteration));
yield return allRepresentativesInThisIteration;
}
if(methodsWithFewSubsumed.Any())
{
Console.WriteLine(" Those are the methods with few subsumed {0}", ToString(methodsWithFewSubsumed));
yield return methodsWithFewSubsumed;
}
}
#region Private workers
private int RunOneAnalysis(int id, string[] args, string selectedMethods)
{
var watch = new Stopwatch(); watch.Start();
var idStr = string.Format("[{0}] ", id);
try
{
Console.WriteLine(idStr + "Running with option = {0}", selectedMethods);
var proc = SetupProcessInfo(GetExecutable(), args, selectedMethods);
using (var exe = Process.Start(proc))
{
Task.Factory.StartNew(
() =>
{
while (!exe.HasExited)
{
var lineErr = exe.StandardError.ReadLine();
Console.WriteLine(idStr + lineErr);
}
var lineOut = exe.StandardError.ReadToEnd();
Console.Write(idStr + lineOut);
});
// Reads the standard output
string line;
while (!exe.HasExited)
{
line = exe.StandardOutput.ReadLine();
Console.WriteLine(idStr + line);
}
line = exe.StandardOutput.ReadToEnd();
Console.WriteLine(idStr + line);
return exe.ExitCode;
}
}
catch
{
Console.WriteLine(idStr + "failed to start the process");
return -1;
}
finally
{
Console.WriteLine(idStr + "Analysis of {0} took {1}", selectedMethods, watch.Elapsed);
// nothing?
}
}
private static string GetExecutable()
{
return System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
// return @"C:\Program Files (x86)\Microsoft\Contracts\Bin\cccheck.exe";
}
private string ToSelectArgument(IEnumerable<int> bucket)
{
var result = new StringBuilder();
result.Append("-select ");
foreach(var i in bucket)
{
result.AppendFormat("{0};",i);
}
return result.ToString();
}
static private ProcessStartInfo SetupProcessInfo(string PathEXE, string[] args, string selectedMethods)
{
var processInfo = new ProcessStartInfo();
processInfo.FileName = PathEXE;
processInfo.CreateNoWindow = false;
processInfo.UseShellExecute = false;
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.RedirectStandardOutput = true;
processInfo.RedirectStandardError = true;
processInfo.Arguments = String.Join(" ", args) + " " + selectedMethods;
return processInfo;
}
private int ComputeBucketSize(int bucketSize, int methodsCount)
{
Contract.Ensures(Contract.Result<int>() >= 1);
if (bucketSize > 0)
{
return bucketSize;
}
else
{
if(methodsCount > 50000)
{
return 1000;
}
if(methodsCount > 10000)
{
return 500;
}
if(methodsCount > 1000)
{
return 50;
}
// else
return 10;
}
}
#endregion
#region Print stuff
private void PrintBucket(Stopwatch watch, IEnumerable<int> bucket)
{
var count = bucket.Count();
// var i = 0;
Console.WriteLine(" There are {0} top-level methods in this bucket ({1} to get it)", count, watch.Elapsed);
/*
foreach(var b in bucket)
{
Console.Write("{0}{1} ", b, i != count - 1 ? ";" : "");
i++;
}
Console.WriteLine();
*/
watch.Restart();
}
private string ToString(IEnumerable<int> what)
{
var str = new StringBuilder();
foreach(var i in what)
{
str.AppendFormat("{0} ", i);
}
return str.ToString();
}
#endregion
}
public class BucketExecutor
{
private static int Threshold()
{
return Math.Max(4, System.Environment.ProcessorCount/2);
}
Set<Task> tasks;
readonly Queue<Action> todo;
public BucketExecutor()
{
this.tasks = new Set<Task>();
this.todo = new Queue<Action>();
}
public void AddJob(Action job)
{
MakeRoom();
this.todo.Enqueue(job);
StartTheAnalysisOfAsManyJobsAsPossible();
}
public void DoAllTheRemainingJobs()
{
do
{
MakeRoom();
StartTheAnalysisOfAsManyJobsAsPossible();
} while (todo.Count != 0);
}
private void StartTheAnalysisOfAsManyJobsAsPossible()
{
while (todo.Count != 0 && tasks.Count <= Threshold())
{
var nextJob = todo.Dequeue();
var task = Task.Factory.StartNew(nextJob);
this.tasks.Add(task);
}
}
private void MakeRoom()
{
if (tasks.Count > 0)
{
var cleanedUp = tasks.Where(t => !t.IsCompleted);
this.tasks = new Set<Task>(cleanedUp);
}
}
internal void WaitForStillActiveJobs()
{
Console.WriteLine("Waiting for all the active tasks to finish");
Task.WaitAll(this.tasks.ToArray());
Console.WriteLine("Done waiting");
}
}
}
| |
// SharpMath - C# Mathematical Library
// Copyright (c) 2014 Morten Bakkedal
// This code is published under the MIT License.
using System;
namespace SharpMath
{
public static class SpecialFunctions
{
/*public static void Test()
{
Console.WriteLine(InverseNormal(Normal(-1.5)));
Console.WriteLine(InverseNormal(Normal(-0.5)));
Console.WriteLine(InverseNormal(Normal(0.5)));
Console.WriteLine(InverseNormal(Normal(1.5)));
Console.WriteLine(InverseNormal(Normal(2.5)));
Console.WriteLine(InverseNormal(Normal(6.5)));
}*/
public static double Polynomial(double x, params double[] coefficients) // FIXME remove
{
double y = 0.0;
for (int i = coefficients.Length - 1; i >= 0; i--)
y = y * x + coefficients[i];
return y;
}
/// <summary>
/// Evaluates the cumulative distribution function (CDF) of the standard normal distribution,
/// $\Phi(x)=\int_{-\infty}^xe^{-t^2/2}dt/\sqrt{2\pi}$.
/// </summary>
public static double Normal(double x)
{
return 0.5 + 0.5 * ErrorFunction(0.70710678118654746 * x);
}
/// <summary>
/// Evaluates the inverse of the cumulative distribution function (CDF) of the standard normal distribution.
/// </summary>
public static double InverseNormal(double p)
{
if (p == 0.0)
{
return double.NegativeInfinity;
}
if (p == 1.0)
{
return double.PositiveInfinity;
}
if (p < 0.0 || p > 1.0)
{
return double.NaN;
}
// This is an implementation of Peter J. Acklam's algorithm. Relative error
// has an absolute value less than 1.15e-9 in the entire region. See
// http://home.online.no/~pjacklam/notes/invnorm/ for details.
double z;
if (p < 0.02425)
{
// Rational approximation for lower region.
double q = Math.Sqrt(-2.0 * Math.Log(p));
z = Polynomial(q, 2.938163982698783, 4.374664141464968, -2.549732539343734, -2.400758277161838, -3.223964580411365e-1, -7.784894002430293e-3) / Polynomial(q, 1.0, 3.754408661907416, 2.445134137142996, 3.224671290700398e-1, 7.784695709041462e-3);
}
else if (p > 0.97575)
{
// Rational approximation for upper region.
double q = Math.Sqrt(-2.0 * Math.Log(1.0 - p));
z = Polynomial(q, -2.938163982698783, -4.374664141464968, 2.549732539343734, 2.400758277161838, 3.223964580411365e-1, 7.784894002430293e-3) / Polynomial(q, 1.0, 3.754408661907416, 2.445134137142996, 3.224671290700398e-1, 7.784695709041462e-3);
}
else
{
// Rational approximation for central region.
double q = p - 0.5;
double q2 = q * q;
z = q * Polynomial(q * q, 2.506628277459239, -3.066479806614716e1, 1.383577518672690e2, -2.759285104469687e2, 2.209460984245205e2, -3.969683028665376e1) / Polynomial(q * q, 1.0, -1.328068155288572e1, 6.680131188771972e1, -1.556989798598866e2, 1.615858368580409e2, -5.447609879822406e1);
}
// Refining algorithm is based on Halley rational method
// for finding roots of equations as described at:
// http://www.math.uio.no/~jacklam/notes/invnorm/index.html
double e = 0.5 * ComplementaryErrorFunction(-z / 1.4142135623730951) - p;
double u = e * Math.Sqrt(2.0 * Math.PI) * Math.Exp(z * z / 2.0);
z = z - u / (1.0 + z * u / 2.0);
return z;
}
/// <summary>
/// Evaluates the density of the standard normal distribution at the point specified.
/// </summary>
public static double NormalDensity(double x)
{
return 0.3989422804014327 * Math.Exp(-0.5 * x * x);
}
public static double ErrorFunction(double x)
{
if (Math.Abs(x) > 1.0)
{
return 1.0 - ComplementaryErrorFunction(x);
}
else
{
//return x * Polynomial(x * x, 5.55923013010394962768e4, 7.00332514112805075473e3, 2.23200534594684319226e3, 9.00260197203842689217e1, 9.60497373987051638749) / Polynomial(x * x, 4.92673942608635921086e4, 2.26290000613890934246e4, 4.59432382970980127987e3, 5.21357949780152679795e2, 3.35617141647503099647e1, 1.0);
double x2 = x * x;
return x * ((((9.60497373987051638749 * x2 + 9.00260197203842689217e1) * x2 + 2.23200534594684319226e3) * x2 + 7.00332514112805075473e3) * x2 + 5.55923013010394962768e4) / (((((x2 + 3.35617141647503099647e1) * x2 + 5.21357949780152679795e2) * x2 + 4.59432382970980127987e3) * x2 + 2.26290000613890934246e4) * x2 + 4.92673942608635921086e4);
}
}
public static double ComplementaryErrorFunction(double a)
{
// This is based on the Cephes Math Library.
double x = Math.Abs(a);
if (x < 1.0)
{
return 1.0 - ErrorFunction(a);
}
double z = -a * a;
if (z < -7.09782712893383996732e2) // -MAXLOG
{
if (a < 0)
{
return 2.0;
}
else
{
return 0.0;
}
}
z = Math.Exp(z);
double p, q;
if (x < 8.0)
{
p = Polynomial(x, 5.57535335369399327526e2, 1.02755188689515710272e3, 9.34528527171957607540e2, 5.26445194995477358631e2, 1.96520832956077098242e2, 4.86371970985681366614e1, 7.46321056442269912687, 5.64189564831068821977e-1, 2.46196981473530512524e-10);
q = Polynomial(x, 5.57535340817727675546e2, 1.65666309194161350182e3, 2.24633760818710981792e3, 1.82390916687909736289e3, 9.75708501743205489753e2, 3.54937778887819891062e2, 8.67072140885989742329e1, 1.32281951154744992508e1, 1.0);
}
else
{
p = Polynomial(x, 2.97886665372100240670, 7.40974269950448939160, 6.16021097993053585195, 5.01905042251180477414, 1.27536670759978104416, 5.64189583547755073984e-1);
q = Polynomial(x, 3.36907645100081516050, 9.60896809063285878198, 1.70814450747565897222e1, 1.20489539808096656605e1, 9.39603524938001434673, 2.26052863220117276590, 1.0);
}
double y = (z * p) / q;
if (a < 0.0)
{
y = 2.0 - y;
}
if (y == 0.0)
{
if (a < 0.0)
{
return 2.0;
}
else
{
return 0.0;
}
}
return y;
}
public static double InverseErrorFunction(double x)
{
return 0.70710678118654746 * InverseNormal(0.5 + 0.5 * x);
}
public static double Gamma(double x)
{
if (x <= 0.0 && Math.Round(x) == x)
{
// Not defined for negative integers.
return double.NaN;
}
// See http://en.wikipedia.org/wiki/Lanczos_approximation. Exact to the 15th digit.
if (x < 0.5)
{
return Math.PI / (Math.Sin(Math.PI * x) * Gamma(1.0 - x));
}
else
{
return Math.Sqrt(2.0 * Math.PI) * Math.Pow(6.5 + x, x - 0.5) * Math.Exp(-6.5 - x) * (0.99999999999980993 + 676.5203681218851 / x - 1259.1392167224028 / (x + 1.0) + 771.32342877765313 / (x + 2.0) - 176.61502916214059 / (x + 3.0) + 12.507343278686905 / (x + 4.0) - 0.13857109526572012 / (x + 5.0) + 9.9843695780195716e-6 / (x + 6.0) + 1.5056327351493116e-7 / (x + 7.0));
}
}
public static double LogGamma(double x)
{
if (x <= 0.0)
{
// Not defined for negative values.
return double.NaN;
}
if (x < 1.0)
{
return LogGamma(x + 1.0) - Math.Log(x);
}
else
{
return (x - 0.5) * Math.Log(x + 4.5) - x - 4.5 + Math.Log(2.50662827465 * (1.0 + 76.18009173 / x - 86.50532033 / (x + 1.0) + 24.01409822 / (x + 2.0) - 1.231739516 / (x + 3.0) + 0.120858003e-2 / (x + 4.0) - 0.536382e-5 / (x + 5.0)));
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using System.Diagnostics;
using System.Collections.Generic;
using Xunit;
#pragma warning disable 0649 // Yes, we know - test class have fields we don't assign to.
namespace System.Reflection.Tests
{
public static class MemberInfoNetCoreAppTests
{
[Fact]
public static void HasSameMetadataDefinitionAs_GenericClassMembers()
{
Type tGeneric = typeof(GenericTestClass<>);
IEnumerable<MethodInfo> methodsOnGeneric = tGeneric.GetTypeInfo().GetDeclaredMethods(nameof(GenericTestClass<object>.Foo));
List<Type> typeInsts = new List<Type>();
foreach (MethodInfo method in methodsOnGeneric)
{
Debug.Assert(method.GetParameters().Length == 1);
Type parameterType = method.GetParameters()[0].ParameterType;
typeInsts.Add(tGeneric.MakeGenericType(parameterType));
}
typeInsts.Add(tGeneric);
CrossTestHasSameMethodDefinitionAs(typeInsts.ToArray());
}
private static void CrossTestHasSameMethodDefinitionAs(params Type[] types)
{
Assert.All(types,
delegate (Type type1)
{
Assert.All(type1.GenerateTestMemberList(),
delegate (MemberInfo m1)
{
MarkerAttribute mark1 = m1.GetCustomAttribute<MarkerAttribute>();
if (mark1 == null)
return;
Assert.All(types,
delegate (Type type2)
{
Assert.All(type2.GenerateTestMemberList(),
delegate (MemberInfo m2)
{
MarkerAttribute mark2 = m2.GetCustomAttribute<MarkerAttribute>();
if (mark2 == null)
return;
bool hasSameMetadata = m1.HasSameMetadataDefinitionAs(m2);
Assert.Equal(hasSameMetadata, m2.HasSameMetadataDefinitionAs(m1));
if (hasSameMetadata)
{
Assert.Equal(mark1.Mark, mark2.Mark);
}
else
{
Assert.NotEqual(mark1.Mark, mark2.Mark);
}
}
);
}
);
}
);
}
);
}
[Fact]
public static void HasSameMetadataDefinitionAs_ReflectedTypeNotPartOfComparison()
{
Type tBase = typeof(GenericTestClass<>);
Type tDerived = typeof(DerivedFromGenericTestClass<int>);
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
IEnumerable<MemberInfo> baseMembers = tBase.GetMembers(bf).Where(m => m.IsDefined(typeof(MarkerAttribute)));
baseMembers = baseMembers.Where(bm => !(bm is ConstructorInfo)); // Constructors cannot be seen from derived types.
IEnumerable<MemberInfo> derivedMembers = tDerived.GetMembers(bf).Where(m => m.IsDefined(typeof(MarkerAttribute)));
Assert.All(baseMembers,
delegate (MemberInfo baseMember)
{
MemberInfo matchingDerivedMember = derivedMembers.Single(dm => dm.HasSameMarkAs(baseMember));
Assert.True(baseMember.HasSameMetadataDefinitionAs(matchingDerivedMember));
Assert.True(matchingDerivedMember.HasSameMetadataDefinitionAs(matchingDerivedMember));
}
);
}
[Fact]
public static void HasSameMetadataDefinitionAs_ConstructedGenericMethods()
{
Type t1 = typeof(TestClassWithGenericMethod<>);
Type theT = t1.GetTypeInfo().GenericTypeParameters[0];
MethodInfo mooNormal = t1.GetConfirmedMethod(nameof(TestClassWithGenericMethod<object>.Moo), theT);
MethodInfo mooGeneric = t1.GetTypeInfo().GetDeclaredMethods("Moo").Single(m => m.IsGenericMethod);
MethodInfo mooInst = mooGeneric.MakeGenericMethod(typeof(int));
Assert.True(mooGeneric.HasSameMetadataDefinitionAs(mooInst));
Assert.True(mooInst.HasSameMetadataDefinitionAs(mooGeneric));
MethodInfo mooInst2 = mooGeneric.MakeGenericMethod(typeof(double));
Assert.True(mooInst2.HasSameMetadataDefinitionAs(mooInst));
Assert.True(mooInst.HasSameMetadataDefinitionAs(mooInst2));
Type t2 = typeof(TestClassWithGenericMethod<int>);
MethodInfo mooNormalOnT2 = t2.GetConfirmedMethod(nameof(TestClassWithGenericMethod<object>.Moo), typeof(int));
Assert.False(mooInst.HasSameMetadataDefinitionAs(mooNormalOnT2));
}
[Fact]
public static void HasSameMetadataDefinitionAs_NamedAndGenericTypes()
{
Type tnong = typeof(TestClass);
Type tnong2 = typeof(TestClass2);
Type tg = typeof(GenericTestClass<>);
Type tginst1 = typeof(GenericTestClass<int>);
Type tginst2 = typeof(GenericTestClass<string>);
Assert.True(tnong.HasSameMetadataDefinitionAs(tnong));
Assert.True(tnong2.HasSameMetadataDefinitionAs(tnong2));
Assert.True(tg.HasSameMetadataDefinitionAs(tg));
Assert.True(tginst1.HasSameMetadataDefinitionAs(tginst1));
Assert.True(tginst2.HasSameMetadataDefinitionAs(tginst2));
Assert.True(tg.HasSameMetadataDefinitionAs(tginst1));
Assert.True(tginst1.HasSameMetadataDefinitionAs(tginst1));
Assert.True(tginst1.HasSameMetadataDefinitionAs(tginst2));
Assert.False(tnong.HasSameMetadataDefinitionAs(tnong2));
Assert.False(tnong.HasSameMetadataDefinitionAs(tg));
Assert.False(tg.HasSameMetadataDefinitionAs(tnong));
Assert.False(tnong.HasSameMetadataDefinitionAs(tginst1));
Assert.False(tginst1.HasSameMetadataDefinitionAs(tnong));
}
[Fact]
public static void HasSameMetadataDefinitionAs_GenericTypeParameters()
{
Type theT = typeof(GenericTestClass<>).GetTypeInfo().GenericTypeParameters[0];
Type theT2 = typeof(TestClassWithGenericMethod<>).GetTypeInfo().GenericTypeParameters[0];
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.ExactBinding;
MethodInfo mooNong = theT2.GetMethod("Moo", bf, null, new Type[] { theT2 }, null);
MethodInfo mooGeneric = typeof(TestClassWithGenericMethod<>).GetTypeInfo().GetDeclaredMethods("Moo").Single(m => m.IsGenericMethod);
Type theM = mooGeneric.GetGenericArguments()[0];
Assert.True(theT.HasSameMetadataDefinitionAs(theT));
Assert.False(theT2.HasSameMetadataDefinitionAs(theT));
Assert.False(theT.HasSameMetadataDefinitionAs(theT2));
Assert.False(theM.HasSameMetadataDefinitionAs(theT));
Assert.False(theM.HasSameMetadataDefinitionAs(theT2));
Assert.False(theT2.HasSameMetadataDefinitionAs(theM));
Assert.False(theT.HasSameMetadataDefinitionAs(theM));
}
[Fact]
public static void HasSameMetadataDefinitionAs_Twins()
{
// This situation is particularly treacherous for CoreRT as the .NET Native toolchain can and does assign
// the same native metadata tokens to identically structured members in unrelated types.
Type twin1 = typeof(Twin1);
Type twin2 = typeof(Twin2);
Assert.All(twin1.GenerateTestMemberList(),
delegate (MemberInfo m1)
{
Assert.All(twin2.GenerateTestMemberList(),
delegate (MemberInfo m2)
{
Assert.False(m1.HasSameMetadataDefinitionAs(m2));
}
);
}
);
}
private class Twin1
{
public Twin1() { }
public int Field1;
public Action Event1;
public void Method1() { }
public int Property1 { get; set; }
}
private class Twin2
{
public Twin2() { }
public int Field1;
public Action Event1;
public void Method1() { }
public int Property1 { get; set; }
}
[Fact]
[OuterLoop] // Time-consuming.
public static void HasSameMetadataDefinitionAs_CrossAssembly()
{
// Make sure that identical tokens in different assemblies don't confuse the api.
foreach (Type t1 in typeof(object).Assembly.DefinedTypes)
{
foreach (Type t2 in typeof(MemberInfoNetCoreAppTests).Assembly.DefinedTypes)
{
Assert.False(t1.HasSameMetadataDefinitionAs(t2));
}
}
}
[Theory]
[MemberData(nameof(NegativeTypeData))]
public static void HasSameMetadataDefinitionAs_Negative_NonRuntimeType(Type type)
{
Type mockType = new MockType();
Assert.False(type.HasSameMetadataDefinitionAs(mockType));
Assert.All(type.GenerateTestMemberList(),
delegate (MemberInfo member)
{
Assert.False(member.HasSameMetadataDefinitionAs(mockType));
}
);
}
[Theory]
[MemberData(nameof(NegativeTypeData))]
public static void HasSameMetadataDefinitionAs_Negative_Null(Type type)
{
AssertExtensions.Throws<ArgumentNullException>("other", () => type.HasSameMetadataDefinitionAs(null));
Assert.All(type.GenerateTestMemberList(),
delegate (MemberInfo member)
{
AssertExtensions.Throws<ArgumentNullException>("other", () => member.HasSameMetadataDefinitionAs(null));
}
);
}
public static IEnumerable<object[]> NegativeTypeData => NegativeTypeDataRaw.Select(t => new object[] { t });
private static IEnumerable<Type> NegativeTypeDataRaw
{
get
{
yield return typeof(TestClass);
yield return typeof(GenericTestClass<>);
yield return typeof(GenericTestClass<int>);
yield return typeof(int[]);
yield return typeof(int).MakeArrayType(1);
yield return typeof(int[,]);
yield return typeof(int).MakeByRefType();
yield return typeof(int).MakePointerType();
yield return typeof(GenericTestClass<>).GetTypeInfo().GenericTypeParameters[0];
if (PlatformDetection.IsWindows)
yield return Type.GetTypeFromCLSID(new Guid("DCA66D18-E253-4695-9E08-35B54420AFA2"));
}
}
[Fact]
public static void HasSameMetadataDefinitionAs__CornerCase_HasElementTypes()
{
// HasSameMetadataDefinitionAs on an array/byref/pointer type is uninteresting (they'll never be an actual member of a type)
// but for future compat, we'll establish their known behavior here. Since these types all return a MetadataToken of 0x02000000,
// they'll all "match" each other.
Type[] types =
{
typeof(int[]),
typeof(double[]),
typeof(int).MakeArrayType(1),
typeof(double).MakeArrayType(1),
typeof(int[,]),
typeof(double[,]),
typeof(int).MakeByRefType(),
typeof(double).MakeByRefType(),
typeof(int).MakePointerType(),
typeof(double).MakePointerType(),
};
Assert.All(types,
delegate (Type t1)
{
Assert.All(types, t2 => Assert.True(t1.HasSameMetadataDefinitionAs(t2)));
}
);
}
[Fact]
public static void HasSameMetadataDefinitionAs_CornerCase_ArrayMethods()
{
// The magic methods and constructors exposed on array types do not have metadata backing and report a MetadataToken of 0x06000000
// and hence compare identically with each other. This may be surprising but this test records that fact for future compat.
//
Type[] arrayTypes =
{
typeof(int[]),
typeof(double[]),
typeof(int).MakeArrayType(1),
typeof(double).MakeArrayType(1),
typeof(int[,]),
typeof(double[,]),
};
List<MemberInfo> members = new List<MemberInfo>();
foreach (Type arrayType in arrayTypes)
{
foreach (MemberInfo member in arrayType.GetMembers(BindingFlags.Public|BindingFlags.Instance | BindingFlags.DeclaredOnly))
{
if (member is MethodBase)
{
members.Add(member);
}
}
}
Assert.All(members,
delegate (MemberInfo member1)
{
Assert.All(members,
delegate (MemberInfo member2)
{
if (member1.MemberType == member2.MemberType)
Assert.True(member1.HasSameMetadataDefinitionAs(member2));
else
Assert.False(member1.HasSameMetadataDefinitionAs(member2));
}
);
}
);
}
[Fact]
[PlatformSpecific(TestPlatforms.Windows)]
public static void HasSameMetadataDefinitionAs_CornerCase_CLSIDConstructor()
{
// HasSameMetadataDefinitionAs on a GetTypeFromCLSID type is uninteresting (they'll never be an actual member of a type)
// but for future compat, we'll establish their known behavior here. Since these types and their constructors all return the same
// MetadataToken, they'll all "match" each other.
Type t1 = Type.GetTypeFromCLSID(new Guid("23A54889-7738-4F16-8AB2-CB23F8E756BE"));
Type t2 = Type.GetTypeFromCLSID(new Guid("DCA66D18-E253-4695-9E08-35B54420AFA2"));
Assert.True(t1.HasSameMetadataDefinitionAs(t2));
ConstructorInfo c1 = t1.GetConfirmedConstructor();
ConstructorInfo c2 = t2.GetConfirmedConstructor();
Assert.True(c1.HasSameMetadataDefinitionAs(c2));
}
private static bool HasSameMarkAs(this MemberInfo m1, MemberInfo m2)
{
MarkerAttribute marker1 = m1.GetCustomAttribute<MarkerAttribute>();
Assert.NotNull(marker1);
MarkerAttribute marker2 = m2.GetCustomAttribute<MarkerAttribute>();
Assert.NotNull(marker2);
return marker1.Mark == marker2.Mark;
}
private static MethodInfo GetConfirmedMethod(this Type t, string name, params Type[] parameterTypes)
{
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.ExactBinding;
MethodInfo method = t.GetMethod(name, bf, null, parameterTypes, null);
Assert.NotNull(method);
return method;
}
private static ConstructorInfo GetConfirmedConstructor(this Type t, params Type[] parameterTypes)
{
BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.ExactBinding;
ConstructorInfo ctor = t.GetConstructor(bf, null, parameterTypes, null);
Assert.NotNull(ctor);
return ctor;
}
private static IEnumerable<MemberInfo> GenerateTestMemberList(this Type t)
{
if (t.IsGenericTypeDefinition)
{
foreach (Type gp in t.GetTypeInfo().GenericTypeParameters)
{
yield return gp;
}
}
foreach (MemberInfo m in t.GetTypeInfo().DeclaredMembers)
{
yield return m;
MethodInfo method = m as MethodInfo;
if (method != null && method.IsGenericMethodDefinition)
{
foreach (Type mgp in method.GetGenericArguments())
{
yield return mgp;
}
yield return method.MakeGenericMethod(method.GetGenericArguments().Select(ga => typeof(object)).ToArray());
}
}
}
private class TestClassWithGenericMethod<T>
{
public void Moo(T t) { }
public void Moo<M>(M m) { }
}
private class TestClass
{
public void Foo() { }
public void Foo(object o) { }
public void Foo(string s) { }
public void Bar() { }
}
private class TestClass2 { }
private class GenericTestClass<T>
{
[Marker(1)]
public void Foo(object o) { }
[Marker(2)]
public void Foo(int i) { }
[Marker(3)]
public void Foo(T t) { }
[Marker(4)]
public void Foo(double d) { }
[Marker(5)]
public void Foo(string s) { }
[Marker(6)]
public void Foo(int[] s) { }
[Marker(7)]
public void Foo<U>(U t) { }
[Marker(8)]
public void Foo<U>(T t) { }
[Marker(9)]
public void Foo<U, V>(T t) { }
[Marker(101)]
public GenericTestClass() { }
[Marker(102)]
public GenericTestClass(T t) { }
[Marker(103)]
public GenericTestClass(int t) { }
[Marker(201)]
public int Field1;
[Marker(202)]
public int Field2;
[Marker(203)]
public T Field3;
[Marker(301)]
public int Property1 { get { throw null; } set { throw null; } }
[Marker(302)]
public int Property2 { get { throw null; } set { throw null; } }
[Marker(303)]
public T Property3 { get { throw null; } set { throw null; } }
[Marker(401)]
public event Action Event1 { add { } remove { } }
[Marker(402)]
public event Action<int> Event2 { add { } remove { } }
[Marker(403)]
public event Action<T> Event3 { add { } remove { } }
}
private class DerivedFromGenericTestClass<T> : GenericTestClass<T> { }
[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = false)]
public class MarkerAttribute : Attribute
{
public MarkerAttribute(int mark)
{
Mark = mark;
}
public readonly int Mark;
}
}
}
| |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse 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.
*********************************************************************/
namespace Multiverse.Tools.WorldEditor
{
partial class SetAssetRepositoryDialog
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SetAssetRepositoryDialog));
this.label1 = new System.Windows.Forms.Label();
this.downloadButton = new System.Windows.Forms.Button();
this.repositoryButton = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.continueButton = new System.Windows.Forms.Button();
this.quitButton = new System.Windows.Forms.Button();
this.helpButton = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(25, 28);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(349, 52);
this.label1.TabIndex = 0;
this.label1.Text = resources.GetString("label1.Text");
//
// downloadButton
//
this.downloadButton.Location = new System.Drawing.Point(46, 182);
this.downloadButton.Name = "downloadButton";
this.downloadButton.Size = new System.Drawing.Size(203, 23);
this.downloadButton.TabIndex = 1;
this.downloadButton.Text = "Download a new Asset Repository";
this.downloadButton.UseVisualStyleBackColor = true;
this.downloadButton.Click += new System.EventHandler(this.downloadButton_Click);
//
// repositoryButton
//
this.repositoryButton.Location = new System.Drawing.Point(46, 287);
this.repositoryButton.Name = "repositoryButton";
this.repositoryButton.Size = new System.Drawing.Size(203, 23);
this.repositoryButton.TabIndex = 2;
this.repositoryButton.Text = "Designate an existing Asset Repository";
this.repositoryButton.UseVisualStyleBackColor = true;
this.repositoryButton.Click += new System.EventHandler(this.repositoryButton_Click);
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(25, 95);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(195, 13);
this.label2.TabIndex = 3;
this.label2.Text = "1. Download an Asset Repository";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(43, 127);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(301, 39);
this.label3.TabIndex = 4;
this.label3.Text = "If you already have an Asset Repository, skip ahead to Step 2,\r\notherwise press t" +
"he button below to visit a web page that will\r\nassist you in downloading an Asse" +
"t Repository.";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(25, 221);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(196, 13);
this.label4.TabIndex = 5;
this.label4.Text = "2. Designate an Asset Repository";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(49, 255);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(270, 13);
this.label5.TabIndex = 6;
this.label5.Text = "Click the button below to designate an Asset Repository";
//
// continueButton
//
this.continueButton.DialogResult = System.Windows.Forms.DialogResult.OK;
this.continueButton.Enabled = false;
this.continueButton.Location = new System.Drawing.Point(28, 342);
this.continueButton.Name = "continueButton";
this.continueButton.Size = new System.Drawing.Size(75, 23);
this.continueButton.TabIndex = 7;
this.continueButton.Text = "&Continue";
this.continueButton.UseVisualStyleBackColor = true;
//
// quitButton
//
this.quitButton.Location = new System.Drawing.Point(324, 342);
this.quitButton.Name = "quitButton";
this.quitButton.Size = new System.Drawing.Size(75, 23);
this.quitButton.TabIndex = 8;
this.quitButton.Text = "&Quit";
this.quitButton.UseVisualStyleBackColor = true;
this.quitButton.Click += new System.EventHandler(this.quitButton_Click);
//
// helpButton
//
this.helpButton.Location = new System.Drawing.Point(217, 342);
this.helpButton.Name = "helpButton";
this.helpButton.Size = new System.Drawing.Size(75, 23);
this.helpButton.TabIndex = 9;
this.helpButton.Text = "&Help";
this.helpButton.UseVisualStyleBackColor = true;
this.helpButton.Click += new System.EventHandler(this.helpButton_Click);
//
// SetAssetRepositoryDialog
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(428, 388);
this.Controls.Add(this.helpButton);
this.Controls.Add(this.quitButton);
this.Controls.Add(this.continueButton);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.repositoryButton);
this.Controls.Add(this.downloadButton);
this.Controls.Add(this.label1);
this.Name = "SetAssetRepositoryDialog";
this.ShowInTaskbar = false;
this.Text = "Designate an Asset Repository";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button downloadButton;
private System.Windows.Forms.Button repositoryButton;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.Button continueButton;
private System.Windows.Forms.Button quitButton;
private System.Windows.Forms.Button helpButton;
}
}
| |
using System;
using System.Net.Sockets;
using System.Threading;
using Orleans.Runtime;
namespace Orleans.Messaging
{
/// <summary>
/// The GatewayConnection class does double duty as both the manager of the connection itself (the socket) and the sender of messages
/// to the gateway. It uses a single instance of the Receiver class to handle messages from the gateway.
///
/// Note that both sends and receives are synchronous.
/// </summary>
internal class GatewayConnection : OutgoingMessageSender
{
internal bool IsLive { get; private set; }
internal ProxiedMessageCenter MsgCenter { get; private set; }
private Uri addr;
internal Uri Address
{
get { return addr; }
private set
{
addr = value;
Silo = addr.ToSiloAddress();
}
}
internal SiloAddress Silo { get; private set; }
private readonly GatewayClientReceiver receiver;
internal Socket Socket { get; private set; } // Shared by the receiver
private DateTime lastConnect;
internal GatewayConnection(Uri address, ProxiedMessageCenter mc)
: base("GatewayClientSender_" + address, mc.MessagingConfiguration)
{
Address = address;
MsgCenter = mc;
receiver = new GatewayClientReceiver(this);
lastConnect = new DateTime();
IsLive = true;
}
public override void Start()
{
if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_GatewayConnStarted, "Starting gateway connection for gateway {0}", Address);
lock (Lockable)
{
if (State == ThreadState.Running)
{
return;
}
Connect();
if (!IsLive) return;
// If the Connect succeeded
receiver.Start();
base.Start();
}
}
public override void Stop()
{
IsLive = false;
receiver.Stop();
base.Stop();
RuntimeClient.Current.BreakOutstandingMessagesToDeadSilo(Silo);
Socket s;
lock (Lockable)
{
s = Socket;
Socket = null;
}
if (s == null) return;
SocketManager.CloseSocket(s);
NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket();
}
// passed the exact same socket on which it got SocketException. This way we prevent races between connect and disconnect.
public void MarkAsDisconnected(Socket socket2Disconnect)
{
Socket s = null;
lock (Lockable)
{
if (socket2Disconnect == null || Socket == null) return;
if (Socket == socket2Disconnect) // handles races between connect and disconnect, since sometimes we grab the socket outside lock.
{
s = Socket;
Socket = null;
Log.Warn(ErrorCode.ProxyClient_MarkGatewayDisconnected, String.Format("Marking gateway at address {0} as Disconnected", Address));
if ( MsgCenter != null && MsgCenter.GatewayManager != null)
// We need a refresh...
MsgCenter.GatewayManager.ExpediteUpdateLiveGatewaysSnapshot();
}
}
if (s != null)
{
SocketManager.CloseSocket(s);
NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket();
}
if (socket2Disconnect == s) return;
SocketManager.CloseSocket(socket2Disconnect);
NetworkingStatisticsGroup.OnClosedGatewayDuplexSocket();
}
public void MarkAsDead()
{
Log.Warn(ErrorCode.ProxyClient_MarkGatewayDead, String.Format("Marking gateway at address {0} as Dead in my client local gateway list.", Address));
MsgCenter.GatewayManager.MarkAsDead(Address);
Stop();
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
public void Connect()
{
if (!MsgCenter.Running)
{
if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_MsgCtrNotRunning, "Ignoring connection attempt to gateway {0} because the proxy message center is not running", Address);
return;
}
// Yes, we take the lock around a Sleep. The point is to ensure that no more than one thread can try this at a time.
// There's still a minor problem as written -- if the sending thread and receiving thread both get here, the first one
// will try to reconnect. eventually do so, and then the other will try to reconnect even though it doesn't have to...
// Hopefully the initial "if" statement will prevent that.
lock (Lockable)
{
if (!IsLive)
{
if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_DeadGateway, "Ignoring connection attempt to gateway {0} because this gateway connection is already marked as non live", Address);
return; // if the connection is already marked as dead, don't try to reconnect. It has been doomed.
}
for (var i = 0; i < ProxiedMessageCenter.CONNECT_RETRY_COUNT; i++)
{
try
{
if (Socket != null)
{
if (Socket.Connected)
return;
MarkAsDisconnected(Socket); // clean up the socket before reconnecting.
}
if (lastConnect != new DateTime())
{
var millisecondsSinceLastAttempt = DateTime.UtcNow - lastConnect;
if (millisecondsSinceLastAttempt < ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY)
{
var wait = ProxiedMessageCenter.MINIMUM_INTERCONNECT_DELAY - millisecondsSinceLastAttempt;
if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_PauseBeforeRetry, "Pausing for {0} before trying to connect to gateway {1} on trial {2}", wait, Address, i);
Thread.Sleep(wait);
}
}
lastConnect = DateTime.UtcNow;
Socket = new Socket(Silo.Endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Socket.Connect(Silo.Endpoint);
NetworkingStatisticsGroup.OnOpenedGatewayDuplexSocket();
SocketManager.WriteConnectionPreamble(Socket, MsgCenter.ClientId); // Identifies this client
Log.Info(ErrorCode.ProxyClient_Connected, "Connected to gateway at address {0} on trial {1}.", Address, i);
return;
}
catch (Exception)
{
Log.Warn(ErrorCode.ProxyClient_CannotConnect, "Unable to connect to gateway at address {0} on trial {1}.", Address, i);
MarkAsDisconnected(Socket);
}
}
// Failed too many times -- give up
MarkAsDead();
}
}
protected override SocketDirection GetSocketDirection() { return SocketDirection.ClientToGateway; }
protected override bool PrepareMessageForSend(Message msg)
{
// Check to make sure we're not stopped
if (Cts.IsCancellationRequested)
{
// Recycle the message we've dequeued. Note that this will recycle messages that were queued up to be sent when the gateway connection is declared dead
MsgCenter.SendMessage(msg);
return false;
}
if (msg.TargetSilo != null) return true;
msg.TargetSilo = Silo;
if (msg.TargetGrain.IsSystemTarget)
msg.TargetActivation = ActivationId.GetSystemActivation(msg.TargetGrain, msg.TargetSilo);
return true;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override bool GetSendingSocket(Message msg, out Socket socketCapture, out SiloAddress targetSilo, out string error)
{
error = null;
targetSilo = Silo;
socketCapture = null;
try
{
if (Socket == null || !Socket.Connected)
{
Connect();
}
socketCapture = Socket;
if (socketCapture == null || !socketCapture.Connected)
{
// Failed to connect -- Connect will have already declared this connection dead, so recycle the message
return false;
}
}
catch (Exception)
{
//No need to log any errors, as we alraedy do it inside Connect().
return false;
}
return true;
}
protected override void OnGetSendingSocketFailure(Message msg, string error)
{
msg.TargetSilo = null; // clear previous destination!
MsgCenter.SendMessage(msg);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
protected override void OnMessageSerializationFailure(Message msg, Exception exc)
{
// we only get here if we failed to serialise the msg (or any other catastrophic failure).
// Request msg fails to serialise on the sending silo, so we just enqueue a rejection msg.
Log.Warn(ErrorCode.ProxyClient_SerializationError, String.Format("Unexpected error serializing message to gateway {0}.", Address), exc);
FailMessage(msg, String.Format("Unexpected error serializing message to gateway {0}. {1}", Address, exc));
if (msg.Direction == Message.Directions.Request || msg.Direction == Message.Directions.OneWay)
{
return;
}
// Response msg fails to serialize on the responding silo, so we try to send an error response back.
// if we failed sending an original response, turn the response body into an error and reply with it.
msg.Result = Message.ResponseTypes.Error;
msg.BodyObject = Response.ExceptionResponse(exc);
try
{
MsgCenter.SendMessage(msg);
}
catch (Exception ex)
{
// If we still can't serialize, drop the message on the floor
Log.Warn(ErrorCode.ProxyClient_DroppingMsg, "Unable to serialize message - DROPPING " + msg, ex);
msg.ReleaseBodyAndHeaderBuffers();
}
}
protected override void OnSendFailure(Socket socket, SiloAddress targetSilo)
{
MarkAsDisconnected(socket);
}
protected override void ProcessMessageAfterSend(Message msg, bool sendError, string sendErrorStr)
{
msg.ReleaseBodyAndHeaderBuffers();
if (sendError)
{
// We can't recycle the current message, because that might wind up with it getting delivered out of order, so we have to reject it
FailMessage(msg, sendErrorStr);
}
}
protected override void FailMessage(Message msg, string reason)
{
msg.ReleaseBodyAndHeaderBuffers();
MessagingStatisticsGroup.OnFailedSentMessage(msg);
if (MsgCenter.Running && msg.Direction == Message.Directions.Request)
{
if (Log.IsVerbose) Log.Verbose(ErrorCode.ProxyClient_RejectingMsg, "Rejecting message: {0}. Reason = {1}", msg, reason);
MessagingStatisticsGroup.OnRejectedMessage(msg);
Message error = msg.CreateRejectionResponse(Message.RejectionTypes.Unrecoverable, reason);
MsgCenter.QueueIncomingMessage(error);
}
else
{
Log.Warn(ErrorCode.ProxyClient_DroppingMsg, "Dropping message: {0}. Reason = {1}", msg, reason);
MessagingStatisticsGroup.OnDroppedSentMessage(msg);
}
}
}
}
| |
// Authors:
// Rafael Mizrahi <rafim@mainsoft.com>
// Erez Lotan <erezl@mainsoft.com>
// Oren Gurfinkel <oreng@mainsoft.com>
// Ofer Borstein
//
// Copyright (c) 2004 Mainsoft Co.
//
// 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 NUnit.Framework;
using System;
using System.Data;
using GHTUtils;
using GHTUtils.Base;
namespace tests.system_data_dll.System_Data
{
[TestFixture] public class DataSet_Merge_DsBM : GHTBase
{
[Test] public void Main()
{
DataSet_Merge_DsBM tc = new DataSet_Merge_DsBM();
Exception exp = null;
try
{
tc.BeginTest("DataSet_Merge_DsBM");
tc.run();
}
catch(Exception ex)
{
exp = ex;
}
finally
{
tc.EndTest(exp);
}
}
//Activate This Construntor to log All To Standard output
//public TestClass():base(true){}
//Activate this constructor to log Failures to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, false){}
//Activate this constructor to log All to a log file
//public TestClass(System.IO.TextWriter tw):base(tw, true){}
//BY DEFAULT LOGGING IS DONE TO THE STANDARD OUTPUT ONLY FOR FAILURES
public void run()
{
Exception exp = null;
//create source dataset
DataSet ds = new DataSet();
DataTable dt = GHTUtils.DataProvider.CreateParentDataTable();
dt.TableName = "Table1";
dt.PrimaryKey = new DataColumn[] {dt.Columns[0]};
//add table to dataset
ds.Tables.Add(dt.Copy());
dt = ds.Tables[0];
//create target dataset (copy of source dataset)
DataSet dsTarget = ds.Copy();
//add new column (for checking MissingSchemaAction)
DataColumn dc = new DataColumn("NewColumn",typeof(float));
//make the column to be primary key
dt.Columns.Add(dc);
//add new table (for checking MissingSchemaAction)
ds.Tables.Add(new DataTable("NewTable"));
ds.Tables["NewTable"].Columns.Add("NewColumn1",typeof(int));
ds.Tables["NewTable"].Columns.Add("NewColumn2",typeof(long));
ds.Tables["NewTable"].Rows.Add(new object[] {1,2});
ds.Tables["NewTable"].Rows.Add(new object[] {3,4});
ds.Tables["NewTable"].PrimaryKey = new DataColumn[] {ds.Tables["NewTable"].Columns["NewColumn1"]};
#region "ds,false,MissingSchemaAction.Add)"
DataSet dsTarget1 = dsTarget.Copy();
dsTarget1.Merge(ds,false,MissingSchemaAction.Add);
try
{
BeginCase("Merge MissingSchemaAction.Add - Column");
Compare(dsTarget1.Tables["Table1"].Columns.Contains("NewColumn"),true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge MissingSchemaAction.Add - Table");
Compare(dsTarget1.Tables.Contains("NewTable"),true);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
//failed, should be success by MSDN Library documentation
// try
// {
// BeginCase("Merge MissingSchemaAction.Add - PrimaryKey");
// Compare(dsTarget1.Tables["NewTable"].PrimaryKey.Length,0);
// }
// catch(Exception ex) {exp = ex;}
// finally {EndCase(exp); exp = null;}
#endregion
#region "ds,false,MissingSchemaAction.AddWithKey)"
//MissingSchemaAction.Add,MissingSchemaAction.AddWithKey - behave the same, checked only Add
// DataSet dsTarget2 = dsTarget.Copy();
// dsTarget2.Merge(ds,false,MissingSchemaAction.AddWithKey);
// try
// {
// BeginCase("Merge MissingSchemaAction.AddWithKey - Column");
// Compare(dsTarget2.Tables["Table1"].Columns.Contains("NewColumn"),true);
// }
// catch(Exception ex) {exp = ex;}
// finally {EndCase(exp); exp = null;}
//
// try
// {
// BeginCase("Merge MissingSchemaAction.AddWithKey - Table");
// Compare(dsTarget2.Tables.Contains("NewTable"),true);
// }
// catch(Exception ex) {exp = ex;}
// finally {EndCase(exp); exp = null;}
//
// try
// {
// BeginCase("Merge MissingSchemaAction.AddWithKey - PrimaryKey");
// Compare(dsTarget2.Tables["NewTable"].PrimaryKey[0],dsTarget2.Tables["NewTable"].Columns["NewColumn1"]);
// }
// catch(Exception ex) {exp = ex;}
// finally {EndCase(exp); exp = null;}
#endregion
#region "ds,false,MissingSchemaAction.Error)"
//Error - throw System.Data.DataException, should throw InvalidOperationException
// DataSet dsTarget3 ;
// Exception expMerge = null;
// try
// {
// BeginCase("Merge MissingSchemaAction.Error ");
// dsTarget3 = dsTarget.Copy();
// try {dsTarget3.Merge(ds,false,MissingSchemaAction.Error);}
// catch (Exception e) {expMerge = e;}
// Compare(expMerge.GetType() , typeof(InvalidOperationException));
// }
// catch(Exception ex) {exp = ex;}
// finally {EndCase(exp); exp = null;}
#endregion
#region "ds,false,MissingSchemaAction.Ignore )"
DataSet dsTarget4 = dsTarget.Copy();
dsTarget4.Merge(ds,false,MissingSchemaAction.Ignore );
try
{
BeginCase("Merge MissingSchemaAction.Ignore - Column");
Compare(dsTarget4.Tables["Table1"].Columns.Contains("NewColumn"),false);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
try
{
BeginCase("Merge MissingSchemaAction.Ignore - Table");
Compare(dsTarget4.Tables.Contains("NewTable"),false);
}
catch(Exception ex) {exp = ex;}
finally {EndCase(exp); exp = null;}
#endregion
}
}
}
| |
/*
Copyright 2009 KISS Intelligent Systems Limited
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.Text;
using Apache.Hadoop.Hbase.Thrift;
namespace OHM
{
public abstract class BaseTable
{
public BaseTable()
{
}
public abstract void save();
public abstract void delete();
public abstract void loadAll();
protected String generateNewKey(OHMConnection connection, byte[] tableName, Random rand)
{
String key = null;
OHMRow result = null;
bool found = false;
while(!found)
{
//Generate throw random 5 digit numbers
int no1 = rand.Next(10000, 99999);
int no2 = rand.Next(10000, 99999);
int no3 = rand.Next(10000, 99999);
key = no1.ToString() + no2.ToString() + no3.ToString();
Console.WriteLine("New Key: " + key);
try
{
result = connection.getRow(tableName, fromString(key));
}
catch(Exception exp)
{
}
if(result == null || result.Columns.Count == 0)
{
//The key is not already in use
found = true;
}
}
return key;
}
public static byte[] fromBool(bool value)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.GetBytes(value);
}
public static byte[] fromByte(byte value)
{
//Just put it straight in to the array
return new byte[]{value};
}
public static byte[] fromByteStream(byte[] value)
{
//Just user the array directly
return value;
}
public static byte[] fromDouble(double value)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.GetBytes(value);
}
public static byte[] fromFloat(float value)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.GetBytes(value);
}
public static byte[] fromInt(int value)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.GetBytes(value);
}
public static byte[] fromLong(long value)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.GetBytes(value);
}
public static byte[] fromString(String value)
{
//Use the UTF8 encoding
return Encoding.UTF8.GetBytes(value);
}
public static byte[] fromUInt(uint value)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.GetBytes(value);
}
public static byte[] fromULong(ulong value)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.GetBytes(value);
}
public static bool toBool(byte[] data)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.ToBoolean(data, 0);
}
public static byte toByte(byte[] data)
{
if(data.Length > 0)
//Just use the first value from the array
return data[0];
else
return 0;
}
public static byte[] toByteStream(byte[] data)
{
//Just use the array directly
return data;
}
public static double toDouble(byte[] data)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.ToDouble(data, 0);
}
public static float toFloat(byte[] data)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.ToSingle(data, 0);
}
public static int toInt(byte[] data)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.ToInt32(data, 0);
}
public static long toLong(byte[] data)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.ToInt64(data, 0);
}
public static String toString(byte[] data)
{
//Use the UTF8 encoding
return Encoding.UTF8.GetString(data);
}
public static uint toUInt(byte[] data)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.ToUInt32(data, 0);
}
public static ulong toULong(byte[] data)
{
//Use Bit Conveters Little Endian conversion
return BitConverter.ToUInt64(data, 0);
}
}
}
| |
// Copyright (C) Pash Contributors. License GPL/BSD. See https://github.com/Pash-Project/Pash/
using System;
using System.Collections;
using NUnit.Framework;
using System.Text.RegularExpressions;
public delegate void MethodThatThrows();
public static class NUnitSpecificationExtensions
{
public static void ShouldBeFalse(this bool condition, string message)
{
Assert.IsFalse(condition, message);
}
public static void ShouldBeFalse(this bool condition)
{
ShouldBeFalse(condition, string.Empty);
}
public static void ShouldBeTrue(this bool condition, string message)
{
Assert.IsTrue(condition, message);
}
public static void ShouldBeTrue(this bool condition)
{
ShouldBeTrue(condition, string.Empty);
}
public static T ShouldEqual<T>(this T actual, T expected)
{
return ShouldEqual(actual, expected, string.Empty);
}
public static T ShouldEqual<T>(this T actual, T expected, string message)
{
Assert.AreEqual(expected, actual, message);
return actual;
}
public static T ShouldNotEqual<T>(this T actual, T expected)
{
Assert.AreNotEqual(expected, actual);
return actual;
}
public static void ShouldBeNull(this object anObject)
{
Assert.IsNull(anObject);
}
public static T ShouldNotBeNull<T>(this T anObject)
{
Assert.IsNotNull(anObject);
return anObject;
}
public static T ShouldNotBeNull<T>(this T anObject, string message)
{
Assert.IsNotNull(anObject, message);
return anObject;
}
public static object ShouldBeTheSameAs(this object actual, object expected)
{
Assert.AreSame(expected, actual);
return expected;
}
public static object ShouldNotBeTheSameAs(this object actual, object expected)
{
Assert.AreNotSame(expected, actual);
return expected;
}
public static void ShouldBeOfType(this object actual, Type expected)
{
Assert.IsInstanceOf(expected, actual);
}
public static void ShouldNotBeOfType(this object actual, Type expected)
{
Assert.IsNotInstanceOf(expected, actual);
}
public static void ShouldContain(this IList actual, object expected)
{
Assert.Contains(expected, actual);
}
public static void ShouldNotContain(this IList collection, object expected)
{
CollectionAssert.DoesNotContain(collection, expected);
}
public static IComparable ShouldBeGreaterThan(this IComparable arg1, IComparable arg2, string message = "")
{
Assert.Greater(arg1, arg2, message);
return arg2;
}
public static IComparable ShouldBeLessThan(this IComparable arg1, IComparable arg2, string message = "")
{
Assert.Less(arg1, arg2, message);
return arg2;
}
public static IComparable ShouldBeGreaterOrEqualThan(this IComparable arg1, IComparable arg2, string message = "")
{
Assert.GreaterOrEqual(arg1, arg2, message);
return arg2;
}
public static IComparable ShouldBeLessOrEqualThan(this IComparable arg1, IComparable arg2, string message = "")
{
Assert.LessOrEqual(arg1, arg2, message);
return arg2;
}
public static void ShouldBeEmpty(this ICollection collection)
{
Assert.IsEmpty(collection);
}
public static void ShouldBeEmpty(this string aString)
{
Assert.IsEmpty(aString);
}
public static void ShouldNotBeEmpty(this ICollection collection)
{
Assert.IsNotEmpty(collection);
}
public static void ShouldNotBeEmpty(this string aString)
{
Assert.IsNotEmpty(aString);
}
public static string ShouldContain(this string actual, string expected)
{
StringAssert.Contains(expected, actual);
return actual;
}
public static void ShouldNotContain(this string actual, string expected)
{
try
{
StringAssert.Contains(expected, actual);
}
catch (AssertionException)
{
return;
}
throw new AssertionException(String.Format("\"{0}\" should not contain \"{1}\".", actual, expected));
}
public static string ShouldBeEqualIgnoringCase(this string actual, string expected)
{
StringAssert.AreEqualIgnoringCase(expected, actual);
return expected;
}
public static void ShouldStartWith(this string actual, string expected)
{
StringAssert.StartsWith(expected, actual);
}
public static void ShouldEndWith(this string actual, string expected)
{
StringAssert.EndsWith(expected, actual);
}
public static void ShouldBeSurroundedWith(this string actual, string expectedStartDelimiter, string expectedEndDelimiter)
{
StringAssert.StartsWith(expectedStartDelimiter, actual);
StringAssert.EndsWith(expectedEndDelimiter, actual);
}
public static void ShouldBeSurroundedWith(this string actual, string expectedDelimiter)
{
StringAssert.StartsWith(expectedDelimiter, actual);
StringAssert.EndsWith(expectedDelimiter, actual);
}
public static void ShouldContainErrorMessage(this Exception exception, string expected)
{
StringAssert.Contains(expected, exception.Message);
}
public static Exception ShouldBeThrownBy(this Type exceptionType, MethodThatThrows method)
{
Exception exception = method.GetException();
if (exception == null)
Assert.Fail("Method " + method.Method.Name + " failed to throw expected exception [" + exceptionType.Name + "].");
Assert.AreEqual(exceptionType, exception.GetType());
return exception;
}
public static Exception GetException(this MethodThatThrows method)
{
Exception exception = null;
try
{
method();
}
catch (Exception e)
{
exception = e;
}
return exception;
}
internal static System.Management.Path ShouldEqual(this System.Management.Path inputPath, System.Management.Path expectedPath, string message = null)
{
Assert.AreEqual((string)expectedPath, (string)inputPath, message);
return inputPath;
}
[Obsolete("We need to find a way to run distinct tests per OS (or at least windows/unix). This function is a hack to get tests to run in both places")]
internal static string PathShouldEqual(this System.Management.Path actual, System.Management.Path expected, string message = null)
{
return PathShouldEqual((string)actual, (string)expected, message);
}
[Obsolete("We need to find a way to run distinct tests per OS (or at least windows/unix). This function is a hack to get tests to run in both places")]
public static string PathShouldEqual(this string actual, string expected, string message = null)
{
expected = Regex.Replace(expected, @"[a-zA-Z]:\\", "/").Replace(System.IO.Path.AltDirectorySeparatorChar, System.IO.Path.DirectorySeparatorChar);
actual = Regex.Replace(actual, @"[a-zA-Z]:\\", "/").Replace(System.IO.Path.AltDirectorySeparatorChar, System.IO.Path.DirectorySeparatorChar);
return ShouldEqual(actual, expected, message);
}
}
| |
#region License
/*
* ResponseStream.cs
*
* This code is derived from ResponseStream.cs (System.Net) of Mono
* (http://www.mono-project.com).
*
* The MIT License
*
* Copyright (c) 2005 Novell, Inc. (http://www.novell.com)
* Copyright (c) 2012-2015 sta.blockhead
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#endregion
#region Authors
/*
* Authors:
* - Gonzalo Paniagua Javier <gonzalo@novell.com>
*/
#endregion
using System;
using System.IO;
using System.Text;
namespace WebSocketSharp.Net
{
// FIXME: Does this buffer the response until close?
// Update: We send a single packet for the first non-chunked write.
// What happens when we set Content-Length to X and write X-1 bytes then close?
// What happens if we don't set Content-Length at all?
internal class ResponseStream : Stream
{
#region Private Fields
private MemoryStream _body;
private bool _chunked;
private static readonly byte[] _crlf = new byte[] { 13, 10 };
private bool _disposed;
private HttpListenerResponse _response;
private Stream _stream;
private Action<byte[], int, int> _write;
private Action<byte[], int, int> _writeBody;
private Action<byte[], int, int> _writeChunked;
#endregion
#region Internal Constructors
internal ResponseStream (
Stream stream, HttpListenerResponse response, bool ignoreWriteExceptions)
{
_stream = stream;
_response = response;
if (ignoreWriteExceptions) {
_write = writeWithoutThrowingException;
_writeChunked = writeChunkedWithoutThrowingException;
}
else {
_write = stream.Write;
_writeChunked = writeChunked;
}
_body = new MemoryStream ();
}
#endregion
#region Public Properties
public override bool CanRead {
get {
return false;
}
}
public override bool CanSeek {
get {
return false;
}
}
public override bool CanWrite {
get {
return !_disposed;
}
}
public override long Length {
get {
throw new NotSupportedException ();
}
}
public override long Position {
get {
throw new NotSupportedException ();
}
set {
throw new NotSupportedException ();
}
}
#endregion
#region Private Methods
private void flush (bool closing)
{
if (!_response.HeadersSent) {
using (var headers = new MemoryStream ()) {
_response.SendHeaders (headers, closing);
var start = headers.Position;
_write (headers.GetBuffer (), (int) start, (int) (headers.Length - start));
}
_chunked = _response.SendChunked;
_writeBody = _chunked ? _writeChunked : _write;
}
flushBody (closing);
if (closing && _chunked) {
var last = getChunkSizeBytes (0, true);
_write (last, 0, last.Length);
}
}
private void flushBody (bool closing)
{
using (_body) {
var len = _body.Length;
if (len > Int32.MaxValue) {
_body.Position = 0;
var buffLen = 1024;
var buff = new byte[buffLen];
var nread = 0;
while ((nread = _body.Read (buff, 0, buffLen)) > 0)
_writeBody (buff, 0, nread);
}
else if (len > 0) {
_writeBody (_body.GetBuffer (), 0, (int) len);
}
}
_body = !closing ? new MemoryStream () : null;
}
private static byte[] getChunkSizeBytes (int size, bool final)
{
return Encoding.ASCII.GetBytes (String.Format ("{0:x}\r\n{1}", size, final ? "\r\n" : ""));
}
private void writeChunked (byte[] buffer, int offset, int count)
{
var size = getChunkSizeBytes (count, false);
_stream.Write (size, 0, size.Length);
_stream.Write (buffer, offset, count);
_stream.Write (_crlf, 0, 2);
}
private void writeChunkedWithoutThrowingException (byte[] buffer, int offset, int count)
{
try {
writeChunked (buffer, offset, count);
}
catch {
}
}
private void writeWithoutThrowingException (byte[] buffer, int offset, int count)
{
try {
_stream.Write (buffer, offset, count);
}
catch {
}
}
#endregion
#region Internal Methods
internal void Close (bool force)
{
if (_disposed)
return;
_disposed = true;
if (!force) {
flush (true);
_response.Close ();
}
else {
_body.Dispose ();
_body = null;
if (_chunked) {
var last = getChunkSizeBytes (0, true);
_write (last, 0, last.Length);
}
_response.Abort ();
}
_response = null;
_stream = null;
}
internal void InternalWrite (byte[] buffer, int offset, int count)
{
_write (buffer, offset, count);
}
#endregion
#region Public Methods
public override IAsyncResult BeginRead (
byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException ();
}
public override IAsyncResult BeginWrite (
byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
return _body.BeginWrite (buffer, offset, count, callback, state);
}
public override void Close ()
{
Close (false);
}
protected override void Dispose (bool disposing)
{
Close (!disposing);
}
public override int EndRead (IAsyncResult asyncResult)
{
throw new NotSupportedException ();
}
public override void EndWrite (IAsyncResult asyncResult)
{
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
_body.EndWrite (asyncResult);
}
public override void Flush ()
{
if (!_disposed && (_chunked || _response.SendChunked))
flush (false);
}
public override int Read (byte[] buffer, int offset, int count)
{
throw new NotSupportedException ();
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException ();
}
public override void SetLength (long value)
{
throw new NotSupportedException ();
}
public override void Write (byte[] buffer, int offset, int count)
{
if (_disposed)
throw new ObjectDisposedException (GetType ().ToString ());
_body.Write (buffer, offset, count);
}
#endregion
}
}
| |
using System.Collections.Generic;
using NUnit.Framework;
using Plivo.Http;
using Plivo.Resource;
using Plivo.Resource.Call;
using Plivo.Resource.Conference;
using Plivo.Utilities;
namespace Plivo.Test.Resources
{
[TestFixture]
public class TestConference : BaseTestCase
{
[Test]
public void TestConferenceList()
{
var request =
new PlivoRequest(
"GET",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/",
"");
var response =
System.IO.File.ReadAllText(
SOURCE_DIR + @"Mocks/conferenceListResponse.json"
);
Setup<ConferenceListResponse>(200, response);
Assert.IsEmpty(
ComparisonUtilities.Compare(
response,
Api.Conference.List()
)
);
AssertRequest(request);
}
[Test]
public void TestConferenceGet()
{
var name = "my conference";
var request =
new PlivoRequest(
"GET",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/",
"");
var response =
System.IO.File.ReadAllText(
SOURCE_DIR + @"Mocks/conferenceGetResponse.json"
);
Setup<Conference>(200, response);
Assert.IsEmpty(
ComparisonUtilities.Compare(
response,
Api.Conference.Get(name)
)
);
AssertRequest(request);
}
[Test]
public void TestConferenceDelete()
{
var name = "my conference";
var request =
new PlivoRequest(
"DELETE",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/",
"");
var response =
System.IO.File.ReadAllText(
SOURCE_DIR + @"Mocks/conferenceDeleteResponse.json"
);
Setup<Conference>(204, response);
Assert.IsEmpty(
ComparisonUtilities.Compare(
response,
Api.Conference.Delete(name)
)
);
AssertRequest(request);
}
[Test]
public void TestConferenceDeleteAll()
{
// var name = "my conference";
var request =
new PlivoRequest(
"DELETE",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/",
"");
var response =
System.IO.File.ReadAllText(
SOURCE_DIR + @"Mocks/conferenceDeleteAllResponse.json"
);
Setup<Conference>(204, response);
Assert.IsEmpty(
ComparisonUtilities.Compare(
response,
Api.Conference.DeleteAll()
)
);
AssertRequest(request);
}
[Test]
public void TestConferenceMemberDelete()
{
var name = "my conference";
var memberId = "11";
var request =
new PlivoRequest(
"DELETE",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/Member/" + memberId + "/",
"");
var response =
System.IO.File.ReadAllText(
SOURCE_DIR + @"Mocks/conferenceMemberDeleteResponse.json"
);
Setup<ConferenceMemberActionResponse>(204, response);
Assert.IsEmpty(
ComparisonUtilities.Compare(
response,
Api.Conference.HangupMember(name, memberId)
)
);
AssertRequest(request);
}
[Test]
public void TestConferenceMemberKick()
{
var name = "my conference";
var memberId = "11";
var request =
new PlivoRequest(
"POST",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/Member/" + memberId + "/Kick/",
"");
var response =
System.IO.File.ReadAllText(
SOURCE_DIR + @"Mocks/conferenceMemberKickCreateResponse.json"
);
Setup<ConferenceMemberActionResponse>(204, response);
Assert.IsEmpty(
ComparisonUtilities.Compare(
response,
Api.Conference.KickMember(name, memberId)
)
);
AssertRequest(request);
}
[Test]
public void TestConferenceMemberMute()
{
var name = "my conference";
var memberId = "11";
var request =
new PlivoRequest(
"POST",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/Member/" + memberId + "/Mute/",
"");
var response =
System.IO.File.ReadAllText(
SOURCE_DIR + @"Mocks/conferenceMemberMuteCreateResponse.json"
);
Setup<ConferenceMemberActionResponse>(204, response);
Assert.IsEmpty(
ComparisonUtilities.Compare(
response,
Api.Conference.MuteMember(name, new List<string>() {"11"})
)
);
AssertRequest(request);
}
[Test]
public void TestConferenceMemberUnMute()
{
var name = "my conference";
var memberId = "11";
var request =
new PlivoRequest(
"DELETE",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/Member/" + memberId + "/Mute/",
"");
var response = "";
Setup<ConferenceMemberActionResponse>(204, response);
Api.Conference.UnmuteMember(name, new List<string>() {"11"});
AssertRequest(request);
}
[Test]
public void TestConferenceMemberPlay()
{
var name = "my conference";
var memberId = "11";
var data = new Dictionary<string, object>()
{
{"url", "http://url.url"}
};
var request =
new PlivoRequest(
"POST",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/Member/" + memberId + "/Play/",
"",
data);
var response =
System.IO.File.ReadAllText(
SOURCE_DIR + @"Mocks/conferenceMemberPlayCreateResponse.json"
);
Setup<ConferenceMemberActionResponse>(204, response);
Assert.IsEmpty(
ComparisonUtilities.Compare(
response,
Api.Conference.PlayMember(name, new List<string>() {"11"}, "http://url.url")
)
);
AssertRequest(request);
}
[Test]
public void TestConferenceMemberStopPlaying()
{
var name = "my conference";
var memberId = "11";
var request =
new PlivoRequest(
"DELETE",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/Member/" + memberId + "/Play/",
"");
var response =
System.IO.File.ReadAllText(
SOURCE_DIR + @"Mocks/conferenceMemberPlayDeleteResponse.json"
);
Setup<ConferenceMemberActionResponse>(204, response);
Assert.IsEmpty(
ComparisonUtilities.Compare(
response,
Api.Conference.StopPlayMember(name, new List<string>() {"11"})
)
);
AssertRequest(request);
}
[Test]
public void TestConferenceMemberSpeak()
{
var name = "my conference";
var memberId = "11";
var data = new Dictionary<string, object>()
{
{"text", "speak this"}
};
var request =
new PlivoRequest(
"POST",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/Member/" + memberId + "/Speak/",
"",
data);
var response =
System.IO.File.ReadAllText(
SOURCE_DIR + @"Mocks/conferenceMemberSpeakCreateResponse.json"
);
Setup<ConferenceMemberActionResponse>(204, response);
Assert.IsEmpty(
ComparisonUtilities.Compare(
response,
Api.Conference.SpeakMember(name, new List<string>() {"11"}, "speak this")
)
);
AssertRequest(request);
}
[Test]
public void TestConferenceMemberStopSpeaking()
{
var name = "my conference";
var memberId = "11";
var request =
new PlivoRequest(
"DELETE",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/Member/" + memberId + "/Speak/",
"");
var response =
System.IO.File.ReadAllText(
SOURCE_DIR + @"Mocks/conferenceMemberSpeakCreateResponse.json"
);
Setup<ConferenceMemberActionResponse>(204, response);
Assert.IsEmpty(
ComparisonUtilities.Compare(
response,
Api.Conference.StopSpeakMember(name, new List<string>() {"11"})
)
);
AssertRequest(request);
}
[Test]
public void TestConferenceMemberDeaf()
{
var name = "my conference";
var memberId = "11";
var request =
new PlivoRequest(
"POST",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/Member/" + memberId + "/Deaf/",
"");
var response =
System.IO.File.ReadAllText(
SOURCE_DIR + @"Mocks/conferenceMemberDeafCreateResponse.json"
);
Setup<ConferenceMemberActionResponse>(204, response);
Assert.IsEmpty(
ComparisonUtilities.Compare(
response,
Api.Conference.DeafMember(name, new List<string>() {"11"})
)
);
AssertRequest(request);
}
[Test]
public void TestConferenceMemberUnDeaf()
{
var name = "my conference";
var memberId = "11,123";
var request =
new PlivoRequest(
"DELETE",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/Member/" + memberId + "/Deaf/",
"");
var response = "";
Setup<ConferenceMemberActionResponse>(204, response);
Api.Conference.UnDeafMember(name, new List<string>() {"11", "123"});
AssertRequest(request);
}
[Test]
public void TestConferenceRecord()
{
var name = "my conference";
// var memberId = "11,123";
var data = new Dictionary<string, object>()
{
{"file_format", "mp3"}
};
var request =
new PlivoRequest(
"POST",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/Record/",
"",
data);
var response =
System.IO.File.ReadAllText(
SOURCE_DIR + @"Mocks/conferenceRecordCreateResponse.json"
);
Setup<RecordCreateResponse<Conference>>(202, response);
Assert.IsEmpty(
ComparisonUtilities.Compare(
response,
Api.Conference.StartRecording(name, fileFormat: "mp3")
)
);
AssertRequest(request);
}
[Test]
public void TestConferenceStopRecording()
{
var name = "my conference";
// var memberId = "11,123";
var request =
new PlivoRequest(
"DELETE",
"Account/MAXXXXXXXXXXXXXXXXXX/Conference/" + name + "/Record/",
"");
var response = "";
Setup<ConferenceMemberActionResponse>(204, response);
Api.Conference.StopRecording(name);
AssertRequest(request);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace System.IO
{
// A MemoryStream represents a Stream in memory (ie, it has no backing store).
// This stream may reduce the need for temporary buffers and files in
// an application.
//
// There are two ways to create a MemoryStream. You can initialize one
// from an unsigned byte array, or you can create an empty one. Empty
// memory streams are resizable, while ones created with a byte array provide
// a stream "view" of the data.
public class MemoryStream : Stream
{
private byte[] _buffer; // Either allocated internally or externally.
private int _origin; // For user-provided arrays, start at this origin
private int _position; // read/write head.
private int _length; // Number of bytes within the memory stream
private int _capacity; // length of usable portion of buffer for stream
// Note that _capacity == _buffer.Length for non-user-provided byte[]'s
private bool _expandable; // User-provided buffers aren't expandable.
private bool _writable; // Can user write to this stream?
private bool _exposable; // Whether the array can be returned to the user.
private bool _isOpen; // Is this stream open or closed?
private Task<int> _lastReadTask; // The last successful task returned from ReadAsync
private const int MemStreamMaxLength = int.MaxValue;
public MemoryStream()
: this(0)
{
}
public MemoryStream(int capacity)
{
if (capacity < 0)
throw new ArgumentOutOfRangeException(nameof(capacity), SR.ArgumentOutOfRange_NegativeCapacity);
_buffer = capacity != 0 ? new byte[capacity] : Array.Empty<byte>();
_capacity = capacity;
_expandable = true;
_writable = true;
_exposable = true;
_origin = 0; // Must be 0 for byte[]'s created by MemoryStream
_isOpen = true;
}
public MemoryStream(byte[] buffer)
: this(buffer, true)
{
}
public MemoryStream(byte[] buffer, bool writable)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
_buffer = buffer;
_length = _capacity = buffer.Length;
_writable = writable;
_exposable = false;
_origin = 0;
_isOpen = true;
}
public MemoryStream(byte[] buffer, int index, int count)
: this(buffer, index, count, true, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable)
: this(buffer, index, count, writable, false)
{
}
public MemoryStream(byte[] buffer, int index, int count, bool writable, bool publiclyVisible)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (index < 0)
throw new ArgumentOutOfRangeException(nameof(index), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - index < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
_buffer = buffer;
_origin = _position = index;
_length = _capacity = index + count;
_writable = writable;
_exposable = publiclyVisible; // Can TryGetBuffer/GetBuffer return the array?
_expandable = false;
_isOpen = true;
}
public override bool CanRead => _isOpen;
public override bool CanSeek => _isOpen;
public override bool CanWrite => _writable;
private void EnsureNotClosed()
{
if (!_isOpen)
throw Error.GetStreamIsClosed();
}
private void EnsureWriteable()
{
if (!CanWrite)
throw Error.GetWriteNotSupported();
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
_isOpen = false;
_writable = false;
_expandable = false;
// Don't set buffer to null - allow TryGetBuffer, GetBuffer & ToArray to work.
_lastReadTask = null;
}
}
finally
{
// Call base.Close() to cleanup async IO resources
base.Dispose(disposing);
}
}
// returns a bool saying whether we allocated a new array.
private bool EnsureCapacity(int value)
{
// Check for overflow
if (value < 0)
throw new IOException(SR.IO_StreamTooLong);
if (value > _capacity)
{
int newCapacity = Math.Max(value, 256);
// We are ok with this overflowing since the next statement will deal
// with the cases where _capacity*2 overflows.
if (newCapacity < _capacity * 2)
{
newCapacity = _capacity * 2;
}
// We want to expand the array up to Array.MaxByteArrayLength
// And we want to give the user the value that they asked for
if ((uint)(_capacity * 2) > Array.MaxByteArrayLength)
{
newCapacity = Math.Max(value, Array.MaxByteArrayLength);
}
Capacity = newCapacity;
return true;
}
return false;
}
public override void Flush()
{
}
public override Task FlushAsync(CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Flush();
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
public virtual byte[] GetBuffer()
{
if (!_exposable)
throw new UnauthorizedAccessException(SR.UnauthorizedAccess_MemStreamBuffer);
return _buffer;
}
public virtual bool TryGetBuffer(out ArraySegment<byte> buffer)
{
if (!_exposable)
{
buffer = default;
return false;
}
buffer = new ArraySegment<byte>(_buffer, offset: _origin, count: (_length - _origin));
return true;
}
// -------------- PERF: Internal functions for fast direct access of MemoryStream buffer (cf. BinaryReader for usage) ---------------
// PERF: Internal sibling of GetBuffer, always returns a buffer (cf. GetBuffer())
internal byte[] InternalGetBuffer()
{
return _buffer;
}
// PERF: True cursor position, we don't need _origin for direct access
internal int InternalGetPosition()
{
return _position;
}
// PERF: Expose internal buffer for BinaryReader instead of going via the regular Stream interface which requires to copy the data out
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ReadOnlySpan<byte> InternalReadSpan(int count)
{
EnsureNotClosed();
int origPos = _position;
int newPos = origPos + count;
if ((uint)newPos > (uint)_length)
{
_position = _length;
throw Error.GetEndOfFile();
}
var span = new ReadOnlySpan<byte>(_buffer, origPos, count);
_position = newPos;
return span;
}
// PERF: Get actual length of bytes available for read; do sanity checks; shift position - i.e. everything except actual copying bytes
internal int InternalEmulateRead(int count)
{
EnsureNotClosed();
int n = _length - _position;
if (n > count)
n = count;
if (n < 0)
n = 0;
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
_position += n;
return n;
}
// Gets & sets the capacity (number of bytes allocated) for this stream.
// The capacity cannot be set to a value less than the current length
// of the stream.
//
public virtual int Capacity
{
get
{
EnsureNotClosed();
return _capacity - _origin;
}
set
{
// Only update the capacity if the MS is expandable and the value is different than the current capacity.
// Special behavior if the MS isn't expandable: we don't throw if value is the same as the current capacity
if (value < Length)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_SmallCapacity);
EnsureNotClosed();
if (!_expandable && (value != Capacity))
throw new NotSupportedException(SR.NotSupported_MemStreamNotExpandable);
// MemoryStream has this invariant: _origin > 0 => !expandable (see ctors)
if (_expandable && value != _capacity)
{
if (value > 0)
{
byte[] newBuffer = new byte[value];
if (_length > 0)
{
Buffer.BlockCopy(_buffer, 0, newBuffer, 0, _length);
}
_buffer = newBuffer;
}
else
{
_buffer = null;
}
_capacity = value;
}
}
}
public override long Length
{
get
{
EnsureNotClosed();
return _length - _origin;
}
}
public override long Position
{
get
{
EnsureNotClosed();
return _position - _origin;
}
set
{
if (value < 0)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_NeedNonNegNum);
EnsureNotClosed();
if (value > MemStreamMaxLength)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
_position = _origin + (int)value;
}
}
public override int Read(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
EnsureNotClosed();
int n = _length - _position;
if (n > count)
n = count;
if (n <= 0)
return 0;
Debug.Assert(_position + n >= 0, "_position + n >= 0"); // len is less than 2^31 -1.
if (n <= 8)
{
int byteCount = n;
while (--byteCount >= 0)
buffer[offset + byteCount] = _buffer[_position + byteCount];
}
else
Buffer.BlockCopy(_buffer, _position, buffer, offset, n);
_position += n;
return n;
}
public override int Read(Span<byte> buffer)
{
if (GetType() != typeof(MemoryStream))
{
// MemoryStream is not sealed, and a derived type may have overridden Read(byte[], int, int) prior
// to this Read(Span<byte>) overload being introduced. In that case, this Read(Span<byte>) overload
// should use the behavior of Read(byte[],int,int) overload.
return base.Read(buffer);
}
EnsureNotClosed();
int n = Math.Min(_length - _position, buffer.Length);
if (n <= 0)
return 0;
// TODO https://github.com/dotnet/coreclr/issues/15076:
// Read(byte[], int, int) has an n <= 8 optimization, presumably based
// on benchmarking. Determine if/where such a cut-off is here and add
// an equivalent optimization if necessary.
new Span<byte>(_buffer, _position, n).CopyTo(buffer);
_position += n;
return n;
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
// If cancellation was requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled<int>(cancellationToken);
try
{
int n = Read(buffer, offset, count);
var t = _lastReadTask;
Debug.Assert(t == null || t.Status == TaskStatus.RanToCompletion,
"Expected that a stored last task completed successfully");
return (t != null && t.Result == n) ? t : (_lastReadTask = Task.FromResult<int>(n));
}
catch (OperationCanceledException oce)
{
return Task.FromCanceled<int>(oce);
}
catch (Exception exception)
{
return Task.FromException<int>(exception);
}
}
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask<int>(Task.FromCanceled<int>(cancellationToken));
}
try
{
// ReadAsync(Memory<byte>,...) needs to delegate to an existing virtual to do the work, in case an existing derived type
// has changed or augmented the logic associated with reads. If the Memory wraps an array, we could delegate to
// ReadAsync(byte[], ...), but that would defeat part of the purpose, as ReadAsync(byte[], ...) often needs to allocate
// a Task<int> for the return value, so we want to delegate to one of the synchronous methods. We could always
// delegate to the Read(Span<byte>) method, and that's the most efficient solution when dealing with a concrete
// MemoryStream, but if we're dealing with a type derived from MemoryStream, Read(Span<byte>) will end up delegating
// to Read(byte[], ...), which requires it to get a byte[] from ArrayPool and copy the data. So, we special-case the
// very common case of the Memory<byte> wrapping an array: if it does, we delegate to Read(byte[], ...) with it,
// as that will be efficient in both cases, and we fall back to Read(Span<byte>) if the Memory<byte> wrapped something
// else; if this is a concrete MemoryStream, that'll be efficient, and only in the case where the Memory<byte> wrapped
// something other than an array and this is a MemoryStream-derived type that doesn't override Read(Span<byte>) will
// it then fall back to doing the ArrayPool/copy behavior.
return new ValueTask<int>(
MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> destinationArray) ?
Read(destinationArray.Array, destinationArray.Offset, destinationArray.Count) :
Read(buffer.Span));
}
catch (OperationCanceledException oce)
{
return new ValueTask<int>(Task.FromCanceled<int>(oce));
}
catch (Exception exception)
{
return new ValueTask<int>(Task.FromException<int>(exception));
}
}
public override int ReadByte()
{
EnsureNotClosed();
if (_position >= _length)
return -1;
return _buffer[_position++];
}
public override void CopyTo(Stream destination, int bufferSize)
{
// Since we did not originally override this method, validate the arguments
// the same way Stream does for back-compat.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Read() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Read) when we are not sure.
if (GetType() != typeof(MemoryStream))
{
base.CopyTo(destination, bufferSize);
return;
}
int originalPosition = _position;
// Seek to the end of the MemoryStream.
int remaining = InternalEmulateRead(_length - originalPosition);
// If we were already at or past the end, there's no copying to do so just quit.
if (remaining > 0)
{
// Call Write() on the other Stream, using our internal buffer and avoiding any
// intermediary allocations.
destination.Write(_buffer, originalPosition, remaining);
}
}
public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken)
{
// This implementation offers better performance compared to the base class version.
StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize);
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to ReadAsync() which a subclass might have overridden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into ReadAsync) when we are not sure.
if (GetType() != typeof(MemoryStream))
return base.CopyToAsync(destination, bufferSize, cancellationToken);
// If cancelled - return fast:
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
// Avoid copying data from this buffer into a temp buffer:
// (require that InternalEmulateRead does not throw,
// otherwise it needs to be wrapped into try-catch-Task.FromException like memStrDest.Write below)
int pos = _position;
int n = InternalEmulateRead(_length - _position);
// If we were already at or past the end, there's no copying to do so just quit.
if (n == 0)
return Task.CompletedTask;
// If destination is not a memory stream, write there asynchronously:
if (!(destination is MemoryStream memStrDest))
return destination.WriteAsync(_buffer, pos, n, cancellationToken);
try
{
// If destination is a MemoryStream, CopyTo synchronously:
memStrDest.Write(_buffer, pos, n);
return Task.CompletedTask;
}
catch (Exception ex)
{
return Task.FromException(ex);
}
}
public override long Seek(long offset, SeekOrigin loc)
{
EnsureNotClosed();
if (offset > MemStreamMaxLength)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_StreamLength);
switch (loc)
{
case SeekOrigin.Begin:
{
int tempPosition = unchecked(_origin + (int)offset);
if (offset < 0 || tempPosition < _origin)
throw new IOException(SR.IO_SeekBeforeBegin);
_position = tempPosition;
break;
}
case SeekOrigin.Current:
{
int tempPosition = unchecked(_position + (int)offset);
if (unchecked(_position + offset) < _origin || tempPosition < _origin)
throw new IOException(SR.IO_SeekBeforeBegin);
_position = tempPosition;
break;
}
case SeekOrigin.End:
{
int tempPosition = unchecked(_length + (int)offset);
if (unchecked(_length + offset) < _origin || tempPosition < _origin)
throw new IOException(SR.IO_SeekBeforeBegin);
_position = tempPosition;
break;
}
default:
throw new ArgumentException(SR.Argument_InvalidSeekOrigin);
}
Debug.Assert(_position >= 0, "_position >= 0");
return _position;
}
// Sets the length of the stream to a given value. The new
// value must be nonnegative and less than the space remaining in
// the array, int.MaxValue - origin
// Origin is 0 in all cases other than a MemoryStream created on
// top of an existing array and a specific starting offset was passed
// into the MemoryStream constructor. The upper bounds prevents any
// situations where a stream may be created on top of an array then
// the stream is made longer than the maximum possible length of the
// array (int.MaxValue).
//
public override void SetLength(long value)
{
if (value < 0 || value > int.MaxValue)
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
EnsureWriteable();
// Origin wasn't publicly exposed above.
Debug.Assert(MemStreamMaxLength == int.MaxValue); // Check parameter validation logic in this method if this fails.
if (value > (int.MaxValue - _origin))
throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_StreamLength);
int newLength = _origin + (int)value;
bool allocatedNewArray = EnsureCapacity(newLength);
if (!allocatedNewArray && newLength > _length)
Array.Clear(_buffer, _length, newLength - _length);
_length = newLength;
if (_position > newLength)
_position = newLength;
}
public virtual byte[] ToArray()
{
int count = _length - _origin;
if (count == 0)
return Array.Empty<byte>();
byte[] copy = new byte[count];
Buffer.BlockCopy(_buffer, _origin, copy, 0, count);
return copy;
}
public override void Write(byte[] buffer, int offset, int count)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
EnsureNotClosed();
EnsureWriteable();
int i = _position + count;
// Check for overflow
if (i < 0)
throw new IOException(SR.IO_StreamTooLong);
if (i > _length)
{
bool mustZero = _position > _length;
if (i > _capacity)
{
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, i - _length);
}
_length = i;
}
if ((count <= 8) && (buffer != _buffer))
{
int byteCount = count;
while (--byteCount >= 0)
{
_buffer[_position + byteCount] = buffer[offset + byteCount];
}
}
else
{
Buffer.BlockCopy(buffer, offset, _buffer, _position, count);
}
_position = i;
}
public override void Write(ReadOnlySpan<byte> buffer)
{
if (GetType() != typeof(MemoryStream))
{
// MemoryStream is not sealed, and a derived type may have overridden Write(byte[], int, int) prior
// to this Write(Span<byte>) overload being introduced. In that case, this Write(Span<byte>) overload
// should use the behavior of Write(byte[],int,int) overload.
base.Write(buffer);
return;
}
EnsureNotClosed();
EnsureWriteable();
// Check for overflow
int i = _position + buffer.Length;
if (i < 0)
throw new IOException(SR.IO_StreamTooLong);
if (i > _length)
{
bool mustZero = _position > _length;
if (i > _capacity)
{
bool allocatedNewArray = EnsureCapacity(i);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, i - _length);
}
_length = i;
}
buffer.CopyTo(new Span<byte>(_buffer, _position, buffer.Length));
_position = i;
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
if (buffer == null)
throw new ArgumentNullException(nameof(buffer), SR.ArgumentNull_Buffer);
if (offset < 0)
throw new ArgumentOutOfRangeException(nameof(offset), SR.ArgumentOutOfRange_NeedNonNegNum);
if (count < 0)
throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum);
if (buffer.Length - offset < count)
throw new ArgumentException(SR.Argument_InvalidOffLen);
// If cancellation is already requested, bail early
if (cancellationToken.IsCancellationRequested)
return Task.FromCanceled(cancellationToken);
try
{
Write(buffer, offset, count);
return Task.CompletedTask;
}
catch (OperationCanceledException oce)
{
return Task.FromCanceled(oce);
}
catch (Exception exception)
{
return Task.FromException(exception);
}
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
if (cancellationToken.IsCancellationRequested)
{
return new ValueTask(Task.FromCanceled(cancellationToken));
}
try
{
// See corresponding comment in ReadAsync for why we don't just always use Write(ReadOnlySpan<byte>).
// Unlike ReadAsync, we could delegate to WriteAsync(byte[], ...) here, but we don't for consistency.
if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> sourceArray))
{
Write(sourceArray.Array, sourceArray.Offset, sourceArray.Count);
}
else
{
Write(buffer.Span);
}
return default;
}
catch (OperationCanceledException oce)
{
return new ValueTask(Task.FromCanceled(oce));
}
catch (Exception exception)
{
return new ValueTask(Task.FromException(exception));
}
}
public override void WriteByte(byte value)
{
EnsureNotClosed();
EnsureWriteable();
if (_position >= _length)
{
int newLength = _position + 1;
bool mustZero = _position > _length;
if (newLength >= _capacity)
{
bool allocatedNewArray = EnsureCapacity(newLength);
if (allocatedNewArray)
{
mustZero = false;
}
}
if (mustZero)
{
Array.Clear(_buffer, _length, _position - _length);
}
_length = newLength;
}
_buffer[_position++] = value;
}
// Writes this MemoryStream to another stream.
public virtual void WriteTo(Stream stream)
{
if (stream == null)
throw new ArgumentNullException(nameof(stream), SR.ArgumentNull_Stream);
EnsureNotClosed();
stream.Write(_buffer, _origin, _length - _origin);
}
}
}
| |
using System;
using System.Configuration;
using System.Reflection;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using RabbitMQ.Client;
namespace MessageBus.Binding.RabbitMQ
{
public sealed class RabbitMQTransportElement : TransportElement
{
public override void ApplyConfiguration(BindingElement bindingElement)
{
base.ApplyConfiguration(bindingElement);
if (bindingElement == null)
throw new ArgumentNullException("bindingElement");
RabbitMQTransportBindingElement rabbind = bindingElement as RabbitMQTransportBindingElement;
if (rabbind == null)
{
throw new ArgumentException(
string.Format("Invalid type for binding. Expected {0}, Passed: {1}",
typeof(RabbitMQBinding).AssemblyQualifiedName,
bindingElement.GetType().AssemblyQualifiedName));
}
rabbind.PersistentDelivery = PersistentDelivery;
rabbind.AutoBindExchange = AutoBindExchange;
rabbind.TTL = TTL;
rabbind.AutoDelete = AutoDelete;
rabbind.BrokerProtocol = Protocol;
rabbind.TransactedReceiveEnabled = ExactlyOnce;
rabbind.ReplyToQueue = ReplyToQueue;
rabbind.ReplyToExchange = ReplyToExchange != null ? new Uri(ReplyToExchange) : null;
rabbind.OneWayOnly = OneWayOnly;
rabbind.MessageFormat = MessageFormat;
}
public override void CopyFrom(ServiceModelExtensionElement from)
{
base.CopyFrom(from);
RabbitMQTransportElement element = from as RabbitMQTransportElement;
if (element != null)
{
PersistentDelivery = element.PersistentDelivery;
AutoBindExchange = element.AutoBindExchange;
TTL = element.TTL;
ProtocolVersion = element.ProtocolVersion;
ExactlyOnce = element.ExactlyOnce;
ReplyToQueue = element.ReplyToQueue;
ReplyToExchange = element.ReplyToExchange;
OneWayOnly = element.OneWayOnly;
MessageFormat = element.MessageFormat;
ApplicationId = element.ApplicationId;
HeaderNamespace = element.HeaderNamespace;
}
}
protected override BindingElement CreateBindingElement()
{
TransportBindingElement element = CreateDefaultBindingElement();
ApplyConfiguration(element);
return element;
}
protected override TransportBindingElement CreateDefaultBindingElement()
{
return new RabbitMQTransportBindingElement();
}
protected override void InitializeFrom(BindingElement bindingElement)
{
base.InitializeFrom(bindingElement);
if (bindingElement == null)
throw new ArgumentNullException("bindingElement");
RabbitMQTransportBindingElement rabbind = bindingElement as RabbitMQTransportBindingElement;
if (rabbind == null)
{
throw new ArgumentException(
string.Format("Invalid type for binding. Expected {0}, Passed: {1}",
typeof(RabbitMQBinding).AssemblyQualifiedName,
bindingElement.GetType().AssemblyQualifiedName));
}
PersistentDelivery = rabbind.PersistentDelivery;
AutoBindExchange = rabbind.AutoBindExchange;
TTL = rabbind.TTL;
ProtocolVersion = rabbind.BrokerProtocol.ApiName;
ReplyToQueue = rabbind.ReplyToQueue;
ReplyToExchange = rabbind.ReplyToExchange.ToString();
OneWayOnly = rabbind.OneWayOnly;
MessageFormat = rabbind.MessageFormat;
ApplicationId = rabbind.ApplicationId;
HeaderNamespace = rabbind.HeaderNamespace;
}
public override Type BindingElementType
{
get { return typeof(RabbitMQTransportElement); }
}
[ConfigurationProperty("autoBindExchange", IsRequired = true, DefaultValue = "")]
public string AutoBindExchange
{
get { return ((string)base["autoBindExchange"]); }
set { base["autoBindExchange"] = value; }
}
[ConfigurationProperty("persistentDelivery", IsRequired = false, DefaultValue = false)]
public bool PersistentDelivery
{
get { return ((bool)base["persistentDelivery"]); }
set { base["persistentDelivery"] = value; }
}
/// <summary>
/// Defines if one way or duplex comunication is required over this binding
/// </summary>
[ConfigurationProperty("oneWayOnly", DefaultValue = true)]
public bool OneWayOnly
{
get { return ((bool)base["oneWayOnly"]); }
set { base["oneWayOnly"] = value; }
}
/// <summary>
/// Application identificator. If not blanked will attached to the published messages.
/// </summary>
/// <remarks>
/// If IgnoreSelfPublished is True messages with same application id will be dropped.
/// </remarks>
/// <remarks>
/// If not blanked application id will be used as queue name if queue name is not supplied by listener address or ReplyToQueue
/// </remarks>
[ConfigurationProperty("applicationId", DefaultValue = null)]
public string ApplicationId
{
get { return ((string)base["applicationId"]); }
set { base["applicationId"] = value; }
}
/// <summary>
/// Specify SOAP headers namespace to map to AMQP message header
/// </summary>
[ConfigurationProperty("headerNamespace", DefaultValue = null)]
public string HeaderNamespace
{
get { return ((string)base["headerNamespace"]); }
set { base["headerNamespace"] = value; }
}
/// <summary>
/// Specifies the port of the broker that the binding should connect to.
/// </summary>
[ConfigurationProperty("TTL", IsRequired = false, DefaultValue = "")]
public string TTL
{
get { return ((string)base["TTL"]); }
set { base["TTL"] = value; }
}
/// <summary>
/// Specifies if the queue is temporary.
/// </summary>
[ConfigurationProperty("AutoDelete", IsRequired = false, DefaultValue = false)]
public bool AutoDelete
{
get { return ((bool)base["AutoDelete"]); }
set { base["AutoDelete"] = value; }
}
/// <summary>
/// Enables transactional message delivery
/// </summary>
[ConfigurationProperty("exactlyOnce", IsRequired = false, DefaultValue = false)]
public bool ExactlyOnce
{
get { return ((bool)base["exactlyOnce"]); }
set { base["exactlyOnce"] = value; }
}
/// <summary>
/// Specifies the protocol version to use when communicating with the broker
/// </summary>
[ConfigurationProperty("protocolversion", DefaultValue = "DefaultProtocol")]
public string ProtocolVersion
{
get
{
return ((string)base["protocolversion"]);
}
set
{
base["protocolversion"] = value;
GetProtocol();
}
}
/// <summary>
/// ReplyTo exchange URI for duplex communication callbacks
/// </summary>
[ConfigurationProperty("replyToExchange", DefaultValue = "")]
public string ReplyToExchange
{
get
{
return ((string)base["replyToExchange"]);
}
set
{
base["replyToExchange"] = value;
}
}
/// <summary>
/// ReplyTo queue name for duplex communication
/// </summary>
/// <remarks>If null will auto delete queue will be generated</remarks>
[ConfigurationProperty("replyToQueue", DefaultValue = "")]
public string ReplyToQueue
{
get
{
return ((string)base["replyToQueue"]);
}
set
{
base["replyToQueue"] = value;
}
}
/// <summary>
/// Defines which message format to use when messages are sent
/// </summary>
/// <remarks>
/// Received messages may be in all supported format even for the same binding
/// </remarks>
[ConfigurationProperty("messageFormat", DefaultValue = MessageFormat.Text)]
public MessageFormat MessageFormat
{
get { return ((MessageFormat)base["messageFormat"]); }
set { base["messageFormat"] = value; }
}
private IProtocol GetProtocol()
{
IProtocol result = Protocols.DefaultProtocol;
if (result == null)
{
throw new ConfigurationErrorsException(string.Format("'{0}' is not a valid AMQP protocol name", ProtocolVersion));
}
return result;
}
/// <summary>
/// Gets the protocol version specified by the current configuration
/// </summary>
public IProtocol Protocol { get { return GetProtocol(); } }
protected override ConfigurationPropertyCollection Properties
{
get
{
ConfigurationPropertyCollection configProperties = base.Properties;
foreach (PropertyInfo prop in GetType().GetProperties(BindingFlags.DeclaredOnly
| BindingFlags.Public
| BindingFlags.Instance))
{
foreach (ConfigurationPropertyAttribute attr in prop.GetCustomAttributes(typeof(ConfigurationPropertyAttribute), false))
{
configProperties.Add(
new ConfigurationProperty(attr.Name, prop.PropertyType, attr.DefaultValue));
}
}
return configProperties;
}
}
}
}
| |
//-------------------------------------------------------------------------------
// <copyright file="StreamDecoratorStream.cs" company="Appccelerate">
// Copyright (c) 2008-2015
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//-------------------------------------------------------------------------------
namespace Appccelerate.IO.Streams
{
using System;
using System.IO;
/// <summary>
/// Abstract decorator class for a Stream
/// </summary>
/// <remarks>
/// <para>
/// This class is used to implement stream decorator classes.
/// For creating a new stream decorator derive a new class from this one and override
/// the methods that you want to decorate. All methods that are not overwritten
/// are passed to the decorated stream.
/// </para>
/// <para>
/// All methods throw a NoStreamException when no stream is assigned to this class
/// at the time a method is called.
/// </para>
/// </remarks>
public abstract class StreamDecoratorStream : Stream
{
/// <summary>
/// The decorated stream
/// </summary>
private Stream decoratedStream;
/// <summary>
/// Initializes a new instance of the <see cref="StreamDecoratorStream"/> class.
/// </summary>
/// <param name="decoratedStream">The decorated stream.</param>
protected StreamDecoratorStream(Stream decoratedStream)
{
this.SetStream(decoratedStream);
}
/// <summary>
/// Gets a value indicating whether the current stream supports reading.
/// </summary>
/// <value></value>
/// <returns>true if the stream supports reading; otherwise, false.</returns>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override bool CanRead
{
get
{
this.AssertStreamNotNull();
return this.decoratedStream.CanRead;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports seeking.
/// </summary>
/// <value></value>
/// <returns>true if the stream supports seeking; otherwise, false.</returns>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override bool CanSeek
{
get
{
this.AssertStreamNotNull();
return this.decoratedStream.CanSeek;
}
}
/// <summary>
/// Gets a value indicating whether the current stream supports writing.
/// </summary>
/// <value></value>
/// <returns>true if the stream supports writing; otherwise, false.</returns>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override bool CanWrite
{
get
{
this.AssertStreamNotNull();
return this.decoratedStream.CanWrite;
}
}
/// <summary>
/// Gets the length in bytes of the stream.
/// </summary>
/// <value></value>
/// <returns>A long value representing the length of the stream in bytes.</returns>
/// <exception cref="NotSupportedException">The stream does not support seeking.</exception>
/// <exception cref="ObjectDisposedException">Property was called after the stream was closed.</exception>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override long Length
{
get
{
this.AssertStreamNotNull();
return this.decoratedStream.Length;
}
}
/// <summary>
/// Gets or sets the position within the current stream.
/// </summary>
/// <value></value>
/// <returns>The current position within the stream.</returns>
/// <exception cref="IOException">An I/O error occurs. </exception>
/// <exception cref="NotSupportedException">The stream does not support seeking. </exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override long Position
{
get
{
this.AssertStreamNotNull();
return this.decoratedStream.Position;
}
set
{
this.AssertStreamNotNull();
this.decoratedStream.Position = value;
}
}
/// <summary>
/// Gets or sets a value that determines how long the stream will attempt to read before timing out.
/// </summary>
/// <value></value>
/// <returns>A value that determines how long the stream will attempt to read before timing out.</returns>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override int ReadTimeout
{
get
{
this.AssertStreamNotNull();
return this.decoratedStream.ReadTimeout;
}
set
{
this.AssertStreamNotNull();
this.decoratedStream.ReadTimeout = value;
}
}
/// <summary>
/// Gets or sets a value that determines how long the stream will attempt to write before timing out.
/// </summary>
/// <value></value>
/// <returns>A value that determines how long the stream will attempt to write before timing out.</returns>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override int WriteTimeout
{
get
{
this.AssertStreamNotNull();
return this.decoratedStream.WriteTimeout;
}
set
{
this.AssertStreamNotNull();
this.decoratedStream.WriteTimeout = value;
}
}
/// <summary>
/// Begins an asynchronous read operation.
/// </summary>
/// <param name="buffer">The buffer to read the data into.</param>
/// <param name="offset">The byte offset in buffer at which to begin writing data read from the stream.</param>
/// <param name="count">The maximum number of bytes to read.</param>
/// <param name="callback">An optional asynchronous callback, to be called when the read is complete.</param>
/// <param name="state">A user-provided object that distinguishes this particular asynchronous read request
/// from other requests.</param>
/// <returns>
/// An <see cref="IAsyncResult"></see> that represents the asynchronous read, which could still be
/// pending.
/// </returns>
/// <exception cref="IOException">Attempted an asynchronous read past the end of the stream, or a disk error
/// occurs. </exception>
/// <exception cref="NotSupportedException">The current Stream implementation does not support the read
/// operation. </exception>
/// <exception cref="ArgumentException">One or more of the arguments is invalid. </exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override IAsyncResult BeginRead(
byte[] buffer,
int offset,
int count,
AsyncCallback callback,
object state)
{
this.AssertStreamNotNull();
return this.decoratedStream.BeginRead(buffer, offset, count, callback, state);
}
/// <summary>
/// Waits for the pending asynchronous read to complete.
/// </summary>
/// <param name="asyncResult">The reference to the pending asynchronous request to finish.</param>
/// <returns>
/// The number of bytes read from the stream, between zero (0) and the number of bytes you requested.
/// Streams return zero (0) only at the end of the stream, otherwise, they should block until at least one
/// byte is available.
/// </returns>
/// <exception cref="ArgumentException">asyncResult did not originate from a
/// <see cref="BeginRead(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object)">
/// </see> method on the current stream.</exception>
/// <exception cref="ArgumentNullException">asyncResult is null. </exception>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override int EndRead(IAsyncResult asyncResult)
{
this.AssertStreamNotNull();
return this.decoratedStream.EndRead(asyncResult);
}
/// <summary>
/// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the
/// position within the stream by the number of bytes read.
/// </summary>
/// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte
/// array with the values between offset and (offset + count - 1) replaced by the bytes read from the current
/// source.</param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin storing the data read from
/// the current stream.</param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than the number of bytes requested if
/// that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
/// </returns>
/// <exception cref="ArgumentException">The sum of offset and count is larger than the buffer length.
/// </exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
/// <exception cref="NotSupportedException">The stream does not support reading.</exception>
/// <exception cref="ArgumentNullException">buffer is null. </exception>
/// <exception cref="IOException">An I/O error occurs. </exception>
/// <exception cref="ArgumentOutOfRangeException">offset or count is negative. </exception>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override int Read(byte[] buffer, int offset, int count)
{
this.AssertStreamNotNull();
return this.decoratedStream.Read(buffer, offset, count);
}
public override int ReadByte()
{
this.AssertStreamNotNull();
return this.decoratedStream.ReadByte();
}
/// <summary>
/// Begins an asynchronous write operation.
/// </summary>
/// <param name="buffer">The buffer to write data from.</param>
/// <param name="offset">The byte offset in buffer from which to begin writing.</param>
/// <param name="count">The maximum number of bytes to write.</param>
/// <param name="callback">An optional asynchronous callback, to be called when the write is complete.</param>
/// <param name="state">A user-provided object that distinguishes this particular asynchronous write request
/// from other requests.</param>
/// <returns> An IAsyncResult that represents the asynchronous write, which could still be pending.</returns>
/// <exception cref="NotSupportedException">The current Stream implementation does not support the write
/// operation. </exception>
/// <exception cref="IOException">Attempted an asynchronous write past the end of the stream,
/// or a disk error occurs. </exception>
/// <exception cref="ArgumentException">One or more of the arguments is invalid. </exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed.</exception>
public override IAsyncResult BeginWrite(
byte[] buffer,
int offset,
int count,
AsyncCallback callback,
object state)
{
this.AssertStreamNotNull();
return this.decoratedStream.BeginWrite(buffer, offset, count, callback, state);
}
/// <summary>
/// Ends an asynchronous write operation.
/// </summary>
/// <param name="asyncResult">A reference to the outstanding asynchronous I/O request.</param>
/// <exception cref="T:System.ArgumentNullException">asyncResult is null. </exception>
/// <exception cref="T:System.ArgumentException">asyncResult did not originate from a
/// <see cref="BeginWrite(System.Byte[],System.Int32,System.Int32,System.AsyncCallback,System.Object)"/>
/// method on the current stream. </exception>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override void EndWrite(IAsyncResult asyncResult)
{
this.AssertStreamNotNull();
this.decoratedStream.EndWrite(asyncResult);
}
/// <summary>
/// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the
/// current position within this stream by the number of bytes written.
/// </summary>
/// <param name="buffer">An array of bytes. This method copies count bytes from buffer to the current stream.
/// </param>
/// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes to the current
/// stream.</param>
/// <param name="count">The number of bytes to be written to the current stream.</param>
/// <exception cref="IOException">An I/O error occurs. </exception>
/// <exception cref="NotSupportedException">The stream does not support writing. </exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
/// <exception cref="ArgumentNullException">buffer is null. </exception>
/// <exception cref="ArgumentException">The sum of offset and count is greater than the buffer length.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">offset or count is negative. </exception>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override void Write(byte[] buffer, int offset, int count)
{
this.AssertStreamNotNull();
this.decoratedStream.Write(buffer, offset, count);
}
/// <summary>
/// Writes a byte to the current position in the stream and advances the position within the stream by one byte.
/// </summary>
/// <param name="value">The byte to write to the stream.</param>
/// <exception cref="IOException">An I/O error occurs. </exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
/// <exception cref="NotSupportedException">The stream does not support writing, or the stream is already
/// closed. </exception>
public override void WriteByte(byte value)
{
this.AssertStreamNotNull();
this.decoratedStream.WriteByte(value);
}
/// <summary>
/// Closes the current stream and releases any resources (such as sockets and file handles) associated with
/// the current stream.
/// </summary>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override void Close()
{
this.AssertStreamNotNull();
this.decoratedStream.Close();
}
/// <summary>
/// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to
/// be written to the underlying device.
/// </summary>
/// <exception cref="IOException">An I/O error occurs. </exception>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override void Flush()
{
this.AssertStreamNotNull();
this.decoratedStream.Flush();
}
/// <summary>
/// When overridden in a derived class, sets the position within the current stream.
/// </summary>
/// <param name="offset">A byte offset relative to the origin parameter.</param>
/// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin"></see> indicating the reference
/// point used to obtain the new position.</param>
/// <returns>
/// The new position within the current stream.
/// </returns>
/// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
/// <exception cref="T:System.NotSupportedException">The stream does not support seeking, such as if the stream
/// is constructed from a pipe or console output. </exception>
/// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed.
/// </exception>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override long Seek(long offset, SeekOrigin origin)
{
this.AssertStreamNotNull();
return this.decoratedStream.Seek(offset, origin);
}
/// <summary>
/// When overridden in a derived class, sets the length of the current stream.
/// </summary>
/// <param name="value">The desired length of the current stream in bytes.</param>
/// <exception cref="NotSupportedException">The stream does not support both writing and seeking,
/// such as if the stream is constructed from a pipe or console output. </exception>
/// <exception cref="IOException">An I/O error occurs. </exception>
/// <exception cref="ObjectDisposedException">Methods were called after the stream was closed. </exception>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override void SetLength(long value)
{
this.AssertStreamNotNull();
this.decoratedStream.SetLength(value);
}
/// <summary>
/// Returns a <see cref="String"></see> that represents the current <see cref="Object"></see>.
/// </summary>
/// <returns>
/// A <see cref="String"></see> that represents the current <see cref="Object"></see>.
/// </returns>
/// <exception cref="InvalidOperationException">Thrown when no stream is assigned as decorated stream.
/// </exception>
public override string ToString()
{
this.AssertStreamNotNull();
return this.decoratedStream.ToString();
}
/// <summary>
/// Derived classes can override this method to handle cases where a method is called while the decorated
/// device is not assigned.
/// </summary>
protected virtual void ThrowNoStreamException()
{
throw new InvalidOperationException("The decorated stream must not be null.");
}
/// <summary>
/// Sets the stream that shall be decorated.
/// </summary>
/// <param name="stream">The stream that shall be decorated.</param>
// ReSharper disable once MemberCanBePrivate.Global
protected void SetStream(Stream stream)
{
this.decoratedStream = stream;
}
/// <summary>
/// Asserts the stream is not null.
/// </summary>
private void AssertStreamNotNull()
{
if (this.decoratedStream == null)
{
this.ThrowNoStreamException();
}
}
}
}
| |
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Android.Animation;
using Android.Graphics;
using Android.Views;
using Android.Widget;
using AScrollView = Android.Widget.ScrollView;
namespace Xamarin.Forms.Platform.Android
{
public class ScrollViewRenderer : AScrollView, IVisualElementRenderer
{
ScrollViewContainer _container;
HorizontalScrollView _hScrollView;
bool _isAttached;
internal bool ShouldSkipOnTouch;
bool _isBidirectional;
ScrollView _view;
public ScrollViewRenderer() : base(Forms.Context)
{
}
protected IScrollViewController Controller
{
get { return (IScrollViewController)Element; }
}
internal float LastX { get; set; }
internal float LastY { get; set; }
public VisualElement Element
{
get { return _view; }
}
public event EventHandler<VisualElementChangedEventArgs> ElementChanged;
public SizeRequest GetDesiredSize(int widthConstraint, int heightConstraint)
{
Measure(widthConstraint, heightConstraint);
return new SizeRequest(new Size(MeasuredWidth, MeasuredHeight), new Size(40, 40));
}
public void SetElement(VisualElement element)
{
ScrollView oldElement = _view;
_view = (ScrollView)element;
if (oldElement != null)
{
oldElement.PropertyChanged -= HandlePropertyChanged;
((IScrollViewController)oldElement).ScrollToRequested -= OnScrollToRequested;
}
if (element != null)
{
OnElementChanged(new VisualElementChangedEventArgs(oldElement, element));
if (_container == null)
{
Tracker = new VisualElementTracker(this);
_container = new ScrollViewContainer(_view, Forms.Context);
}
_view.PropertyChanged += HandlePropertyChanged;
Controller.ScrollToRequested += OnScrollToRequested;
LoadContent();
UpdateBackgroundColor();
UpdateOrientation();
element.SendViewInitialized(this);
if (!string.IsNullOrEmpty(element.AutomationId))
ContentDescription = element.AutomationId;
}
}
public VisualElementTracker Tracker { get; private set; }
public void UpdateLayout()
{
if (Tracker != null)
Tracker.UpdateLayout();
}
public ViewGroup ViewGroup
{
get { return this; }
}
public override void Draw(Canvas canvas)
{
canvas.ClipRect(canvas.ClipBounds);
base.Draw(canvas);
}
public override bool OnInterceptTouchEvent(MotionEvent ev)
{
if (Element.InputTransparent)
return false;
// set the start point for the bidirectional scroll;
// Down is swallowed by other controls, so we'll just sneak this in here without actually preventing
// other controls from getting the event.
if (_isBidirectional && ev.Action == MotionEventActions.Down)
{
LastY = ev.RawY;
LastX = ev.RawX;
}
return base.OnInterceptTouchEvent(ev);
}
public override bool OnTouchEvent(MotionEvent ev)
{
if (ShouldSkipOnTouch)
{
ShouldSkipOnTouch = false;
return false;
}
// The nested ScrollViews will allow us to scroll EITHER vertically OR horizontally in a single gesture.
// This will allow us to also scroll diagonally.
// We'll fall through to the base event so we still get the fling from the ScrollViews.
// We have to do this in both ScrollViews, since a single gesture will be owned by one or the other, depending
// on the initial direction of movement (i.e., horizontal/vertical).
if (_isBidirectional && !Element.InputTransparent)
{
float dX = LastX - ev.RawX;
float dY = LastY - ev.RawY;
LastY = ev.RawY;
LastX = ev.RawX;
if (ev.Action == MotionEventActions.Move)
{
ScrollBy(0, (int)dY);
foreach (AHorizontalScrollView child in this.GetChildrenOfType<AHorizontalScrollView>())
{
child.ScrollBy((int)dX, 0);
break;
}
}
}
return base.OnTouchEvent(ev);
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
SetElement(null);
if (disposing)
{
Tracker.Dispose();
Tracker = null;
RemoveAllViews();
_container.Dispose();
_container = null;
}
}
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
_isAttached = true;
}
protected override void OnDetachedFromWindow()
{
base.OnDetachedFromWindow();
_isAttached = false;
}
protected virtual void OnElementChanged(VisualElementChangedEventArgs e)
{
EventHandler<VisualElementChangedEventArgs> changed = ElementChanged;
if (changed != null)
changed(this, e);
}
protected override void OnLayout(bool changed, int left, int top, int right, int bottom)
{
base.OnLayout(changed, left, top, right, bottom);
if (_view.Content != null && _hScrollView != null)
_hScrollView.Layout(0, 0, right - left, Math.Max(bottom - top, (int)Context.ToPixels(_view.Content.Height)));
}
protected override void OnScrollChanged(int l, int t, int oldl, int oldt)
{
base.OnScrollChanged(l, t, oldl, oldt);
UpdateScrollPosition(Forms.Context.FromPixels(l), Forms.Context.FromPixels(t));
}
internal void UpdateScrollPosition(double x, double y)
{
if (_view != null)
{
if (_view.Orientation == ScrollOrientation.Both)
{
if (x == 0)
x = Forms.Context.FromPixels(_hScrollView.ScrollX);
if (y == 0)
y = Forms.Context.FromPixels(ScrollY);
}
Controller.SetScrolledPosition(x, y);
}
}
static int GetDistance(double start, double position, double v)
{
return (int)(start + (position - start) * v);
}
void HandlePropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "Content")
LoadContent();
else if (e.PropertyName == VisualElement.BackgroundColorProperty.PropertyName)
UpdateBackgroundColor();
else if (e.PropertyName == ScrollView.OrientationProperty.PropertyName)
UpdateOrientation();
}
void LoadContent()
{
_container.ChildView = _view.Content;
}
async void OnScrollToRequested(object sender, ScrollToRequestedEventArgs e)
{
if (!_isAttached || Handle == IntPtr.Zero)
{
return;
}
// 99.99% of the time simply queuing to the end of the execution queue should handle this case.
// However it is possible to end a layout cycle and STILL be layout requested. We want to
// back off until all are done, even if they trigger layout storms over and over. So we back off
// for 10ms tops then move on.
var cycle = 0;
while (IsLayoutRequested)
{
await Task.Delay(TimeSpan.FromMilliseconds(1));
cycle++;
if (cycle >= 10)
break;
}
var x = (int)Forms.Context.ToPixels(e.ScrollX);
var y = (int)Forms.Context.ToPixels(e.ScrollY);
int currentX = _view.Orientation == ScrollOrientation.Horizontal || _view.Orientation == ScrollOrientation.Both ? _hScrollView.ScrollX : ScrollX;
int currentY = _view.Orientation == ScrollOrientation.Vertical || _view.Orientation == ScrollOrientation.Both ? ScrollY : _hScrollView.ScrollY;
if (e.Mode == ScrollToMode.Element)
{
Point itemPosition = Controller.GetScrollPositionForElement(e.Element as VisualElement, e.Position);
x = (int)Forms.Context.ToPixels(itemPosition.X);
y = (int)Forms.Context.ToPixels(itemPosition.Y);
}
if (e.ShouldAnimate)
{
ValueAnimator animator = ValueAnimator.OfFloat(0f, 1f);
animator.SetDuration(1000);
animator.Update += (o, animatorUpdateEventArgs) =>
{
var v = (double)animatorUpdateEventArgs.Animation.AnimatedValue;
int distX = GetDistance(currentX, x, v);
int distY = GetDistance(currentY, y, v);
if (_view == null)
{
// This is probably happening because the page with this Scroll View
// was popped off the stack during animation
animator.Cancel();
return;
}
switch (_view.Orientation)
{
case ScrollOrientation.Horizontal:
_hScrollView.ScrollTo(distX, distY);
break;
case ScrollOrientation.Vertical:
ScrollTo(distX, distY);
break;
default:
_hScrollView.ScrollTo(distX, distY);
ScrollTo(distX, distY);
break;
}
};
animator.AnimationEnd += delegate
{
if (Controller == null)
return;
Controller.SendScrollFinished();
};
animator.Start();
}
else
{
switch (_view.Orientation)
{
case ScrollOrientation.Horizontal:
_hScrollView.ScrollTo(x, y);
break;
case ScrollOrientation.Vertical:
ScrollTo(x, y);
break;
default:
_hScrollView.ScrollTo(x, y);
ScrollTo(x, y);
break;
}
Controller.SendScrollFinished();
}
ScrollTo(x, y);
}
void UpdateBackgroundColor()
{
SetBackgroundColor(Element.BackgroundColor.ToAndroid(Color.Transparent));
}
void UpdateOrientation()
{
if (_view.Orientation == ScrollOrientation.Horizontal || _view.Orientation == ScrollOrientation.Both)
{
if (_hScrollView == null)
_hScrollView = new AHorizontalScrollView(Context, this);
((AHorizontalScrollView)_hScrollView).IsBidirectional = _isBidirectional = _view.Orientation == ScrollOrientation.Both;
if (_hScrollView.Parent != this)
{
_container.RemoveFromParent();
_hScrollView.AddView(_container);
AddView(_hScrollView);
}
}
else
{
if (_container.Parent != this)
{
_container.RemoveFromParent();
if (_hScrollView != null)
_hScrollView.RemoveFromParent();
AddView(_container);
}
}
}
}
}
| |
//----------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//----------------------------------------------------------------
namespace System.ServiceModel.Discovery
{
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime;
abstract class ProbeDuplexAsyncResult<TProbeMessage, TResponseChannel> : AsyncResult
{
readonly IDiscoveryServiceImplementation discoveryServiceImpl;
readonly IMulticastSuppressionImplementation multicastSuppressionImpl;
readonly DuplexFindContext findRequest;
readonly DiscoveryOperationContext context;
readonly TimeoutHelper timeoutHelper;
static AsyncCompletion onShouldRedirectFindCompletedCallback = new AsyncCompletion(OnShouldRedirectFindCompleted);
static AsyncCompletion onSendProxyAnnouncementsCompletedCallback = new AsyncCompletion(OnSendProxyAnnouncementsCompleted);
static AsyncCallback onFindCompletedCallback = Fx.ThunkCallback(new AsyncCallback(OnFindCompleted));
static AsyncCompletion onSendFindResponsesCompletedCallback = new AsyncCompletion(OnSendFindResponsesCompleted);
bool isFindCompleted;
[Fx.Tag.SynchronizationObject]
object findCompletedLock;
TResponseChannel responseChannel;
Exception findException;
[SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
protected ProbeDuplexAsyncResult(TProbeMessage probeMessage,
IDiscoveryServiceImplementation discoveryServiceImpl,
IMulticastSuppressionImplementation multicastSuppressionImpl,
AsyncCallback callback,
object state)
: base(callback, state)
{
Fx.Assert(probeMessage != null, "The probeMessage must be non null.");
Fx.Assert(discoveryServiceImpl != null, "The discoveryServiceImpl must be non null.");
this.discoveryServiceImpl = discoveryServiceImpl;
this.multicastSuppressionImpl = multicastSuppressionImpl;
this.findCompletedLock = new object();
if (!this.Validate(probeMessage))
{
this.Complete(true);
return;
}
else
{
this.context = new DiscoveryOperationContext(OperationContext.Current);
this.findRequest = new DuplexFindContext(this.GetFindCriteria(probeMessage), this);
this.timeoutHelper = new TimeoutHelper(this.findRequest.Criteria.Duration);
this.timeoutHelper.RemainingTime();
this.Process();
}
}
protected DiscoveryOperationContext Context
{
get
{
return this.context;
}
}
TResponseChannel ResponseChannel
{
get
{
if (this.responseChannel == null)
{
this.responseChannel = this.context.GetCallbackChannel<TResponseChannel>();
}
return this.responseChannel;
}
}
protected virtual bool Validate(TProbeMessage probeMessage)
{
return (DiscoveryService.EnsureMessageId() &&
DiscoveryService.EnsureReplyTo() &&
this.ValidateContent(probeMessage) &&
this.EnsureNotDuplicate());
}
protected abstract bool ValidateContent(TProbeMessage probeMessage);
protected abstract FindCriteria GetFindCriteria(TProbeMessage probeMessage);
protected abstract IAsyncResult BeginSendFindResponse(
TResponseChannel responseChannel,
DiscoveryMessageSequence discoveryMessageSequence,
EndpointDiscoveryMetadata matchingEndpoint,
AsyncCallback callback,
object state);
protected abstract void EndSendFindResponse(TResponseChannel responseChannel, IAsyncResult result);
protected abstract IAsyncResult BeginSendProxyAnnouncement(
TResponseChannel responseChannel,
DiscoveryMessageSequence discoveryMessageSequence,
EndpointDiscoveryMetadata proxyEndpointDiscoveryMetadata,
AsyncCallback callback,
object state);
protected abstract void EndSendProxyAnnouncement(TResponseChannel responseChannel, IAsyncResult result);
static bool OnShouldRedirectFindCompleted(IAsyncResult result)
{
Collection<EndpointDiscoveryMetadata> redirectionEndpoints = null;
ProbeDuplexAsyncResult<TProbeMessage, TResponseChannel> thisPtr =
(ProbeDuplexAsyncResult<TProbeMessage, TResponseChannel>)result.AsyncState;
if (thisPtr.multicastSuppressionImpl.EndShouldRedirectFind(result, out redirectionEndpoints))
{
return thisPtr.SendProxyAnnouncements(redirectionEndpoints);
}
else
{
return thisPtr.ProcessFindRequest();
}
}
static bool OnSendProxyAnnouncementsCompleted(IAsyncResult result)
{
ProxyAnnouncementsSendAsyncResult.End(result);
return true;
}
static void OnFindCompleted(IAsyncResult result)
{
if (result.CompletedSynchronously)
{
return;
}
else
{
ProbeDuplexAsyncResult<TProbeMessage, TResponseChannel> thisPtr =
(ProbeDuplexAsyncResult<TProbeMessage, TResponseChannel>)result.AsyncState;
thisPtr.FinishFind(result);
}
}
static bool OnSendFindResponsesCompleted(IAsyncResult result)
{
FindResponsesSendAsyncResult.End(result);
ProbeDuplexAsyncResult<TProbeMessage, TResponseChannel> thisPtr =
(ProbeDuplexAsyncResult<TProbeMessage, TResponseChannel>)result.AsyncState;
if (thisPtr.findException != null)
{
throw FxTrace.Exception.AsError(thisPtr.findException);
}
return true;
}
void FinishFind(IAsyncResult result)
{
try
{
lock (this.findCompletedLock)
{
this.isFindCompleted = true;
}
this.discoveryServiceImpl.EndFind(result);
}
catch (Exception e)
{
if (Fx.IsFatal(e))
{
throw;
}
this.findException = e;
}
finally
{
this.findRequest.MatchingEndpoints.Shutdown();
}
}
void Process()
{
if ((this.multicastSuppressionImpl != null) && (this.context.DiscoveryMode == ServiceDiscoveryMode.Adhoc))
{
if (this.SuppressFindRequest())
{
this.Complete(true);
return;
}
}
else
{
if (this.ProcessFindRequest())
{
this.Complete(true);
return;
}
}
}
bool SuppressFindRequest()
{
IAsyncResult result = this.multicastSuppressionImpl.BeginShouldRedirectFind(
this.findRequest.Criteria,
this.PrepareAsyncCompletion(onShouldRedirectFindCompletedCallback),
this);
return (result.CompletedSynchronously && OnShouldRedirectFindCompleted(result));
}
bool SendProxyAnnouncements(Collection<EndpointDiscoveryMetadata> redirectionEndpoints)
{
if ((redirectionEndpoints == null) || (redirectionEndpoints.Count == 0))
{
return true;
}
IAsyncResult result = new ProxyAnnouncementsSendAsyncResult(
this,
redirectionEndpoints,
this.PrepareAsyncCompletion(onSendProxyAnnouncementsCompletedCallback),
this);
return (result.CompletedSynchronously && OnSendProxyAnnouncementsCompleted(result));
}
bool ProcessFindRequest()
{
IAsyncResult result = this.discoveryServiceImpl.BeginFind(
findRequest,
onFindCompletedCallback,
this);
if (result.CompletedSynchronously)
{
this.FinishFind(result);
}
return this.SendFindResponses();
}
bool SendFindResponses()
{
IAsyncResult result = new FindResponsesSendAsyncResult(
this,
this.PrepareAsyncCompletion(onSendFindResponsesCompletedCallback),
this);
return (result.CompletedSynchronously && OnSendFindResponsesCompleted(result));
}
bool EnsureNotDuplicate()
{
bool isDuplicate = this.discoveryServiceImpl.IsDuplicate(OperationContext.Current.IncomingMessageHeaders.MessageId);
if (isDuplicate && TD.DuplicateDiscoveryMessageIsEnabled())
{
TD.DuplicateDiscoveryMessage(
this.context.EventTraceActivity,
ProtocolStrings.TracingStrings.Probe,
OperationContext.Current.IncomingMessageHeaders.MessageId.ToString());
}
return !isDuplicate;
}
IAsyncResult BeginSendFindResponse(
EndpointDiscoveryMetadata matchingEndpoint,
TimeSpan timeout,
AsyncCallback callback,
object state)
{
IAsyncResult result;
IContextChannel contextChannel = (IContextChannel)this.ResponseChannel;
using (new OperationContextScope(contextChannel))
{
this.context.AddressDuplexResponseMessage(OperationContext.Current);
contextChannel.OperationTimeout = timeout;
result = this.BeginSendFindResponse(
this.ResponseChannel,
this.discoveryServiceImpl.GetNextMessageSequence(),
matchingEndpoint,
callback,
state);
}
return result;
}
void EndSendFindResponse(IAsyncResult result)
{
this.EndSendFindResponse(this.ResponseChannel, result);
}
IAsyncResult BeginSendProxyAnnouncement(
EndpointDiscoveryMetadata proxyEndpoint,
TimeSpan timeout,
AsyncCallback callback,
object state)
{
IAsyncResult result;
IContextChannel contextChannel = (IContextChannel)this.ResponseChannel;
using (new OperationContextScope(contextChannel))
{
this.context.AddressDuplexResponseMessage(OperationContext.Current);
contextChannel.OperationTimeout = timeout;
result = this.BeginSendProxyAnnouncement(
this.ResponseChannel,
this.discoveryServiceImpl.GetNextMessageSequence(),
proxyEndpoint,
callback,
state);
}
return result;
}
void EndSendProxyAnnouncement(IAsyncResult result)
{
this.EndSendProxyAnnouncement(this.ResponseChannel, result);
}
class ProxyAnnouncementsSendAsyncResult : RandomDelaySendsAsyncResult
{
ProbeDuplexAsyncResult<TProbeMessage, TResponseChannel> probeDuplexAsyncResult;
Collection<EndpointDiscoveryMetadata> redirectionEndpoints;
public ProxyAnnouncementsSendAsyncResult(
ProbeDuplexAsyncResult<TProbeMessage, TResponseChannel> probeDuplexAsyncResult,
Collection<EndpointDiscoveryMetadata> redirectionEndpoints,
AsyncCallback callback,
object state)
: base(
redirectionEndpoints.Count,
probeDuplexAsyncResult.context.MaxResponseDelay,
callback,
state)
{
this.probeDuplexAsyncResult = probeDuplexAsyncResult;
this.redirectionEndpoints = redirectionEndpoints;
this.Start(this.probeDuplexAsyncResult.timeoutHelper.RemainingTime());
}
public static void End(IAsyncResult result)
{
AsyncResult.End<ProxyAnnouncementsSendAsyncResult>(result);
}
protected override IAsyncResult OnBeginSend(int index, TimeSpan timeout, AsyncCallback callback, object state)
{
return this.probeDuplexAsyncResult.BeginSendProxyAnnouncement(
this.redirectionEndpoints[index],
timeout,
callback,
state);
}
protected override void OnEndSend(IAsyncResult result)
{
this.probeDuplexAsyncResult.EndSendProxyAnnouncement(result);
}
}
class FindResponsesSendAsyncResult : RandomDelayQueuedSendsAsyncResult<EndpointDiscoveryMetadata>
{
readonly ProbeDuplexAsyncResult<TProbeMessage, TResponseChannel> probeDuplexAsyncResult;
public FindResponsesSendAsyncResult(
ProbeDuplexAsyncResult<TProbeMessage, TResponseChannel> probeDuplexAsyncResult,
AsyncCallback callback,
object state)
: base(
probeDuplexAsyncResult.context.MaxResponseDelay,
probeDuplexAsyncResult.findRequest.MatchingEndpoints,
callback,
state)
{
this.probeDuplexAsyncResult = probeDuplexAsyncResult;
this.Start(this.probeDuplexAsyncResult.timeoutHelper.RemainingTime());
}
public static void End(IAsyncResult result)
{
AsyncResult.End<FindResponsesSendAsyncResult>(result);
}
protected override IAsyncResult OnBeginSendItem(
EndpointDiscoveryMetadata item,
TimeSpan timeout,
AsyncCallback callback,
object state)
{
return this.probeDuplexAsyncResult.BeginSendFindResponse(
item,
timeout,
callback,
state);
}
protected override void OnEndSendItem(IAsyncResult result)
{
this.probeDuplexAsyncResult.EndSendFindResponse(result);
}
}
class DuplexFindContext : FindRequestContext
{
readonly InputQueue<EndpointDiscoveryMetadata> matchingEndpoints;
readonly ProbeDuplexAsyncResult<TProbeMessage, TResponseChannel> probeDuplexAsyncResult;
public DuplexFindContext(FindCriteria criteria, ProbeDuplexAsyncResult<TProbeMessage, TResponseChannel> probeDuplexAsyncResult)
: base(criteria)
{
this.matchingEndpoints = new InputQueue<EndpointDiscoveryMetadata>();
this.probeDuplexAsyncResult = probeDuplexAsyncResult;
}
public InputQueue<EndpointDiscoveryMetadata> MatchingEndpoints
{
get
{
return this.matchingEndpoints;
}
}
protected override void OnAddMatchingEndpoint(EndpointDiscoveryMetadata matchingEndpoint)
{
lock (this.probeDuplexAsyncResult.findCompletedLock)
{
if (this.probeDuplexAsyncResult.isFindCompleted)
{
throw FxTrace.Exception.AsError(
new InvalidOperationException(SR.DiscoveryCannotAddMatchingEndpoint));
}
else
{
this.matchingEndpoints.EnqueueAndDispatch(matchingEndpoint, null, false);
}
}
}
}
}
}
| |
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
//defined by default, since this is not a controversial extension
#define PROTO_TYPE_SINGLE
using System;
using System.Text;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace NDesk.DBus
{
class MessageReader
{
protected EndianFlag endianness;
protected byte[] data;
//TODO: this should be uint or long to handle long messages
protected int pos = 0;
protected Message message;
public MessageReader (EndianFlag endianness, byte[] data)
{
if (data == null)
throw new ArgumentNullException ("data");
this.endianness = endianness;
this.data = data;
}
public MessageReader (Message message) : this (message.Header.Endianness, message.Body)
{
if (message == null)
throw new ArgumentNullException ("message");
this.message = message;
}
public void GetValue (Type type, out object val)
{
if (type == typeof (void)) {
val = null;
return;
}
if (type.IsArray) {
Array valArr;
GetValue (type, out valArr);
val = valArr;
} else if (type == typeof (ObjectPath)) {
ObjectPath valOP;
GetValue (out valOP);
val = valOP;
} else if (type == typeof (Signature)) {
Signature valSig;
GetValue (out valSig);
val = valSig;
} else if (type == typeof (object)) {
GetValue (out val);
} else if (type == typeof (string)) {
string valStr;
GetValue (out valStr);
val = valStr;
} else if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (IDictionary<,>)) {
Type[] genArgs = type.GetGenericArguments ();
Type dictType = typeof (Dictionary<,>).MakeGenericType (genArgs);
val = Activator.CreateInstance(dictType, new object[0]);
System.Collections.IDictionary idict = (System.Collections.IDictionary)val;
GetValueToDict (genArgs[0], genArgs[1], idict);
} else if (Mapper.IsPublic (type)) {
GetObject (type, out val);
} else if (!type.IsPrimitive && !type.IsEnum) {
GetValueStruct (type, out val);
} else {
DType dtype = Signature.TypeToDType (type);
GetValue (dtype, out val);
}
if (type.IsEnum)
val = Enum.ToObject (type, val);
}
//helper method, should not be used generally
public void GetValue (DType dtype, out object val)
{
switch (dtype)
{
case DType.Byte:
{
byte vval;
GetValue (out vval);
val = vval;
}
break;
case DType.Boolean:
{
bool vval;
GetValue (out vval);
val = vval;
}
break;
case DType.Int16:
{
short vval;
GetValue (out vval);
val = vval;
}
break;
case DType.UInt16:
{
ushort vval;
GetValue (out vval);
val = vval;
}
break;
case DType.Int32:
{
int vval;
GetValue (out vval);
val = vval;
}
break;
case DType.UInt32:
{
uint vval;
GetValue (out vval);
val = vval;
}
break;
case DType.Int64:
{
long vval;
GetValue (out vval);
val = vval;
}
break;
case DType.UInt64:
{
ulong vval;
GetValue (out vval);
val = vval;
}
break;
#if PROTO_TYPE_SINGLE
case DType.Single:
{
float vval;
GetValue (out vval);
val = vval;
}
break;
#endif
case DType.Double:
{
double vval;
GetValue (out vval);
val = vval;
}
break;
case DType.String:
{
string vval;
GetValue (out vval);
val = vval;
}
break;
case DType.ObjectPath:
{
ObjectPath vval;
GetValue (out vval);
val = vval;
}
break;
case DType.Signature:
{
Signature vval;
GetValue (out vval);
val = vval;
}
break;
case DType.Variant:
{
object vval;
GetValue (out vval);
val = vval;
}
break;
default:
val = null;
throw new Exception ("Unhandled D-Bus type: " + dtype);
}
}
public void GetObject (Type type, out object val)
{
ObjectPath path;
GetValue (out path);
val = message.Connection.GetObject (type, (string)message.Header.Fields[FieldCode.Sender], path);
}
public void GetValue (out byte val)
{
val = data[pos++];
}
public void GetValue (out bool val)
{
uint intval;
GetValue (out intval);
switch (intval) {
case 0:
val = false;
break;
case 1:
val = true;
break;
default:
throw new Exception ("Read value " + intval + " at position " + pos + " while expecting boolean (0/1)");
}
}
unsafe protected void MarshalUShort (byte *dst)
{
ReadPad (2);
if (endianness == Connection.NativeEndianness) {
dst[0] = data[pos + 0];
dst[1] = data[pos + 1];
} else {
dst[0] = data[pos + 1];
dst[1] = data[pos + 0];
}
pos += 2;
}
unsafe public void GetValue (out short val)
{
fixed (short* ret = &val)
MarshalUShort ((byte*)ret);
}
unsafe public void GetValue (out ushort val)
{
fixed (ushort* ret = &val)
MarshalUShort ((byte*)ret);
}
unsafe protected void MarshalUInt (byte *dst)
{
ReadPad (4);
if (endianness == Connection.NativeEndianness) {
dst[0] = data[pos + 0];
dst[1] = data[pos + 1];
dst[2] = data[pos + 2];
dst[3] = data[pos + 3];
} else {
dst[0] = data[pos + 3];
dst[1] = data[pos + 2];
dst[2] = data[pos + 1];
dst[3] = data[pos + 0];
}
pos += 4;
}
unsafe public void GetValue (out int val)
{
fixed (int* ret = &val)
MarshalUInt ((byte*)ret);
}
unsafe public void GetValue (out uint val)
{
fixed (uint* ret = &val)
MarshalUInt ((byte*)ret);
}
unsafe protected void MarshalULong (byte *dst)
{
ReadPad (8);
if (endianness == Connection.NativeEndianness) {
for (int i = 0; i < 8; ++i)
dst[i] = data[pos + i];
} else {
for (int i = 0; i < 8; ++i)
dst[i] = data[pos + (7 - i)];
}
pos += 8;
}
unsafe public void GetValue (out long val)
{
fixed (long* ret = &val)
MarshalULong ((byte*)ret);
}
unsafe public void GetValue (out ulong val)
{
fixed (ulong* ret = &val)
MarshalULong ((byte*)ret);
}
#if PROTO_TYPE_SINGLE
unsafe public void GetValue (out float val)
{
fixed (float* ret = &val)
MarshalUInt ((byte*)ret);
}
#endif
unsafe public void GetValue (out double val)
{
fixed (double* ret = &val)
MarshalULong ((byte*)ret);
}
public void GetValue (out string val)
{
uint ln;
GetValue (out ln);
val = Encoding.UTF8.GetString (data, pos, (int)ln);
pos += (int)ln;
ReadNull ();
}
public void GetValue (out ObjectPath val)
{
//exactly the same as string
string sval;
GetValue (out sval);
val = new ObjectPath (sval);
}
public void GetValue (out Signature val)
{
byte ln;
GetValue (out ln);
byte[] sigData = new byte[ln];
Array.Copy (data, pos, sigData, 0, (int)ln);
val = new Signature (sigData);
pos += (int)ln;
ReadNull ();
}
//variant
public void GetValue (out object val)
{
Signature sig;
GetValue (out sig);
GetValue (sig, out val);
}
public void GetValue (Signature sig, out object val)
{
GetValue (sig.ToType (), out val);
}
//not pretty or efficient but works
public void GetValueToDict (Type keyType, Type valType, System.Collections.IDictionary val)
{
uint ln;
GetValue (out ln);
//advance to the alignment of the element
//ReadPad (Protocol.GetAlignment (Signature.TypeToDType (type)));
ReadPad (8);
int endPos = pos + (int)ln;
//while (stream.Position != endPos)
while (pos < endPos)
{
ReadPad (8);
object keyVal;
GetValue (keyType, out keyVal);
object valVal;
GetValue (valType, out valVal);
val.Add (keyVal, valVal);
}
if (pos != endPos)
throw new Exception ("Read pos " + pos + " != ep " + endPos);
}
//this could be made generic to avoid boxing
public void GetValue (Type type, out Array val)
{
Type elemType = type.GetElementType ();
uint ln;
GetValue (out ln);
//advance to the alignment of the element
ReadPad (Protocol.GetAlignment (Signature.TypeToDType (elemType)));
int endPos = pos + (int)ln;
//List<T> vals = new List<T> ();
System.Collections.ArrayList vals = new System.Collections.ArrayList ();
//while (stream.Position != endPos)
while (pos < endPos)
{
object elem;
//GetValue (Signature.TypeToDType (elemType), out elem);
GetValue (elemType, out elem);
vals.Add (elem);
}
if (pos != endPos)
throw new Exception ("Read pos " + pos + " != ep " + endPos);
val = vals.ToArray (elemType);
//val = Array.CreateInstance (elemType.UnderlyingSystemType, vals.Count);
}
//struct
//probably the wrong place for this
//there might be more elegant solutions
public void GetValueStruct (Type type, out object val)
{
ReadPad (8);
val = Activator.CreateInstance (type);
/*
if (type.IsGenericType && type.GetGenericTypeDefinition () == typeof (KeyValuePair<,>)) {
object elem;
System.Reflection.PropertyInfo key_prop = type.GetProperty ("Key");
GetValue (key_prop.PropertyType, out elem);
key_prop.SetValue (val, elem, null);
System.Reflection.PropertyInfo val_prop = type.GetProperty ("Value");
GetValue (val_prop.PropertyType, out elem);
val_prop.SetValue (val, elem, null);
return;
}
*/
FieldInfo[] fis = type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (System.Reflection.FieldInfo fi in fis) {
object elem;
//GetValue (Signature.TypeToDType (fi.FieldType), out elem);
GetValue (fi.FieldType, out elem);
//public virtual void SetValueDirect (TypedReference obj, object value);
fi.SetValue (val, elem);
}
}
public void ReadNull ()
{
if (data[pos] != 0)
throw new Exception ("Read non-zero byte at position " + pos + " while expecting null terminator");
pos++;
}
/*
public void ReadPad (int alignment)
{
pos = Protocol.Padded (pos, alignment);
}
*/
public void ReadPad (int alignment)
{
for (int endPos = Protocol.Padded (pos, alignment) ; pos != endPos ; pos++)
if (data[pos] != 0)
throw new Exception ("Read non-zero byte at position " + pos + " while expecting padding");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Xml;
using libsecondlife;
using libsecondlife.Packets;
using libsecondlife.Utilities;
namespace libsecondlife.TestClient
{
public class TestClient : SecondLife
{
public LLUUID GroupID = LLUUID.Zero;
public Dictionary<LLUUID, GroupMember> GroupMembers;
public Dictionary<LLUUID, AvatarAppearancePacket> Appearances = new Dictionary<LLUUID, AvatarAppearancePacket>();
public Dictionary<string, Command> Commands = new Dictionary<string,Command>();
public bool Running = true;
public bool GroupCommands = false;
public string MasterName = String.Empty;
public LLUUID MasterKey = LLUUID.Zero;
public ClientManager ClientManager;
public VoiceManager VoiceManager;
// Shell-like inventory commands need to be aware of the 'current' inventory folder.
public InventoryFolder CurrentDirectory = null;
private LLQuaternion bodyRotation = LLQuaternion.Identity;
private LLVector3 forward = new LLVector3(0, 0.9999f, 0);
private LLVector3 left = new LLVector3(0.9999f, 0, 0);
private LLVector3 up = new LLVector3(0, 0, 0.9999f);
private System.Timers.Timer updateTimer;
/// <summary>
///
/// </summary>
public TestClient(ClientManager manager)
{
ClientManager = manager;
updateTimer = new System.Timers.Timer(500);
updateTimer.Elapsed += new System.Timers.ElapsedEventHandler(updateTimer_Elapsed);
RegisterAllCommands(Assembly.GetExecutingAssembly());
Settings.LOG_LEVEL = Helpers.LogLevel.Debug;
Settings.LOG_RESENDS = false;
Settings.STORE_LAND_PATCHES = true;
Settings.ALWAYS_DECODE_OBJECTS = true;
Settings.ALWAYS_REQUEST_OBJECTS = true;
Settings.SEND_AGENT_UPDATES = true;
Settings.USE_TEXTURE_CACHE = true;
Network.RegisterCallback(PacketType.AgentDataUpdate, new NetworkManager.PacketCallback(AgentDataUpdateHandler));
Network.OnLogin += new NetworkManager.LoginCallback(LoginHandler);
Self.OnInstantMessage += new AgentManager.InstantMessageCallback(Self_OnInstantMessage);
Groups.OnGroupMembers += new GroupManager.GroupMembersCallback(GroupMembersHandler);
Inventory.OnObjectOffered += new InventoryManager.ObjectOfferedCallback(Inventory_OnInventoryObjectReceived);
Network.RegisterCallback(PacketType.AvatarAppearance, new NetworkManager.PacketCallback(AvatarAppearanceHandler));
Network.RegisterCallback(PacketType.AlertMessage, new NetworkManager.PacketCallback(AlertMessageHandler));
VoiceManager = new VoiceManager(this);
updateTimer.Start();
}
/// <summary>
/// Initialize everything that needs to be initialized once we're logged in.
/// </summary>
/// <param name="login">The status of the login</param>
/// <param name="message">Error message on failure, MOTD on success.</param>
public void LoginHandler(LoginStatus login, string message)
{
if (login == LoginStatus.Success)
{
// Start in the inventory root folder.
CurrentDirectory = Inventory.Store.RootFolder;
}
}
public void RegisterAllCommands(Assembly assembly)
{
foreach (Type t in assembly.GetTypes())
{
try
{
if (t.IsSubclassOf(typeof(Command)))
{
ConstructorInfo info = t.GetConstructor(new Type[] { typeof(TestClient) });
Command command = (Command)info.Invoke(new object[] { this });
RegisterCommand(command);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
public void RegisterCommand(Command command)
{
command.Client = this;
if (!Commands.ContainsKey(command.Name.ToLower()))
{
Commands.Add(command.Name.ToLower(), command);
}
}
//breaks up large responses to deal with the max IM size
private void SendResponseIM(SecondLife client, LLUUID fromAgentID, string data)
{
for ( int i = 0 ; i < data.Length ; i += 1024 ) {
int y;
if ((i + 1023) > data.Length)
{
y = data.Length - i;
}
else
{
y = 1023;
}
string message = data.Substring(i, y);
client.Self.InstantMessage(fromAgentID, message);
}
}
public void DoCommand(string cmd, LLUUID fromAgentID)
{
string[] tokens;
try { tokens = Parsing.ParseArguments(cmd); }
catch (FormatException ex) { Console.WriteLine(ex.Message); return; }
if (tokens.Length == 0)
return;
string firstToken = tokens[0].ToLower();
// "all balance" will send the balance command to all currently logged in bots
if (firstToken == "all" && tokens.Length > 1)
{
cmd = String.Empty;
// Reserialize all of the arguments except for "all"
for (int i = 1; i < tokens.Length; i++)
{
cmd += tokens[i] + " ";
}
ClientManager.DoCommandAll(cmd, fromAgentID);
return;
}
if (Commands.ContainsKey(firstToken))
{
string[] args = new string[tokens.Length - 1];
Array.Copy(tokens, 1, args, 0, args.Length);
string response = Commands[firstToken].Execute(args, fromAgentID);
if (!String.IsNullOrEmpty(response))
{
Console.WriteLine(response);
if (fromAgentID != LLUUID.Zero && Network.Connected)
{
// IMs don't like \r\n line endings, clean them up first
response = response.Replace("\r", String.Empty);
SendResponseIM(this, fromAgentID, response);
}
}
}
}
private void updateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
foreach (Command c in Commands.Values)
if (c.Active)
c.Think();
}
private void AgentDataUpdateHandler(Packet packet, Simulator sim)
{
AgentDataUpdatePacket p = (AgentDataUpdatePacket)packet;
if (p.AgentData.AgentID == sim.Client.Self.AgentID)
{
Console.WriteLine("Got the group ID for " + sim.Client.ToString() + ", requesting group members...");
GroupID = p.AgentData.ActiveGroupID;
sim.Client.Groups.RequestGroupMembers(GroupID);
}
}
private void GroupMembersHandler(Dictionary<LLUUID, GroupMember> members)
{
Console.WriteLine("Got " + members.Count + " group members.");
GroupMembers = members;
}
private void AvatarAppearanceHandler(Packet packet, Simulator simulator)
{
AvatarAppearancePacket appearance = (AvatarAppearancePacket)packet;
lock (Appearances) Appearances[appearance.Sender.ID] = appearance;
}
private void AlertMessageHandler(Packet packet, Simulator simulator)
{
AlertMessagePacket message = (AlertMessagePacket)packet;
Logger.Log("[AlertMessage] " + Helpers.FieldToUTF8String(message.AlertData.Message), Helpers.LogLevel.Info, this);
}
private void Self_OnInstantMessage(InstantMessage im, Simulator simulator)
{
bool groupIM = im.GroupIM && GroupMembers != null && GroupMembers.ContainsKey(im.FromAgentID) ? true : false;
if (im.FromAgentID == MasterKey || (GroupCommands && groupIM))
{
// Received an IM from someone that is authenticated
Console.WriteLine("<{0} ({1})> {2}: {3} (@{4}:{5})", im.GroupIM ? "GroupIM" : "IM", im.Dialog, im.FromAgentName, im.Message, im.RegionID, im.Position);
if (im.Dialog == InstantMessageDialog.RequestTeleport)
{
Console.WriteLine("Accepting teleport lure.");
Self.TeleportLureRespond(im.FromAgentID, true);
}
else if (
im.Dialog == InstantMessageDialog.MessageFromAgent ||
im.Dialog == InstantMessageDialog.MessageFromObject)
{
DoCommand(im.Message, im.FromAgentID);
}
}
else
{
// Received an IM from someone that is not the bot's master, ignore
Console.WriteLine("<{0} ({1})> {2} (not master): {3} (@{4}:{5})", im.GroupIM ? "GroupIM" : "IM", im.Dialog, im.FromAgentName, im.Message,
im.RegionID, im.Position);
return;
}
}
private bool Inventory_OnInventoryObjectReceived(InstantMessage offer, AssetType type,
LLUUID objectID, bool fromTask)
{
if (MasterKey != LLUUID.Zero)
{
if (offer.FromAgentID != MasterKey)
return false;
}
else if (GroupMembers != null && !GroupMembers.ContainsKey(offer.FromAgentID))
{
return false;
}
return true;
}
}
}
| |
/*
* 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 lambda-2015-03-31.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.Lambda.Model
{
/// <summary>
/// A complex type that describes function metadata.
/// </summary>
public partial class GetFunctionConfigurationResponse : AmazonWebServiceResponse
{
private string _codeSha256;
private long? _codeSize;
private string _description;
private string _functionArn;
private string _functionName;
private string _handler;
private string _lastModified;
private int? _memorySize;
private string _role;
private Runtime _runtime;
private int? _timeout;
private string _version;
/// <summary>
/// Gets and sets the property CodeSha256.
/// <para>
/// It is the SHA256 hash of your function deployment package.
/// </para>
/// </summary>
public string CodeSha256
{
get { return this._codeSha256; }
set { this._codeSha256 = value; }
}
// Check to see if CodeSha256 property is set
internal bool IsSetCodeSha256()
{
return this._codeSha256 != null;
}
/// <summary>
/// Gets and sets the property CodeSize.
/// <para>
/// The size, in bytes, of the function .zip file you uploaded.
/// </para>
/// </summary>
public long CodeSize
{
get { return this._codeSize.GetValueOrDefault(); }
set { this._codeSize = value; }
}
// Check to see if CodeSize property is set
internal bool IsSetCodeSize()
{
return this._codeSize.HasValue;
}
/// <summary>
/// Gets and sets the property Description.
/// <para>
/// The user-provided description.
/// </para>
/// </summary>
public string Description
{
get { return this._description; }
set { this._description = value; }
}
// Check to see if Description property is set
internal bool IsSetDescription()
{
return this._description != null;
}
/// <summary>
/// Gets and sets the property FunctionArn.
/// <para>
/// The Amazon Resource Name (ARN) assigned to the function.
/// </para>
/// </summary>
public string FunctionArn
{
get { return this._functionArn; }
set { this._functionArn = value; }
}
// Check to see if FunctionArn property is set
internal bool IsSetFunctionArn()
{
return this._functionArn != null;
}
/// <summary>
/// Gets and sets the property FunctionName.
/// <para>
/// The name of the function.
/// </para>
/// </summary>
public string FunctionName
{
get { return this._functionName; }
set { this._functionName = value; }
}
// Check to see if FunctionName property is set
internal bool IsSetFunctionName()
{
return this._functionName != null;
}
/// <summary>
/// Gets and sets the property Handler.
/// <para>
/// The function Lambda calls to begin executing your function.
/// </para>
/// </summary>
public string Handler
{
get { return this._handler; }
set { this._handler = value; }
}
// Check to see if Handler property is set
internal bool IsSetHandler()
{
return this._handler != null;
}
/// <summary>
/// Gets and sets the property LastModified.
/// <para>
/// The timestamp of the last time you updated the function.
/// </para>
/// </summary>
public string LastModified
{
get { return this._lastModified; }
set { this._lastModified = value; }
}
// Check to see if LastModified property is set
internal bool IsSetLastModified()
{
return this._lastModified != null;
}
/// <summary>
/// Gets and sets the property MemorySize.
/// <para>
/// The memory size, in MB, you configured for the function. Must be a multiple of 64
/// MB.
/// </para>
/// </summary>
public int MemorySize
{
get { return this._memorySize.GetValueOrDefault(); }
set { this._memorySize = value; }
}
// Check to see if MemorySize property is set
internal bool IsSetMemorySize()
{
return this._memorySize.HasValue;
}
/// <summary>
/// Gets and sets the property Role.
/// <para>
/// The Amazon Resource Name (ARN) of the IAM role that Lambda assumes when it executes
/// your function to access any other Amazon Web Services (AWS) resources.
/// </para>
/// </summary>
public string Role
{
get { return this._role; }
set { this._role = value; }
}
// Check to see if Role property is set
internal bool IsSetRole()
{
return this._role != null;
}
/// <summary>
/// Gets and sets the property Runtime.
/// <para>
/// The runtime environment for the Lambda function.
/// </para>
/// </summary>
public Runtime Runtime
{
get { return this._runtime; }
set { this._runtime = value; }
}
// Check to see if Runtime property is set
internal bool IsSetRuntime()
{
return this._runtime != null;
}
/// <summary>
/// Gets and sets the property Timeout.
/// <para>
/// The function execution time at which Lambda should terminate the function. Because
/// the execution time has cost implications, we recommend you set this value based on
/// your expected execution time. The default is 3 seconds.
/// </para>
/// </summary>
public int Timeout
{
get { return this._timeout.GetValueOrDefault(); }
set { this._timeout = value; }
}
// Check to see if Timeout property is set
internal bool IsSetTimeout()
{
return this._timeout.HasValue;
}
/// <summary>
/// Gets and sets the property Version.
/// <para>
/// The version of the Lambda function.
/// </para>
/// </summary>
public string Version
{
get { return this._version; }
set { this._version = value; }
}
// Check to see if Version property is set
internal bool IsSetVersion()
{
return this._version != null;
}
}
}
| |
using J2N.Text;
using YAF.Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
namespace YAF.Lucene.Net.Util
{
/*
* 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.
*/
/// <summary>
/// Provides a merged sorted view from several sorted iterators.
/// <para/>
/// If built with <see cref="removeDuplicates"/> set to <c>true</c> and an element
/// appears in multiple iterators then it is deduplicated, that is this iterator
/// returns the sorted union of elements.
/// <para/>
/// If built with <see cref="removeDuplicates"/> set to <c>false</c> then all elements
/// in all iterators are returned.
/// <para/>
/// Caveats:
/// <list type="bullet">
/// <item><description>The behavior is undefined if the iterators are not actually sorted.</description></item>
/// <item><description>Null elements are unsupported.</description></item>
/// <item><description>If <see cref="removeDuplicates"/> is set to <c>true</c> and if a single iterator contains
/// duplicates then they will not be deduplicated.</description></item>
/// <item><description>When elements are deduplicated it is not defined which one is returned.</description></item>
/// <item><description>If <see cref="removeDuplicates"/> is set to <c>false</c> then the order in which duplicates
/// are returned isn't defined.</description></item>
/// </list>
/// <para/>
/// The caller is responsible for disposing the <see cref="IEnumerator{T}"/> instances that are passed
/// into the constructor, <see cref="MergedEnumerator{T}"/> doesn't do it automatically.
/// <para/>
/// @lucene.internal
/// </summary>
public sealed class MergedEnumerator<T> : IEnumerator<T>
where T : IComparable<T>
{
private readonly TermMergeQueue<T> queue;
private readonly SubEnumerator<T>[] top;
private readonly bool removeDuplicates;
private int numTop;
private T current;
public MergedEnumerator(params IEnumerator<T>[] enumerators) : this(true, enumerators) { }
public MergedEnumerator(bool removeDuplicates, params IEnumerator<T>[] enumerators) : this(removeDuplicates, (IList<IEnumerator<T>>)enumerators) { }
public MergedEnumerator(IList<IEnumerator<T>> enumerators) : this(true, enumerators) { } // LUCENENET specific - added overload for better compatibity
public MergedEnumerator(bool removeDuplicates, IList<IEnumerator<T>> enumerators) // LUCENENET specific - added overload for better compatibity
{
if (enumerators is null)
throw new ArgumentNullException(nameof(enumerators)); // LUCENENET specific - added guard clause
this.removeDuplicates = removeDuplicates;
queue = new TermMergeQueue<T>(enumerators.Count);
top = new SubEnumerator<T>[enumerators.Count];
int index = 0;
foreach (IEnumerator<T> iter in enumerators)
{
// If hasNext
if (iter.MoveNext())
{
queue.Add(new SubEnumerator<T>
{
Current = iter.Current,
Enumerator = iter,
Index = index++
});
}
}
}
public bool MoveNext()
{
PushTop();
if (queue.Count > 0)
{
PullTop();
}
else
{
return false;
}
return true;
}
public T Current => current;
object System.Collections.IEnumerator.Current => Current;
public void Reset()
{
throw UnsupportedOperationException.Create();
}
public void Dispose()
{
}
private void PullTop()
{
if (Debugging.AssertsEnabled) Debugging.Assert(numTop == 0);
top[numTop++] = queue.Pop();
if (removeDuplicates)
{
//extract all subs from the queue that have the same top element
while (queue.Count != 0 && queue.Top.Current.Equals(top[0].Current))
{
top[numTop++] = queue.Pop();
}
}
current = top[0].Current;
}
private void PushTop()
{
for (int i = 0; i < numTop; ++i)
{
if (top[i].Enumerator.MoveNext())
{
top[i].Current = top[i].Enumerator.Current;
queue.Add(top[i]);
}
else
{
top[i].Current = default;
}
}
numTop = 0;
}
private class SubEnumerator<I>
where I : IComparable<I>
{
internal IEnumerator<I> Enumerator { get; set; }
internal I Current { get; set; }
internal int Index { get; set; }
}
private class TermMergeQueue<C> : PriorityQueue<SubEnumerator<C>>
where C : IComparable<C>
{
internal TermMergeQueue(int size)
: base(size)
{
}
protected internal override bool LessThan(SubEnumerator<C> a, SubEnumerator<C> b)
{
int cmp;
// LUCNENENET specific: For strings, we need to ensure we compare them ordinal
if (typeof(C).Equals(typeof(string)))
{
cmp = (a.Current as string).CompareToOrdinal(b.Current as string);
}
else
{
cmp = a.Current.CompareTo(b.Current);
}
if (cmp != 0)
{
return cmp < 0;
}
else
{
return a.Index < b.Index;
}
}
}
}
/// <summary>
/// Provides a merged sorted view from several sorted iterators.
/// <para/>
/// If built with <see cref="removeDuplicates"/> set to <c>true</c> and an element
/// appears in multiple iterators then it is deduplicated, that is this iterator
/// returns the sorted union of elements.
/// <para/>
/// If built with <see cref="removeDuplicates"/> set to <c>false</c> then all elements
/// in all iterators are returned.
/// <para/>
/// Caveats:
/// <list type="bullet">
/// <item><description>The behavior is undefined if the iterators are not actually sorted.</description></item>
/// <item><description>Null elements are unsupported.</description></item>
/// <item><description>If <see cref="removeDuplicates"/> is set to <c>true</c> and if a single iterator contains
/// duplicates then they will not be deduplicated.</description></item>
/// <item><description>When elements are deduplicated it is not defined which one is returned.</description></item>
/// <item><description>If <see cref="removeDuplicates"/> is set to <c>false</c> then the order in which duplicates
/// are returned isn't defined.</description></item>
/// </list>
/// <para/>
/// The caller is responsible for disposing the <see cref="IEnumerator{T}"/> instances that are passed
/// into the constructor, <see cref="MergedIterator{T}"/> doesn't do it automatically.
/// <para/>
/// @lucene.internal
/// </summary>
[Obsolete("Use MergedEnumerator instead. This class will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public sealed class MergedIterator<T> : IEnumerator<T>
where T : IComparable<T>
{
private readonly TermMergeQueue<T> queue;
private readonly SubIterator<T>[] top;
private readonly bool removeDuplicates;
private int numTop;
private T current;
public MergedIterator(params IEnumerator<T>[] iterators)
: this(true, iterators)
{
}
public MergedIterator(bool removeDuplicates, params IEnumerator<T>[] iterators)
{
this.removeDuplicates = removeDuplicates;
queue = new TermMergeQueue<T>(iterators.Length);
top = new SubIterator<T>[iterators.Length];
int index = 0;
foreach (IEnumerator<T> iter in iterators)
{
// If hasNext
if (iter.MoveNext())
{
SubIterator<T> sub = new SubIterator<T>();
sub.Current = iter.Current;
sub.Iterator = iter;
sub.Index = index++;
queue.Add(sub);
}
}
}
public bool MoveNext()
{
PushTop();
if (queue.Count > 0)
{
PullTop();
}
else
{
return false;
}
return true;
}
public T Current => current;
object System.Collections.IEnumerator.Current => Current;
public void Reset()
{
throw UnsupportedOperationException.Create();
}
public void Dispose()
{
}
private void PullTop()
{
if (Debugging.AssertsEnabled) Debugging.Assert(numTop == 0);
top[numTop++] = queue.Pop();
if (removeDuplicates)
{
//extract all subs from the queue that have the same top element
while (queue.Count != 0 && queue.Top.Current.Equals(top[0].Current))
{
top[numTop++] = queue.Pop();
}
}
current = top[0].Current;
}
private void PushTop()
{
for (int i = 0; i < numTop; ++i)
{
if (top[i].Iterator.MoveNext())
{
top[i].Current = top[i].Iterator.Current;
queue.Add(top[i]);
}
else
{
top[i].Current = default;
}
}
numTop = 0;
}
private class SubIterator<I>
where I : IComparable<I>
{
internal IEnumerator<I> Iterator { get; set; }
internal I Current { get; set; }
internal int Index { get; set; }
}
private class TermMergeQueue<C> : PriorityQueue<SubIterator<C>>
where C : IComparable<C>
{
internal TermMergeQueue(int size)
: base(size)
{
}
protected internal override bool LessThan(SubIterator<C> a, SubIterator<C> b)
{
int cmp;
// LUCNENENET specific: For strings, we need to ensure we compare them ordinal
if (typeof(C).Equals(typeof(string)))
{
cmp = (a.Current as string).CompareToOrdinal(b.Current as string);
}
else
{
cmp = a.Current.CompareTo(b.Current);
}
if (cmp != 0)
{
return cmp < 0;
}
else
{
return a.Index < b.Index;
}
}
}
}
}
| |
//
// Copyright 2012 Thinksquirrel Software, LLC. All rights reserved.
//
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu("Utilities/Camera Shake")]
public class _CameraShake : ThinksquirrelSoftware.Utilities.CameraShake {}
namespace ThinksquirrelSoftware.Utilities
{
/// <summary>
/// Shakes the camera and GUI.
/// </summary>
/// <remarks>
/// All events use the System.Action method signature.
/// </remarks>
/// Check README.txt for more information.
public class CameraShake : MonoBehaviour
{
/// <summary>
/// The cameras to shake.
/// </summary>
public List<Camera> cameras = new List<Camera>();
/// <summary>
/// The maximum number of shakes to perform.
/// </summary>
public int numberOfShakes = 2;
/// <summary>
/// The amount to shake in each direction.
/// </summary>
public Vector3 shakeAmount = Vector3.one;
/// <summary>
/// The amount to rotate in each direction.
/// </summary>
public Vector3 rotationAmount = Vector3.one;
/// <summary>
/// The initial distance for the first shake.
/// </summary>
public float distance = 00.10f;
/// <summary>
/// The speed multiplier for the shake.
/// </summary>
public float speed = 50.00f;
/// <summary>
/// The decay speed (between 0 and 1). Higher values will stop shaking sooner.
/// </summary>
public float decay = 00.20f;
/// <summary>
/// The modifier applied to speed in order to shake the GUI.
/// </summary>
public float guiShakeModifier = 01.00f;
/// <summary>
/// If true, multiplies the final shake speed by the time scale.
/// </summary>
public bool multiplyByTimeScale = true;
// Shake rect (for GUI)
private Rect shakeRect;
// States
private bool shaking = false;
private bool cancelling = false;
internal class ShakeState
{
internal readonly Vector3 startPosition;
internal readonly Quaternion startRotation;
internal readonly Vector2 guiStartPosition;
internal Vector3 shakePosition;
internal Quaternion shakeRotation;
internal Vector2 guiShakePosition;
internal ShakeState(Vector3 position, Quaternion rotation, Vector2 guiPosition)
{
startPosition = position;
startRotation = rotation;
guiStartPosition = guiPosition;
shakePosition = position;
shakeRotation = rotation;
guiShakePosition = guiPosition;
}
}
private Dictionary<Camera, List<ShakeState>> states = new Dictionary<Camera, List<ShakeState>>();
private Dictionary<Camera, int> shakeCount = new Dictionary<Camera, int>();
// Minimum shake values
private const bool checkForMinimumValues = true;
private const float minShakeValue = 0.001f;
private const float minRotationValue = 0.001f;
#region Singleton
/// <summary>
/// The Camera Shake singleton instance.
/// </summary>
public static CameraShake instance;
private void OnEnable()
{
if (cameras.Count < 1)
{
if (GetComponent<Camera>())
cameras.Add(GetComponent<Camera>());
}
if (cameras.Count < 1)
{
if (Camera.main)
cameras.Add(Camera.main);
}
if (cameras.Count < 1)
{
Debug.LogError("Camera Shake: No cameras assigned in the inspector!");
}
instance = this;
}
#endregion
#region Static properties
public static bool isShaking
{
get
{
return instance.IsShaking();
}
}
public static bool isCancelling
{
get
{
return instance.IsCancelling();
}
}
#endregion
#region Static methods
public static void Shake()
{
instance.DoShake();
}
public static void Shake(int numberOfShakes, Vector3 shakeAmount, Vector3 rotationAmount, float distance, float speed, float decay, float guiShakeModifier, bool multiplyByTimeScale)
{
instance.DoShake(numberOfShakes, shakeAmount, rotationAmount, distance, speed, decay, guiShakeModifier, multiplyByTimeScale);
}
public static void Shake(System.Action callback)
{
instance.DoShake(callback);
}
public static void Shake(int numberOfShakes, Vector3 shakeAmount, Vector3 rotationAmount, float distance, float speed, float decay, float guiShakeModifier, bool multiplyByTimeScale, System.Action callback)
{
instance.DoShake(numberOfShakes, shakeAmount, rotationAmount, distance, speed, decay, guiShakeModifier, multiplyByTimeScale, callback);
}
public static void CancelShake()
{
instance.DoCancelShake();
}
public static void CancelShake(float time)
{
instance.DoCancelShake(time);
}
public static void BeginShakeGUI()
{
instance.DoBeginShakeGUI();
}
public static void EndShakeGUI()
{
instance.DoEndShakeGUI();
}
public static void BeginShakeGUILayout()
{
instance.DoBeginShakeGUILayout();
}
public static void EndShakeGUILayout()
{
instance.DoEndShakeGUILayout();
}
#endregion
#region Events
/// <summary>
/// Occurs when a camera starts shaking.
/// </summary>
public event System.Action cameraShakeStarted;
/// <summary>
/// Occurs when a camera has completely stopped shaking and has been reset to its original position.
/// </summary>
public event System.Action allCameraShakesCompleted;
#endregion
#region Public methods
public bool IsShaking()
{
return shaking;
}
public bool IsCancelling()
{
return cancelling;
}
public void DoShake()
{
Vector3 seed = Random.insideUnitSphere;
foreach(Camera cam in cameras)
{
StartCoroutine(DoShake_Internal(cam, seed, this.numberOfShakes, this.shakeAmount, this.rotationAmount, this.distance, this.speed, this.decay, this.guiShakeModifier, this.multiplyByTimeScale, null));
}
}
public void DoShake(int numberOfShakes, Vector3 shakeAmount, Vector3 rotationAmount, float distance, float speed, float decay, float guiShakeModifier, bool multiplyByTimeScale)
{
Vector3 seed = Random.insideUnitSphere;
foreach(Camera cam in cameras)
{
StartCoroutine(DoShake_Internal(cam, seed, numberOfShakes, shakeAmount, rotationAmount, distance, speed, decay, guiShakeModifier, multiplyByTimeScale, null));
}
}
public void DoShake(System.Action callback)
{
Vector3 seed = Random.insideUnitSphere;
foreach(Camera cam in cameras)
{
StartCoroutine(DoShake_Internal(cam, seed, this.numberOfShakes, this.shakeAmount, this.rotationAmount, this.distance, this.speed, this.decay, this.guiShakeModifier, this.multiplyByTimeScale, callback));
}
}
public void DoShake(int numberOfShakes, Vector3 shakeAmount, Vector3 rotationAmount, float distance, float speed, float decay, float guiShakeModifier, bool multiplyByTimeScale, System.Action callback)
{
Vector3 seed = Random.insideUnitSphere;
foreach(Camera cam in cameras)
{
StartCoroutine(DoShake_Internal(cam, seed, numberOfShakes, shakeAmount, rotationAmount, distance, speed, decay, guiShakeModifier, multiplyByTimeScale, callback));
}
}
public void DoCancelShake()
{
if (shaking && !cancelling)
{
shaking = false;
this.StopAllCoroutines();
foreach(Camera cam in cameras)
{
if (shakeCount.ContainsKey(cam))
{
shakeCount[cam] = 0;
}
ResetState(cam.transform, cam);
}
}
}
public void DoCancelShake(float time)
{
if (shaking && !cancelling)
{
this.StopAllCoroutines();
this.StartCoroutine(DoResetState(cameras, shakeCount, time));
}
}
public void DoBeginShakeGUI()
{
CheckShakeRect();
GUI.BeginGroup(shakeRect);
}
public void DoEndShakeGUI()
{
GUI.EndGroup();
}
public void DoBeginShakeGUILayout()
{
CheckShakeRect();
GUILayout.BeginArea(shakeRect);
}
public void DoEndShakeGUILayout()
{
GUILayout.EndArea();
}
#endregion
#region Private methods
private void OnDrawGizmosSelected()
{
foreach(Camera cam in cameras)
{
if (!cam)
continue;
if (IsShaking())
{
Vector3 offset = cam.worldToCameraMatrix.GetColumn(3);
offset.z *= -1;
offset = cam.transform.position + cam.transform.TransformPoint(offset);
Quaternion rot = QuaternionFromMatrix(cam.worldToCameraMatrix.inverse * Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1,1,-1)));
Matrix4x4 matrix = Matrix4x4.TRS(offset, rot, cam.transform.lossyScale);
Gizmos.matrix = matrix;
}
else
{
Matrix4x4 matrix = Matrix4x4.TRS(cam.transform.position, cam.transform.rotation, cam.transform.lossyScale);
Gizmos.matrix = matrix;
}
Gizmos.DrawWireCube(Vector3.zero, shakeAmount);
Gizmos.color = Color.cyan;
if (cam.orthographic)
{
Vector3 pos = new Vector3(0, 0, (cam.near + cam.far) / 2f);
Vector3 size = new Vector3(cam.orthographicSize / cam.aspect, cam.orthographicSize * 2f, cam.far - cam.near);
Gizmos.DrawWireCube(pos, size);
}
else
{
Gizmos.DrawFrustum(Vector3.zero, cam.fov, cam.far, cam.near, (.7f / cam.aspect));
}
}
}
private IEnumerator DoShake_Internal(Camera cam, Vector3 seed, int numberOfShakes, Vector3 shakeAmount, Vector3 rotationAmount, float distance, float speed, float decay, float guiShakeModifier, bool multiplyByTimeScale, System.Action callback)
{
// Wait for async cancel operations to complete
if (cancelling)
yield return null;
// Set random values
var mod1 = seed.x > .5f ? 1 : -1;
var mod2 = seed.y > .5f ? 1 : -1;
var mod3 = seed.z > .5f ? 1 : -1;
// First shake
if (!shaking)
{
shaking = true;
if (cameraShakeStarted != null)
cameraShakeStarted();
}
if (shakeCount.ContainsKey(cam))
shakeCount[cam]++;
else
shakeCount.Add(cam, 1);
// Pixel width is always based on the first camera
float pixelWidth = GetPixelWidth(cameras[0].transform, cameras[0]);
// Set other values
Transform cachedTransform = cam.transform;
Vector3 camOffset = Vector3.zero;
Quaternion camRot = Quaternion.identity;
int currentShakes = numberOfShakes;
float shakeDistance = distance;
float rotationStrength = 1;
float startTime = Time.time;
float scale = multiplyByTimeScale ? Time.timeScale : 1;
float pixelScale = pixelWidth * guiShakeModifier * scale;
Vector3 start1 = Vector2.zero;
Quaternion startR = Quaternion.identity;
Vector2 start2 = Vector2.zero;
ShakeState state = new ShakeState(cachedTransform.position, cachedTransform.rotation, new Vector2(shakeRect.x, shakeRect.y));
List<ShakeState> stateList;
if (states.TryGetValue(cam, out stateList))
{
stateList.Add(state);
}
else
{
stateList = new List<ShakeState>();
stateList.Add(state);
states.Add(cam, stateList);
}
// Main loop
while (currentShakes > 0)
{
if (checkForMinimumValues)
{
// Early break when rotation is less than the minimum value.
if (rotationAmount.sqrMagnitude != 0 && rotationStrength <= minRotationValue)
break;
// Early break when shake amount is less than the minimum value.
if (shakeAmount.sqrMagnitude != 0 && distance != 0 && shakeDistance <= minShakeValue)
break;
}
var timer = (Time.time - startTime) * speed;
state.shakePosition = start1 + new Vector3(
mod1 * Mathf.Sin(timer) * (shakeAmount.x * shakeDistance * scale),
mod2 * Mathf.Cos(timer) * (shakeAmount.y * shakeDistance * scale),
mod3 * Mathf.Sin(timer) * (shakeAmount.z * shakeDistance * scale));
state.shakeRotation = startR * Quaternion.Euler(
mod1 * Mathf.Cos(timer) * (rotationAmount.x * rotationStrength * scale),
mod2 * Mathf.Sin(timer) * (rotationAmount.y * rotationStrength * scale),
mod3 * Mathf.Cos(timer) * (rotationAmount.z * rotationStrength * scale));
state.guiShakePosition = new Vector2(
start2.x - (mod1 * Mathf.Sin(timer) * (shakeAmount.x * shakeDistance * pixelScale)),
start2.y - (mod2 * Mathf.Cos(timer) * (shakeAmount.y * shakeDistance * pixelScale)));
camOffset = GetGeometricAvg(stateList, true);
camRot = GetAvgRotation(stateList);
NormalizeQuaternion(ref camRot);
Matrix4x4 m = Matrix4x4.TRS(camOffset, camRot, new Vector3(1, 1, -1));
cam.worldToCameraMatrix = m * cachedTransform.worldToLocalMatrix;
var avg = GetGeometricAvg(stateList, false);
shakeRect.x = avg.x;
shakeRect.y = avg.y;
if (timer > Mathf.PI * 2)
{
startTime = Time.time;
shakeDistance *= (1 - Mathf.Clamp01(decay));
rotationStrength *= (1 - Mathf.Clamp01(decay));
currentShakes--;
}
yield return null;
}
// End conditions
shakeCount[cam]--;
// Last shake
if (shakeCount[cam] == 0)
{
shaking = false;
ResetState(cam.transform, cam);
if (allCameraShakesCompleted != null)
{
allCameraShakesCompleted();
}
}
else
{
stateList.Remove(state);
}
if (callback != null)
callback();
}
private Vector3 GetGeometricAvg(List<ShakeState> states, bool position)
{
float x = 0, y = 0, z = 0, l = states.Count;
foreach(ShakeState state in states)
{
if (position)
{
x -= state.shakePosition.x;
y -= state.shakePosition.y;
z -= state.shakePosition.z;
}
else
{
x += state.guiShakePosition.x;
y += state.guiShakePosition.y;
}
}
return new Vector3(x / l, y / l, z / l);
}
private Quaternion GetAvgRotation(List<ShakeState> states)
{
Quaternion avg = new Quaternion(0,0,0,0);
foreach(ShakeState state in states)
{
if (Quaternion.Dot (state.shakeRotation, avg) > 0)
{
avg.x += state.shakeRotation.x;
avg.y += state.shakeRotation.y;
avg.z += state.shakeRotation.z;
avg.w += state.shakeRotation.w;
}
else
{
avg.x += -state.shakeRotation.x;
avg.y += -state.shakeRotation.y;
avg.z += -state.shakeRotation.z;
avg.w += -state.shakeRotation.w;
}
}
var mag = Mathf.Sqrt(avg.x* avg.x + avg.y* avg.y + avg.z * avg.z + avg.w * avg.w);
if (mag > 0.0001f)
{
avg.x /= mag;
avg.y /= mag;
avg.z /= mag;
avg.w /= mag;
}
else
{
avg = states[0].shakeRotation;
}
return avg;
}
private void CheckShakeRect()
{
if (Screen.width != shakeRect.width || Screen.height != shakeRect.height)
{
shakeRect.width = Screen.width;
shakeRect.height = Screen.height;
}
}
private float GetPixelWidth(Transform cachedTransform, Camera cachedCamera)
{
var position = cachedTransform.position;
var screenPos = cachedCamera.WorldToScreenPoint(position - cachedTransform.forward * .01f);
var offset = Vector3.zero;
if (screenPos.x > 0)
offset = screenPos - Vector3.right;
else
offset = screenPos + Vector3.right;
if (screenPos.y > 0)
offset = screenPos - Vector3.up;
else
offset = screenPos + Vector3.up;
offset = cachedCamera.ScreenToWorldPoint(offset);
return 1f / (cachedTransform.InverseTransformPoint(position) - cachedTransform.InverseTransformPoint(offset)).magnitude;
}
private void ResetState(Transform cachedTransform, Camera cam)
{
cam.ResetWorldToCameraMatrix();
shakeRect.x = 0;
shakeRect.y = 0;
states[cam].Clear();
}
private List<Vector3> offsetCache = new List<Vector3>(10);
private List<Quaternion> rotationCache = new List<Quaternion>(10);
private IEnumerator DoResetState(List<Camera> cameras, Dictionary<Camera, int> shakeCount, float time)
{
offsetCache.Clear();
rotationCache.Clear();
foreach(Camera cam in cameras)
{
offsetCache.Add((Vector3)((cam.worldToCameraMatrix * cam.transform.worldToLocalMatrix.inverse).GetColumn(3)));
rotationCache.Add(QuaternionFromMatrix((cam.worldToCameraMatrix * cam.transform.worldToLocalMatrix.inverse).inverse * Matrix4x4.TRS(Vector3.zero, Quaternion.identity, new Vector3(1,1,-1))));
if (shakeCount.ContainsKey(cam))
{
shakeCount[cam] = 0;
}
states[cam].Clear();
}
float t = 0;
float x = shakeRect.x, y = shakeRect.y;
cancelling = true;
while (t < time)
{
int i = 0;
foreach(Camera cam in cameras)
{
Transform cachedTransform = cam.transform;
shakeRect.x = Mathf.Lerp(x, 0, t / time);
shakeRect.y = Mathf.Lerp(y, 0, t / time);
Vector3 pos = Vector3.Lerp(offsetCache[i], Vector3.zero, t / time);
Quaternion rot = Quaternion.Slerp(rotationCache[i], cachedTransform.rotation, t / time);
Matrix4x4 m = Matrix4x4.TRS(pos, rot, new Vector3(1, 1, -1));
cam.worldToCameraMatrix = m * cachedTransform.worldToLocalMatrix;
i++;
}
t += Time.deltaTime;
yield return null;
}
foreach(Camera cam in cameras)
{
cam.ResetWorldToCameraMatrix();
shakeRect.x = 0;
shakeRect.y = 0;
}
this.shaking = false;
this.cancelling = false;
}
#endregion
#region Quaternion helpers
private static Quaternion QuaternionFromMatrix(Matrix4x4 m)
{
return Quaternion.LookRotation(m.GetColumn(2), m.GetColumn(1));
}
private static void NormalizeQuaternion (ref Quaternion q)
{
float sum = 0;
for (int i = 0; i < 4; ++i)
sum += q[i] * q[i];
float magnitudeInverse = 1 / Mathf.Sqrt(sum);
for (int i = 0; i < 4; ++i)
q[i] *= magnitudeInverse;
}
#endregion
}
}
| |
/*
* Copyright 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using ZXing.Common;
namespace ZXing.OneD
{
/// <summary>
/// Encapsulates functionality and implementation that is common to all families
/// of one-dimensional barcodes.
/// <author>dswitkin@google.com (Daniel Switkin)</author>
/// <author>Sean Owen</author>
/// </summary>
public abstract class OneDReader : Reader
{
/// <summary>
///
/// </summary>
protected static int INTEGER_MATH_SHIFT = 8;
/// <summary>
///
/// </summary>
protected static int PATTERN_MATCH_RESULT_SCALE_FACTOR = 1 << INTEGER_MATH_SHIFT;
/// <summary>
/// Locates and decodes a barcode in some format within an image.
/// </summary>
/// <param name="image">image of barcode to decode</param>
/// <returns>
/// String which the barcode encodes
/// </returns>
public Result decode(BinaryBitmap image)
{
return decode(image, null);
}
/// <summary>
/// Locates and decodes a barcode in some format within an image. This method also accepts
/// hints, each possibly associated to some data, which may help the implementation decode.
/// Note that we don't try rotation without the try harder flag, even if rotation was supported.
/// </summary>
/// <param name="image">image of barcode to decode</param>
/// <param name="hints">passed as a <see cref="IDictionary{TKey, TValue}"/> from <see cref="DecodeHintType"/>
/// to arbitrary data. The
/// meaning of the data depends upon the hint type. The implementation may or may not do
/// anything with these hints.</param>
/// <returns>
/// String which the barcode encodes
/// </returns>
virtual public Result decode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
{
var result = doDecode(image, hints);
if (result == null)
{
bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
bool tryHarderWithoutRotation = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER_WITHOUT_ROTATION);
if (tryHarder && !tryHarderWithoutRotation && image.RotateSupported)
{
BinaryBitmap rotatedImage = image.rotateCounterClockwise();
result = doDecode(rotatedImage, hints);
if (result == null)
return null;
// Record that we found it rotated 90 degrees CCW / 270 degrees CW
IDictionary<ResultMetadataType, object> metadata = result.ResultMetadata;
int orientation = 270;
if (metadata != null && metadata.ContainsKey(ResultMetadataType.ORIENTATION))
{
// But if we found it reversed in doDecode(), add in that result here:
orientation = (orientation +
(int) metadata[ResultMetadataType.ORIENTATION])%360;
}
result.putMetadata(ResultMetadataType.ORIENTATION, orientation);
// Update result points
ResultPoint[] points = result.ResultPoints;
if (points != null)
{
int height = rotatedImage.Height;
for (int i = 0; i < points.Length; i++)
{
points[i] = new ResultPoint(height - points[i].Y - 1, points[i].X);
}
}
}
}
return result;
}
/// <summary>
/// Resets any internal state the implementation has after a decode, to prepare it
/// for reuse.
/// </summary>
virtual public void reset()
{
// do nothing
}
/// <summary>
/// We're going to examine rows from the middle outward, searching alternately above and below the
/// middle, and farther out each time. rowStep is the number of rows between each successive
/// attempt above and below the middle. So we'd scan row middle, then middle - rowStep, then
/// middle + rowStep, then middle - (2 * rowStep), etc.
/// rowStep is bigger as the image is taller, but is always at least 1. We've somewhat arbitrarily
/// decided that moving up and down by about 1/16 of the image is pretty good; we try more of the
/// image if "trying harder".
/// </summary>
/// <param name="image">The image to decode</param>
/// <param name="hints">Any hints that were requested</param>
/// <returns>The contents of the decoded barcode</returns>
virtual protected Result doDecode(BinaryBitmap image, IDictionary<DecodeHintType, object> hints)
{
int width = image.Width;
int height = image.Height;
BitArray row = new BitArray(width);
bool tryHarder = hints != null && hints.ContainsKey(DecodeHintType.TRY_HARDER);
int rowStep = Math.Max(1, height >> (tryHarder ? 8 : 5));
int maxLines;
if (tryHarder)
{
maxLines = height; // Look at the whole image, not just the center
}
else
{
maxLines = 15; // 15 rows spaced 1/32 apart is roughly the middle half of the image
}
int middle = height >> 1;
for (int x = 0; x < maxLines; x++)
{
// Scanning from the middle out. Determine which row we're looking at next:
int rowStepsAboveOrBelow = (x + 1) >> 1;
bool isAbove = (x & 0x01) == 0; // i.e. is x even?
int rowNumber = middle + rowStep * (isAbove ? rowStepsAboveOrBelow : -rowStepsAboveOrBelow);
if (rowNumber < 0 || rowNumber >= height)
{
// Oops, if we run off the top or bottom, stop
break;
}
// Estimate black point for this row and load it:
row = image.getBlackRow(rowNumber, row);
if (row == null)
continue;
// While we have the image data in a BitArray, it's fairly cheap to reverse it in place to
// handle decoding upside down barcodes.
for (int attempt = 0; attempt < 2; attempt++)
{
if (attempt == 1)
{
// trying again?
row.reverse(); // reverse the row and continue
// This means we will only ever draw result points *once* in the life of this method
// since we want to avoid drawing the wrong points after flipping the row, and,
// don't want to clutter with noise from every single row scan -- just the scans
// that start on the center line.
if (hints != null && hints.ContainsKey(DecodeHintType.NEED_RESULT_POINT_CALLBACK))
{
IDictionary<DecodeHintType, Object> newHints = new Dictionary<DecodeHintType, Object>();
foreach (var hint in hints)
{
if (hint.Key != DecodeHintType.NEED_RESULT_POINT_CALLBACK)
newHints.Add(hint.Key, hint.Value);
}
hints = newHints;
}
}
// Look for a barcode
Result result = decodeRow(rowNumber, row, hints);
if (result == null)
continue;
// We found our barcode
if (attempt == 1)
{
// But it was upside down, so note that
result.putMetadata(ResultMetadataType.ORIENTATION, 180);
// And remember to flip the result points horizontally.
ResultPoint[] points = result.ResultPoints;
if (points != null)
{
points[0] = new ResultPoint(width - points[0].X - 1, points[0].Y);
points[1] = new ResultPoint(width - points[1].X - 1, points[1].Y);
}
}
return result;
}
}
return null;
}
/// <summary>
/// Records the size of successive runs of white and black pixels in a row, starting at a given point.
/// The values are recorded in the given array, and the number of runs recorded is equal to the size
/// of the array. If the row starts on a white pixel at the given start point, then the first count
/// recorded is the run of white pixels starting from that point; likewise it is the count of a run
/// of black pixels if the row begin on a black pixels at that point.
/// </summary>
/// <param name="row">row to count from</param>
/// <param name="start">offset into row to start at</param>
/// <param name="counters">array into which to record counts</param>
protected static bool recordPattern(BitArray row,
int start,
int[] counters)
{
return recordPattern(row, start, counters, counters.Length);
}
/// <summary>
/// Records the size of successive runs of white and black pixels in a row, starting at a given point.
/// The values are recorded in the given array, and the number of runs recorded is equal to the size
/// of the array. If the row starts on a white pixel at the given start point, then the first count
/// recorded is the run of white pixels starting from that point; likewise it is the count of a run
/// of black pixels if the row begin on a black pixels at that point.
/// </summary>
/// <param name="row">row to count from</param>
/// <param name="start">offset into row to start at</param>
/// <param name="counters">array into which to record counts</param>
protected static bool recordPattern(BitArray row,
int start,
int[] counters,
int numCounters)
{
for (int idx = 0; idx < numCounters; idx++)
{
counters[idx] = 0;
}
int end = row.Size;
if (start >= end)
{
return false;
}
bool isWhite = !row[start];
int counterPosition = 0;
int i = start;
while (i < end)
{
if (row[i] != isWhite)
{
counters[counterPosition]++;
}
else
{
counterPosition++;
if (counterPosition == numCounters)
{
break;
}
else
{
counters[counterPosition] = 1;
isWhite = !isWhite;
}
}
i++;
}
// If we read fully the last section of pixels and filled up our counters -- or filled
// the last counter but ran off the side of the image, OK. Otherwise, a problem.
return (counterPosition == numCounters || (counterPosition == numCounters - 1 && i == end));
}
/// <summary>
/// Records the pattern in reverse.
/// </summary>
/// <param name="row">The row.</param>
/// <param name="start">The start.</param>
/// <param name="counters">The counters.</param>
/// <returns></returns>
protected static bool recordPatternInReverse(BitArray row, int start, int[] counters)
{
// This could be more efficient I guess
int numTransitionsLeft = counters.Length;
bool last = row[start];
while (start > 0 && numTransitionsLeft >= 0)
{
if (row[--start] != last)
{
numTransitionsLeft--;
last = !last;
}
}
if (numTransitionsLeft >= 0)
{
return false;
}
return recordPattern(row, start + 1, counters);
}
/// <summary>
/// Determines how closely a set of observed counts of runs of black/white values matches a given
/// target pattern. This is reported as the ratio of the total variance from the expected pattern
/// proportions across all pattern elements, to the length of the pattern.
/// </summary>
/// <param name="counters">observed counters</param>
/// <param name="pattern">expected pattern</param>
/// <param name="maxIndividualVariance">The most any counter can differ before we give up</param>
/// <returns>ratio of total variance between counters and pattern compared to total pattern size,
/// where the ratio has been multiplied by 256. So, 0 means no variance (perfect match); 256 means
/// the total variance between counters and patterns equals the pattern length, higher values mean
/// even more variance</returns>
protected static int patternMatchVariance(int[] counters,
int[] pattern,
int maxIndividualVariance)
{
int numCounters = counters.Length;
int total = 0;
int patternLength = 0;
for (int i = 0; i < numCounters; i++)
{
total += counters[i];
patternLength += pattern[i];
}
if (total < patternLength)
{
// If we don't even have one pixel per unit of bar width, assume this is too small
// to reliably match, so fail:
return Int32.MaxValue;
}
// We're going to fake floating-point math in integers. We just need to use more bits.
// Scale up patternLength so that intermediate values below like scaledCounter will have
// more "significant digits"
int unitBarWidth = (total << INTEGER_MATH_SHIFT) / patternLength;
maxIndividualVariance = (maxIndividualVariance * unitBarWidth) >> INTEGER_MATH_SHIFT;
int totalVariance = 0;
for (int x = 0; x < numCounters; x++)
{
int counter = counters[x] << INTEGER_MATH_SHIFT;
int scaledPattern = pattern[x] * unitBarWidth;
int variance = counter > scaledPattern ? counter - scaledPattern : scaledPattern - counter;
if (variance > maxIndividualVariance)
{
return Int32.MaxValue;
}
totalVariance += variance;
}
return totalVariance / total;
}
/// <summary>
/// Attempts to decode a one-dimensional barcode format given a single row of
/// an image.
/// </summary>
/// <param name="rowNumber">row number from top of the row</param>
/// <param name="row">the black/white pixel data of the row</param>
/// <param name="hints">decode hints</param>
/// <returns>
/// <see cref="Result"/>containing encoded string and start/end of barcode
/// </returns>
public abstract Result decodeRow(int rowNumber, BitArray row, IDictionary<DecodeHintType, object> hints);
}
}
| |
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
namespace tk2dEditor.SpriteCollectionEditor
{
public class TextureEditor
{
public enum Mode
{
None,
Texture,
Anchor,
Collider,
AttachPoint,
}
int textureBorderPixels = 16;
Mode mode = Mode.Texture;
Vector2 textureScrollPos = new Vector2(0.0f, 0.0f);
bool drawColliderNormals = false;
float editorDisplayScale
{
get { return SpriteCollection.editorDisplayScale; }
set { SpriteCollection.editorDisplayScale = value; }
}
Color[] _handleInactiveColors = new Color[] {
new Color32(127, 201, 122, 255), // default
new Color32(180, 0, 0, 255), // red
new Color32(255, 255, 255, 255), // white
new Color32(32, 32, 32, 255), // black
};
Color[] _handleActiveColors = new Color[] {
new Color32(228, 226, 60, 255),
new Color32(255, 0, 0, 255),
new Color32(255, 0, 0, 255),
new Color32(96, 0, 0, 255),
};
tk2dSpriteCollectionDefinition.ColliderColor currentColliderColor = tk2dSpriteCollectionDefinition.ColliderColor.Default;
Color handleInactiveColor { get { return _handleInactiveColors[(int)currentColliderColor]; } }
Color handleActiveColor { get { return _handleActiveColors[(int)currentColliderColor]; } }
IEditorHost host;
public TextureEditor(IEditorHost host)
{
this.host = host;
}
SpriteCollectionProxy SpriteCollection { get { return host.SpriteCollection; } }
public void SetMode(Mode mode)
{
if (this.mode != mode)
{
this.mode = mode;
HandleUtility.Repaint();
}
}
Vector2 ClosestPointOnLine(Vector2 p, Vector2 p1, Vector2 p2)
{
float magSq = (p2 - p1).sqrMagnitude;
if (magSq < float.Epsilon)
return p1;
float u = ((p.x - p1.x) * (p2.x - p1.x) + (p.y - p1.y) * (p2.y - p1.y)) / magSq;
if (u < 0.0f || u > 1.0f)
return p1;
return p1 + (p2 - p1) * u;
}
void DrawPolygonColliderEditor(Rect r, ref tk2dSpriteColliderIsland[] islands, Texture2D tex, bool forceClosed)
{
Vector2 origin = new Vector2(r.x, r.y);
Vector3 origin3 = new Vector3(r.x, r.y, 0);
// Sanitize
if (islands == null || islands.Length == 0 ||
!islands[0].IsValid())
{
islands = new tk2dSpriteColliderIsland[1];
islands[0] = new tk2dSpriteColliderIsland();
islands[0].connected = true;
int w = tex.width;
int h = tex.height;
Vector2[] p = new Vector2[4];
p[0] = new Vector2(0, 0);
p[1] = new Vector2(0, h);
p[2] = new Vector2(w, h);
p[3] = new Vector2(w, 0);
islands[0].points = p;
}
Color previousHandleColor = Handles.color;
bool insertPoint = false;
if (Event.current.clickCount == 2 && Event.current.type == EventType.MouseDown)
{
insertPoint = true;
Event.current.Use();
}
if (r.Contains(Event.current.mousePosition) && Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.C)
{
Vector2 min = Event.current.mousePosition / editorDisplayScale - new Vector2(16.0f, 16.0f);
Vector3 max = Event.current.mousePosition / editorDisplayScale + new Vector2(16.0f, 16.0f);
min.x = Mathf.Clamp(min.x, 0, tex.width * editorDisplayScale);
min.y = Mathf.Clamp(min.y, 0, tex.height * editorDisplayScale);
max.x = Mathf.Clamp(max.x, 0, tex.width * editorDisplayScale);
max.y = Mathf.Clamp(max.y, 0, tex.height * editorDisplayScale);
tk2dSpriteColliderIsland island = new tk2dSpriteColliderIsland();
island.connected = true;
Vector2[] p = new Vector2[4];
p[0] = new Vector2(min.x, min.y);
p[1] = new Vector2(min.x, max.y);
p[2] = new Vector2(max.x, max.y);
p[3] = new Vector2(max.x, min.y);
island.points = p;
System.Array.Resize(ref islands, islands.Length + 1);
islands[islands.Length - 1] = island;
Event.current.Use();
}
// Draw outline lines
int deletedIsland = -1;
for (int islandId = 0; islandId < islands.Length; ++islandId)
{
float closestDistanceSq = 1.0e32f;
Vector2 closestPoint = Vector2.zero;
int closestPreviousPoint = 0;
var island = islands[islandId];
Handles.color = handleInactiveColor;
Vector2 ov = (island.points.Length>0)?island.points[island.points.Length-1]:Vector2.zero;
for (int i = 0; i < island.points.Length; ++i)
{
Vector2 v = island.points[i];
// Don't draw last connection if its not connected
if (!island.connected && i == 0)
{
ov = v;
continue;
}
if (insertPoint)
{
Vector2 localMousePosition = (Event.current.mousePosition - origin) / editorDisplayScale;
Vector2 closestPointToCursor = ClosestPointOnLine(localMousePosition, ov, v);
float lengthSq = (closestPointToCursor - localMousePosition).sqrMagnitude;
if (lengthSq < closestDistanceSq)
{
closestDistanceSq = lengthSq;
closestPoint = closestPointToCursor;
closestPreviousPoint = i;
}
}
if (drawColliderNormals)
{
Vector2 l = (ov - v).normalized;
Vector2 n = new Vector2(l.y, -l.x);
Vector2 c = (v + ov) * 0.5f * editorDisplayScale + origin;
Handles.DrawLine(c, c + n * 16.0f);
}
Handles.DrawLine(v * editorDisplayScale + origin, ov * editorDisplayScale + origin);
ov = v;
}
Handles.color = previousHandleColor;
if (insertPoint && closestDistanceSq < 16.0f)
{
var tmpList = new List<Vector2>(island.points);
tmpList.Insert(closestPreviousPoint, closestPoint);
island.points = tmpList.ToArray();
HandleUtility.Repaint();
}
int deletedIndex = -1;
bool flipIsland = false;
bool disconnectIsland = false;
Event ev = Event.current;
for (int i = 0; i < island.points.Length; ++i)
{
Vector3 cp = island.points[i];
int id = "tk2dPolyEditor".GetHashCode() + islandId * 10000 + i;
cp = (tk2dGuiUtility.Handle(tk2dEditorSkin.MoveHandle, id, cp * editorDisplayScale + origin3, true) - origin) / editorDisplayScale;
if (GUIUtility.keyboardControl == id && ev.type == EventType.KeyDown) {
switch (ev.keyCode) {
case KeyCode.Backspace:
case KeyCode.Delete: {
GUIUtility.keyboardControl = 0;
GUIUtility.hotControl = 0;
deletedIndex = i;
ev.Use();
break;
}
case KeyCode.X: {
GUIUtility.keyboardControl = 0;
GUIUtility.hotControl = 0;
deletedIsland = islandId;
ev.Use();
break;
}
case KeyCode.T: {
if (!forceClosed) {
GUIUtility.keyboardControl = 0;
GUIUtility.hotControl = 0;
disconnectIsland = true;
ev.Use();
}
break;
}
case KeyCode.F: {
flipIsland = true;
GUIUtility.keyboardControl = 0;
GUIUtility.hotControl = 0;
ev.Use();
break;
}
case KeyCode.Escape: {
GUIUtility.hotControl = 0;
GUIUtility.keyboardControl = 0;
ev.Use();
break;
}
}
}
cp.x = Mathf.Round(cp.x * 2) / 2.0f; // allow placing point at half texel
cp.y = Mathf.Round(cp.y * 2) / 2.0f;
// constrain
cp.x = Mathf.Clamp(cp.x, 0.0f, tex.width);
cp.y = Mathf.Clamp(cp.y, 0.0f, tex.height);
tk2dGuiUtility.SetPositionHandleValue(id, new Vector2(cp.x, cp.y));
island.points[i] = cp;
}
if (flipIsland)
{
System.Array.Reverse(island.points);
}
if (disconnectIsland)
{
island.connected = !island.connected;
if (island.connected && island.points.Length < 3)
{
Vector2 pp = (island.points[1] - island.points[0]);
float l = pp.magnitude;
pp.Normalize();
Vector2 nn = new Vector2(pp.y, -pp.x);
nn.y = Mathf.Clamp(nn.y, 0, tex.height);
nn.x = Mathf.Clamp(nn.x, 0, tex.width);
System.Array.Resize(ref island.points, island.points.Length + 1);
island.points[island.points.Length - 1] = (island.points[0] + island.points[1]) * 0.5f + nn * l * 0.5f;
}
}
if (deletedIndex != -1 &&
((island.connected && island.points.Length > 3) ||
(!island.connected && island.points.Length > 2)) )
{
var tmpList = new List<Vector2>(island.points);
tmpList.RemoveAt(deletedIndex);
island.points = tmpList.ToArray();
}
}
// Can't delete the last island
if (deletedIsland != -1 && islands.Length > 1)
{
var tmpIslands = new List<tk2dSpriteColliderIsland>(islands);
tmpIslands.RemoveAt(deletedIsland);
islands = tmpIslands.ToArray();
}
}
void DrawCustomBoxColliderEditor(Rect r, tk2dSpriteCollectionDefinition param, Texture2D tex)
{
Vector2 origin = new Vector2(r.x, r.y);
// sanitize
if (param.boxColliderMin == Vector2.zero && param.boxColliderMax == Vector2.zero)
{
param.boxColliderMax = new Vector2(tex.width, tex.height);
}
Vector3[] pt = new Vector3[] {
new Vector3(param.boxColliderMin.x * editorDisplayScale + origin.x, param.boxColliderMin.y * editorDisplayScale + origin.y, 0.0f),
new Vector3(param.boxColliderMax.x * editorDisplayScale + origin.x, param.boxColliderMin.y * editorDisplayScale + origin.y, 0.0f),
new Vector3(param.boxColliderMax.x * editorDisplayScale + origin.x, param.boxColliderMax.y * editorDisplayScale + origin.y, 0.0f),
new Vector3(param.boxColliderMin.x * editorDisplayScale + origin.x, param.boxColliderMax.y * editorDisplayScale + origin.y, 0.0f),
};
Color32 transparentColor = handleInactiveColor;
transparentColor.a = 10;
Handles.DrawSolidRectangleWithOutline(pt, transparentColor, handleInactiveColor);
// Draw grab handles
Vector3 handlePos;
int id = 16433;
// Draw top handle
handlePos = (pt[0] + pt[1]) * 0.5f;
handlePos = (tk2dGuiUtility.PositionHandle(id + 0, handlePos) - origin) / editorDisplayScale;
param.boxColliderMin.y = handlePos.y;
if (param.boxColliderMin.y > param.boxColliderMax.y) param.boxColliderMin.y = param.boxColliderMax.y;
// Draw bottom handle
handlePos = (pt[2] + pt[3]) * 0.5f;
handlePos = (tk2dGuiUtility.PositionHandle(id + 1, handlePos) - origin) / editorDisplayScale;
param.boxColliderMax.y = handlePos.y;
if (param.boxColliderMax.y < param.boxColliderMin.y) param.boxColliderMax.y = param.boxColliderMin.y;
// Draw left handle
handlePos = (pt[0] + pt[3]) * 0.5f;
handlePos = (tk2dGuiUtility.PositionHandle(id + 2, handlePos) - origin) / editorDisplayScale;
param.boxColliderMin.x = handlePos.x;
if (param.boxColliderMin.x > param.boxColliderMax.x) param.boxColliderMin.x = param.boxColliderMax.x;
// Draw right handle
handlePos = (pt[1] + pt[2]) * 0.5f;
handlePos = (tk2dGuiUtility.PositionHandle(id + 3, handlePos) - origin) / editorDisplayScale;
param.boxColliderMax.x = handlePos.x;
if (param.boxColliderMax.x < param.boxColliderMin.x) param.boxColliderMax.x = param.boxColliderMin.x;
param.boxColliderMax.x = Mathf.Round(param.boxColliderMax.x);
param.boxColliderMax.y = Mathf.Round(param.boxColliderMax.y);
param.boxColliderMin.x = Mathf.Round(param.boxColliderMin.x);
param.boxColliderMin.y = Mathf.Round(param.boxColliderMin.y);
// constrain
param.boxColliderMax.x = Mathf.Clamp(param.boxColliderMax.x, 0.0f, tex.width);
param.boxColliderMax.y = Mathf.Clamp(param.boxColliderMax.y, 0.0f, tex.height);
param.boxColliderMin.x = Mathf.Clamp(param.boxColliderMin.x, 0.0f, tex.width);
param.boxColliderMin.y = Mathf.Clamp(param.boxColliderMin.y, 0.0f, tex.height);
tk2dGuiUtility.SetPositionHandleValue(id + 0, new Vector2(0, param.boxColliderMin.y));
tk2dGuiUtility.SetPositionHandleValue(id + 1, new Vector2(0, param.boxColliderMax.y));
tk2dGuiUtility.SetPositionHandleValue(id + 2, new Vector2(param.boxColliderMin.x, 0));
tk2dGuiUtility.SetPositionHandleValue(id + 3, new Vector2(param.boxColliderMax.x, 0));
}
static int advancedColliderEditorControlBase = "AdvancedColliderEditor".GetHashCode();
tk2dSpriteCollectionDefinition.ColliderData currentInspectedColliderData = null;
tk2dSpriteCollectionDefinition.ColliderData editingColliderDataName = null;
tk2dSpriteCollectionDefinition.ColliderData SelectedColliderData(tk2dSpriteCollectionDefinition param, bool allowActive) {
int selectedColliderData = tk2dGuiUtility.ActiveTweakable - advancedColliderEditorControlBase;
if (allowActive && (selectedColliderData < 0 || selectedColliderData >= param.colliderData.Count)) {
selectedColliderData = GUIUtility.hotControl - advancedColliderEditorControlBase;
}
return (selectedColliderData < 0 || selectedColliderData >= param.colliderData.Count) ? null : param.colliderData[selectedColliderData];
}
void DrawAdvancedColliderInspector(tk2dSpriteCollectionDefinition param, Texture2D tex) {
GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
GUILayout.Label("Advanced collider editor", EditorStyles.miniLabel);
GUILayout.FlexibleSpace();
bool doAddCollider = false;
if (GUILayout.Button("Add", EditorStyles.toolbarButton)) {
doAddCollider = true;
}
GUILayout.EndHorizontal();
// catalog all names
HashSet<string> apHashSet = new HashSet<string>();
foreach (tk2dSpriteCollectionDefinition def in SpriteCollection.textureParams) {
if (def.colliderType != tk2dSpriteCollectionDefinition.ColliderType.Advanced) {
continue;
}
foreach ( tk2dSpriteCollectionDefinition.ColliderData cd in def.colliderData) {
if (cd.name.Length > 0) {
apHashSet.Add( cd.name );
}
}
}
Dictionary<string, int> apNameLookup = new Dictionary<string, int>();
List<string> apNames = new List<string>( apHashSet );
for (int i = 0; i < apNames.Count; ++i) {
apNameLookup.Add( apNames[i], i );
}
apNames.Add( "Create..." );
if (param.colliderData.Count == 0) {
EditorGUILayout.HelpBox("No colliders on this sprite.\nClick on the add button above to add a new collider to the sprite.", MessageType.Info);
}
int toDelete = -1;
for (int i = 0; i < param.colliderData.Count; ++i) {
GUILayout.BeginHorizontal();
tk2dSpriteCollectionDefinition.ColliderData def = param.colliderData[i];
bool oldSel = currentInspectedColliderData == def;
bool newSel = GUILayout.Toggle(oldSel, "", GUILayout.ExpandWidth(false));
if (newSel == true && newSel != oldSel) {
int rr = i;
deferredAction = delegate(int e) {
currentInspectedColliderData = param.colliderData[rr];
tk2dGuiUtility.ActiveTweakable = advancedColliderEditorControlBase.GetHashCode() + rr;
};
}
if (apNameLookup.Count == 0) {
editingColliderDataName = def;
}
if (editingColliderDataName == def) {
if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return) {
editingColliderDataName = null;
HandleUtility.Repaint();
GUIUtility.keyboardControl = 0;
}
def.name = GUILayout.TextField(def.name);
}
else {
int currSel = apNameLookup.ContainsKey(def.name) ? apNameLookup[def.name] : -1;
int sel = EditorGUILayout.Popup(currSel, apNames.ToArray());
if (currSel != sel) {
if (sel == apNames.Count - 1) {
editingColliderDataName = def;
HandleUtility.Repaint();
}
else {
def.name = apNames[sel];
}
}
}
if (GUILayout.Button("x", EditorStyles.miniButton, GUILayout.Width(22))) {
toDelete = i;
}
GUILayout.EndHorizontal();
if (currentInspectedColliderData == def) {
EditorGUI.indentLevel+=2;
currentInspectedColliderData.type = (tk2dSpriteCollectionDefinition.ColliderData.Type)EditorGUILayout.EnumPopup("Type", currentInspectedColliderData.type);
currentInspectedColliderData.origin = EditorGUILayout.Vector2Field("Origin", currentInspectedColliderData.origin);
if (currentInspectedColliderData.type == tk2dSpriteCollectionDefinition.ColliderData.Type.Circle) {
float x = EditorGUILayout.FloatField("Radius", currentInspectedColliderData.size.x);
currentInspectedColliderData.size.Set(x, x);
}
else {
currentInspectedColliderData.size = EditorGUILayout.Vector2Field("Size", currentInspectedColliderData.size);
currentInspectedColliderData.angle = EditorGUILayout.FloatField("Angle", currentInspectedColliderData.angle);
}
EditorGUI.indentLevel-=2;
}
}
GUILayout.Space(8);
if (doAddCollider) {
string unused = "";
foreach (string n in apHashSet) {
bool used = false;
for (int i = 0; i < param.colliderData.Count; ++i) {
if (n == param.colliderData[i].name) {
used = true;
break;
}
}
if (!used) {
unused = n;
break;
}
}
tk2dSpriteCollectionDefinition.ColliderData d = new tk2dSpriteCollectionDefinition.ColliderData();
d.type = tk2dSpriteCollectionDefinition.ColliderData.Type.Box;
d.origin = new Vector3(tex.width / 2, tex.height / 2);
float m = Mathf.Min(tex.width, tex.height) / 4;
d.size = new Vector2(m, m);
d.angle = 0;
d.name = unused;
param.colliderData.Add(d);
HandleUtility.Repaint();
currentInspectedColliderData = d;
if (unused == "") {
editingColliderDataName = d;
}
tk2dGuiUtility.ActiveTweakable = advancedColliderEditorControlBase.GetHashCode() + param.colliderData.Count - 1;
}
if (toDelete != -1) {
param.colliderData.RemoveAt(toDelete);
HandleUtility.Repaint();
}
}
void DrawAdvancedColliderEditor(Rect r, tk2dSpriteCollectionDefinition param, Texture2D tex) {
int controlId = advancedColliderEditorControlBase.GetHashCode();
Vector2 origin = new Vector2(r.x, r.y);
for (int pass = 0; pass < 2; ++pass) {
for (int i = 0; i < param.colliderData.Count; ++i) {
int thisControlId = controlId + i;
// process selected control first, this could be written better
if (pass == 0 && thisControlId != GUIUtility.hotControl && thisControlId != tk2dGuiUtility.ActiveTweakable) { continue; }
else if (pass == 1 && (thisControlId == GUIUtility.hotControl || thisControlId == tk2dGuiUtility.ActiveTweakable)) { continue; }
tk2dSpriteCollectionDefinition.ColliderData data = param.colliderData[i];
if (data.type == tk2dSpriteCollectionDefinition.ColliderData.Type.Circle) {
tk2dGuiUtility.TweakableCircle( thisControlId, origin + data.origin * editorDisplayScale, data.size.x * editorDisplayScale,
delegate(Vector2 pos, float radius) {
data.origin = ( pos - origin ) / editorDisplayScale;
radius /= editorDisplayScale;
data.size.Set( radius, radius );
} );
}
else if (data.type == tk2dSpriteCollectionDefinition.ColliderData.Type.Box) {
tk2dGuiUtility.TweakableBox( thisControlId, origin + data.origin * editorDisplayScale, data.size * editorDisplayScale, data.angle,
delegate(Vector2 pos, Vector2 size, float angle) {
data.origin = ( pos - origin ) / editorDisplayScale;
data.size = size / editorDisplayScale;
data.angle = angle;
} );
}
if (tk2dGuiUtility.ActiveTweakable == thisControlId && currentInspectedColliderData != param.colliderData[i]) {
int rr = i;
deferredAction = delegate(int q) {
currentInspectedColliderData = param.colliderData[rr];
};
}
}
}
Event ev = Event.current;
tk2dSpriteCollectionDefinition.ColliderData selection = SelectedColliderData(param, false);
if (selection != null) {
if (ev.type == EventType.ValidateCommand && ev.commandName == "Duplicate") {
ev.Use();
}
else if (ev.type == EventType.ExecuteCommand && ev.commandName == "Duplicate") {
tk2dSpriteCollectionDefinition.ColliderData dup = new tk2dSpriteCollectionDefinition.ColliderData();
dup.CopyFrom(selection);
dup.origin += new Vector2(10, 10);
param.colliderData.Add(dup);
tk2dGuiUtility.ActiveTweakable = controlId + param.colliderData.Count - 1;
HandleUtility.Repaint();
ev.Use();
}
if (ev.type == EventType.ValidateCommand && ev.commandName == "Delete") {
ev.Use();
}
else if (ev.type == EventType.ExecuteCommand && ev.commandName == "Delete") {
param.colliderData.Remove(selection);
tk2dGuiUtility.ActiveTweakable = 0;
GUIUtility.hotControl = 0;
ev.Use();
}
if (ev.type == EventType.MouseDown) {
tk2dGuiUtility.ActiveTweakable = 0;
GUIUtility.hotControl = 0;
currentInspectedColliderData = null;
}
if (ev.type == EventType.KeyDown) {
switch (ev.keyCode) {
case KeyCode.Escape:
tk2dGuiUtility.ActiveTweakable = 0;
GUIUtility.hotControl = 0;
currentInspectedColliderData = null;
ev.Use();
break;
case KeyCode.RightBracket:
case KeyCode.Tab:
int selectionIdx = 0;
for (int i = 0; i < param.colliderData.Count; ++i) {
if (param.colliderData[i] == selection) {
currentInspectedColliderData = param.colliderData[i];
selectionIdx = i;
break;
}
}
tk2dGuiUtility.ActiveTweakable = advancedColliderEditorControlBase + ((selectionIdx + 1) % param.colliderData.Count);
HandleUtility.Repaint();
ev.Use();
break;
case KeyCode.UpArrow: selection.origin += new Vector2(0, -1); ev.Use(); break;
case KeyCode.DownArrow: selection.origin += new Vector2(0, 1); ev.Use(); break;
case KeyCode.LeftArrow: selection.origin += new Vector2(-1, 0); ev.Use(); break;
case KeyCode.RightArrow: selection.origin += new Vector2(1, 0); ev.Use(); break;
}
}
}
}
System.Action<int> deferredAction = null;
void HandleKeys()
{
if (GUIUtility.keyboardControl != 0)
return;
Event evt = Event.current;
if (evt.type == EventType.KeyUp && evt.shift)
{
Mode newMode = Mode.None;
switch (evt.keyCode)
{
case KeyCode.Q: newMode = Mode.Texture; break;
case KeyCode.W: newMode = Mode.Anchor; break;
case KeyCode.E: newMode = Mode.Collider; break;
case KeyCode.R: newMode = Mode.AttachPoint; break;
case KeyCode.N: drawColliderNormals = !drawColliderNormals; HandleUtility.Repaint(); break;
}
if (newMode != Mode.None)
{
mode = newMode;
evt.Use();
}
}
}
public Vector2 Rotate(Vector2 v, float angle) {
float angleRad = angle * Mathf.Deg2Rad;
float cosa = Mathf.Cos(angleRad);
float sina = -Mathf.Sin(angleRad);
return new Vector2( v.x * cosa - v.y * sina, v.x * sina + v.y * cosa );
}
public void DrawTextureView(tk2dSpriteCollectionDefinition param, Texture2D texture)
{
HandleKeys();
if (mode == Mode.None)
mode = Mode.Texture;
// sanity check
if (editorDisplayScale <= 1.0f) editorDisplayScale = 1.0f;
// mirror data
currentColliderColor = param.colliderColor;
GUILayout.BeginVertical(tk2dEditorSkin.SC_BodyBackground, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
if (texture == null)
{
// Get somewhere to put the texture...
GUILayoutUtility.GetRect(128.0f, 128.0f, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
}
else
{
bool allowAnchor = param.anchor == tk2dSpriteCollectionDefinition.Anchor.Custom;
bool allowCollider = (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon ||
param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.BoxCustom ||
param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Advanced);
if (mode == Mode.Anchor && !allowAnchor) mode = Mode.Texture;
if (mode == Mode.Collider && !allowCollider) mode = Mode.Texture;
Rect rect = GUILayoutUtility.GetRect(128.0f, 128.0f, GUILayout.ExpandWidth(true), GUILayout.ExpandHeight(true));
tk2dGrid.Draw(rect);
// middle mouse drag and scroll zoom
if (rect.Contains(Event.current.mousePosition))
{
if (Event.current.type == EventType.MouseDrag && Event.current.button == 2)
{
textureScrollPos -= Event.current.delta * editorDisplayScale;
Event.current.Use();
HandleUtility.Repaint();
}
if (Event.current.type == EventType.ScrollWheel)
{
editorDisplayScale -= Event.current.delta.y * 0.03f;
Event.current.Use();
HandleUtility.Repaint();
}
}
bool alphaBlend = true;
textureScrollPos = GUI.BeginScrollView(rect, textureScrollPos,
new Rect(0, 0, textureBorderPixels * 2 + (texture.width) * editorDisplayScale, textureBorderPixels * 2 + (texture.height) * editorDisplayScale));
Rect textureRect = new Rect(textureBorderPixels, textureBorderPixels, texture.width * editorDisplayScale, texture.height * editorDisplayScale);
texture.filterMode = FilterMode.Point;
GUI.DrawTexture(textureRect, texture, ScaleMode.ScaleAndCrop, alphaBlend);
if (mode == Mode.Collider)
{
if (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.BoxCustom)
DrawCustomBoxColliderEditor(textureRect, param, texture);
if (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon)
DrawPolygonColliderEditor(textureRect, ref param.polyColliderIslands, texture, false);
if (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Advanced)
DrawAdvancedColliderEditor(textureRect, param, texture);
}
if (mode == Mode.Texture && param.customSpriteGeometry)
{
DrawPolygonColliderEditor(textureRect, ref param.geometryIslands, texture, true);
}
// Anchor
if (mode == Mode.Anchor)
{
Color lineColor = Color.white;
Vector2 anchor = new Vector2(param.anchorX, param.anchorY);
Vector2 origin = new Vector2(textureRect.x, textureRect.y);
int id = 99999;
anchor = (tk2dGuiUtility.PositionHandle(id, anchor * editorDisplayScale + origin) - origin) / editorDisplayScale;
Color oldColor = Handles.color;
Handles.color = lineColor;
float w = Mathf.Max(rect.width, texture.width * editorDisplayScale);
float h = Mathf.Max(rect.height, texture.height * editorDisplayScale);
Handles.DrawLine(new Vector3(textureRect.x, textureRect.y + anchor.y * editorDisplayScale, 0), new Vector3(textureRect.x + w, textureRect.y + anchor.y * editorDisplayScale, 0));
Handles.DrawLine(new Vector3(textureRect.x + anchor.x * editorDisplayScale, textureRect.y + 0, 0), new Vector3(textureRect.x + anchor.x * editorDisplayScale, textureRect.y + h, 0));
Handles.color = oldColor;
// constrain
param.anchorX = Mathf.Clamp(Mathf.Round(anchor.x), 0.0f, texture.width);
param.anchorY = Mathf.Clamp(Mathf.Round(anchor.y), 0.0f, texture.height);
tk2dGuiUtility.SetPositionHandleValue(id, new Vector2(param.anchorX, param.anchorY));
HandleUtility.Repaint();
}
if (mode == Mode.AttachPoint) {
Vector2 origin = new Vector2(textureRect.x, textureRect.y);
int id = "Mode.AttachPoint".GetHashCode();
foreach (tk2dSpriteDefinition.AttachPoint ap in param.attachPoints) {
Vector2 apPosition = new Vector2(ap.position.x, ap.position.y);
if (showAttachPointSprites) {
tk2dSpriteCollection.AttachPointTestSprite spriteProxy = null;
if (SpriteCollection.attachPointTestSprites.TryGetValue(ap.name, out spriteProxy) && spriteProxy.spriteCollection != null &&
spriteProxy.spriteCollection.IsValidSpriteId(spriteProxy.spriteId)) {
tk2dSpriteDefinition def = spriteProxy.spriteCollection.inst.spriteDefinitions[ spriteProxy.spriteId ];
tk2dSpriteThumbnailCache.DrawSpriteTextureInRect( textureRect, def, Color.white, ap.position, ap.angle, new Vector2(editorDisplayScale, editorDisplayScale) );
}
}
Vector2 pos = apPosition * editorDisplayScale + origin;
GUI.color = Color.clear; // don't actually draw the move handle center
apPosition = (tk2dGuiUtility.PositionHandle(id, pos) - origin) / editorDisplayScale;
GUI.color = Color.white;
float handleSize = 30;
Handles.color = Color.green; Handles.DrawLine(pos, pos - Rotate(Vector2.up, ap.angle) * handleSize);
Handles.color = Color.red; Handles.DrawLine(pos, pos + Rotate(Vector2.right, ap.angle) * handleSize);
Handles.color = Color.white;
Handles.DrawWireDisc(pos, Vector3.forward, handleSize);
// rotation handle
Vector2 rotHandlePos = pos + Rotate(Vector2.right, ap.angle) * handleSize;
Vector2 newRotHandlePos = tk2dGuiUtility.Handle(tk2dEditorSkin.RotateHandle, id + 1, rotHandlePos, false);
if (newRotHandlePos != rotHandlePos) {
Vector2 deltaRot = newRotHandlePos - pos;
float angle = -Mathf.Atan2(deltaRot.y, deltaRot.x) * Mathf.Rad2Deg;
if (Event.current.control) {
float snapAmount = Event.current.shift ? 15 : 5;
angle = Mathf.Floor(angle / snapAmount) * snapAmount;
}
else if (!Event.current.shift) {
angle = Mathf.Floor(angle);
}
ap.angle = angle;
}
Rect r = new Rect(pos.x + 8, pos.y + 6, 1000, 50);
GUI.Label( r, ap.name, EditorStyles.whiteMiniLabel );
ap.position.x = Mathf.Round(apPosition.x);
ap.position.y = Mathf.Round(apPosition.y);
tk2dGuiUtility.SetPositionHandleValue(id, new Vector2(ap.position.x, ap.position.y));
id += 2;
}
Handles.color = Color.white;
}
if (mode == Mode.Texture) {
if (param.dice) {
Handles.color = Color.red;
Vector3 p1, p2;
int q, dq;
p1 = new Vector3(textureRect.x, textureRect.y, 0);
p2 = new Vector3(textureRect.x, textureRect.y + textureRect.height, 0);
q = 0;
dq = param.diceUnitX;
if (dq > 0) {
while (q <= texture.width) {
Handles.DrawLine(p1, p2);
int q0 = q;
if (q < texture.width && (q + dq) > texture.width)
q = texture.width;
else
q += dq;
p1.x += (float)(q - q0) * editorDisplayScale;
p2.x += (float)(q - q0) * editorDisplayScale;
}
}
p1 = new Vector3(textureRect.x, textureRect.y + textureRect.height, 0);
p2 = new Vector3(textureRect.x + textureRect.width, textureRect.y + textureRect.height, 0);
q = 0;
dq = param.diceUnitY;
if (dq > 0) {
while (q <= texture.height) {
Handles.DrawLine(p1, p2);
int q0 = q;
if (q < texture.height && (q + dq) > texture.height)
q = texture.height;
else
q += dq;
p1.y -= (float)(q - q0) * editorDisplayScale;
p2.y -= (float)(q - q0) * editorDisplayScale;
}
}
Handles.color = Color.white;
}
}
GUI.EndScrollView();
}
// Draw toolbar
DrawToolbar(param, texture);
GUILayout.EndVertical();
}
public void DrawToolbar(tk2dSpriteCollectionDefinition param, Texture2D texture)
{
bool allowAnchor = param.anchor == tk2dSpriteCollectionDefinition.Anchor.Custom;
bool allowCollider = (param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon ||
param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.BoxCustom ||
param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Advanced);
bool allowAttachPoint = true;
GUILayout.BeginHorizontal(EditorStyles.toolbar, GUILayout.ExpandWidth(true));
mode = GUILayout.Toggle((mode == Mode.Texture), new GUIContent("Sprite", "Shift+Q"), EditorStyles.toolbarButton)?Mode.Texture:mode;
if (allowAnchor)
mode = GUILayout.Toggle((mode == Mode.Anchor), new GUIContent("Anchor", "Shift+W"), EditorStyles.toolbarButton)?Mode.Anchor:mode;
if (allowCollider)
mode = GUILayout.Toggle((mode == Mode.Collider), new GUIContent("Collider", "Shift+E"), EditorStyles.toolbarButton)?Mode.Collider:mode;
if (allowAttachPoint)
mode = GUILayout.Toggle((mode == Mode.AttachPoint), new GUIContent("AttachPoint", "Shift+R"), EditorStyles.toolbarButton)?Mode.AttachPoint:mode;
GUILayout.FlexibleSpace();
if (tk2dGuiUtility.HasActivePositionHandle)
{
string str = "X: " + tk2dGuiUtility.ActiveHandlePosition.x + " Y: " + tk2dGuiUtility.ActiveHandlePosition.y;
GUILayout.Label(str, EditorStyles.toolbarTextField);
}
if ((mode == Mode.Collider && param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon) ||
(mode == Mode.Texture && param.customSpriteGeometry))
{
drawColliderNormals = GUILayout.Toggle(drawColliderNormals, new GUIContent("Show Normals", "Shift+N"), EditorStyles.toolbarButton);
}
if (mode == Mode.Texture && texture != null) {
GUILayout.Label(string.Format("W: {0} H: {1}", texture.width, texture.height));
}
GUILayout.EndHorizontal();
}
public void DrawEmptyTextureView()
{
mode = Mode.None;
GUILayout.FlexibleSpace();
}
tk2dSpriteDefinition.AttachPoint editingAttachPointName = null;
bool showAttachPointSprites = false;
void AttachPointSpriteHandler(tk2dSpriteCollectionData newSpriteCollection, int newSpriteId, object callbackData) {
string attachPointName = (string)callbackData;
tk2dSpriteCollection.AttachPointTestSprite proxy = null;
if (SpriteCollection.attachPointTestSprites.TryGetValue(attachPointName, out proxy)) {
proxy.spriteCollection = newSpriteCollection;
proxy.spriteId = newSpriteId;
HandleUtility.Repaint();
}
}
public void DrawAttachPointInspector(tk2dSpriteCollectionDefinition param, Texture2D texture) {
// catalog all names
HashSet<string> apHashSet = new HashSet<string>();
foreach (tk2dSpriteCollectionDefinition def in SpriteCollection.textureParams) {
foreach (tk2dSpriteDefinition.AttachPoint currAp in def.attachPoints) {
apHashSet.Add( currAp.name );
}
}
Dictionary<string, int> apNameLookup = new Dictionary<string, int>();
List<string> apNames = new List<string>( apHashSet );
for (int i = 0; i < apNames.Count; ++i) {
apNameLookup.Add( apNames[i], i );
}
apNames.Add( "Create..." );
int toDelete = -1;
tk2dSpriteGuiUtility.showOpenEditShortcuts = false;
tk2dSpriteDefinition.AttachPoint newEditingAttachPointName = editingAttachPointName;
int apIdx = 0;
foreach (var ap in param.attachPoints) {
GUILayout.BeginHorizontal();
if (editingAttachPointName == ap) {
if (Event.current.type == EventType.KeyDown && Event.current.keyCode == KeyCode.Return) {
newEditingAttachPointName = null;
HandleUtility.Repaint();
GUIUtility.keyboardControl = 0;
}
ap.name = GUILayout.TextField(ap.name);
}
else {
int sel = EditorGUILayout.Popup(apNameLookup[ap.name], apNames.ToArray());
if (sel == apNames.Count - 1) {
newEditingAttachPointName = ap;
HandleUtility.Repaint();
}
else {
ap.name = apNames[sel];
}
}
ap.angle = EditorGUILayout.FloatField(ap.angle, GUILayout.Width(45));
if (GUILayout.Button("x", GUILayout.Width(22))) {
toDelete = apIdx;
}
GUILayout.EndHorizontal();
if (showAttachPointSprites) {
bool pushGUIEnabled = GUI.enabled;
string tmpName;
if (editingAttachPointName != ap) {
tmpName = ap.name;
} else {
tmpName = "";
GUI.enabled = false;
}
tk2dSpriteCollection.AttachPointTestSprite spriteProxy = null;
if (!SpriteCollection.attachPointTestSprites.TryGetValue(tmpName, out spriteProxy)) {
spriteProxy = new tk2dSpriteCollection.AttachPointTestSprite();
SpriteCollection.attachPointTestSprites.Add( tmpName, spriteProxy );
}
tk2dSpriteGuiUtility.SpriteSelector( spriteProxy.spriteCollection, spriteProxy.spriteId, AttachPointSpriteHandler, tmpName );
GUI.enabled = pushGUIEnabled;
}
editingAttachPointName = newEditingAttachPointName;
++apIdx;
}
if (GUILayout.Button("Add AttachPoint")) {
// Find an unused attach point name
string unused = "";
foreach (string n in apHashSet) {
bool used = false;
for (int i = 0; i < param.attachPoints.Count; ++i) {
if (n == param.attachPoints[i].name) {
used = true;
break;
}
}
if (!used) {
unused = n;
break;
}
}
tk2dSpriteDefinition.AttachPoint ap = new tk2dSpriteDefinition.AttachPoint();
ap.name = unused;
ap.position = Vector3.zero;
param.attachPoints.Add(ap);
if (unused == "") {
editingAttachPointName = ap;
}
}
if (toDelete != -1) {
param.attachPoints.RemoveAt(toDelete);
HandleUtility.Repaint();
}
showAttachPointSprites = GUILayout.Toggle(showAttachPointSprites, "Preview", "button");
tk2dSpriteGuiUtility.showOpenEditShortcuts = true;
}
public void DrawTextureInspector(tk2dSpriteCollectionDefinition param, Texture2D texture)
{
if (mode == Mode.Collider && param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Polygon)
{
param.colliderColor = (tk2dSpriteCollectionDefinition.ColliderColor)EditorGUILayout.EnumPopup("Display Color", param.colliderColor);
tk2dGuiUtility.InfoBox("Points" +
"\nClick drag - move point" +
"\nClick hold + delete/bkspace - delete point" +
"\nDouble click on line - add point", tk2dGuiUtility.WarningLevel.Info);
tk2dGuiUtility.InfoBox("Islands" +
"\nClick hold point + X - delete island" +
"\nPress C - create island at cursor" +
"\nClick hold point + T - toggle connected" +
"\nClick hold point + F - flip island", tk2dGuiUtility.WarningLevel.Info);
}
else if (mode == Mode.Collider && param.colliderType == tk2dSpriteCollectionDefinition.ColliderType.Advanced) {
DrawAdvancedColliderInspector(param, texture);
}
if (mode == Mode.Texture && param.customSpriteGeometry)
{
param.colliderColor = (tk2dSpriteCollectionDefinition.ColliderColor)EditorGUILayout.EnumPopup("Display Color", param.colliderColor);
tk2dGuiUtility.InfoBox("Points" +
"\nClick drag - move point" +
"\nClick hold + delete/bkspace - delete point" +
"\nDouble click on line - add point", tk2dGuiUtility.WarningLevel.Info);
tk2dGuiUtility.InfoBox("Islands" +
"\nClick hold point + X - delete island" +
"\nPress C - create island at cursor" +
"\nClick hold point + F - flip island", tk2dGuiUtility.WarningLevel.Info);
}
if (mode == Mode.AttachPoint) {
DrawAttachPointInspector( param, texture );
}
if (deferredAction != null) {
if (Event.current.type == EventType.Repaint) {
deferredAction(0);
deferredAction = null;
}
else {
HandleUtility.Repaint();
}
}
}
}
}
| |
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using System.Linq;
using osuTK;
using osu.Game.Audio;
using osu.Game.Beatmaps;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Mania.MathUtils;
using osu.Game.Rulesets.Mania.Objects;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.Objects.Types;
namespace osu.Game.Rulesets.Mania.Beatmaps.Patterns.Legacy
{
internal class HitObjectPatternGenerator : PatternGenerator
{
public PatternType StairType { get; private set; }
private readonly PatternType convertType;
public HitObjectPatternGenerator(FastRandom random, HitObject hitObject, ManiaBeatmap beatmap, Pattern previousPattern, double previousTime, Vector2 previousPosition, double density,
PatternType lastStair, IBeatmap originalBeatmap)
: base(random, hitObject, beatmap, previousPattern, originalBeatmap)
{
StairType = lastStair;
TimingControlPoint timingPoint = beatmap.ControlPointInfo.TimingPointAt(hitObject.StartTime);
EffectControlPoint effectPoint = beatmap.ControlPointInfo.EffectPointAt(hitObject.StartTime);
var positionData = hitObject as IHasPosition;
float positionSeparation = ((positionData?.Position ?? Vector2.Zero) - previousPosition).Length;
double timeSeparation = hitObject.StartTime - previousTime;
if (timeSeparation <= 80)
{
// More than 187 BPM
convertType |= PatternType.ForceNotStack | PatternType.KeepSingle;
}
else if (timeSeparation <= 95)
{
// More than 157 BPM
convertType |= PatternType.ForceNotStack | PatternType.KeepSingle | lastStair;
}
else if (timeSeparation <= 105)
{
// More than 140 BPM
convertType |= PatternType.ForceNotStack | PatternType.LowProbability;
}
else if (timeSeparation <= 125)
{
// More than 120 BPM
convertType |= PatternType.ForceNotStack;
}
else if (timeSeparation <= 135 && positionSeparation < 20)
{
// More than 111 BPM stream
convertType |= PatternType.Cycle | PatternType.KeepSingle;
}
else if (timeSeparation <= 150 && positionSeparation < 20)
{
// More than 100 BPM stream
convertType |= PatternType.ForceStack | PatternType.LowProbability;
}
else if (positionSeparation < 20 && density >= timingPoint.BeatLength / 2.5)
{
// Low density stream
convertType |= PatternType.Reverse | PatternType.LowProbability;
}
else if (density < timingPoint.BeatLength / 2.5 || effectPoint.KiaiMode)
{
// High density
}
else
convertType |= PatternType.LowProbability;
if (!convertType.HasFlag(PatternType.KeepSingle))
{
if (HitObject.Samples.Any(s => s.Name == HitSampleInfo.HIT_FINISH) && TotalColumns != 8)
convertType |= PatternType.Mirror;
else if (HitObject.Samples.Any(s => s.Name == HitSampleInfo.HIT_CLAP))
convertType |= PatternType.Gathered;
}
}
public override IEnumerable<Pattern> Generate()
{
yield return generate();
}
private Pattern generate()
{
var pattern = new Pattern();
try
{
if (TotalColumns == 1)
{
addToPattern(pattern, 0);
return pattern;
}
int lastColumn = PreviousPattern.HitObjects.FirstOrDefault()?.Column ?? 0;
if (convertType.HasFlag(PatternType.Reverse) && PreviousPattern.HitObjects.Any())
{
// Generate a new pattern by copying the last hit objects in reverse-column order
for (int i = RandomStart; i < TotalColumns; i++)
if (PreviousPattern.ColumnHasObject(i))
addToPattern(pattern, RandomStart + TotalColumns - i - 1);
return pattern;
}
if (convertType.HasFlag(PatternType.Cycle) && PreviousPattern.HitObjects.Count() == 1
// If we convert to 7K + 1, let's not overload the special key
&& (TotalColumns != 8 || lastColumn != 0)
// Make sure the last column was not the centre column
&& (TotalColumns % 2 == 0 || lastColumn != TotalColumns / 2))
{
// Generate a new pattern by cycling backwards (similar to Reverse but for only one hit object)
int column = RandomStart + TotalColumns - lastColumn - 1;
addToPattern(pattern, column);
return pattern;
}
if (convertType.HasFlag(PatternType.ForceStack) && PreviousPattern.HitObjects.Any())
{
// Generate a new pattern by placing on the already filled columns
for (int i = RandomStart; i < TotalColumns; i++)
if (PreviousPattern.ColumnHasObject(i))
addToPattern(pattern, i);
return pattern;
}
if (PreviousPattern.HitObjects.Count() == 1)
{
if (convertType.HasFlag(PatternType.Stair))
{
// Generate a new pattern by placing on the next column, cycling back to the start if there is no "next"
int targetColumn = lastColumn + 1;
if (targetColumn == TotalColumns)
targetColumn = RandomStart;
addToPattern(pattern, targetColumn);
return pattern;
}
if (convertType.HasFlag(PatternType.ReverseStair))
{
// Generate a new pattern by placing on the previous column, cycling back to the end if there is no "previous"
int targetColumn = lastColumn - 1;
if (targetColumn == RandomStart - 1)
targetColumn = TotalColumns - 1;
addToPattern(pattern, targetColumn);
return pattern;
}
}
if (convertType.HasFlag(PatternType.KeepSingle))
return pattern = generateRandomNotes(1);
if (convertType.HasFlag(PatternType.Mirror))
{
if (ConversionDifficulty > 6.5)
return pattern = generateRandomPatternWithMirrored(0.12, 0.38, 0.12);
if (ConversionDifficulty > 4)
return pattern = generateRandomPatternWithMirrored(0.12, 0.17, 0);
return pattern = generateRandomPatternWithMirrored(0.12, 0, 0);
}
if (ConversionDifficulty > 6.5)
{
if (convertType.HasFlag(PatternType.LowProbability))
return pattern = generateRandomPattern(0.78, 0.42, 0, 0);
return pattern = generateRandomPattern(1, 0.62, 0, 0);
}
if (ConversionDifficulty > 4)
{
if (convertType.HasFlag(PatternType.LowProbability))
return pattern = generateRandomPattern(0.35, 0.08, 0, 0);
return pattern = generateRandomPattern(0.52, 0.15, 0, 0);
}
if (ConversionDifficulty > 2)
{
if (convertType.HasFlag(PatternType.LowProbability))
return pattern = generateRandomPattern(0.18, 0, 0, 0);
return pattern = generateRandomPattern(0.45, 0, 0, 0);
}
return pattern = generateRandomPattern(0, 0, 0, 0);
}
finally
{
foreach (var obj in pattern.HitObjects)
{
if (convertType.HasFlag(PatternType.Stair) && obj.Column == TotalColumns - 1)
StairType = PatternType.ReverseStair;
if (convertType.HasFlag(PatternType.ReverseStair) && obj.Column == RandomStart)
StairType = PatternType.Stair;
}
}
}
/// <summary>
/// Generates random notes.
/// <para>
/// This will generate as many as it can up to <paramref name="noteCount"/>, accounting for
/// any stacks if <see cref="convertType"/> is forcing no stacks.
/// </para>
/// </summary>
/// <param name="noteCount">The amount of notes to generate.</param>
/// <returns>The <see cref="Pattern"/> containing the hit objects.</returns>
private Pattern generateRandomNotes(int noteCount)
{
var pattern = new Pattern();
bool allowStacking = !convertType.HasFlag(PatternType.ForceNotStack);
if (!allowStacking)
noteCount = Math.Min(noteCount, TotalColumns - RandomStart - PreviousPattern.ColumnWithObjects);
int nextColumn = GetColumn((HitObject as IHasXPosition)?.X ?? 0, true);
for (int i = 0; i < noteCount; i++)
{
nextColumn = allowStacking
? FindAvailableColumn(nextColumn, nextColumn: getNextColumn, patterns: pattern)
: FindAvailableColumn(nextColumn, nextColumn: getNextColumn, patterns: new[] { pattern, PreviousPattern });
addToPattern(pattern, nextColumn);
}
return pattern;
int getNextColumn(int last)
{
if (convertType.HasFlag(PatternType.Gathered))
{
last++;
if (last == TotalColumns)
last = RandomStart;
}
else
last = GetRandomColumn();
return last;
}
}
/// <summary>
/// Whether this hit object can generate a note in the special column.
/// </summary>
private bool hasSpecialColumn => HitObject.Samples.Any(s => s.Name == HitSampleInfo.HIT_CLAP) && HitObject.Samples.Any(s => s.Name == HitSampleInfo.HIT_FINISH);
/// <summary>
/// Generates a random pattern.
/// </summary>
/// <param name="p2">Probability for 2 notes to be generated.</param>
/// <param name="p3">Probability for 3 notes to be generated.</param>
/// <param name="p4">Probability for 4 notes to be generated.</param>
/// <param name="p5">Probability for 5 notes to be generated.</param>
/// <returns>The <see cref="Pattern"/> containing the hit objects.</returns>
private Pattern generateRandomPattern(double p2, double p3, double p4, double p5)
{
var pattern = new Pattern();
pattern.Add(generateRandomNotes(getRandomNoteCount(p2, p3, p4, p5)));
if (RandomStart > 0 && hasSpecialColumn)
addToPattern(pattern, 0);
return pattern;
}
/// <summary>
/// Generates a random pattern which has both normal and mirrored notes.
/// </summary>
/// <param name="centreProbability">The probability for a note to be added to the centre column.</param>
/// <param name="p2">Probability for 2 notes to be generated.</param>
/// <param name="p3">Probability for 3 notes to be generated.</param>
/// <returns>The <see cref="Pattern"/> containing the hit objects.</returns>
private Pattern generateRandomPatternWithMirrored(double centreProbability, double p2, double p3)
{
if (convertType.HasFlag(PatternType.ForceNotStack))
return generateRandomPattern(1 / 2f + p2 / 2, p2, (p2 + p3) / 2, p3);
var pattern = new Pattern();
bool addToCentre;
int noteCount = getRandomNoteCountMirrored(centreProbability, p2, p3, out addToCentre);
int columnLimit = (TotalColumns % 2 == 0 ? TotalColumns : TotalColumns - 1) / 2;
int nextColumn = GetRandomColumn(upperBound: columnLimit);
for (int i = 0; i < noteCount; i++)
{
nextColumn = FindAvailableColumn(nextColumn, upperBound: columnLimit, patterns: pattern);
// Add normal note
addToPattern(pattern, nextColumn);
// Add mirrored note
addToPattern(pattern, RandomStart + TotalColumns - nextColumn - 1);
}
if (addToCentre)
addToPattern(pattern, TotalColumns / 2);
if (RandomStart > 0 && hasSpecialColumn)
addToPattern(pattern, 0);
return pattern;
}
/// <summary>
/// Generates a count of notes to be generated from a list of probabilities.
/// </summary>
/// <param name="p2">Probability for 2 notes to be generated.</param>
/// <param name="p3">Probability for 3 notes to be generated.</param>
/// <param name="p4">Probability for 4 notes to be generated.</param>
/// <param name="p5">Probability for 5 notes to be generated.</param>
/// <returns>The amount of notes to be generated.</returns>
private int getRandomNoteCount(double p2, double p3, double p4, double p5)
{
switch (TotalColumns)
{
case 2:
p2 = 0;
p3 = 0;
p4 = 0;
p5 = 0;
break;
case 3:
p2 = Math.Min(p2, 0.1);
p3 = 0;
p4 = 0;
p5 = 0;
break;
case 4:
p2 = Math.Min(p2, 0.23);
p3 = Math.Min(p3, 0.04);
p4 = 0;
p5 = 0;
break;
case 5:
p3 = Math.Min(p3, 0.15);
p4 = Math.Min(p4, 0.03);
p5 = 0;
break;
}
if (HitObject.Samples.Any(s => s.Name == HitSampleInfo.HIT_CLAP))
p2 = 1;
return GetRandomNoteCount(p2, p3, p4, p5);
}
/// <summary>
/// Generates a count of notes to be generated from a list of probabilities.
/// </summary>
/// <param name="centreProbability">The probability for a note to be added to the centre column.</param>
/// <param name="p2">Probability for 2 notes to be generated.</param>
/// <param name="p3">Probability for 3 notes to be generated.</param>
/// <param name="addToCentre">Whether to add a note to the centre column.</param>
/// <returns>The amount of notes to be generated. The note to be added to the centre column will NOT be part of this count.</returns>
private int getRandomNoteCountMirrored(double centreProbability, double p2, double p3, out bool addToCentre)
{
addToCentre = false;
switch (TotalColumns)
{
case 2:
centreProbability = 0;
p2 = 0;
p3 = 0;
break;
case 3:
centreProbability = Math.Min(centreProbability, 0.03);
p2 = 0;
p3 = 0;
break;
case 4:
centreProbability = 0;
p2 = Math.Min(p2 * 2, 0.2);
p3 = 0;
break;
case 5:
centreProbability = Math.Min(centreProbability, 0.03);
p3 = 0;
break;
case 6:
centreProbability = 0;
p2 = Math.Min(p2 * 2, 0.5);
p3 = Math.Min(p3 * 2, 0.15);
break;
}
double centreVal = Random.NextDouble();
int noteCount = GetRandomNoteCount(p2, p3);
addToCentre = TotalColumns % 2 != 0 && noteCount != 3 && centreVal > 1 - centreProbability;
return noteCount;
}
/// <summary>
/// Constructs and adds a note to a pattern.
/// </summary>
/// <param name="pattern">The pattern to add to.</param>
/// <param name="column">The column to add the note to.</param>
private void addToPattern(Pattern pattern, int column)
{
pattern.Add(new Note
{
StartTime = HitObject.StartTime,
Samples = HitObject.Samples,
Column = column
});
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Android.App;
using Android.Content;
using Android.Database;
using Android.Media;
using Android.Net;
using Android.Net.Wifi;
using Android.OS;
using Android.Provider;
using Android.Support.V4.Media.Session;
using Plugin.MediaManager.Abstractions;
using Plugin.MediaManager.Abstractions.Enums;
using Plugin.MediaManager.Abstractions.EventArguments;
using Plugin.MediaManager.Abstractions.Implementations;
using Plugin.MediaManager.Audio;
using Plugin.MediaManager.MediaSession;
namespace Plugin.MediaManager
{
public abstract class MediaServiceBase : Service, AudioManager.IOnAudioFocusChangeListener, IPlaybackManager
{
//Actions
public const string ActionPlay = "com.xamarin.action.PLAY";
public const string ActionPause = "com.xamarin.action.PAUSE";
public const string ActionStop = "com.xamarin.action.STOP";
public const string ActionTogglePlayback = "com.xamarin.action.TOGGLEPLAYBACK";
public const string ActionNext = "com.xamarin.action.NEXT";
public const string ActionPrevious = "com.xamarin.action.PREVIOUS";
//internal const int NotificationId = 1;
private WifiManager wifiManager;
private WifiManager.WifiLock wifiLock;
private IntentFilter _intentFilter;
private AudioPlayerBroadcastReceiver _noisyAudioStreamReceiver;
public event StatusChangedEventHandler StatusChanged;
public event PlayingChangedEventHandler PlayingChanged;
public event BufferingChangedEventHandler BufferingChanged;
public event MediaFinishedEventHandler MediaFinished;
public event MediaFailedEventHandler MediaFailed;
public event MediaFileChangedEventHandler MediaFileChanged;
public event MediaFileFailedEventHandler MediaFileFailed;
public bool ManuallyPaused { get; set; } = false;
public bool TransientPaused { get; set; } = false;
public AudioManager AudioManager { get; set; }
public IMediaFile CurrentFile { get; set; }
public MediaSessionManager SessionManager { get; set; }
public int MediaPlayerState => SessionManager.MediaPlayerState;
public IBinder Binder { get; set; }
public MediaSessionCompat.Callback AlternateRemoteCallback { get; set; }
public abstract TimeSpan Position { get; }
public abstract TimeSpan Duration { get; }
public abstract TimeSpan Buffered { get; }
public Dictionary<string, string> RequestHeaders { get; set; }
public MediaPlayerStatus Status
{
get
{
throw new NotImplementedException();
}
}
/// <summary>
/// On create simply detect some of our managers
/// </summary>
public override void OnCreate()
{
base.OnCreate();
//Find our audio and notificaton managers
AudioManager = (AudioManager)GetSystemService(AudioService);
wifiManager = (WifiManager)GetSystemService(WifiService);
}
/// <summary>
/// Intializes the player.
/// </summary>
public abstract void InitializePlayer();
public abstract void InitializePlayerWithUrl(string audioUrl);
public abstract void SetMediaPlayerOptions();
public virtual async Task Play(IMediaFile mediaFile = null)
{
if (!ValidateMediaFile(mediaFile))
return;
bool alreadyPlaying = await CheckIfFileAlreadyIsPlaying(mediaFile);
if (alreadyPlaying)
return;
CurrentFile = mediaFile;
bool dataSourceSet;
try
{
InitializePlayer();
// Buffering states similar to how iOS has been implemented
SessionManager.UpdatePlaybackState(PlaybackStateCompat.StateBuffering);
SessionManager.InitMediaSession(PackageName, Binder as MediaServiceBinder);
_noisyAudioStreamReceiver = new AudioPlayerBroadcastReceiver(SessionManager);
_intentFilter = new IntentFilter(AudioManager.ActionAudioBecomingNoisy);
SessionManager.ApplicationContext.RegisterReceiver(_noisyAudioStreamReceiver, _intentFilter);
dataSourceSet = await SetMediaPlayerDataSource();
}
catch (Exception ex)
{
dataSourceSet = false;
OnMediaFileFailed(new MediaFileFailedEventArgs(ex, mediaFile));
}
if (dataSourceSet)
{
try
{
var focusResult = AudioManager.RequestAudioFocus(this, Stream.Music, AudioFocus.LossTransientCanDuck);
if (focusResult != AudioFocusRequest.Granted)
Console.WriteLine("Could not get audio focus");
AquireWifiLock();
}
catch (Exception ex)
{
OnMediaFileFailed(new MediaFileFailedEventArgs(ex, CurrentFile));
}
}
}
public abstract Task Seek(TimeSpan position);
public virtual Task Pause()
{
SessionManager.UpdatePlaybackState(PlaybackStateCompat.StatePaused, Position.Seconds);
return Task.CompletedTask;
}
public virtual async Task Stop()
{
await Task.Run(() =>
{
SessionManager.UpdatePlaybackState(PlaybackStateCompat.StateStopped, Position.Seconds);
SessionManager.NotificationManager.StopNotifications();
StopForeground(true);
ReleaseWifiLock();
SessionManager.Release();
});
}
public abstract Task Play(IEnumerable<IMediaFile> mediaFiles);
public abstract void SetVolume(float leftVolume, float rightVolume);
public abstract Task<bool> SetMediaPlayerDataSource();
public void HandleIntent(Intent intent)
{
if (intent?.Action == null || SessionManager == null)
return;
SessionManager?.HandleAction(intent?.Action);
}
/// <summary>
/// Lock the wifi so we can still stream under lock screen
/// </summary>
public void AquireWifiLock()
{
if (wifiLock == null)
{
wifiLock = wifiManager.CreateWifiLock(WifiMode.Full, "xamarin_wifi_lock");
}
if (!wifiLock.IsHeld)
wifiLock.Acquire();
}
/// <summary>
/// This will release the wifi lock if it is no longer needed
/// </summary>
public void ReleaseWifiLock()
{
try
{
if (wifiLock == null || !wifiLock.IsHeld)
return;
wifiLock.Release();
}
catch (Java.Lang.RuntimeException ex)
{
Console.WriteLine(ex.Message);
}
wifiLock = null;
}
public override IBinder OnBind(Intent intent)
{
Binder = new MediaServiceBinder(this);
return Binder;
}
public override bool OnUnbind(Intent intent)
{
SessionManager.NotificationManager.StopNotifications();
if (_noisyAudioStreamReceiver != null)
SessionManager.ApplicationContext.UnregisterReceiver(_noisyAudioStreamReceiver);
return base.OnUnbind(intent);
}
/// <summary>
/// Properly cleanup of your player by releasing resources
/// </summary>
public override void OnDestroy()
{
base.OnDestroy();
SessionManager.NotificationManager.StopNotifications();
StopForeground(true);
ReleaseWifiLock();
SessionManager.Release();
}
/// <summary>
/// For a good user experience we should account for when audio focus has changed.
/// There is only 1 audio output there may be several media services trying to use it so
/// we should act correctly based on this. "duck" to be quiet and when we gain go full.
/// All applications are encouraged to follow this, but are not enforced.
/// </summary>
/// <param name="focusChange"></param>
public async void OnAudioFocusChange(AudioFocus focusChange)
{
switch (focusChange)
{
case AudioFocus.Gain:
if (TransientPaused && !ManuallyPaused)
{
await Play();
}
SetVolume(1.0f, 1.0f);//Turn it up!
TransientPaused = false;
break;
case AudioFocus.Loss:
//We have lost focus stop!
await Stop();
break;
case AudioFocus.LossTransient:
//We have lost focus for a short time, but likely to resume so pause
TransientPaused = true;
await Pause();
break;
case AudioFocus.LossTransientCanDuck:
//We have lost focus but should still play at a muted 10% volume
SetVolume(.1f, .1f);
break;
}
}
internal void SetMediaSession(MediaSessionManager sessionManager)
{
SessionManager = sessionManager;
SessionManager.RemoteComponentName = new ComponentName(PackageName, new RemoteControlBroadcastReceiver().ComponentName);
}
public static string GetUriFromPath(Context context, string path)
{
Android.Net.Uri uri = MediaStore.Audio.Media.GetContentUriForPath(path);
string[] selection = { path };
ICursor cursor = context.ContentResolver.Query(uri, null, MediaStore.Audio.Media.InterfaceConsts.Data + "=?", selection, null);
bool firstSuccess = cursor.MoveToFirst();
if (!firstSuccess)
return path;
int idColumnIndex = cursor.GetColumnIndex(MediaStore.Audio.Media.InterfaceConsts.Id);
long id = cursor.GetLong(idColumnIndex);
cursor.Close();
if (!uri.ToString().EndsWith(id.ToString()))
{
return uri + "/" + id;
}
return uri.ToString();
}
protected virtual void OnStatusChanged(StatusChangedEventArgs e)
{
StatusChanged?.Invoke(this, e);
}
protected virtual void OnPlayingChanged(PlayingChangedEventArgs e)
{
PlayingChanged?.Invoke(this, e);
}
protected virtual void OnBufferingChanged(BufferingChangedEventArgs e)
{
BufferingChanged?.Invoke(this, e);
}
protected virtual void OnMediaFinished(MediaFinishedEventArgs e)
{
MediaFinished?.Invoke(this, e);
}
protected virtual void OnMediaFailed(MediaFailedEventArgs e)
{
MediaFailed?.Invoke(this, e);
}
protected virtual void OnMediaFileChanged(MediaFileChangedEventArgs e)
{
MediaFileChanged?.Invoke(this, e);
}
protected virtual void OnMediaFileFailed(MediaFileFailedEventArgs e)
{
MediaFileFailed?.Invoke(this, e);
}
protected abstract void Resume();
/// <summary>
/// Checks if player just paused.
/// </summary>
/// <param name="mediaFile">The media file.</param>
private async Task<bool> CheckIfFileAlreadyIsPlaying(IMediaFile mediaFile)
{
var isNewFile = CurrentFile == null || string.IsNullOrEmpty(mediaFile?.Url)
|| mediaFile?.Url != CurrentFile?.Url;
//New File selected
if (isNewFile)
return await Task.FromResult(false);
//just paused.. restart playback!
if (MediaPlayerState == PlaybackStateCompat.StatePaused && ManuallyPaused)
{
ManuallyPaused = false;
SessionManager.UpdatePlaybackState(PlaybackStateCompat.StatePlaying, Position.Seconds);
SessionManager.UpdateMetadata(mediaFile);
SessionManager.NotificationManager.StartNotification(mediaFile);
CurrentFile = mediaFile;
Resume();
return await Task.FromResult(true);
}
return await Task.FromResult(false);
}
private bool ValidateMediaFile(IMediaFile mediaFile)
{
if (CurrentFile != null || mediaFile != null) return true;
OnMediaFileFailed(new MediaFileFailedEventArgs(new Exception("No mediafile set"), null));
return false;
}
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System.Collections.Generic;
using NUnit.Framework;
using System.Linq;
namespace QuantConnect.Tests
{
[TestFixture, Category("TravisExclude")]
public class RegressionTests
{
[Test, TestCaseSource("GetRegressionTestParameters")]
public void AlgorithmStatisticsRegression(AlgorithmStatisticsTestParameters parameters)
{
QuantConnect.Configuration.Config.Set("quandl-auth-token", "WyAazVXnq7ATy_fefTqm");
if (parameters.Algorithm == "OptionChainConsistencyRegressionAlgorithm")
{
// special arrangement for consistency test - we check if limits work fine
QuantConnect.Configuration.Config.Set("symbol-minute-limit", "100");
QuantConnect.Configuration.Config.Set("symbol-second-limit", "100");
QuantConnect.Configuration.Config.Set("symbol-tick-limit", "100");
}
AlgorithmRunner.RunLocalBacktest(parameters.Algorithm, parameters.Statistics, parameters.Language);
}
private static TestCaseData[] GetRegressionTestParameters()
{
var basicTemplateStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "264.956%"},
{"Drawdown", "2.200%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "4.411"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.002"},
{"Beta", "1"},
{"Annual Standard Deviation", "0.193"},
{"Annual Variance", "0.037"},
{"Information Ratio", "6.816"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0.851"},
{"Total Fees", "$3.09"}
};
var basicTemplateOptionsStatistics = new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.28%"},
{"Compounding Annual Return", "-78.105%"},
{"Drawdown", "0.300%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.280%"},
{"Sharpe Ratio", "0"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.50"},
};
var limitFillRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "34"},
{"Average Win", "0.02%"},
{"Average Loss", "-0.02%"},
{"Compounding Annual Return", "8.350%"},
{"Drawdown", "0.400%"},
{"Expectancy", "0.447"},
{"Net Profit", "0.103%"},
{"Sharpe Ratio", "1.747"},
{"Loss Rate", "31%"},
{"Win Rate", "69%"},
{"Profit-Loss Ratio", "1.10"},
{"Alpha", "-0.077"},
{"Beta", "0.152"},
{"Annual Standard Deviation", "0.03"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-4.87"},
{"Tracking Error", "0.164"},
{"Treynor Ratio", "0.343"},
{"Total Fees", "$34.00"}
};
var updateOrderRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "21"},
{"Average Win", "0%"},
{"Average Loss", "-1.71%"},
{"Compounding Annual Return", "-8.289%"},
{"Drawdown", "16.700%"},
{"Expectancy", "-1"},
{"Net Profit", "-15.892%"},
{"Sharpe Ratio", "-1.225"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.011"},
{"Beta", "-0.469"},
{"Annual Standard Deviation", "0.056"},
{"Annual Variance", "0.003"},
{"Information Ratio", "-1.573"},
{"Tracking Error", "0.152"},
{"Treynor Ratio", "0.147"},
{"Total Fees", "$21.00"}
};
var regressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "5433"},
{"Average Win", "0.00%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-3.886%"},
{"Drawdown", "0.100%"},
{"Expectancy", "-0.991"},
{"Net Profit", "-0.054%"},
{"Sharpe Ratio", "-30.336"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "2.40"},
{"Alpha", "-0.022"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-4.198"},
{"Tracking Error", "0.174"},
{"Treynor Ratio", "35.023"},
{"Total Fees", "$5433.00"}
};
var universeSelectionRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "5"},
{"Average Win", "0.70%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-73.872%"},
{"Drawdown", "6.600%"},
{"Expectancy", "0"},
{"Net Profit", "-6.060%"},
{"Sharpe Ratio", "-3.562"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.681"},
{"Beta", "2.014"},
{"Annual Standard Deviation", "0.284"},
{"Annual Variance", "0.08"},
{"Information Ratio", "-3.67"},
{"Tracking Error", "0.231"},
{"Treynor Ratio", "-0.502"},
{"Total Fees", "$5.00"}
};
var customDataRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "155.210%"},
{"Drawdown", "84.800%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "1.199"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.99"},
{"Beta", "0.168"},
{"Annual Standard Deviation", "0.84"},
{"Annual Variance", "0.706"},
{"Information Ratio", "1.072"},
{"Tracking Error", "0.845"},
{"Treynor Ratio", "5.997"},
{"Total Fees", "$0.00"}
};
var addRemoveSecurityRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "5"},
{"Average Win", "0.49%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "307.853%"},
{"Drawdown", "1.400%"},
{"Expectancy", "0"},
{"Net Profit", "1.814%"},
{"Sharpe Ratio", "6.474"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.306"},
{"Beta", "0.718"},
{"Annual Standard Deviation", "0.141"},
{"Annual Variance", "0.02"},
{"Information Ratio", "1.077"},
{"Tracking Error", "0.062"},
{"Treynor Ratio", "1.275"},
{"Total Fees", "$25.20"}
};
var dropboxBaseDataUniverseSelectionStatistics = new Dictionary<string, string>
{
{"Total Trades", "67"},
{"Average Win", "1.13%"},
{"Average Loss", "-0.69%"},
{"Compounding Annual Return", "17.718%"},
{"Drawdown", "5.100%"},
{"Expectancy", "0.813"},
{"Net Profit", "17.718%"},
{"Sharpe Ratio", "1.38"},
{"Loss Rate", "31%"},
{"Win Rate", "69%"},
{"Profit-Loss Ratio", "1.64"},
{"Alpha", "0.055"},
{"Beta", "0.379"},
{"Annual Standard Deviation", "0.099"},
{"Annual Variance", "0.01"},
{"Information Ratio", "-0.703"},
{"Tracking Error", "0.11"},
{"Treynor Ratio", "0.359"},
{"Total Fees", "$300.15"}
};
var dropboxUniverseSelectionStatistics = new Dictionary<string, string>
{
{"Total Trades", "49"},
{"Average Win", "1.58%"},
{"Average Loss", "-1.03%"},
{"Compounding Annual Return", "21.281%"},
{"Drawdown", "8.200%"},
{"Expectancy", "0.646"},
{"Net Profit", "21.281%"},
{"Sharpe Ratio", "1.362"},
{"Loss Rate", "35%"},
{"Win Rate", "65%"},
{"Profit-Loss Ratio", "1.52"},
{"Alpha", "0.012"},
{"Beta", "0.705"},
{"Annual Standard Deviation", "0.12"},
{"Annual Variance", "0.014"},
{"Information Ratio", "-0.51"},
{"Tracking Error", "0.101"},
{"Treynor Ratio", "0.232"},
{"Total Fees", "$232.92"}
};
var parameterizedStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "278.616%"},
{"Drawdown", "0.300%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "11.017"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.553"},
{"Beta", "0.364"},
{"Annual Standard Deviation", "0.078"},
{"Annual Variance", "0.006"},
{"Information Ratio", "0.101"},
{"Tracking Error", "0.127"},
{"Treynor Ratio", "2.367"},
{"Total Fees", "$3.09"},
};
var historyAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "372.677%"},
{"Drawdown", "1.100%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "4.521"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.006"},
{"Beta", "0.997"},
{"Annual Standard Deviation", "0.193"},
{"Annual Variance", "0.037"},
{"Information Ratio", "6.231"},
{"Tracking Error", "0.001"},
{"Treynor Ratio", "0.876"},
{"Total Fees", "$3.09"},
};
var coarseFundamentalTop5AlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "10"},
{"Average Win", "1.15%"},
{"Average Loss", "-0.47%"},
{"Compounding Annual Return", "-0.746%"},
{"Drawdown", "3.000%"},
{"Expectancy", "-0.313"},
{"Net Profit", "-0.746%"},
{"Sharpe Ratio", "-0.242"},
{"Loss Rate", "80%"},
{"Win Rate", "20%"},
{"Profit-Loss Ratio", "2.44"},
{"Alpha", "-0.01"},
{"Beta", "0.044"},
{"Annual Standard Deviation", "0.024"},
{"Annual Variance", "0.001"},
{"Information Ratio", "-0.973"},
{"Tracking Error", "0.1"},
{"Treynor Ratio", "-0.13"},
{"Total Fees", "$10.61"},
};
var coarseFineFundamentalRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "6"},
{"Average Win", "0%"},
{"Average Loss", "-0.84%"},
{"Compounding Annual Return", "-57.345%"},
{"Drawdown", "9.100%"},
{"Expectancy", "-1"},
{"Net Profit", "-6.763%"},
{"Sharpe Ratio", "-3.025"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.754"},
{"Beta", "1.258"},
{"Annual Standard Deviation", "0.217"},
{"Annual Variance", "0.047"},
{"Information Ratio", "-4.525"},
{"Tracking Error", "0.162"},
{"Treynor Ratio", "-0.521"},
{"Total Fees", "$13.92"},
};
var macdTrendAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "127"},
{"Average Win", "3.65%"},
{"Average Loss", "-2.38%"},
{"Compounding Annual Return", "2.295%"},
{"Drawdown", "31.900%"},
{"Expectancy", "0.209"},
{"Net Profit", "28.377%"},
{"Sharpe Ratio", "0.226"},
{"Loss Rate", "52%"},
{"Win Rate", "48%"},
{"Profit-Loss Ratio", "1.54"},
{"Alpha", "-0.006"},
{"Beta", "0.394"},
{"Annual Standard Deviation", "0.108"},
{"Annual Variance", "0.012"},
{"Information Ratio", "-0.392"},
{"Tracking Error", "0.135"},
{"Treynor Ratio", "0.062"},
{"Total Fees", "$604.31"},
};
var optionSplitRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0.00%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "0.198%"},
{"Drawdown", "0.500%"},
{"Expectancy", "0"},
{"Net Profit", "0.002%"},
{"Sharpe Ratio", "0.609"},
{"Loss Rate", "0%"},
{"Win Rate", "100%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.013"},
{"Beta", "0"},
{"Annual Standard Deviation", "0.002"},
{"Annual Variance", "0"},
{"Information Ratio", "7.935"},
{"Tracking Error", "6.787"},
{"Treynor Ratio", "-4.913"},
{"Total Fees", "$1.25"},
};
var optionRenameRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "4"},
{"Average Win", "0%"},
{"Average Loss", "-0.02%"},
{"Compounding Annual Return", "-0.472%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.006%"},
{"Sharpe Ratio", "-3.403"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.016"},
{"Beta", "-0.001"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "10.014"},
{"Tracking Error", "0.877"},
{"Treynor Ratio", "4.203"},
{"Total Fees", "$2.50"},
};
var optionOpenInterestRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-0.01%"},
{"Compounding Annual Return", "-2.042%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.010%"},
{"Sharpe Ratio", "-11.225"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "-0.036"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "-11.225"},
{"Tracking Error", "0.033"},
{"Treynor Ratio", "0.355"},
{"Total Fees", "$0.50"},
};
var optionChainConsistencyRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "2"},
{"Average Win", "0%"},
{"Average Loss", "-3.86%"},
{"Compounding Annual Return", "-100.000%"},
{"Drawdown", "3.900%"},
{"Expectancy", "-1"},
{"Net Profit", "-3.855%"},
{"Sharpe Ratio", "0"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.50"},
};
var weeklyUniverseSelectionRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "8"},
{"Average Win", "1.68%"},
{"Average Loss", "-0.77%"},
{"Compounding Annual Return", "23.389%"},
{"Drawdown", "1.900%"},
{"Expectancy", "0.597"},
{"Net Profit", "1.801%"},
{"Sharpe Ratio", "1.884"},
{"Loss Rate", "50%"},
{"Win Rate", "50%"},
{"Profit-Loss Ratio", "2.19"},
{"Alpha", "-0.003"},
{"Beta", "0.421"},
{"Annual Standard Deviation", "0.087"},
{"Annual Variance", "0.008"},
{"Information Ratio", "-2.459"},
{"Tracking Error", "0.094"},
{"Treynor Ratio", "0.391"},
{"Total Fees", "$23.05"},
};
var optionExerciseAssignRegressionAlgorithmStatistics = new Dictionary<string, string>
{
{"Total Trades", "4"},
{"Average Win", "0.30%"},
{"Average Loss", "-0.32%"},
{"Compounding Annual Return", "-85.023%"},
{"Drawdown", "0.400%"},
{"Expectancy", "-0.359"},
{"Net Profit", "-0.350%"},
{"Sharpe Ratio", "0"},
{"Loss Rate", "67%"},
{"Win Rate", "33%"},
{"Profit-Loss Ratio", "0.92"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$0.50"},
};
var basicTemplateDailyStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "244.780%"},
{"Drawdown", "1.100%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "6.165"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0.254"},
{"Beta", "0.898"},
{"Annual Standard Deviation", "0.14"},
{"Annual Variance", "0.02"},
{"Information Ratio", "4.625"},
{"Tracking Error", "0.04"},
{"Treynor Ratio", "0.963"},
{"Total Fees", "$3.09"}
};
var hourSplitStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-0.096%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "-11.225"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$1.00"}
};
var hourReverseSplitStatistics = new Dictionary<string, string>
{
{"Total Trades", "1"},
{"Average Win", "0%"},
{"Average Loss", "0%"},
{"Compounding Annual Return", "-1.444%"},
{"Drawdown", "0.000%"},
{"Expectancy", "0"},
{"Net Profit", "0%"},
{"Sharpe Ratio", "-11.225"},
{"Loss Rate", "0%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0.001"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$1.00"}
};
var fractionalQuantityRegressionStatistics = new Dictionary<string, string>
{
{"Total Trades", "6"},
{"Average Win", "1.29%"},
{"Average Loss", "0.0%"},
{"Compounding Annual Return", "920.568%"},
{"Drawdown", "3.300%"},
{"Expectancy", "-0.333"},
{"Net Profit", "2.578%"},
{"Sharpe Ratio", "3.031"},
{"Loss Rate", "33%"},
{"Win Rate", "67%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "-0.001"},
{"Beta", "0.995"},
{"Annual Standard Deviation", "0.451"},
{"Annual Variance", "0.203"},
{"Information Ratio", "-3.42"},
{"Tracking Error", "0.002"},
{"Treynor Ratio", "1.374"},
{"Total Fees", "$0.00"}
};
var basicTemplateFuturesAlgorithmDailyStatistics = new Dictionary<string, string>
{
{"Total Trades", "8"},
{"Average Win", "0%"},
{"Average Loss", "0.00%"},
{"Compounding Annual Return", "-1.655%"},
{"Drawdown", "0.000%"},
{"Expectancy", "-1"},
{"Net Profit", "-0.018%"},
{"Sharpe Ratio", "-23.092"},
{"Loss Rate", "100%"},
{"Win Rate", "0%"},
{"Profit-Loss Ratio", "0"},
{"Alpha", "0"},
{"Beta", "0"},
{"Annual Standard Deviation", "0"},
{"Annual Variance", "0"},
{"Information Ratio", "0"},
{"Tracking Error", "0"},
{"Treynor Ratio", "0"},
{"Total Fees", "$14.80"}
};
return new List<AlgorithmStatisticsTestParameters>
{
// CSharp
new AlgorithmStatisticsTestParameters("BasicTemplateFuturesAlgorithmDaily", basicTemplateFuturesAlgorithmDailyStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("AddRemoveSecurityRegressionAlgorithm", addRemoveSecurityRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("BasicTemplateAlgorithm", basicTemplateStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("BasicTemplateOptionsAlgorithm", basicTemplateOptionsStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("CustomDataRegressionAlgorithm", customDataRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("DropboxBaseDataUniverseSelectionAlgorithm", dropboxBaseDataUniverseSelectionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("DropboxUniverseSelectionAlgorithm", dropboxUniverseSelectionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("LimitFillRegressionAlgorithm", limitFillRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("ParameterizedAlgorithm", parameterizedStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("RegressionAlgorithm", regressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("UniverseSelectionRegressionAlgorithm", universeSelectionRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("UpdateOrderRegressionAlgorithm", updateOrderRegressionStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("HistoryAlgorithm", historyAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("CoarseFundamentalTop5Algorithm", coarseFundamentalTop5AlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("CoarseFineFundamentalRegressionAlgorithm", coarseFineFundamentalRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("MACDTrendAlgorithm", macdTrendAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("OptionSplitRegressionAlgorithm", optionSplitRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("OptionRenameRegressionAlgorithm", optionRenameRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("OptionOpenInterestRegressionAlgorithm", optionOpenInterestRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("OptionChainConsistencyRegressionAlgorithm", optionChainConsistencyRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("WeeklyUniverseSelectionRegressionAlgorithm", weeklyUniverseSelectionRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("OptionExerciseAssignRegressionAlgorithm",optionExerciseAssignRegressionAlgorithmStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("BasicTemplateDailyAlgorithm", basicTemplateDailyStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("HourSplitRegressionAlgorithm", hourSplitStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("HourReverseSplitRegressionAlgorithm", hourReverseSplitStatistics, Language.CSharp),
new AlgorithmStatisticsTestParameters("FractionalQuantityRegressionAlgorithm", fractionalQuantityRegressionStatistics, Language.CSharp),
// FSharp
// new AlgorithmStatisticsTestParameters("BasicTemplateAlgorithm", basicTemplateStatistics, Language.FSharp),
// VisualBasic
// new AlgorithmStatisticsTestParameters("BasicTemplateAlgorithm", basicTemplateStatistics, Language.VisualBasic),
}.Select(x => new TestCaseData(x).SetName(x.Language + "/" + x.Algorithm)).ToArray();
}
public class AlgorithmStatisticsTestParameters
{
public readonly string Algorithm;
public readonly Dictionary<string, string> Statistics;
public readonly Language Language;
public AlgorithmStatisticsTestParameters(string algorithm, Dictionary<string, string> statistics, Language language)
{
Algorithm = algorithm;
Statistics = statistics;
Language = language;
}
}
}
}
| |
using LambdicSql.ConverterServices;
using LambdicSql.ConverterServices.SymbolConverters;
namespace LambdicSql.SqlServer
{
//@@@
public static partial class Symbol
{
/// <summary>
/// CERTENCODED
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/certencoded-transact-sql
/// </summary>
/// <param name="cert_id">certificate id</param>
/// <returns>the public portion of a certificate in binary format.</returns>
[FuncStyleConverter]
public static byte[] CertenCoded(int cert_id) => throw new InvalitContextException(nameof(CertenCoded));
/// <summary>
/// CERTPRIVATEKEY
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/certprivatekey-transact-sql
/// </summary>
/// <param name="cert_id">certificate id.</param>
/// <param name="password">password.</param>
/// <returns>the private key of a certificate in binary format. </returns>
[FuncStyleConverter]
public static byte[] CertPrivateKey(int cert_id, string password) => throw new InvalitContextException(nameof(CertPrivateKey));
/// <summary>
/// CURRENT_USER
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/current-user-transact-sql
/// </summary>
/// <returns>user name.</returns>
[FuncStyleConverter]
public static string Current_User() => throw new InvalitContextException(nameof(Current_User));
/// <summary>
/// HAS_DBACCESS
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/has-dbaccess-transact-sql
/// </summary>
/// <param name="database_name">database name</param>
/// <returns>information about whether the user has access to the specified database.</returns>
[FuncStyleConverter]
public static int Has_DbAccess(string database_name) => throw new InvalitContextException(nameof(Has_DbAccess));
/// <summary>
/// HAS_PERMS_BY_NAME
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/has-perms-by-name-transact-sql
/// </summary>
/// <param name="securable">securable</param>
/// <param name="securable_class">securable class</param>
/// <param name="permission">permission</param>
/// <returns>the effective permission of the current user on a securable.</returns>
[FuncStyleConverter]
public static int? Has_Perms_By_Name(string securable, string securable_class , string permission) => throw new InvalitContextException(nameof(Has_Perms_By_Name));
/// <summary>
/// IS_MEMBER.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/is-member-transact-sql
/// </summary>
/// <param name="groupOrRole">group or role.</param>
/// <returns>Indicates whether the current user is a member of the specified Microsoft Windows group or SQL Server database role..</returns>
[FuncStyleConverter]
public static int Is_Member(string groupOrRole) => throw new InvalitContextException(nameof(Is_Member));
/// <summary>
/// IS_ROLEMEMBER
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/is-rolemember-transact-sql
/// </summary>
/// <param name="role">database principal</param>
/// <returns>Indicates whether a specified database principle is a member of the specified database role.</returns>
[FuncStyleConverter]
public static int? Is_RoleMenmber(string role) => throw new InvalitContextException(nameof(Is_RoleMenmber));
/// <summary>
/// IS_SRVROLEMEMBER
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/is-srvrolemember-transact-sql
/// </summary>
/// <param name="role">role</param>
/// <returns>Indicates whether a SQL Server login is a member of the specified server role.</returns>
[FuncStyleConverter]
public static int? Is_SrvroleMember(string role) => throw new InvalitContextException(nameof(Is_SrvroleMember));
/// <summary>
/// LOGINPROPERTY
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/loginproperty-transact-sql
/// </summary>
/// <param name="login_name">login name.</param>
/// <param name="property_name">property name.</param>
/// <returns>Information about login policy settings.</returns>
[FuncStyleConverter]
public static int? LoginProperty(string login_name, string property_name) => throw new InvalitContextException(nameof(LoginProperty));
/// <summary>
/// ORIGINAL_LOGIN
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/original-login-transact-sql
/// </summary>
/// <returns>login name.</returns>
[FuncStyleConverter]
public static string Original_Login() => throw new InvalitContextException(nameof(Original_Login));
/// <summary>
/// PERMISSIONS
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/permissions-transact-sql
/// </summary>
/// <param name="object_id">object id.</param>
/// <returns>permissions</returns>
[FuncStyleConverter]
public static int? Permissions(int? object_id) => throw new InvalitContextException(nameof(Permissions));
/// <summary>
/// PWDENCRYPT
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/pwdencrypt-transact-sql
/// </summary>
/// <param name="password">password</param>
/// <returns>the SQL Server password hash of the input value that uses the current version of the password hashing algorithm.</returns>
[FuncStyleConverter]
public static byte[] PwdEncrypt(string password) => throw new InvalitContextException(nameof(Permissions));
/// <summary>
/// PWDCOMPARE
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/pwdcompare-transact-sql
/// </summary>
/// <param name="password">password</param>
/// <param name="password_hash">password hash</param>
/// <returns></returns>
[FuncStyleConverter]
public static int PwdCompare(string password, byte[] password_hash) => throw new InvalitContextException(nameof(PwdCompare));
/// <summary>
/// SESSION_USER
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/session-user-transact-sql
/// </summary>
/// <returns>session user</returns>
[ClauseStyleConverter]
public static string Session_User() => throw new InvalitContextException(nameof(Session_User));
/// <summary>
/// SESSIONPROPERTY
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/sessionproperty-transact-sql
/// </summary>
/// <param name="option">option</param>
/// <returns>session property</returns>
[FuncStyleConverter]
public static string SessionProperty(string option) => throw new InvalitContextException(nameof(SessionProperty));
/// <summary>
/// SUSER_ID.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/suser-id-transact-sql
/// </summary>
/// <param name="login_name">login name.</param>
/// <returns>server user id.</returns>
[FuncStyleConverter]
public static int? SUser_Id(string login_name) => throw new InvalitContextException(nameof(SUser_Id));
/// <summary>
/// SUSER_NAME.
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/suser-name-transact-sql
/// </summary>
/// <param name="server_user_id">server user id.</param>
/// <returns>login name.</returns>
[FuncStyleConverter]
public static string SUser_Name(int? server_user_id) => throw new InvalitContextException(nameof(SUser_Name));
/// <summary>
/// SUSER_SID
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/suser-sid-transact-sql
/// </summary>
/// <param name="login_name">login name.</param>
/// <returns>the security identification number (SID) for the specified login name.</returns>
[FuncStyleConverter]
public static byte[] SUser_SId(string login_name) => throw new InvalitContextException(nameof(SUser_SId));
/// <summary>
/// SUSER_SID
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/suser-sid-transact-sql
/// </summary>
/// <param name="login_name">login name.</param>
/// <param name="option">option.</param>
/// <returns>the security identification number (SID) for the specified login name.</returns>
[FuncStyleConverter]
public static byte[] SUser_SId(string login_name, int option) => throw new InvalitContextException(nameof(SUser_SId));
/// <summary>
/// SUSER_SNAME
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/suser-sname-transact-sql.
/// </summary>
/// <param name="server_user_sid">server user sid.</param>
/// <returns>user name.</returns>
[FuncStyleConverter]
public static string SUser_SName(byte[] server_user_sid) => throw new InvalitContextException(nameof(SUser_SName));
/// <summary>
/// SYSTEM_USER
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/system-user-transact-sql
/// </summary>
/// <returns>system user.</returns>
[ClauseStyleConverter]
public static string System_User() => throw new InvalitContextException(nameof(System_User));
/// <summary>
/// USER
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/user-transact-sql
/// </summary>
/// <returns>user</returns>
[ClauseStyleConverter]
public static string User() => throw new InvalitContextException(nameof(User));
/// <summary>
/// USER_ID
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/user-id-transact-sql
/// </summary>
/// <param name="user">user</param>
/// <returns>user id.</returns>
[FuncStyleConverter]
public static int? User_Id(string user) => throw new InvalitContextException(nameof(User_Id));
/// <summary>
/// USER_NAME
/// https://docs.microsoft.com/en-us/sql/t-sql/functions/user-name-transact-sql
/// </summary>
/// <param name="user_id">user id.</param>
/// <returns>user name.</returns>
[FuncStyleConverter]
public static string User_Name(int? user_id) => throw new InvalitContextException(nameof(User_Name));
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="XPathDocumentNavigator.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
using System;
using System.IO;
using System.Collections;
using System.Globalization;
using System.Text;
using System.Diagnostics;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Schema;
namespace MS.Internal.Xml.Cache {
/// <summary>
/// This is the default XPath/XQuery data model cache implementation. It will be used whenever
/// the user does not supply his own XPathNavigator implementation.
/// </summary>
internal sealed class XPathDocumentNavigator : XPathNavigator, IXmlLineInfo {
private XPathNode[] pageCurrent;
private XPathNode[] pageParent;
private int idxCurrent;
private int idxParent;
private string atomizedLocalName;
//-----------------------------------------------
// Constructors
//-----------------------------------------------
/// <summary>
/// Create a new navigator positioned on the specified current node. If the current node is a namespace or a collapsed
/// text node, then the parent is a virtualized parent (may be different than .Parent on the current node).
/// </summary>
public XPathDocumentNavigator(XPathNode[] pageCurrent, int idxCurrent, XPathNode[] pageParent, int idxParent) {
Debug.Assert(pageCurrent != null && idxCurrent != 0);
Debug.Assert((pageParent == null) == (idxParent == 0));
this.pageCurrent = pageCurrent;
this.pageParent = pageParent;
this.idxCurrent = idxCurrent;
this.idxParent = idxParent;
}
/// <summary>
/// Copy constructor.
/// </summary>
public XPathDocumentNavigator(XPathDocumentNavigator nav) : this(nav.pageCurrent, nav.idxCurrent, nav.pageParent, nav.idxParent) {
this.atomizedLocalName = nav.atomizedLocalName;
}
//-----------------------------------------------
// XPathItem
//-----------------------------------------------
/// <summary>
/// Get the string value of the current node, computed using data model dm:string-value rules.
/// If the node has a typed value, return the string representation of the value. If the node
/// is not a parent type (comment, text, pi, etc.), get its simple text value. Otherwise,
/// concatenate all text node descendants of the current node.
/// </summary>
public override string Value {
get {
string value;
XPathNode[] page, pageEnd;
int idx, idxEnd;
// Try to get the pre-computed string value of the node
value = this.pageCurrent[this.idxCurrent].Value;
if (value != null)
return value;
#if DEBUG
switch (this.pageCurrent[this.idxCurrent].NodeType) {
case XPathNodeType.Namespace:
case XPathNodeType.Attribute:
case XPathNodeType.Comment:
case XPathNodeType.ProcessingInstruction:
Debug.Assert(false, "ReadStringValue() should have taken care of these node types.");
break;
case XPathNodeType.Text:
Debug.Assert(this.idxParent != 0 && this.pageParent[this.idxParent].HasCollapsedText,
"ReadStringValue() should have taken care of anything but collapsed text.");
break;
}
#endif
// If current node is collapsed text, then parent element has a simple text value
if (this.idxParent != 0) {
Debug.Assert(this.pageCurrent[this.idxCurrent].NodeType == XPathNodeType.Text);
return this.pageParent[this.idxParent].Value;
}
// Must be node with complex content, so concatenate the string values of all text descendants
string s = string.Empty;
StringBuilder bldr = null;
// Get all text nodes which follow the current node in document order, but which are still descendants
page = pageEnd = this.pageCurrent;
idx = idxEnd = this.idxCurrent;
if (!XPathNodeHelper.GetNonDescendant(ref pageEnd, ref idxEnd)) {
pageEnd = null;
idxEnd = 0;
}
while (XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd)) {
Debug.Assert(page[idx].NodeType == XPathNodeType.Element || page[idx].IsText);
if (s.Length == 0) {
s = page[idx].Value;
}
else {
if (bldr == null) {
bldr = new StringBuilder();
bldr.Append(s);
}
bldr.Append(page[idx].Value);
}
}
return (bldr != null) ? bldr.ToString() : s;
}
}
//-----------------------------------------------
// XPathNavigator
//-----------------------------------------------
/// <summary>
/// Create a copy of this navigator, positioned to the same node in the tree.
/// </summary>
public override XPathNavigator Clone() {
return new XPathDocumentNavigator(this.pageCurrent, this.idxCurrent, this.pageParent, this.idxParent);
}
/// <summary>
/// Get the XPath node type of the current node.
/// </summary>
public override XPathNodeType NodeType {
get { return this.pageCurrent[this.idxCurrent].NodeType; }
}
/// <summary>
/// Get the local name portion of the current node's name.
/// </summary>
public override string LocalName {
get { return this.pageCurrent[this.idxCurrent].LocalName; }
}
/// <summary>
/// Get the namespace portion of the current node's name.
/// </summary>
public override string NamespaceURI {
get { return this.pageCurrent[this.idxCurrent].NamespaceUri; }
}
/// <summary>
/// Get the name of the current node.
/// </summary>
public override string Name {
get { return this.pageCurrent[this.idxCurrent].Name; }
}
/// <summary>
/// Get the prefix portion of the current node's name.
/// </summary>
public override string Prefix {
get { return this.pageCurrent[this.idxCurrent].Prefix; }
}
/// <summary>
/// Get the base URI of the current node.
/// </summary>
public override string BaseURI {
get {
XPathNode[] page;
int idx;
if (this.idxParent != 0) {
// Get BaseUri of parent for attribute, namespace, and collapsed text nodes
page = this.pageParent;
idx = this.idxParent;
}
else {
page = this.pageCurrent;
idx = this.idxCurrent;
}
do {
switch (page[idx].NodeType) {
case XPathNodeType.Element:
case XPathNodeType.Root:
case XPathNodeType.ProcessingInstruction:
// BaseUri is always stored with Elements, Roots, and PIs
return page[idx].BaseUri;
}
// Get BaseUri of parent
idx = page[idx].GetParent(out page);
}
while (idx != 0);
return string.Empty;
}
}
/// <summary>
/// Return true if this is an element which used a shortcut tag in its Xml 1.0 serialized form.
/// </summary>
public override bool IsEmptyElement {
get { return this.pageCurrent[this.idxCurrent].AllowShortcutTag; }
}
/// <summary>
/// Return the xml name table which was used to atomize all prefixes, local-names, and
/// namespace uris in the document.
/// </summary>
public override XmlNameTable NameTable {
get { return this.pageCurrent[this.idxCurrent].Document.NameTable; }
}
/// <summary>
/// Position the navigator on the first attribute of the current node and return true. If no attributes
/// can be found, return false.
/// </summary>
public override bool MoveToFirstAttribute() {
XPathNode[] page = this.pageCurrent;
int idx = this.idxCurrent;
if (XPathNodeHelper.GetFirstAttribute(ref this.pageCurrent, ref this.idxCurrent)) {
// Save element parent in order to make node-order comparison simpler
this.pageParent = page;
this.idxParent = idx;
return true;
}
return false;
}
/// <summary>
/// If positioned on an attribute, move to its next sibling attribute. If no attributes can be found,
/// return false.
/// </summary>
public override bool MoveToNextAttribute() {
return XPathNodeHelper.GetNextAttribute(ref this.pageCurrent, ref this.idxCurrent);
}
/// <summary>
/// True if the current node has one or more attributes.
/// </summary>
public override bool HasAttributes {
get { return this.pageCurrent[this.idxCurrent].HasAttribute; }
}
/// <summary>
/// Position the navigator on the attribute with the specified name and return true. If no matching
/// attribute can be found, return false. Don't assume the name parts are atomized with respect
/// to this document.
/// </summary>
public override bool MoveToAttribute(string localName, string namespaceURI) {
XPathNode[] page = this.pageCurrent;
int idx = this.idxCurrent;
if ((object) localName != (object) this.atomizedLocalName)
this.atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null;
if (XPathNodeHelper.GetAttribute(ref this.pageCurrent, ref this.idxCurrent, this.atomizedLocalName, namespaceURI)) {
// Save element parent in order to make node-order comparison simpler
this.pageParent = page;
this.idxParent = idx;
return true;
}
return false;
}
/// <summary>
/// Position the navigator on the namespace within the specified scope. If no matching namespace
/// can be found, return false.
/// </summary>
public override bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) {
XPathNode[] page;
int idx;
if (namespaceScope == XPathNamespaceScope.Local) {
// Get local namespaces only
idx = XPathNodeHelper.GetLocalNamespaces(this.pageCurrent, this.idxCurrent, out page);
}
else {
// Get all in-scope namespaces
idx = XPathNodeHelper.GetInScopeNamespaces(this.pageCurrent, this.idxCurrent, out page);
}
while (idx != 0) {
// Don't include the xmlns:xml namespace node if scope is ExcludeXml
if (namespaceScope != XPathNamespaceScope.ExcludeXml || !page[idx].IsXmlNamespaceNode) {
this.pageParent = this.pageCurrent;
this.idxParent = this.idxCurrent;
this.pageCurrent = page;
this.idxCurrent = idx;
return true;
}
// Skip past xmlns:xml
idx = page[idx].GetSibling(out page);
}
return false;
}
/// <summary>
/// Position the navigator on the next namespace within the specified scope. If no matching namespace
/// can be found, return false.
/// </summary>
public override bool MoveToNextNamespace(XPathNamespaceScope scope) {
XPathNode[] page = this.pageCurrent, pageParent;
int idx = this.idxCurrent, idxParent;
// If current node is not a namespace node, return false
if (page[idx].NodeType != XPathNodeType.Namespace)
return false;
while (true) {
// Get next namespace sibling
idx = page[idx].GetSibling(out page);
// If there are no more nodes, return false
if (idx == 0)
return false;
switch (scope) {
case XPathNamespaceScope.Local:
// Once parent changes, there are no longer any local namespaces
idxParent = page[idx].GetParent(out pageParent);
if (idxParent != this.idxParent || (object) pageParent != (object) this.pageParent)
return false;
break;
case XPathNamespaceScope.ExcludeXml:
// If node is xmlns:xml, then skip it
if (page[idx].IsXmlNamespaceNode)
continue;
break;
}
// Found a matching next namespace node, so return it
break;
}
this.pageCurrent = page;
this.idxCurrent = idx;
return true;
}
/// <summary>
/// If the current node is an attribute or namespace (not content), return false. Otherwise,
/// move to the next content node. Return false if there are no more content nodes.
/// </summary>
public override bool MoveToNext() {
return XPathNodeHelper.GetContentSibling(ref this.pageCurrent, ref this.idxCurrent);
}
/// <summary>
/// If the current node is an attribute or namespace (not content), return false. Otherwise,
/// move to the previous (sibling) content node. Return false if there are no previous content nodes.
/// </summary>
public override bool MoveToPrevious() {
// If parent exists, then this is a namespace, an attribute, or a collapsed text node, all of which do
// not have previous siblings.
if (this.idxParent != 0)
return false;
return XPathNodeHelper.GetPreviousContentSibling(ref this.pageCurrent, ref this.idxCurrent);
}
/// <summary>
/// Move to the first content-typed child of the current node. Return false if the current
/// node has no content children.
/// </summary>
public override bool MoveToFirstChild() {
if (this.pageCurrent[this.idxCurrent].HasCollapsedText) {
// Virtualize collapsed text nodes
this.pageParent = this.pageCurrent;
this.idxParent = this.idxCurrent;
this.idxCurrent = this.pageCurrent[this.idxCurrent].Document.GetCollapsedTextNode(out this.pageCurrent);
return true;
}
return XPathNodeHelper.GetContentChild(ref this.pageCurrent, ref this.idxCurrent);
}
/// <summary>
/// Position the navigator on the parent of the current node. If the current node has no parent,
/// return false.
/// </summary>
public override bool MoveToParent() {
if (this.idxParent != 0) {
// 1. For attribute nodes, element parent is always stored in order to make node-order
// comparison simpler.
// 2. For namespace nodes, parent is always stored in navigator in order to virtualize
// XPath 1.0 namespaces.
// 3. For collapsed text nodes, element parent is always stored in navigator.
Debug.Assert(this.pageParent != null);
this.pageCurrent = this.pageParent;
this.idxCurrent = this.idxParent;
this.pageParent = null;
this.idxParent = 0;
return true;
}
return XPathNodeHelper.GetParent(ref this.pageCurrent, ref this.idxCurrent);
}
/// <summary>
/// Position this navigator to the same position as the "other" navigator. If the "other" navigator
/// is not of the same type as this navigator, then return false.
/// </summary>
public override bool MoveTo(XPathNavigator other) {
XPathDocumentNavigator that = other as XPathDocumentNavigator;
if (that != null) {
this.pageCurrent = that.pageCurrent;
this.idxCurrent = that.idxCurrent;
this.pageParent = that.pageParent;
this.idxParent = that.idxParent;
return true;
}
return false;
}
/// <summary>
/// Position to the navigator to the element whose id is equal to the specified "id" string.
/// </summary>
public override bool MoveToId(string id) {
XPathNode[] page;
int idx;
idx = this.pageCurrent[this.idxCurrent].Document.LookupIdElement(id, out page);
if (idx != 0) {
// Move to ID element and clear parent state
Debug.Assert(page[idx].NodeType == XPathNodeType.Element);
this.pageCurrent = page;
this.idxCurrent = idx;
this.pageParent = null;
this.idxParent = 0;
return true;
}
return false;
}
/// <summary>
/// Returns true if this navigator is positioned to the same node as the "other" navigator. Returns false
/// if not, or if the "other" navigator is not the same type as this navigator.
/// </summary>
public override bool IsSamePosition(XPathNavigator other) {
XPathDocumentNavigator that = other as XPathDocumentNavigator;
if (that != null) {
return this.idxCurrent == that.idxCurrent && this.pageCurrent == that.pageCurrent &&
this.idxParent == that.idxParent && this.pageParent == that.pageParent;
}
return false;
}
/// <summary>
/// Returns true if the current node has children.
/// </summary>
public override bool HasChildren {
get { return this.pageCurrent[this.idxCurrent].HasContentChild; }
}
/// <summary>
/// Position the navigator on the root node of the current document.
/// </summary>
public override void MoveToRoot() {
if (this.idxParent != 0) {
// Clear parent state
this.pageParent = null;
this.idxParent = 0;
}
this.idxCurrent = this.pageCurrent[this.idxCurrent].GetRoot(out this.pageCurrent);
}
/// <summary>
/// Move to the first element child of the current node with the specified name. Return false
/// if the current node has no matching element children.
/// </summary>
public override bool MoveToChild(string localName, string namespaceURI) {
if ((object) localName != (object) this.atomizedLocalName)
this.atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null;
return XPathNodeHelper.GetElementChild(ref this.pageCurrent, ref this.idxCurrent, this.atomizedLocalName, namespaceURI);
}
/// <summary>
/// Move to the first element sibling of the current node with the specified name. Return false
/// if the current node has no matching element siblings.
/// </summary>
public override bool MoveToNext(string localName, string namespaceURI) {
if ((object) localName != (object) this.atomizedLocalName)
this.atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null;
return XPathNodeHelper.GetElementSibling(ref this.pageCurrent, ref this.idxCurrent, this.atomizedLocalName, namespaceURI);
}
/// <summary>
/// Move to the first content child of the current node with the specified type. Return false
/// if the current node has no matching children.
/// </summary>
public override bool MoveToChild(XPathNodeType type) {
if (this.pageCurrent[this.idxCurrent].HasCollapsedText) {
// Only XPathNodeType.Text and XPathNodeType.All matches collapsed text node
if (type != XPathNodeType.Text && type != XPathNodeType.All)
return false;
// Virtualize collapsed text nodes
this.pageParent = this.pageCurrent;
this.idxParent = this.idxCurrent;
this.idxCurrent = this.pageCurrent[this.idxCurrent].Document.GetCollapsedTextNode(out this.pageCurrent);
return true;
}
return XPathNodeHelper.GetContentChild(ref this.pageCurrent, ref this.idxCurrent, type);
}
/// <summary>
/// Move to the first content sibling of the current node with the specified type. Return false
/// if the current node has no matching siblings.
/// </summary>
public override bool MoveToNext(XPathNodeType type) {
return XPathNodeHelper.GetContentSibling(ref this.pageCurrent, ref this.idxCurrent, type);
}
/// <summary>
/// Move to the next element that:
/// 1. Follows the current node in document order (includes descendants, unlike XPath following axis)
/// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered)
/// 3. Has the specified QName
/// Return false if the current node has no matching following elements.
/// </summary>
public override bool MoveToFollowing(string localName, string namespaceURI, XPathNavigator end) {
XPathNode[] pageEnd;
int idxEnd;
if ((object) localName != (object) this.atomizedLocalName)
this.atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null;
// Get node on which scan ends (null if rest of document should be scanned)
idxEnd = GetFollowingEnd(end as XPathDocumentNavigator, false, out pageEnd);
// If this navigator is positioned on a virtual node, then compute following of parent
if (this.idxParent != 0) {
if (!XPathNodeHelper.GetElementFollowing(ref this.pageParent, ref this.idxParent, pageEnd, idxEnd, this.atomizedLocalName, namespaceURI))
return false;
this.pageCurrent = this.pageParent;
this.idxCurrent = this.idxParent;
this.pageParent = null;
this.idxParent = 0;
return true;
}
return XPathNodeHelper.GetElementFollowing(ref this.pageCurrent, ref this.idxCurrent, pageEnd, idxEnd, this.atomizedLocalName, namespaceURI);
}
/// <summary>
/// Move to the next node that:
/// 1. Follows the current node in document order (includes descendants, unlike XPath following axis)
/// 2. Precedes "end" in document order (if end is null, then all following nodes in the document are considered)
/// 3. Has the specified XPathNodeType
/// Return false if the current node has no matching following nodes.
/// </summary>
public override bool MoveToFollowing(XPathNodeType type, XPathNavigator end) {
XPathDocumentNavigator endTiny = end as XPathDocumentNavigator;
XPathNode[] page, pageEnd;
int idx, idxEnd;
// If searching for text, make sure to handle collapsed text nodes correctly
if (type == XPathNodeType.Text || type == XPathNodeType.All) {
if (this.pageCurrent[this.idxCurrent].HasCollapsedText) {
// Positioned on an element with collapsed text, so return the virtual text node, assuming it's before "end"
if (endTiny != null && this.idxCurrent == endTiny.idxParent && this.pageCurrent == endTiny.pageParent) {
// "end" is positioned to a virtual attribute, namespace, or text node
return false;
}
this.pageParent = this.pageCurrent;
this.idxParent = this.idxCurrent;
this.idxCurrent = this.pageCurrent[this.idxCurrent].Document.GetCollapsedTextNode(out this.pageCurrent);
return true;
}
if (type == XPathNodeType.Text) {
// Get node on which scan ends (null if rest of document should be scanned, parent if positioned on virtual node)
idxEnd = GetFollowingEnd(endTiny, true, out pageEnd);
// If this navigator is positioned on a virtual node, then compute following of parent
if (this.idxParent != 0) {
page = this.pageParent;
idx = this.idxParent;
}
else {
page = this.pageCurrent;
idx = this.idxCurrent;
}
// If ending node is a virtual node, and current node is its parent, then we're done
if (endTiny != null && endTiny.idxParent != 0 && idx == idxEnd && page == pageEnd)
return false;
// Get all virtual (collapsed) and physical text nodes which follow the current node
if (!XPathNodeHelper.GetTextFollowing(ref page, ref idx, pageEnd, idxEnd))
return false;
if (page[idx].NodeType == XPathNodeType.Element) {
// Virtualize collapsed text nodes
Debug.Assert(page[idx].HasCollapsedText);
this.idxCurrent = page[idx].Document.GetCollapsedTextNode(out this.pageCurrent);
this.pageParent = page;
this.idxParent = idx;
}
else {
// Physical text node
Debug.Assert(page[idx].IsText);
this.pageCurrent = page;
this.idxCurrent = idx;
this.pageParent = null;
this.idxParent = 0;
}
return true;
}
}
// Get node on which scan ends (null if rest of document should be scanned, parent + 1 if positioned on virtual node)
idxEnd = GetFollowingEnd(endTiny, false, out pageEnd);
// If this navigator is positioned on a virtual node, then compute following of parent
if (this.idxParent != 0) {
if (!XPathNodeHelper.GetContentFollowing(ref this.pageParent, ref this.idxParent, pageEnd, idxEnd, type))
return false;
this.pageCurrent = this.pageParent;
this.idxCurrent = this.idxParent;
this.pageParent = null;
this.idxParent = 0;
return true;
}
return XPathNodeHelper.GetContentFollowing(ref this.pageCurrent, ref this.idxCurrent, pageEnd, idxEnd, type);
}
/// <summary>
/// Return an iterator that ranges over all children of the current node that match the specified XPathNodeType.
/// </summary>
public override XPathNodeIterator SelectChildren(XPathNodeType type) {
return new XPathDocumentKindChildIterator(this, type);
}
/// <summary>
/// Return an iterator that ranges over all children of the current node that match the specified QName.
/// </summary>
public override XPathNodeIterator SelectChildren(string name, string namespaceURI) {
// If local name is wildcard, then call XPathNavigator.SelectChildren
if (name == null || name.Length == 0)
return base.SelectChildren(name, namespaceURI);
return new XPathDocumentElementChildIterator(this, name, namespaceURI);
}
/// <summary>
/// Return an iterator that ranges over all descendants of the current node that match the specified
/// XPathNodeType. If matchSelf is true, then also perform the match on the current node.
/// </summary>
public override XPathNodeIterator SelectDescendants(XPathNodeType type, bool matchSelf) {
return new XPathDocumentKindDescendantIterator(this, type, matchSelf);
}
/// <summary>
/// Return an iterator that ranges over all descendants of the current node that match the specified
/// QName. If matchSelf is true, then also perform the match on the current node.
/// </summary>
public override XPathNodeIterator SelectDescendants(string name, string namespaceURI, bool matchSelf) {
// If local name is wildcard, then call XPathNavigator.SelectDescendants
if (name == null || name.Length == 0)
return base.SelectDescendants(name, namespaceURI, matchSelf);
return new XPathDocumentElementDescendantIterator(this, name, namespaceURI, matchSelf);
}
/// <summary>
/// Returns:
/// XmlNodeOrder.Unknown -- This navigator and the "other" navigator are not of the same type, or the
/// navigator's are not positioned on nodes in the same document.
/// XmlNodeOrder.Before -- This navigator's current node is before the "other" navigator's current node
/// in document order.
/// XmlNodeOrder.After -- This navigator's current node is after the "other" navigator's current node
/// in document order.
/// XmlNodeOrder.Same -- This navigator is positioned on the same node as the "other" navigator.
/// </summary>
public override XmlNodeOrder ComparePosition(XPathNavigator other) {
XPathDocumentNavigator that = other as XPathDocumentNavigator;
if (that != null) {
XPathDocument thisDoc = this.pageCurrent[this.idxCurrent].Document;
XPathDocument thatDoc = that.pageCurrent[that.idxCurrent].Document;
if ((object) thisDoc == (object) thatDoc) {
int locThis = GetPrimaryLocation();
int locThat = that.GetPrimaryLocation();
if (locThis == locThat) {
locThis = GetSecondaryLocation();
locThat = that.GetSecondaryLocation();
if (locThis == locThat)
return XmlNodeOrder.Same;
}
return (locThis < locThat) ? XmlNodeOrder.Before : XmlNodeOrder.After;
}
}
return XmlNodeOrder.Unknown;
}
/// <summary>
/// Return true if the "other" navigator's current node is a descendant of this navigator's current node.
/// </summary>
public override bool IsDescendant(XPathNavigator other) {
XPathDocumentNavigator that = other as XPathDocumentNavigator;
if (that != null) {
XPathNode[] pageThat;
int idxThat;
// If that current node's parent is virtualized, then start with the virtual parent
if (that.idxParent != 0) {
pageThat = that.pageParent;
idxThat = that.idxParent;
}
else {
idxThat = that.pageCurrent[that.idxCurrent].GetParent(out pageThat);
}
while (idxThat != 0) {
if (idxThat == this.idxCurrent && pageThat == this.pageCurrent)
return true;
idxThat = pageThat[idxThat].GetParent(out pageThat);
}
}
return false;
}
/// <summary>
/// Construct a primary location for this navigator. The location is an integer that can be
/// easily compared with other locations in the same document in order to determine the relative
/// document order of two nodes. If two locations compare equal, then secondary locations should
/// be compared.
/// </summary>
private int GetPrimaryLocation() {
// Is the current node virtualized?
if (this.idxParent == 0) {
// No, so primary location should be derived from current node
return XPathNodeHelper.GetLocation(this.pageCurrent, this.idxCurrent);
}
// Yes, so primary location should be derived from parent node
return XPathNodeHelper.GetLocation(this.pageParent, this.idxParent);
}
/// <summary>
/// Construct a secondary location for this navigator. This location should only be used if
/// primary locations previously compared equal.
/// </summary>
private int GetSecondaryLocation() {
// Is the current node virtualized?
if (this.idxParent == 0) {
// No, so secondary location is int.MinValue (always first)
return int.MinValue;
}
// Yes, so secondary location should be derived from current node
// This happens with attributes nodes, namespace nodes, collapsed text nodes, and atomic values
switch (this.pageCurrent[this.idxCurrent].NodeType) {
case XPathNodeType.Namespace:
// Namespace nodes come first (make location negative, but greater than int.MinValue)
return int.MinValue + 1 + XPathNodeHelper.GetLocation(this.pageCurrent, this.idxCurrent);
case XPathNodeType.Attribute:
// Attribute nodes come next (location is always positive)
return XPathNodeHelper.GetLocation(this.pageCurrent, this.idxCurrent);
default:
// Collapsed text nodes are always last
return int.MaxValue;
}
}
/// <summary>
/// Create a unique id for the current node. This is used by the generate-id() function.
/// </summary>
internal override string UniqueId {
get {
// 32-bit integer is split into 5-bit groups, the maximum number of groups is 7
char[] buf = new char[1+7+1+7];
int idx = 0;
int loc;
// Ensure distinguishing attributes, namespaces and child nodes
buf[idx++] = NodeTypeLetter[(int)this.pageCurrent[this.idxCurrent].NodeType];
// If the current node is virtualized, code its parent
if (this.idxParent != 0) {
loc = (this.pageParent[0].PageInfo.PageNumber - 1) << 16 | (this.idxParent - 1);
do {
buf[idx++] = UniqueIdTbl[loc & 0x1f];
loc >>= 5;
} while (loc != 0);
buf[idx++] = '0';
}
// Code the node itself
loc = (this.pageCurrent[0].PageInfo.PageNumber - 1) << 16 | (this.idxCurrent - 1);
do {
buf[idx++] = UniqueIdTbl[loc & 0x1f];
loc >>= 5;
} while (loc != 0);
return new string(buf, 0, idx);
}
}
public override object UnderlyingObject {
get {
// Since we don't have any underlying PUBLIC object
// the best one we can return is a clone of the navigator.
// Note that it should be a clone as the user might Move the returned navigator
// around and thus cause unexpected behavior of the caller of this class (For example the validator)
return this.Clone();
}
}
//-----------------------------------------------
// IXmlLineInfo
//-----------------------------------------------
/// <summary>
/// Return true if line number information is recorded in the cache.
/// </summary>
public bool HasLineInfo() {
return this.pageCurrent[this.idxCurrent].Document.HasLineInfo;
}
/// <summary>
/// Return the source line number of the current node.
/// </summary>
public int LineNumber {
get {
// If the current node is a collapsed text node, then return parent element's line number
if (this.idxParent != 0 && NodeType == XPathNodeType.Text)
return this.pageParent[this.idxParent].LineNumber;
return this.pageCurrent[this.idxCurrent].LineNumber;
}
}
/// <summary>
/// Return the source line position of the current node.
/// </summary>
public int LinePosition {
get {
// If the current node is a collapsed text node, then get position from parent element
if (this.idxParent != 0 && NodeType == XPathNodeType.Text)
return this.pageParent[this.idxParent].CollapsedLinePosition;
return this.pageCurrent[this.idxCurrent].LinePosition;
}
}
//-----------------------------------------------
// Helper methods
//-----------------------------------------------
/// <summary>
/// Get hashcode based on current position of the navigator.
/// </summary>
public int GetPositionHashCode() {
return this.idxCurrent ^ this.idxParent;
}
/// <summary>
/// Return true if navigator is positioned to an element having the specified name.
/// </summary>
public bool IsElementMatch(string localName, string namespaceURI) {
if ((object) localName != (object) this.atomizedLocalName)
this.atomizedLocalName = (localName != null) ? NameTable.Get(localName) : null;
// Cannot be an element if parent is stored
if (this.idxParent != 0)
return false;
return this.pageCurrent[this.idxCurrent].ElementMatch(this.atomizedLocalName, namespaceURI);
}
/// <summary>
/// Return true if navigator is positioned to a content node of the specified kind. Whitespace/SignficantWhitespace/Text are
/// all treated the same (i.e. they all match each other).
/// </summary>
public bool IsContentKindMatch(XPathNodeType typ) {
return (((1 << (int) this.pageCurrent[this.idxCurrent].NodeType) & GetContentKindMask(typ)) != 0);
}
/// <summary>
/// Return true if navigator is positioned to a node of the specified kind. Whitespace/SignficantWhitespace/Text are
/// all treated the same (i.e. they all match each other).
/// </summary>
public bool IsKindMatch(XPathNodeType typ) {
return (((1 << (int) this.pageCurrent[this.idxCurrent].NodeType) & GetKindMask(typ)) != 0);
}
/// <summary>
/// "end" is positioned on a node which terminates a following scan. Return the page and index of "end" if it
/// is positioned to a non-virtual node. If "end" is positioned to a virtual node:
/// 1. If useParentOfVirtual is true, then return the page and index of the virtual node's parent
/// 2. If useParentOfVirtual is false, then return the page and index of the virtual node's parent + 1.
/// </summary>
private int GetFollowingEnd(XPathDocumentNavigator end, bool useParentOfVirtual, out XPathNode[] pageEnd) {
// If ending navigator is positioned to a node in another document, then return null
if (end != null && this.pageCurrent[this.idxCurrent].Document == end.pageCurrent[end.idxCurrent].Document) {
// If the ending navigator is not positioned on a virtual node, then return its current node
if (end.idxParent == 0) {
pageEnd = end.pageCurrent;
return end.idxCurrent;
}
// If the ending navigator is positioned on an attribute, namespace, or virtual text node, then use the
// next physical node instead, as the results will be the same.
pageEnd = end.pageParent;
return (useParentOfVirtual) ? end.idxParent : end.idxParent + 1;
}
// No following, so set pageEnd to null and return an index of 0
pageEnd = null;
return 0;
}
}
}
| |
//
// Copyright (c) 2004-2016 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// 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 Jaroslaw Kowalski 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.
//
namespace NLog.Targets.Wrappers
{
using System.ComponentModel;
using System.Threading;
using NLog.Common;
using NLog.Internal;
/// <summary>
/// A target that buffers log events and sends them in batches to the wrapped target.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/BufferingWrapper-target">Documentation on NLog Wiki</seealso>
[Target("BufferingWrapper", IsWrapper = true)]
public class BufferingTargetWrapper : WrapperTargetBase
{
private LogEventInfoBuffer buffer;
private Timer flushTimer;
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
public BufferingTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public BufferingTargetWrapper(Target wrappedTarget)
: this(wrappedTarget, 100)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="bufferSize">Size of the buffer.</param>
public BufferingTargetWrapper(Target wrappedTarget, int bufferSize)
: this(wrappedTarget, bufferSize, -1)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="bufferSize">Size of the buffer.</param>
/// <param name="flushTimeout">The flush timeout.</param>
public BufferingTargetWrapper(Target wrappedTarget, int bufferSize, int flushTimeout)
{
this.WrappedTarget = wrappedTarget;
this.BufferSize = bufferSize;
this.FlushTimeout = flushTimeout;
this.SlidingTimeout = true;
}
/// <summary>
/// Gets or sets the number of log events to be buffered.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(100)]
public int BufferSize { get; set; }
/// <summary>
/// Gets or sets the timeout (in milliseconds) after which the contents of buffer will be flushed
/// if there's no write in the specified period of time. Use -1 to disable timed flushes.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(-1)]
public int FlushTimeout { get; set; }
/// <summary>
/// Gets or sets a value indicating whether to use sliding timeout.
/// </summary>
/// <remarks>
/// This value determines how the inactivity period is determined. If sliding timeout is enabled,
/// the inactivity timer is reset after each write, if it is disabled - inactivity timer will
/// count from the first event written to the buffer.
/// </remarks>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(true)]
public bool SlidingTimeout { get; set; }
/// <summary>
/// Flushes pending events in the buffer (if any).
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
AsyncLogEventInfo[] events = this.buffer.GetEventsAndClear();
if (events.Length == 0)
{
this.WrappedTarget.Flush(asyncContinuation);
}
else
{
InternalLogger.Trace("BufferingWrapper '{0}': Flush {1} events async", Name, events.Length);
this.WrappedTarget.WriteAsyncLogEvents(events, ex => this.WrappedTarget.Flush(asyncContinuation));
}
}
/// <summary>
/// Initializes the target.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
this.buffer = new LogEventInfoBuffer(this.BufferSize, false, 0);
InternalLogger.Trace("BufferingWrapper '{0}': start timer", Name);
this.flushTimer = new Timer(this.FlushCallback, null, -1, -1);
}
/// <summary>
/// Closes the target by flushing pending events in the buffer (if any).
/// </summary>
protected override void CloseTarget()
{
base.CloseTarget();
if (this.flushTimer != null)
{
this.flushTimer.Dispose();
this.flushTimer = null;
}
}
/// <summary>
/// Adds the specified log event to the buffer and flushes
/// the buffer in case the buffer gets full.
/// </summary>
/// <param name="logEvent">The log event.</param>
protected override void Write(AsyncLogEventInfo logEvent)
{
this.WrappedTarget.PrecalculateVolatileLayouts(logEvent.LogEvent);
int count = this.buffer.Append(logEvent);
if (count >= this.BufferSize)
{
InternalLogger.Trace("BufferingWrapper '{0}': writing {1} events because of exceeding buffersize ({0}).", Name, count);
AsyncLogEventInfo[] events = this.buffer.GetEventsAndClear();
this.WrappedTarget.WriteAsyncLogEvents(events);
}
else
{
if (this.FlushTimeout > 0)
{
// reset the timer on first item added to the buffer or whenever SlidingTimeout is set to true
if (this.SlidingTimeout || count == 1)
{
this.flushTimer.Change(this.FlushTimeout, -1);
}
}
}
}
private void FlushCallback(object state)
{
lock (this.SyncRoot)
{
if (this.IsInitialized)
{
AsyncLogEventInfo[] events = this.buffer.GetEventsAndClear();
if (events.Length > 0)
{
this.WrappedTarget.WriteAsyncLogEvents(events);
}
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// ------------------------------------------------------------------------------
// Changes to this file must follow the http://aka.ms/api-review process.
// ------------------------------------------------------------------------------
namespace System.Net.NetworkInformation
{
public enum DuplicateAddressDetectionState
{
Deprecated = 3,
Duplicate = 2,
Invalid = 0,
Preferred = 4,
Tentative = 1,
}
public abstract partial class GatewayIPAddressInformation
{
protected GatewayIPAddressInformation() { }
public abstract System.Net.IPAddress Address { get; }
}
public partial class GatewayIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.GatewayIPAddressInformation>, System.Collections.IEnumerable
{
protected internal GatewayIPAddressInformationCollection() { }
public virtual int Count { get { throw null; } }
public virtual bool IsReadOnly { get { throw null; } }
public virtual System.Net.NetworkInformation.GatewayIPAddressInformation this[int index] { get { throw null; } }
public virtual void Add(System.Net.NetworkInformation.GatewayIPAddressInformation address) { }
public virtual void Clear() { }
public virtual bool Contains(System.Net.NetworkInformation.GatewayIPAddressInformation address) { throw null; }
public virtual void CopyTo(System.Net.NetworkInformation.GatewayIPAddressInformation[] array, int offset) { }
public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.GatewayIPAddressInformation> GetEnumerator() { throw null; }
public virtual bool Remove(System.Net.NetworkInformation.GatewayIPAddressInformation address) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public abstract partial class IcmpV4Statistics
{
protected IcmpV4Statistics() { }
public abstract long AddressMaskRepliesReceived { get; }
public abstract long AddressMaskRepliesSent { get; }
public abstract long AddressMaskRequestsReceived { get; }
public abstract long AddressMaskRequestsSent { get; }
public abstract long DestinationUnreachableMessagesReceived { get; }
public abstract long DestinationUnreachableMessagesSent { get; }
public abstract long EchoRepliesReceived { get; }
public abstract long EchoRepliesSent { get; }
public abstract long EchoRequestsReceived { get; }
public abstract long EchoRequestsSent { get; }
public abstract long ErrorsReceived { get; }
public abstract long ErrorsSent { get; }
public abstract long MessagesReceived { get; }
public abstract long MessagesSent { get; }
public abstract long ParameterProblemsReceived { get; }
public abstract long ParameterProblemsSent { get; }
public abstract long RedirectsReceived { get; }
public abstract long RedirectsSent { get; }
public abstract long SourceQuenchesReceived { get; }
public abstract long SourceQuenchesSent { get; }
public abstract long TimeExceededMessagesReceived { get; }
public abstract long TimeExceededMessagesSent { get; }
public abstract long TimestampRepliesReceived { get; }
public abstract long TimestampRepliesSent { get; }
public abstract long TimestampRequestsReceived { get; }
public abstract long TimestampRequestsSent { get; }
}
public abstract partial class IcmpV6Statistics
{
protected IcmpV6Statistics() { }
public abstract long DestinationUnreachableMessagesReceived { get; }
public abstract long DestinationUnreachableMessagesSent { get; }
public abstract long EchoRepliesReceived { get; }
public abstract long EchoRepliesSent { get; }
public abstract long EchoRequestsReceived { get; }
public abstract long EchoRequestsSent { get; }
public abstract long ErrorsReceived { get; }
public abstract long ErrorsSent { get; }
public abstract long MembershipQueriesReceived { get; }
public abstract long MembershipQueriesSent { get; }
public abstract long MembershipReductionsReceived { get; }
public abstract long MembershipReductionsSent { get; }
public abstract long MembershipReportsReceived { get; }
public abstract long MembershipReportsSent { get; }
public abstract long MessagesReceived { get; }
public abstract long MessagesSent { get; }
public abstract long NeighborAdvertisementsReceived { get; }
public abstract long NeighborAdvertisementsSent { get; }
public abstract long NeighborSolicitsReceived { get; }
public abstract long NeighborSolicitsSent { get; }
public abstract long PacketTooBigMessagesReceived { get; }
public abstract long PacketTooBigMessagesSent { get; }
public abstract long ParameterProblemsReceived { get; }
public abstract long ParameterProblemsSent { get; }
public abstract long RedirectsReceived { get; }
public abstract long RedirectsSent { get; }
public abstract long RouterAdvertisementsReceived { get; }
public abstract long RouterAdvertisementsSent { get; }
public abstract long RouterSolicitsReceived { get; }
public abstract long RouterSolicitsSent { get; }
public abstract long TimeExceededMessagesReceived { get; }
public abstract long TimeExceededMessagesSent { get; }
}
public abstract partial class IPAddressInformation
{
protected IPAddressInformation() { }
public abstract System.Net.IPAddress Address { get; }
public abstract bool IsDnsEligible { get; }
public abstract bool IsTransient { get; }
}
public partial class IPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.IPAddressInformation>, System.Collections.IEnumerable
{
internal IPAddressInformationCollection() { }
public virtual int Count { get { throw null; } }
public virtual bool IsReadOnly { get { throw null; } }
public virtual System.Net.NetworkInformation.IPAddressInformation this[int index] { get { throw null; } }
public virtual void Add(System.Net.NetworkInformation.IPAddressInformation address) { }
public virtual void Clear() { }
public virtual bool Contains(System.Net.NetworkInformation.IPAddressInformation address) { throw null; }
public virtual void CopyTo(System.Net.NetworkInformation.IPAddressInformation[] array, int offset) { }
public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.IPAddressInformation> GetEnumerator() { throw null; }
public virtual bool Remove(System.Net.NetworkInformation.IPAddressInformation address) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public abstract partial class IPGlobalProperties
{
protected IPGlobalProperties() { }
public abstract string DhcpScopeName { get; }
public abstract string DomainName { get; }
public abstract string HostName { get; }
public abstract bool IsWinsProxy { get; }
public abstract System.Net.NetworkInformation.NetBiosNodeType NodeType { get; }
public virtual System.IAsyncResult BeginGetUnicastAddresses(System.AsyncCallback callback, object state) { throw null; }
public virtual System.Net.NetworkInformation.UnicastIPAddressInformationCollection EndGetUnicastAddresses(System.IAsyncResult asyncResult) { throw null; }
public abstract System.Net.NetworkInformation.TcpConnectionInformation[] GetActiveTcpConnections();
public abstract System.Net.IPEndPoint[] GetActiveTcpListeners();
public abstract System.Net.IPEndPoint[] GetActiveUdpListeners();
public abstract System.Net.NetworkInformation.IcmpV4Statistics GetIcmpV4Statistics();
public abstract System.Net.NetworkInformation.IcmpV6Statistics GetIcmpV6Statistics();
public static System.Net.NetworkInformation.IPGlobalProperties GetIPGlobalProperties() { throw null; }
public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv4GlobalStatistics();
public abstract System.Net.NetworkInformation.IPGlobalStatistics GetIPv6GlobalStatistics();
public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv4Statistics();
public abstract System.Net.NetworkInformation.TcpStatistics GetTcpIPv6Statistics();
public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv4Statistics();
public abstract System.Net.NetworkInformation.UdpStatistics GetUdpIPv6Statistics();
public virtual System.Net.NetworkInformation.UnicastIPAddressInformationCollection GetUnicastAddresses() { throw null; }
public virtual System.Threading.Tasks.Task<System.Net.NetworkInformation.UnicastIPAddressInformationCollection> GetUnicastAddressesAsync() { throw null; }
}
public abstract partial class IPGlobalStatistics
{
protected IPGlobalStatistics() { }
public abstract int DefaultTtl { get; }
public abstract bool ForwardingEnabled { get; }
public abstract int NumberOfInterfaces { get; }
public abstract int NumberOfIPAddresses { get; }
public abstract int NumberOfRoutes { get; }
public abstract long OutputPacketRequests { get; }
public abstract long OutputPacketRoutingDiscards { get; }
public abstract long OutputPacketsDiscarded { get; }
public abstract long OutputPacketsWithNoRoute { get; }
public abstract long PacketFragmentFailures { get; }
public abstract long PacketReassembliesRequired { get; }
public abstract long PacketReassemblyFailures { get; }
public abstract long PacketReassemblyTimeout { get; }
public abstract long PacketsFragmented { get; }
public abstract long PacketsReassembled { get; }
public abstract long ReceivedPackets { get; }
public abstract long ReceivedPacketsDelivered { get; }
public abstract long ReceivedPacketsDiscarded { get; }
public abstract long ReceivedPacketsForwarded { get; }
public abstract long ReceivedPacketsWithAddressErrors { get; }
public abstract long ReceivedPacketsWithHeadersErrors { get; }
public abstract long ReceivedPacketsWithUnknownProtocol { get; }
}
public abstract partial class IPInterfaceProperties
{
protected IPInterfaceProperties() { }
public abstract System.Net.NetworkInformation.IPAddressInformationCollection AnycastAddresses { get; }
public abstract System.Net.NetworkInformation.IPAddressCollection DhcpServerAddresses { get; }
public abstract System.Net.NetworkInformation.IPAddressCollection DnsAddresses { get; }
public abstract string DnsSuffix { get; }
public abstract System.Net.NetworkInformation.GatewayIPAddressInformationCollection GatewayAddresses { get; }
public abstract bool IsDnsEnabled { get; }
public abstract bool IsDynamicDnsEnabled { get; }
public abstract System.Net.NetworkInformation.MulticastIPAddressInformationCollection MulticastAddresses { get; }
public abstract System.Net.NetworkInformation.UnicastIPAddressInformationCollection UnicastAddresses { get; }
public abstract System.Net.NetworkInformation.IPAddressCollection WinsServersAddresses { get; }
public abstract System.Net.NetworkInformation.IPv4InterfaceProperties GetIPv4Properties();
public abstract System.Net.NetworkInformation.IPv6InterfaceProperties GetIPv6Properties();
}
public abstract partial class IPInterfaceStatistics
{
protected IPInterfaceStatistics() { }
public abstract long BytesReceived { get; }
public abstract long BytesSent { get; }
public abstract long IncomingPacketsDiscarded { get; }
public abstract long IncomingPacketsWithErrors { get; }
public abstract long IncomingUnknownProtocolPackets { get; }
public abstract long NonUnicastPacketsReceived { get; }
public abstract long NonUnicastPacketsSent { get; }
public abstract long OutgoingPacketsDiscarded { get; }
public abstract long OutgoingPacketsWithErrors { get; }
public abstract long OutputQueueLength { get; }
public abstract long UnicastPacketsReceived { get; }
public abstract long UnicastPacketsSent { get; }
}
public abstract partial class IPv4InterfaceStatistics
{
protected IPv4InterfaceStatistics() { }
public abstract long BytesReceived { get; }
public abstract long BytesSent { get; }
public abstract long IncomingPacketsDiscarded { get; }
public abstract long IncomingPacketsWithErrors { get; }
public abstract long IncomingUnknownProtocolPackets { get; }
public abstract long NonUnicastPacketsReceived { get; }
public abstract long NonUnicastPacketsSent { get; }
public abstract long OutgoingPacketsDiscarded { get; }
public abstract long OutgoingPacketsWithErrors { get; }
public abstract long OutputQueueLength { get; }
public abstract long UnicastPacketsReceived { get; }
public abstract long UnicastPacketsSent { get; }
}
public abstract partial class IPv4InterfaceProperties
{
protected IPv4InterfaceProperties() { }
public abstract int Index { get; }
public abstract bool IsAutomaticPrivateAddressingActive { get; }
public abstract bool IsAutomaticPrivateAddressingEnabled { get; }
public abstract bool IsDhcpEnabled { get; }
public abstract bool IsForwardingEnabled { get; }
public abstract int Mtu { get; }
public abstract bool UsesWins { get; }
}
public abstract partial class IPv6InterfaceProperties
{
protected IPv6InterfaceProperties() { }
public abstract int Index { get; }
public abstract int Mtu { get; }
public virtual long GetScopeId(System.Net.NetworkInformation.ScopeLevel scopeLevel) { throw null; }
}
public abstract partial class MulticastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation
{
protected MulticastIPAddressInformation() { }
public abstract long AddressPreferredLifetime { get; }
public abstract long AddressValidLifetime { get; }
public abstract long DhcpLeaseLifetime { get; }
public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; }
public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; }
public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; }
}
public partial class MulticastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.MulticastIPAddressInformation>, System.Collections.IEnumerable
{
protected internal MulticastIPAddressInformationCollection() { }
public virtual int Count { get { throw null; } }
public virtual bool IsReadOnly { get { throw null; } }
public virtual System.Net.NetworkInformation.MulticastIPAddressInformation this[int index] { get { throw null; } }
public virtual void Add(System.Net.NetworkInformation.MulticastIPAddressInformation address) { }
public virtual void Clear() { }
public virtual bool Contains(System.Net.NetworkInformation.MulticastIPAddressInformation address) { throw null; }
public virtual void CopyTo(System.Net.NetworkInformation.MulticastIPAddressInformation[] array, int offset) { }
public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.MulticastIPAddressInformation> GetEnumerator() { throw null; }
public virtual bool Remove(System.Net.NetworkInformation.MulticastIPAddressInformation address) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
public enum NetBiosNodeType
{
Broadcast = 1,
Hybrid = 8,
Mixed = 4,
Peer2Peer = 2,
Unknown = 0,
}
public delegate void NetworkAddressChangedEventHandler(object sender, System.EventArgs e);
public delegate void NetworkAvailabilityChangedEventHandler(object sender, System.Net.NetworkInformation.NetworkAvailabilityEventArgs e);
public partial class NetworkAvailabilityEventArgs : System.EventArgs
{
internal NetworkAvailabilityEventArgs() { }
public bool IsAvailable { get { throw null; } }
}
public partial class NetworkChange
{
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
public NetworkChange() { }
public static event System.Net.NetworkInformation.NetworkAddressChangedEventHandler NetworkAddressChanged { add { } remove { } }
public static event System.Net.NetworkInformation.NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged { add { } remove { } }
[System.ComponentModel.EditorBrowsableAttribute((System.ComponentModel.EditorBrowsableState)(1))]
[System.ObsoleteAttribute("This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.", true)]
public static void RegisterNetworkChange(System.Net.NetworkInformation.NetworkChange nc) { }
}
public partial class NetworkInformationException : System.ComponentModel.Win32Exception
{
public NetworkInformationException() { }
public NetworkInformationException(int errorCode) { }
protected NetworkInformationException(System.Runtime.Serialization.SerializationInfo serializationInfo, System.Runtime.Serialization.StreamingContext streamingContext) { }
public override int ErrorCode { get { throw null; } }
}
public abstract partial class NetworkInterface
{
protected NetworkInterface() { }
public virtual string Description { get { throw null; } }
public virtual string Id { get { throw null; } }
public static int IPv6LoopbackInterfaceIndex { get { throw null; } }
public virtual bool IsReceiveOnly { get { throw null; } }
public static int LoopbackInterfaceIndex { get { throw null; } }
public virtual string Name { get { throw null; } }
public virtual System.Net.NetworkInformation.NetworkInterfaceType NetworkInterfaceType { get { throw null; } }
public virtual System.Net.NetworkInformation.OperationalStatus OperationalStatus { get { throw null; } }
public virtual long Speed { get { throw null; } }
public virtual bool SupportsMulticast { get { throw null; } }
public static System.Net.NetworkInformation.NetworkInterface[] GetAllNetworkInterfaces() { throw null; }
public virtual System.Net.NetworkInformation.IPInterfaceProperties GetIPProperties() { throw null; }
public virtual System.Net.NetworkInformation.IPInterfaceStatistics GetIPStatistics() { throw null; }
public virtual System.Net.NetworkInformation.IPv4InterfaceStatistics GetIPv4Statistics() { throw null; }
public static bool GetIsNetworkAvailable() { throw null; }
public virtual System.Net.NetworkInformation.PhysicalAddress GetPhysicalAddress() { throw null; }
public virtual bool Supports(System.Net.NetworkInformation.NetworkInterfaceComponent networkInterfaceComponent) { throw null; }
}
public enum NetworkInterfaceComponent
{
IPv4 = 0,
IPv6 = 1,
}
public enum NetworkInterfaceType
{
AsymmetricDsl = 94,
Atm = 37,
BasicIsdn = 20,
Ethernet = 6,
Ethernet3Megabit = 26,
FastEthernetFx = 69,
FastEthernetT = 62,
Fddi = 15,
GenericModem = 48,
GigabitEthernet = 117,
HighPerformanceSerialBus = 144,
IPOverAtm = 114,
Isdn = 63,
Loopback = 24,
MultiRateSymmetricDsl = 143,
Ppp = 23,
PrimaryIsdn = 21,
RateAdaptDsl = 95,
Slip = 28,
SymmetricDsl = 96,
TokenRing = 9,
Tunnel = 131,
Unknown = 1,
VeryHighSpeedDsl = 97,
Wireless80211 = 71,
Wman = 237,
Wwanpp = 243,
Wwanpp2 = 244,
}
public enum OperationalStatus
{
Dormant = 5,
Down = 2,
LowerLayerDown = 7,
NotPresent = 6,
Testing = 3,
Unknown = 4,
Up = 1,
}
public partial class PhysicalAddress
{
public static readonly System.Net.NetworkInformation.PhysicalAddress None;
public PhysicalAddress(byte[] address) { }
public override bool Equals(object comparand) { throw null; }
public byte[] GetAddressBytes() { throw null; }
public override int GetHashCode() { throw null; }
public static System.Net.NetworkInformation.PhysicalAddress Parse(string address) { throw null; }
public override string ToString() { throw null; }
}
public enum PrefixOrigin
{
Dhcp = 3,
Manual = 1,
Other = 0,
RouterAdvertisement = 4,
WellKnown = 2,
}
public enum ScopeLevel
{
Admin = 4,
Global = 14,
Interface = 1,
Link = 2,
None = 0,
Organization = 8,
Site = 5,
Subnet = 3,
}
public enum SuffixOrigin
{
LinkLayerAddress = 4,
Manual = 1,
OriginDhcp = 3,
Other = 0,
Random = 5,
WellKnown = 2,
}
public abstract partial class TcpConnectionInformation
{
protected TcpConnectionInformation() { }
public abstract System.Net.IPEndPoint LocalEndPoint { get; }
public abstract System.Net.IPEndPoint RemoteEndPoint { get; }
public abstract System.Net.NetworkInformation.TcpState State { get; }
}
public enum TcpState
{
Closed = 1,
CloseWait = 8,
Closing = 9,
DeleteTcb = 12,
Established = 5,
FinWait1 = 6,
FinWait2 = 7,
LastAck = 10,
Listen = 2,
SynReceived = 4,
SynSent = 3,
TimeWait = 11,
Unknown = 0,
}
public abstract partial class TcpStatistics
{
protected TcpStatistics() { }
public abstract long ConnectionsAccepted { get; }
public abstract long ConnectionsInitiated { get; }
public abstract long CumulativeConnections { get; }
public abstract long CurrentConnections { get; }
public abstract long ErrorsReceived { get; }
public abstract long FailedConnectionAttempts { get; }
public abstract long MaximumConnections { get; }
public abstract long MaximumTransmissionTimeout { get; }
public abstract long MinimumTransmissionTimeout { get; }
public abstract long ResetConnections { get; }
public abstract long ResetsSent { get; }
public abstract long SegmentsReceived { get; }
public abstract long SegmentsResent { get; }
public abstract long SegmentsSent { get; }
}
public abstract partial class UdpStatistics
{
protected UdpStatistics() { }
public abstract long DatagramsReceived { get; }
public abstract long DatagramsSent { get; }
public abstract long IncomingDatagramsDiscarded { get; }
public abstract long IncomingDatagramsWithErrors { get; }
public abstract int UdpListeners { get; }
}
public abstract partial class UnicastIPAddressInformation : System.Net.NetworkInformation.IPAddressInformation
{
protected UnicastIPAddressInformation() { }
public abstract long AddressPreferredLifetime { get; }
public abstract long AddressValidLifetime { get; }
public abstract long DhcpLeaseLifetime { get; }
public abstract System.Net.NetworkInformation.DuplicateAddressDetectionState DuplicateAddressDetectionState { get; }
public abstract System.Net.IPAddress IPv4Mask { get; }
public virtual int PrefixLength { get { throw null; } }
public abstract System.Net.NetworkInformation.PrefixOrigin PrefixOrigin { get; }
public abstract System.Net.NetworkInformation.SuffixOrigin SuffixOrigin { get; }
}
public partial class UnicastIPAddressInformationCollection : System.Collections.Generic.ICollection<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.Generic.IEnumerable<System.Net.NetworkInformation.UnicastIPAddressInformation>, System.Collections.IEnumerable
{
protected internal UnicastIPAddressInformationCollection() { }
public virtual int Count { get { throw null; } }
public virtual bool IsReadOnly { get { throw null; } }
public virtual System.Net.NetworkInformation.UnicastIPAddressInformation this[int index] { get { throw null; } }
public virtual void Add(System.Net.NetworkInformation.UnicastIPAddressInformation address) { }
public virtual void Clear() { }
public virtual bool Contains(System.Net.NetworkInformation.UnicastIPAddressInformation address) { throw null; }
public virtual void CopyTo(System.Net.NetworkInformation.UnicastIPAddressInformation[] array, int offset) { }
public virtual System.Collections.Generic.IEnumerator<System.Net.NetworkInformation.UnicastIPAddressInformation> GetEnumerator() { throw null; }
public virtual bool Remove(System.Net.NetworkInformation.UnicastIPAddressInformation address) { throw null; }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; }
}
}
| |
//
// ExtendedContentDescriptionObject.cs: Provides a representation of an ASF
// Extended Content Description object which can be read from and written to
// disk.
//
// Author:
// Brian Nickel (brian.nickel@gmail.com)
//
// Copyright (C) 2006-2007 Brian Nickel
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
using System;
using System.Collections.Generic;
namespace TagLib.Asf {
/// <summary>
/// This class extends <see cref="Object" /> to provide a
/// representation of an ASF Extended Content Description object
/// which can be read from and written to disk.
/// </summary>
public class ExtendedContentDescriptionObject : Object,
IEnumerable<ContentDescriptor>
{
#region Private Fields
/// <summary>
/// Contains the content descriptors.
/// </summary>
private List<ContentDescriptor> descriptors =
new List<ContentDescriptor> ();
#endregion
#region Constructors
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="ExtendedContentDescriptionObject" /> by reading the
/// contents from a specified position in a specified file.
/// </summary>
/// <param name="file">
/// A <see cref="Asf.File" /> object containing the file from
/// which the contents of the new instance are to be read.
/// </param>
/// <param name="position">
/// A <see cref="long" /> value specify at what position to
/// read the object.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="file" /> is <see langword="null" />.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">
/// <paramref name="position" /> is less than zero or greater
/// than the size of the file.
/// </exception>
/// <exception cref="CorruptFileException">
/// The object read from disk does not have the correct GUID
/// or smaller than the minimum size.
/// </exception>
public ExtendedContentDescriptionObject (Asf.File file,
long position)
: base (file, position)
{
if (!Guid.Equals (
Asf.Guid.AsfExtendedContentDescriptionObject))
throw new CorruptFileException (
"Object GUID incorrect.");
if (OriginalSize < 26)
throw new CorruptFileException (
"Object size too small.");
ushort count = file.ReadWord ();
for (ushort i = 0; i < count; i ++)
AddDescriptor (new ContentDescriptor (file));
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="ExtendedContentDescriptionObject" /> with no
/// contents.
/// </summary>
public ExtendedContentDescriptionObject ()
: base (Asf.Guid.AsfExtendedContentDescriptionObject)
{
}
#endregion
#region Public Properties
/// <summary>
/// Gets whether or not the current instance is empty.
/// </summary>
/// <value>
/// <see langword="true" /> if the current instance doesn't
/// contain any <see cref="ContentDescriptor" /> objects.
/// Otherwise <see langword="false" />.
/// </value>
public bool IsEmpty {
get {return descriptors.Count == 0;}
}
#endregion
#region Public Methods
/// <summary>
/// Renders the current instance as a raw ASF object.
/// </summary>
/// <returns>
/// A <see cref="ByteVector" /> object containing the
/// rendered version of the current instance.
/// </returns>
public override ByteVector Render ()
{
ByteVector output = new ByteVector ();
ushort count = 0;
foreach (ContentDescriptor desc in descriptors) {
count ++;
output.Add (desc.Render ());
}
return Render (RenderWord (count) + output);
}
/// <summary>
/// Removes all descriptors with a given name from the
/// current instance.
/// </summary>
/// <param name="name">
/// A <see cref="string" /> object containing the name of the
/// descriptors to be removed.
/// </param>
public void RemoveDescriptors (string name)
{
for (int i = descriptors.Count - 1; i >= 0; i --)
if (name == descriptors [i].Name)
descriptors.RemoveAt (i);
}
/// <summary>
/// Gets all descriptors with any of a collection of names
/// from the current instance.
/// </summary>
/// <param name="names">
/// A <see cref="string[]" /> containing the names of the
/// descriptors to be retrieved.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="names" /> is <see langword="null" />.
/// </exception>
/// <returns>
/// A <see cref="T:System.Collections.Generic.IEnumerable`1" /> object enumerating
/// through the <see cref="ContentDescriptor" /> objects
/// retrieved from the current instance.
/// </returns>
public IEnumerable<ContentDescriptor> GetDescriptors (params string [] names)
{
if (names == null)
throw new ArgumentNullException ("names");
foreach (string name in names)
foreach (ContentDescriptor desc in descriptors)
if (desc.Name == name)
yield return desc;
}
/// <summary>
/// Adds a descriptor to the current instance.
/// </summary>
/// <param name="descriptor">
/// A <see cref="ContentDescriptor" /> object to add to the
/// current instance.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="descriptor" /> is <see langword="null"
/// />.
/// </exception>
public void AddDescriptor (ContentDescriptor descriptor)
{
if (descriptor == null)
throw new ArgumentNullException ("descriptor");
descriptors.Add (descriptor);
}
/// <summary>
/// Sets the a collection of desciptors for a given name,
/// removing the existing matching records.
/// </summary>
/// <param name="name">
/// A <see cref="string" /> object containing the name of the
/// descriptors to be added.
/// </param>
/// <param name="descriptors">
/// A <see cref="ContentDescriptor[]" /> containing
/// descriptors to add to the new instance.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="name" /> is <see langword="null" />.
/// </exception>
/// <remarks>
/// All added entries in <paramref name="descriptors" />
/// should match <paramref name="name" /> but it is not
/// verified by the method. The descriptors will be added
/// with their own names and not the one provided in this
/// method, which are used for removing existing values and
/// determining where to position the new objects.
/// </remarks>
public void SetDescriptors (string name,
params ContentDescriptor [] descriptors)
{
if (name == null)
throw new ArgumentNullException ("name");
int position = this.descriptors.Count;
for (int i = this.descriptors.Count - 1; i >= 0; i --) {
if (name == this.descriptors [i].Name) {
this.descriptors.RemoveAt (i);
position = i;
}
}
this.descriptors.InsertRange (position, descriptors);
}
#endregion
#region IEnumerable
/// <summary>
/// Gets an enumerator for enumerating through the content
/// descriptors.
/// </summary>
/// <returns>
/// A <see cref="T:System.Collections.IEnumerator`1" /> for
/// enumerating through the content descriptors.
/// </returns>
public IEnumerator<ContentDescriptor> GetEnumerator ()
{
return descriptors.GetEnumerator ();
}
System.Collections.IEnumerator
System.Collections.IEnumerable.GetEnumerator ()
{
return descriptors.GetEnumerator ();
}
#endregion
}
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Collections;
using System.IO;
using System.Linq;
using System.Management.Automation.Internal;
using System.Management.Automation.Language;
using System.Threading;
namespace System.Management.Automation
{
/// <summary>
/// Holds the information for a given breakpoint.
/// </summary>
public abstract class Breakpoint
{
#region properties
/// <summary>
/// The action to take when the breakpoint is hit.
/// </summary>
public ScriptBlock Action { get; }
/// <summary>
/// Gets whether this breakpoint is enabled.
/// </summary>
public bool Enabled { get; private set; }
internal void SetEnabled(bool value)
{
Enabled = value;
}
/// <summary>
/// Records how many times this breakpoint has been triggered.
/// </summary>
public int HitCount { get; private set; }
/// <summary>
/// This breakpoint's Id.
/// </summary>
public int Id { get; }
/// <summary>
/// True if breakpoint is set on a script, false if the breakpoint is not scoped.
/// </summary>
internal bool IsScriptBreakpoint
{
get { return Script != null; }
}
/// <summary>
/// The script this breakpoint is on, or null if the breakpoint is not scoped.
/// </summary>
public string Script { get; }
#endregion properties
#region constructors
/// <summary>
/// Creates a new instance of a <see cref="Breakpoint"/>
/// </summary>
protected Breakpoint(string script)
: this(script, null)
{ }
/// <summary>
/// Creates a new instance of a <see cref="Breakpoint"/>
/// </summary>
protected Breakpoint(string script, ScriptBlock action)
{
Enabled = true;
Script = string.IsNullOrEmpty(script) ? null : script;
Id = Interlocked.Increment(ref s_lastID);
Action = action;
HitCount = 0;
}
/// <summary>
/// Creates a new instance of a <see cref="Breakpoint"/>
/// </summary>
protected Breakpoint(string script, int id)
: this(script, null, id)
{ }
/// <summary>
/// Creates a new instance of a <see cref="Breakpoint"/>
/// </summary>
protected Breakpoint(string script, ScriptBlock action, int id)
{
Enabled = true;
Script = string.IsNullOrEmpty(script) ? null : script;
Id = id;
Action = action;
HitCount = 0;
}
#endregion constructors
#region methods
internal BreakpointAction Trigger()
{
++HitCount;
if (Action == null)
{
return BreakpointAction.Break;
}
try
{
// Pass this to the action so the breakpoint. This could be used to
// implement a "trigger once" breakpoint that disables itself after first hit.
// One could also share an action across many breakpoints - and hence needs
// to know something about the breakpoint that is hit, e.g. in a poor mans code coverage tool.
Action.DoInvoke(dollarUnder: this, input: null, args: Array.Empty<object>());
}
catch (BreakException)
{
return BreakpointAction.Break;
}
catch (Exception)
{
}
return BreakpointAction.Continue;
}
internal virtual bool RemoveSelf(ScriptDebugger debugger) => false;
#endregion methods
#region enums
internal enum BreakpointAction
{
Continue = 0x0,
Break = 0x1
}
#endregion enums
#region private members
private static int s_lastID;
#endregion private members
}
/// <summary>
/// A breakpoint on a command.
/// </summary>
public class CommandBreakpoint : Breakpoint
{
/// <summary>
/// Creates a new instance of a <see cref="CommandBreakpoint"/>
/// </summary>
public CommandBreakpoint(string script, WildcardPattern command, string commandString)
: this(script, command, commandString, null)
{ }
/// <summary>
/// Creates a new instance of a <see cref="CommandBreakpoint"/>
/// </summary>
public CommandBreakpoint(string script, WildcardPattern command, string commandString, ScriptBlock action)
: base(script, action)
{
CommandPattern = command;
Command = commandString;
}
/// <summary>
/// Creates a new instance of a <see cref="CommandBreakpoint"/>
/// </summary>
public CommandBreakpoint(string script, WildcardPattern command, string commandString, int id)
: this(script, command, commandString, null, id)
{ }
/// <summary>
/// Creates a new instance of a <see cref="CommandBreakpoint"/>
/// </summary>
public CommandBreakpoint(string script, WildcardPattern command, string commandString, ScriptBlock action, int id)
: base(script, action, id)
{
CommandPattern = command;
Command = commandString;
}
/// <summary>
/// Which command this breakpoint is on.
/// </summary>
public string Command { get; }
internal WildcardPattern CommandPattern { get; }
/// <summary>
/// Gets a string representation of this breakpoint.
/// </summary>
/// <returns>A string representation of this breakpoint.</returns>
public override string ToString()
{
return IsScriptBreakpoint
? StringUtil.Format(DebuggerStrings.CommandScriptBreakpointString, Script, Command)
: StringUtil.Format(DebuggerStrings.CommandBreakpointString, Command);
}
internal override bool RemoveSelf(ScriptDebugger debugger) =>
debugger.RemoveCommandBreakpoint(this);
private bool CommandInfoMatches(CommandInfo commandInfo)
{
if (commandInfo == null)
return false;
if (CommandPattern.IsMatch(commandInfo.Name))
return true;
// If the breakpoint looks like it might have specified a module name and the command
// we're checking is in a module, try matching the module\command against the pattern
// in the breakpoint.
if (!string.IsNullOrEmpty(commandInfo.ModuleName) && Command.Contains('\\'))
{
if (CommandPattern.IsMatch(commandInfo.ModuleName + "\\" + commandInfo.Name))
return true;
}
var externalScript = commandInfo as ExternalScriptInfo;
if (externalScript != null)
{
if (externalScript.Path.Equals(Command, StringComparison.OrdinalIgnoreCase))
return true;
if (CommandPattern.IsMatch(Path.GetFileNameWithoutExtension(externalScript.Path)))
return true;
}
return false;
}
internal bool Trigger(InvocationInfo invocationInfo)
{
// invocationInfo.MyCommand can be null when invoked via ScriptBlock.Invoke()
if (CommandPattern.IsMatch(invocationInfo.InvocationName) || CommandInfoMatches(invocationInfo.MyCommand))
{
return (Script == null || Script.Equals(invocationInfo.ScriptName, StringComparison.OrdinalIgnoreCase));
}
return false;
}
}
/// <summary>
/// The access type for variable breakpoints to break on.
/// </summary>
public enum VariableAccessMode
{
/// <summary>
/// Break on read access only.
/// </summary>
Read,
/// <summary>
/// Break on write access only (default).
/// </summary>
Write,
/// <summary>
/// Breakon read or write access.
/// </summary>
ReadWrite
}
/// <summary>
/// A breakpoint on a variable.
/// </summary>
public class VariableBreakpoint : Breakpoint
{
/// <summary>
/// Creates a new instance of a <see cref="VariableBreakpoint"/>.
/// </summary>
public VariableBreakpoint(string script, string variable, VariableAccessMode accessMode)
: this(script, variable, accessMode, null)
{ }
/// <summary>
/// Creates a new instance of a <see cref="VariableBreakpoint"/>.
/// </summary>
public VariableBreakpoint(string script, string variable, VariableAccessMode accessMode, ScriptBlock action)
: base(script, action)
{
Variable = variable;
AccessMode = accessMode;
}
/// <summary>
/// Creates a new instance of a <see cref="VariableBreakpoint"/>.
/// </summary>
public VariableBreakpoint(string script, string variable, VariableAccessMode accessMode, int id)
: this(script, variable, accessMode, null, id)
{ }
/// <summary>
/// Creates a new instance of a <see cref="VariableBreakpoint"/>.
/// </summary>
public VariableBreakpoint(string script, string variable, VariableAccessMode accessMode, ScriptBlock action, int id)
: base(script, action, id)
{
Variable = variable;
AccessMode = accessMode;
}
/// <summary>
/// The access mode to trigger this variable breakpoint on.
/// </summary>
public VariableAccessMode AccessMode { get; }
/// <summary>
/// Which variable this breakpoint is on.
/// </summary>
public string Variable { get; }
/// <summary>
/// Gets the string representation of this breakpoint.
/// </summary>
/// <returns>The string representation of this breakpoint.</returns>
public override string ToString()
{
return IsScriptBreakpoint
? StringUtil.Format(DebuggerStrings.VariableScriptBreakpointString, Script, Variable, AccessMode)
: StringUtil.Format(DebuggerStrings.VariableBreakpointString, Variable, AccessMode);
}
internal bool Trigger(string currentScriptFile, bool read)
{
if (!Enabled)
return false;
if (AccessMode != VariableAccessMode.ReadWrite && AccessMode != (read ? VariableAccessMode.Read : VariableAccessMode.Write))
return false;
if (Script == null || Script.Equals(currentScriptFile, StringComparison.OrdinalIgnoreCase))
{
return Trigger() == BreakpointAction.Break;
}
return false;
}
internal override bool RemoveSelf(ScriptDebugger debugger) =>
debugger.RemoveVariableBreakpoint(this);
}
/// <summary>
/// A breakpoint on a line or statement.
/// </summary>
public class LineBreakpoint : Breakpoint
{
/// <summary>
/// Creates a new instance of a <see cref="LineBreakpoint"/>
/// </summary>
public LineBreakpoint(string script, int line)
: this(script, line, null)
{ }
/// <summary>
/// Creates a new instance of a <see cref="LineBreakpoint"/>
/// </summary>
public LineBreakpoint(string script, int line, ScriptBlock action)
: base(script, action)
{
Diagnostics.Assert(!string.IsNullOrEmpty(script), "Caller to verify script parameter is not null or empty.");
Line = line;
Column = 0;
SequencePointIndex = -1;
}
/// <summary>
/// Creates a new instance of a <see cref="LineBreakpoint"/>
/// </summary>
public LineBreakpoint(string script, int line, int column)
: this(script, line, column, null)
{ }
/// <summary>
/// Creates a new instance of a <see cref="LineBreakpoint"/>
/// </summary>
public LineBreakpoint(string script, int line, int column, ScriptBlock action)
: base(script, action)
{
Diagnostics.Assert(!string.IsNullOrEmpty(script), "Caller to verify script parameter is not null or empty.");
Line = line;
Column = column;
SequencePointIndex = -1;
}
/// <summary>
/// Creates a new instance of a <see cref="LineBreakpoint"/>
/// </summary>
public LineBreakpoint(string script, int line, int column, int id)
: this(script, line, column, null, id)
{ }
/// <summary>
/// Creates a new instance of a <see cref="LineBreakpoint"/>
/// </summary>
public LineBreakpoint(string script, int line, int column, ScriptBlock action, int id)
: base(script, action, id)
{
Diagnostics.Assert(!string.IsNullOrEmpty(script), "Caller to verify script parameter is not null or empty.");
Line = line;
Column = column;
SequencePointIndex = -1;
}
/// <summary>
/// Which column this breakpoint is on.
/// </summary>
public int Column { get; }
/// <summary>
/// Which line this breakpoint is on.
/// </summary>
public int Line { get; }
/// <summary>
/// Gets a string representation of this breakpoint.
/// </summary>
/// <returns>A string representation of this breakpoint.</returns>
public override string ToString()
{
return Column == 0
? StringUtil.Format(DebuggerStrings.LineBreakpointString, Script, Line)
: StringUtil.Format(DebuggerStrings.StatementBreakpointString, Script, Line, Column);
}
internal int SequencePointIndex { get; set; }
internal IScriptExtent[] SequencePoints { get; set; }
internal BitArray BreakpointBitArray { get; set; }
private sealed class CheckBreakpointInScript : AstVisitor
{
public static bool IsInNestedScriptBlock(Ast ast, LineBreakpoint breakpoint)
{
var visitor = new CheckBreakpointInScript { _breakpoint = breakpoint };
ast.InternalVisit(visitor);
return visitor._result;
}
private LineBreakpoint _breakpoint;
private bool _result;
public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst)
{
if (functionDefinitionAst.Extent.ContainsLineAndColumn(_breakpoint.Line, _breakpoint.Column))
{
_result = true;
return AstVisitAction.StopVisit;
}
// We don't need to visit the body, we're just checking extents of the topmost functions.
// We'll visit the bodies eventually, but only when the nested function/script is executed.
return AstVisitAction.SkipChildren;
}
public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst)
{
if (scriptBlockExpressionAst.Extent.ContainsLineAndColumn(_breakpoint.Line, _breakpoint.Column))
{
_result = true;
return AstVisitAction.StopVisit;
}
// We don't need to visit the body, we're just checking extents of the topmost functions.
// We'll visit the bodies eventually, but only when the nested function/script is executed.
return AstVisitAction.SkipChildren;
}
}
internal bool TrySetBreakpoint(string scriptFile, FunctionContext functionContext)
{
Diagnostics.Assert(SequencePointIndex == -1, "shouldn't be trying to set on a pending breakpoint");
if (!scriptFile.Equals(this.Script, StringComparison.OrdinalIgnoreCase))
return false;
// A quick check to see if the breakpoint is within the scriptblock.
bool couldBeInNestedScriptBlock;
var scriptBlock = functionContext._scriptBlock;
if (scriptBlock != null)
{
var ast = scriptBlock.Ast;
if (!ast.Extent.ContainsLineAndColumn(Line, Column))
return false;
var sequencePoints = functionContext._sequencePoints;
if (sequencePoints.Length == 1 && sequencePoints[0] == scriptBlock.Ast.Extent)
{
// If there was no real executable code in the function (e.g. only function definitions),
// we added the entire scriptblock as a sequence point, but it shouldn't be allowed as a breakpoint.
return false;
}
couldBeInNestedScriptBlock = CheckBreakpointInScript.IsInNestedScriptBlock(((IParameterMetadataProvider)ast).Body, this);
}
else
{
couldBeInNestedScriptBlock = false;
}
int sequencePointIndex;
var sequencePoint = FindSequencePoint(functionContext, Line, Column, out sequencePointIndex);
if (sequencePoint != null)
{
// If the bp could be in a nested script block, we want to be careful and get the bp in the correct script block.
// If it's a simple line bp (no column specified), then the start line must match the bp line exactly, otherwise
// we assume the bp is in the nested script block.
if (!couldBeInNestedScriptBlock || (sequencePoint.StartLineNumber == Line && Column == 0))
{
SetBreakpoint(functionContext, sequencePointIndex);
return true;
}
}
// Before using heuristics, make sure the breakpoint isn't in a nested function/script block.
if (couldBeInNestedScriptBlock)
{
return false;
}
// Not found. First, we check if the line/column is before any real code. If so, we'll
// move the breakpoint to the first interesting sequence point (could be a dynamicparam,
// begin, process, end, or clean block.)
if (scriptBlock != null)
{
var ast = scriptBlock.Ast;
var bodyAst = ((IParameterMetadataProvider)ast).Body;
if ((bodyAst.DynamicParamBlock == null || bodyAst.DynamicParamBlock.Extent.IsAfter(Line, Column))
&& (bodyAst.BeginBlock == null || bodyAst.BeginBlock.Extent.IsAfter(Line, Column))
&& (bodyAst.ProcessBlock == null || bodyAst.ProcessBlock.Extent.IsAfter(Line, Column))
&& (bodyAst.EndBlock == null || bodyAst.EndBlock.Extent.IsAfter(Line, Column))
&& (bodyAst.CleanBlock == null || bodyAst.CleanBlock.Extent.IsAfter(Line, Column)))
{
SetBreakpoint(functionContext, 0);
return true;
}
}
// Still not found. Try fudging a bit, but only if it's a simple line breakpoint.
if (Column == 0 && FindSequencePoint(functionContext, Line + 1, 0, out sequencePointIndex) != null)
{
SetBreakpoint(functionContext, sequencePointIndex);
return true;
}
return false;
}
private static IScriptExtent FindSequencePoint(FunctionContext functionContext, int line, int column, out int sequencePointIndex)
{
var sequencePoints = functionContext._sequencePoints;
for (int i = 0; i < sequencePoints.Length; ++i)
{
var extent = sequencePoints[i];
if (extent.ContainsLineAndColumn(line, column))
{
sequencePointIndex = i;
return extent;
}
}
sequencePointIndex = -1;
return null;
}
private void SetBreakpoint(FunctionContext functionContext, int sequencePointIndex)
{
// Remember the bitarray so we when the last breakpoint is removed, we can avoid
// stopping at the sequence point.
this.BreakpointBitArray = functionContext._breakPoints;
this.SequencePoints = functionContext._sequencePoints;
SequencePointIndex = sequencePointIndex;
this.BreakpointBitArray.Set(SequencePointIndex, true);
}
internal override bool RemoveSelf(ScriptDebugger debugger)
{
if (this.SequencePoints != null)
{
// Remove ourselves from the list of bound breakpoints in this script. It's possible the breakpoint was never
// bound, in which case there is nothing to do.
var boundBreakPoints = debugger.GetBoundBreakpoints(this.SequencePoints);
if (boundBreakPoints != null)
{
Diagnostics.Assert(boundBreakPoints.Contains(this),
"If we set _scriptBlock, we should have also added the breakpoint to the bound breakpoint list");
boundBreakPoints.Remove(this);
if (boundBreakPoints.All(breakpoint => breakpoint.SequencePointIndex != this.SequencePointIndex))
{
// No other line breakpoints are at the same sequence point, so disable the breakpoint so
// we don't go looking for breakpoints the next time we hit the sequence point.
// This isn't strictly necessary, but script execution will be faster.
this.BreakpointBitArray.Set(SequencePointIndex, false);
}
}
}
return debugger.RemoveLineBreakpoint(this);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 CommandLine;
using Google.Ads.GoogleAds.Lib;
using Google.Ads.GoogleAds.V10.Common;
using Google.Ads.GoogleAds.V10.Enums;
using Google.Ads.GoogleAds.V10.Errors;
using Google.Ads.GoogleAds.V10.Resources;
using Google.Ads.GoogleAds.V10.Services;
using Google.Protobuf.Collections;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Google.Ads.GoogleAds.Examples.V10
{
/// <summary>
/// This code example retrieves the full details of a Promotion Feed-based extension and
/// creates a matching Promotion asset-based extension. The new Asset-based extension will
/// then be associated with the same campaigns and ad groups as the original Feed-based
/// extension.
/// Once copied, you should remove the Feed-based extension; see
/// RemoveEntireSitelinkCampaignExtensionSetting.cs for an example.
/// </summary>
public class MigratePromotionFeedToAsset : ExampleBase
{
/// <summary>
/// Command line options for running the <see cref="MigratePromotionFeedToAsset"/> example.
/// </summary>
public class Options : OptionsBase
{
/// <summary>
/// The customer ID for which the call is made.
/// </summary>
[Option("customerId", Required = true, HelpText =
"The customer ID for which the call is made.")]
public long CustomerId { get; set; }
/// <summary>
/// ID of the extension feed item to migrate.
/// </summary>
[Option("feedItemId", Required = true, HelpText =
"ID of the extension feed item to migrate.")]
public long FeedItemId { get; set; }
}
/// <summary>
/// Main method, to run this code example as a standalone application.
/// </summary>
/// <param name="args">The command line arguments.</param>
public static void Main(string[] args)
{
Options options = new Options();
CommandLine.Parser.Default.ParseArguments<Options>(args).MapResult(
delegate (Options o)
{
options = o;
return 0;
}, delegate (IEnumerable<Error> errors)
{
// The customer ID for which the call is made.
options.CustomerId = long.Parse("INSERT_CUSTOMER_ID_HERE");
// ID of the extension feed item to migrate.
options.FeedItemId = long.Parse("INSERT_FEED_ITEM_ID_HERE");
return 0;
});
MigratePromotionFeedToAsset codeExample = new MigratePromotionFeedToAsset();
Console.WriteLine(codeExample.Description);
codeExample.Run(new GoogleAdsClient(), options.CustomerId, options.FeedItemId);
}
/// <summary>
/// Returns a description about the code example.
/// </summary>
public override string Description =>
"This code example retrieves the full details of a Promotion Feed-based extension " +
"and creates a matching Promotion asset-based extension. The new Asset-based " +
"extension will then be associated with the same campaigns and ad groups as the " +
"original Feed-based extension.\n" +
"Once copied, you should remove the Feed-based extension; see " +
"RemoveEntireSitelinkCampaignExtensionSetting.cs for an example.";
/// <summary>
/// Runs the code example.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="feedItemId">ID of the extension feed item to migrate.</param>
public void Run(GoogleAdsClient client, long customerId, long feedItemId)
{
// Get the GoogleAdsService client.
GoogleAdsServiceClient googleAdsServiceClient =
client.GetService(Services.V10.GoogleAdsService);
string extensionFeedItemResourceName =
ResourceNames.ExtensionFeedItem(customerId, feedItemId);
try
{
// Get the target extension feed item.
ExtensionFeedItem extensionFeedItem =
GetExtensionFeedItem(googleAdsServiceClient, customerId, feedItemId);
// Get all campaign IDs associated with the extension feed item.
List<long> campaignIds = GetTargetedCampaignIds(googleAdsServiceClient, customerId,
extensionFeedItemResourceName);
// Get all ad group IDs associated with the extension feed item.
List<long> adGroupIds = GetTargetedAdGroupIds(googleAdsServiceClient, customerId,
extensionFeedItemResourceName);
// Create a new Promotion asset that matches the target extension feed item.
string promotionAssetResourceName = CreatePromotionAssetFromFeed(client,
customerId, extensionFeedItem);
// Associate the new Promotion asset with the same campaigns as the original.
AssociateAssetWithCampaigns(client, customerId, promotionAssetResourceName,
campaignIds);
// Associate the new Promotion asset with the same ad groups as the original.
AssociateAssetWithAdGroups(client, customerId, promotionAssetResourceName,
adGroupIds);
}
catch (GoogleAdsException e)
{
Console.WriteLine("Failure:");
Console.WriteLine($"Message: {e.Message}");
Console.WriteLine($"Failure: {e.Failure}");
Console.WriteLine($"Request ID: {e.RequestId}");
throw;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
throw;
}
}
/// <summary>
/// Gets the requested Promotion-type extension feed item.
///
/// Note that extension feed items pertain to feeds that were created by Google. Use
/// FeedService to instead retrieve a user-created Feed.
/// </summary>
/// <param name="googleAdsServiceClient">An initialized Google Ads API Service
/// client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="feedItemId">ID of the extension feed item to migrate.</param>
/// <returns>The requested ExtensionFeedItem, or null if no matching item was
/// found.</returns>
private ExtensionFeedItem GetExtensionFeedItem(
GoogleAdsServiceClient googleAdsServiceClient,
long customerId, long feedItemId)
{
// Create a query that will retrieve the requested Promotion-type extension feed item
// and ensure that all fields are populated.
string extensionFeedItemQuery = $@"
SELECT
extension_feed_item.id,
extension_feed_item.ad_schedules,
extension_feed_item.device,
extension_feed_item.status,
extension_feed_item.start_date_time,
extension_feed_item.end_date_time,
extension_feed_item.targeted_campaign,
extension_feed_item.targeted_ad_group,
extension_feed_item.promotion_feed_item.discount_modifier,
extension_feed_item.promotion_feed_item.final_mobile_urls,
extension_feed_item.promotion_feed_item.final_url_suffix,
extension_feed_item.promotion_feed_item.final_urls,
extension_feed_item.promotion_feed_item.language_code,
extension_feed_item.promotion_feed_item.money_amount_off.amount_micros,
extension_feed_item.promotion_feed_item.money_amount_off.currency_code,
extension_feed_item.promotion_feed_item.occasion,
extension_feed_item.promotion_feed_item.orders_over_amount.amount_micros,
extension_feed_item.promotion_feed_item.orders_over_amount.currency_code,
extension_feed_item.promotion_feed_item.percent_off,
extension_feed_item.promotion_feed_item.promotion_code,
extension_feed_item.promotion_feed_item.promotion_end_date,
extension_feed_item.promotion_feed_item.promotion_start_date,
extension_feed_item.promotion_feed_item.promotion_target,
extension_feed_item.promotion_feed_item.tracking_url_template
FROM extension_feed_item
WHERE
extension_feed_item.extension_type = 'PROMOTION'
AND extension_feed_item.id = {feedItemId}
LIMIT 1";
ExtensionFeedItem fetchedExtensionFeedItem = null;
// Issue a search request to get the extension feed item contents.
googleAdsServiceClient.SearchStream(customerId.ToString(), extensionFeedItemQuery,
delegate (SearchGoogleAdsStreamResponse response)
{
fetchedExtensionFeedItem = response.Results.First().ExtensionFeedItem;
}
);
Console.WriteLine(
$"Retrieved details for ad extension with ID {fetchedExtensionFeedItem.Id}.");
// Create a query to retrieve any URL customer parameters attached to the feed item.
string urlCustomParametersQuery = $@"
SELECT feed_item.url_custom_parameters
FROM feed_item
WHERE feed_item.id = {feedItemId}";
// Issue a search request to get any URL custom parameters.
googleAdsServiceClient.SearchStream(customerId.ToString(), urlCustomParametersQuery,
delegate (SearchGoogleAdsStreamResponse response)
{
RepeatedField<CustomParameter> urlCustomParameters =
response.Results.First().FeedItem.UrlCustomParameters;
Console.WriteLine(
$"Retrieved {urlCustomParameters.Count} attached URL custom parameters.");
if (urlCustomParameters.Count > 0)
{
fetchedExtensionFeedItem.PromotionFeedItem.UrlCustomParameters.Add(
urlCustomParameters);
}
}
);
return fetchedExtensionFeedItem;
}
/// <summary>
/// Finds and returns all of the campaigns that are associated with the specified Promotion
/// extension feed item.
/// </summary>
/// <param name="googleAdsServiceClient">An initialized Google Ads API Service
/// client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="extensionFeedResourceName">ID of the extension feed item to
/// migrate.</param>
/// <returns>A list of campaign IDs.</returns>
// [START migrate_promotion_feed_to_asset_1]
private List<long> GetTargetedCampaignIds(GoogleAdsServiceClient googleAdsServiceClient,
long customerId, string extensionFeedResourceName)
{
List<long> campaignIds = new List<long>();
string query = @"
SELECT campaign.id, campaign_extension_setting.extension_feed_items
FROM campaign_extension_setting
WHERE campaign_extension_setting.extension_type = 'PROMOTION'
AND campaign.status != 'REMOVED'";
googleAdsServiceClient.SearchStream(customerId.ToString(), query,
delegate (SearchGoogleAdsStreamResponse response)
{
foreach (GoogleAdsRow googleAdsRow in response.Results)
{
// Add the campaign ID to the list of IDs if the extension feed item is
// associated with this extension setting.
if (googleAdsRow.CampaignExtensionSetting.ExtensionFeedItems.Contains(
extensionFeedResourceName))
{
Console.WriteLine(
$"Found matching campaign with ID {googleAdsRow.Campaign.Id}.");
campaignIds.Add(googleAdsRow.Campaign.Id);
}
}
}
);
return campaignIds;
}
// [END migrate_promotion_feed_to_asset_1]
/// <summary>
/// Finds and returns all of the ad groups that are associated with the specified Promotion
/// extension feed item.
/// </summary>
/// <param name="googleAdsServiceClient">An initialized Google Ads API Service
/// client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="extensionFeedItemResourceName">Resource name of the extension feed item to
/// migrate.</param>
/// <returns>A list of ad group IDs.</returns>
private List<long> GetTargetedAdGroupIds(
GoogleAdsServiceClient googleAdsServiceClient, long customerId,
string extensionFeedItemResourceName)
{
List<long> adGroupIds = new List<long>();
string query = @"
SELECT ad_group.id, ad_group_extension_setting.extension_feed_items
FROM ad_group_extension_setting
WHERE ad_group_extension_setting.extension_type = 'PROMOTION'
AND ad_group.status != 'REMOVED'";
googleAdsServiceClient.SearchStream(customerId.ToString(), query,
delegate (SearchGoogleAdsStreamResponse response)
{
foreach (GoogleAdsRow googleAdsRow in response.Results)
{
// Add the ad group ID to the list of IDs if the extension feed item is
// associated with this extension setting.
if (googleAdsRow.AdGroupExtensionSetting.ExtensionFeedItems.Contains(
extensionFeedItemResourceName))
{
Console.WriteLine(
$"Found matching ad group with ID {googleAdsRow.AdGroup.Id}.");
adGroupIds.Add(googleAdsRow.AdGroup.Id);
}
}
}
);
return adGroupIds;
}
/// <summary>
/// Create a Promotion asset that copies values from the specified extension feed item.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="extensionFeedItem">The extension feed item to be migrated.</param>
/// <returns>The resource name of the newly created Promotion asset.</returns>
// [START migrate_promotion_feed_to_asset]
private string CreatePromotionAssetFromFeed(GoogleAdsClient client, long customerId,
ExtensionFeedItem extensionFeedItem)
{
// Get the Asset Service client.
AssetServiceClient assetServiceClient = client.GetService(Services.V10.AssetService);
PromotionFeedItem promotionFeedItem = extensionFeedItem.PromotionFeedItem;
// Create the Promotion asset.
Asset asset = new Asset
{
// Name field is optional.
Name = $"Migrated from feed item #{extensionFeedItem.Id}",
PromotionAsset = new PromotionAsset
{
PromotionTarget = promotionFeedItem.PromotionTarget,
DiscountModifier = promotionFeedItem.DiscountModifier,
RedemptionStartDate = promotionFeedItem.PromotionStartDate,
RedemptionEndDate = promotionFeedItem.PromotionEndDate,
Occasion = promotionFeedItem.Occasion,
LanguageCode = promotionFeedItem.LanguageCode,
},
TrackingUrlTemplate = promotionFeedItem.TrackingUrlTemplate,
FinalUrlSuffix = promotionFeedItem.FinalUrlSuffix
};
// Either PercentOff or MoneyAmountOff must be set.
if (promotionFeedItem.PercentOff > 0)
{
// Adjust the percent off scale when copying.
asset.PromotionAsset.PercentOff = promotionFeedItem.PercentOff / 100;
}
else
{
asset.PromotionAsset.MoneyAmountOff = new Money
{
AmountMicros = promotionFeedItem.MoneyAmountOff.AmountMicros,
CurrencyCode = promotionFeedItem.MoneyAmountOff.CurrencyCode
};
}
// Either PromotionCode or OrdersOverAmount must be set.
if (!string.IsNullOrEmpty(promotionFeedItem.PromotionCode))
{
asset.PromotionAsset.PromotionCode = promotionFeedItem.PromotionCode;
}
else
{
asset.PromotionAsset.OrdersOverAmount = new Money
{
AmountMicros = promotionFeedItem.OrdersOverAmount.AmountMicros,
CurrencyCode = promotionFeedItem.OrdersOverAmount.CurrencyCode
};
}
// Set the start and end dates if set in the existing extension.
if (extensionFeedItem.HasStartDateTime)
{
asset.PromotionAsset.StartDate = DateTime.Parse(extensionFeedItem.StartDateTime)
.ToString("yyyy-MM-dd");
}
if (extensionFeedItem.HasEndDateTime)
{
asset.PromotionAsset.EndDate = DateTime.Parse(extensionFeedItem.EndDateTime)
.ToString("yyyy-MM-dd");
}
asset.PromotionAsset.AdScheduleTargets.Add(extensionFeedItem.AdSchedules);
asset.FinalUrls.Add(promotionFeedItem.FinalUrls);
asset.FinalMobileUrls.Add(promotionFeedItem.FinalMobileUrls);
asset.UrlCustomParameters.Add(promotionFeedItem.UrlCustomParameters);
// Build an operation to create the Promotion asset.
AssetOperation operation = new AssetOperation
{
Create = asset
};
// Issue the request and return the resource name of the new Promotion asset.
MutateAssetsResponse response = assetServiceClient.MutateAssets(
customerId.ToString(), new[] { operation });
Console.WriteLine("Created Promotion asset with resource name " +
$"{response.Results.First().ResourceName}");
return response.Results.First().ResourceName;
}
// [END migrate_promotion_feed_to_asset]
/// <summary>
/// Associates the specified Promotion asset with the specified campaigns.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="promotionAssetResourceName">The string resource name of the Promotion
/// Asset.</param>
/// <param name="campaignIds">A list of campaign IDs with which the Asset should be
/// associated.</param>
// [START migrate_promotion_feed_to_asset_2]
private void AssociateAssetWithCampaigns(GoogleAdsClient client, long customerId,
string promotionAssetResourceName, List<long> campaignIds)
{
if (campaignIds.Count == 0)
{
Console.WriteLine("Asset was not associated with any campaigns.");
return;
}
CampaignAssetServiceClient campaignAssetServiceClient = client.GetService(Services.V10
.CampaignAssetService);
List<CampaignAssetOperation> operations = new List<CampaignAssetOperation>();
foreach (long campaignId in campaignIds)
{
operations.Add(new CampaignAssetOperation
{
Create = new CampaignAsset
{
Asset = promotionAssetResourceName,
FieldType = AssetFieldTypeEnum.Types.AssetFieldType.Promotion,
Campaign = ResourceNames.Campaign(customerId, campaignId),
}
});
}
MutateCampaignAssetsResponse response = campaignAssetServiceClient.MutateCampaignAssets(
customerId.ToString(), operations);
foreach (MutateCampaignAssetResult result in response.Results)
{
Console.WriteLine($"Created campaign asset with resource name " +
$"{result.ResourceName}.");
}
}
// [END migrate_promotion_feed_to_asset_2]
/// <summary>
/// Associates the specified Promotion asset with the specified ad groups.
/// </summary>
/// <param name="client">The Google Ads client.</param>
/// <param name="customerId">The customer ID for which the call is made.</param>
/// <param name="promotionAssetResourceName">The string resource name of the Promotion
/// Asset.</param>
/// <param name="adGroupIds">A list of ad group IDs with which the Asset should be
/// associated.</param>
private void AssociateAssetWithAdGroups(GoogleAdsClient client, long customerId,
string promotionAssetResourceName, List<long> adGroupIds)
{
if (adGroupIds.Count == 0)
{
Console.WriteLine("Asset was not associated with any ad groups.");
return;
}
AdGroupAssetServiceClient adGroupAssetServiceClient = client.GetService(Services.V10
.AdGroupAssetService);
List<AdGroupAssetOperation> operations = new List<AdGroupAssetOperation>();
foreach (long adGroupId in adGroupIds)
{
operations.Add(new AdGroupAssetOperation
{
Create = new AdGroupAsset
{
Asset = promotionAssetResourceName,
FieldType = AssetFieldTypeEnum.Types.AssetFieldType.Promotion,
AdGroup = ResourceNames.AdGroup(customerId, adGroupId),
}
});
}
MutateAdGroupAssetsResponse response = adGroupAssetServiceClient.MutateAdGroupAssets(
customerId.ToString(), operations);
foreach (MutateAdGroupAssetResult result in response.Results)
{
Console.WriteLine($"Created ad group asset with resource name " +
$"{result.ResourceName}.");
}
}
}
}
| |
// 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.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Reflection.Metadata
{
internal static class BlobWriterImpl
{
internal const int SingleByteCompressedIntegerMaxValue = 0x7f;
internal const int TwoByteCompressedIntegerMaxValue = 0x3fff;
internal const int MaxCompressedIntegerValue = 0x1fffffff;
internal static int GetCompressedIntegerSize(int value)
{
Debug.Assert(value <= MaxCompressedIntegerValue);
if (value <= SingleByteCompressedIntegerMaxValue)
{
return 1;
}
if (value <= TwoByteCompressedIntegerMaxValue)
{
return 2;
}
return 4;
}
internal static void WriteCompressedInteger(ref BlobWriter writer, int value)
{
unchecked
{
if (value <= SingleByteCompressedIntegerMaxValue)
{
writer.WriteByte((byte)value);
}
else if (value <= TwoByteCompressedIntegerMaxValue)
{
writer.WriteUInt16BE((ushort)(0x8000 | value));
}
else if (value <= MaxCompressedIntegerValue)
{
writer.WriteUInt32BE(0xc0000000 | (uint)value);
}
else
{
Throw.ValueArgumentOutOfRange();
}
}
}
internal static void WriteCompressedInteger(BlobBuilder writer, int value)
{
unchecked
{
if (value <= SingleByteCompressedIntegerMaxValue)
{
writer.WriteByte((byte)value);
}
else if (value <= TwoByteCompressedIntegerMaxValue)
{
writer.WriteUInt16BE((ushort)(0x8000 | value));
}
else if (value <= MaxCompressedIntegerValue)
{
writer.WriteUInt32BE(0xc0000000 | (uint)value);
}
else
{
Throw.ValueArgumentOutOfRange();
}
}
}
internal static void WriteCompressedSignedInteger(ref BlobWriter writer, int value)
{
unchecked
{
const int b6 = (1 << 6) - 1;
const int b13 = (1 << 13) - 1;
const int b28 = (1 << 28) - 1;
// 0xffffffff for negative value
// 0x00000000 for non-negative
int signMask = value >> 31;
if ((value & ~b6) == (signMask & ~b6))
{
int n = ((value & b6) << 1) | (signMask & 1);
writer.WriteByte((byte)n);
}
else if ((value & ~b13) == (signMask & ~b13))
{
int n = ((value & b13) << 1) | (signMask & 1);
writer.WriteUInt16BE((ushort)(0x8000 | n));
}
else if ((value & ~b28) == (signMask & ~b28))
{
int n = ((value & b28) << 1) | (signMask & 1);
writer.WriteUInt32BE(0xc0000000 | (uint)n);
}
else
{
Throw.ValueArgumentOutOfRange();
}
}
}
internal static void WriteCompressedSignedInteger(BlobBuilder writer, int value)
{
unchecked
{
const int b6 = (1 << 6) - 1;
const int b13 = (1 << 13) - 1;
const int b28 = (1 << 28) - 1;
// 0xffffffff for negative value
// 0x00000000 for non-negative
int signMask = value >> 31;
if ((value & ~b6) == (signMask & ~b6))
{
int n = ((value & b6) << 1) | (signMask & 1);
writer.WriteByte((byte)n);
}
else if ((value & ~b13) == (signMask & ~b13))
{
int n = ((value & b13) << 1) | (signMask & 1);
writer.WriteUInt16BE((ushort)(0x8000 | n));
}
else if ((value & ~b28) == (signMask & ~b28))
{
int n = ((value & b28) << 1) | (signMask & 1);
writer.WriteUInt32BE(0xc0000000 | (uint)n);
}
else
{
Throw.ValueArgumentOutOfRange();
}
}
}
internal static void WriteConstant(ref BlobWriter writer, object value)
{
if (value == null)
{
// The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a 32-bit.
writer.WriteUInt32(0);
return;
}
var type = value.GetType();
if (type.GetTypeInfo().IsEnum)
{
type = Enum.GetUnderlyingType(type);
}
if (type == typeof(bool))
{
writer.WriteBoolean((bool)value);
}
else if (type == typeof(int))
{
writer.WriteInt32((int)value);
}
else if (type == typeof(string))
{
writer.WriteUTF16((string)value);
}
else if (type == typeof(byte))
{
writer.WriteByte((byte)value);
}
else if (type == typeof(char))
{
writer.WriteUInt16((char)value);
}
else if (type == typeof(double))
{
writer.WriteDouble((double)value);
}
else if (type == typeof(short))
{
writer.WriteInt16((short)value);
}
else if (type == typeof(long))
{
writer.WriteInt64((long)value);
}
else if (type == typeof(sbyte))
{
writer.WriteSByte((sbyte)value);
}
else if (type == typeof(float))
{
writer.WriteSingle((float)value);
}
else if (type == typeof(ushort))
{
writer.WriteUInt16((ushort)value);
}
else if (type == typeof(uint))
{
writer.WriteUInt32((uint)value);
}
else if (type == typeof(ulong))
{
writer.WriteUInt64((ulong)value);
}
else
{
throw new ArgumentException(SR.Format(SR.InvalidConstantValueOfType, type));
}
}
internal static void WriteConstant(BlobBuilder writer, object value)
{
if (value == null)
{
// The encoding of Type for the nullref value for FieldInit is ELEMENT_TYPE_CLASS with a Value of a 32-bit.
writer.WriteUInt32(0);
return;
}
var type = value.GetType();
if (type.GetTypeInfo().IsEnum)
{
type = Enum.GetUnderlyingType(type);
}
if (type == typeof(bool))
{
writer.WriteBoolean((bool)value);
}
else if (type == typeof(int))
{
writer.WriteInt32((int)value);
}
else if (type == typeof(string))
{
writer.WriteUTF16((string)value);
}
else if (type == typeof(byte))
{
writer.WriteByte((byte)value);
}
else if (type == typeof(char))
{
writer.WriteUInt16((char)value);
}
else if (type == typeof(double))
{
writer.WriteDouble((double)value);
}
else if (type == typeof(short))
{
writer.WriteInt16((short)value);
}
else if (type == typeof(long))
{
writer.WriteInt64((long)value);
}
else if (type == typeof(sbyte))
{
writer.WriteSByte((sbyte)value);
}
else if (type == typeof(float))
{
writer.WriteSingle((float)value);
}
else if (type == typeof(ushort))
{
writer.WriteUInt16((ushort)value);
}
else if (type == typeof(uint))
{
writer.WriteUInt32((uint)value);
}
else if (type == typeof(ulong))
{
writer.WriteUInt64((ulong)value);
}
else
{
throw new ArgumentException(SR.Format(SR.InvalidConstantValueOfType, type));
}
}
}
}
| |
using System;
using System.Diagnostics;
namespace Core
{
public class HTable
{
public int Count; // Number of entries with this hash
public HashElem Chain; // Pointer to first entry with this hash
}
public class HashElem
{
public HashElem Next, Prev; // Next and previous elements in the table
public object Data; // Data associated with this element
public string Key; public int KeyLength; // Key associated with this element
}
public class Hash
{
public uint TableSize = 31; // Number of buckets in the hash table
public uint Count; // Number of entries in this table
public HashElem First; // The first element of the array
public HTable[] Table;
public Hash memcpy()
{
return (this == null ? null : (Hash)MemberwiseClone());
}
public Hash()
{
Init();
}
public void Init()
{
First = null;
Count = 0;
TableSize = 0;
Table = null;
}
public void Clear()
{
HashElem elem = First; // For looping over all elements of the table
First = null;
C._free(ref Table); Table = null;
TableSize = 0;
while (elem != null)
{
HashElem nextElem = elem.Next;
C._free(ref elem);
elem = nextElem;
}
Count = 0;
}
static uint GetHashCode(string key, int keyLength)
{
Debug.Assert(keyLength >= 0);
int h = 0;
int _z = 0;
while (keyLength > 0) { h = (h << 3) ^ h ^ (_z < key.Length ? (int)char.ToLowerInvariant(key[_z++]) : 0); keyLength--; }
return (uint)h;
}
static void InsertElement(Hash hash, HTable entry, HashElem newElem)
{
HashElem headElem; // First element already in entry
if (entry != null)
{
headElem = (entry.Count != 0 ? entry.Chain : null);
entry.Count++;
entry.Chain = newElem;
}
else
headElem = null;
if (headElem != null)
{
newElem.Next = headElem;
newElem.Prev = headElem.Prev;
if (headElem.Prev != null) headElem.Prev.Next = newElem;
else hash.First = newElem;
headElem.Prev = newElem;
}
else
{
newElem.Next = hash.First;
if (hash.First != null) hash.First.Prev = newElem;
newElem.Prev = null;
hash.First = newElem;
}
}
static bool Rehash(Hash hash, uint newSize)
{
#if MALLOC_SOFT_LIMIT
if (newSize * sizeof(HTable) > MALLOC_SOFT_LIMIT)
newSize = MALLOC_SOFT_LIMIT / sizeof(HTable);
if (newSize == hash.TableSize) return false;
#endif
// The inability to allocates space for a larger hash table is a performance hit but it is not a fatal error. So mark the
// allocation as a benign. Use sqlite3Malloc()/memset(0) instead of sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
// only zeroes the requested number of bytes whereas this module will use the actual amount of space allocated for the hash table (which
// may be larger than the requested amount).
C._benignalloc_begin();
HTable[] newTable = new HTable[newSize]; // The new hash table
for (int i = 0; i < newSize; i++)
newTable[i] = new HTable();
C._benignalloc_end();
if (newTable == null)
return false;
C._free(ref hash.Table);
hash.Table = newTable;
//hash.TableSize = newSize = SysEx.AllocSize(newTable) / sizeof(HTable);
hash.TableSize = newSize;
HashElem elem, nextElem;
for (elem = hash.First, hash.First = null; elem != null; elem = nextElem)
{
uint h = GetHashCode(elem.Key, elem.KeyLength) % newSize;
nextElem = elem.Next;
InsertElement(hash, newTable[h], elem);
}
return true;
}
static HashElem FindElementGivenHash(Hash hash, string key, int keyLength, uint h)
{
HashElem elem; // Used to loop thru the element list
int count; // Number of elements left to test
if (hash.Table != null && hash.Table[h] != null)
{
HTable entry = hash.Table[h];
elem = entry.Chain;
count = entry.Count;
}
else
{
elem = hash.First;
count = (int)hash.Count;
}
while (count-- > 0 && C._ALWAYS(elem != null))
{
if (elem.KeyLength == keyLength && elem.Key.Equals(key, StringComparison.OrdinalIgnoreCase))
return elem;
elem = elem.Next;
}
return null;
}
static void RemoveElementGivenHash(Hash hash, ref HashElem elem, uint h)
{
HTable entry;
if (elem.Prev != null)
elem.Prev.Next = elem.Next;
else
hash.First = elem.Next;
if (elem.Next != null)
elem.Next.Prev = elem.Prev;
if (hash.Table != null && hash.Table[h] != null)
{
entry = hash.Table[h];
if (entry.Chain == elem)
entry.Chain = elem.Next;
entry.Count--;
Debug.Assert(entry.Count >= 0);
}
C._free(ref elem);
hash.Count--;
if (hash.Count == 0)
{
Debug.Assert(hash.First == null);
Debug.Assert(hash.Count == 0);
hash.Clear();
}
}
public T Find<T>(string key, int keyLength, T nullType) where T : class
{
Debug.Assert(key != null);
Debug.Assert(keyLength >= 0);
uint h = (Table != null ? GetHashCode(key, keyLength) % TableSize : 0);
HashElem elem = FindElementGivenHash(this, key, keyLength, h);
return (elem != null ? (T)elem.Data : nullType);
}
public T Insert<T>(string key, int keyLength, T data) where T : class
{
Debug.Assert(key != null);
Debug.Assert(keyLength >= 0);
uint h = (Table != null ? GetHashCode(key, keyLength) % TableSize : 0); // the hash of the key modulo hash table size
HashElem elem = FindElementGivenHash(this, key, keyLength, h); // Used to loop thru the element list
if (elem != null)
{
T oldData = (T)elem.Data;
if (data == null)
RemoveElementGivenHash(this, ref elem, h);
else
{
elem.Data = data;
elem.Key = key;
Debug.Assert(keyLength == elem.KeyLength);
}
return oldData;
}
if (data == null)
return null;
HashElem newElem = new HashElem();
if (newElem == null)
return null;
newElem.Key = key;
newElem.KeyLength = keyLength;
newElem.Data = data;
Count++;
if (Count >= 10 && Count > 2 * TableSize)
{
if (Rehash(this, Count * 2))
{
Debug.Assert(TableSize > 0);
h = GetHashCode(key, keyLength) % TableSize;
}
}
InsertElement(this, (Table != null ? Table[h] : null), newElem);
return null;
}
}
}
| |
/*
* The MIT License (MIT)
*
* Copyright (c) 2014 LeanIX GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
using System.Collections.Generic;
using LeanIX.Api.Common;
using LeanIX.Api.Models;
namespace LeanIX.Api {
public class ConsumersApi {
private readonly ApiClient apiClient = ApiClient.GetInstance();
public ApiClient getClient() {
return apiClient;
}
/// <summary>
/// Read all User Group
/// </summary>
/// <param name="relations">If set to true, all relations of the Fact Sheet are fetched as well. Fetching all relations can be slower. Default: false.</param>
/// <param name="filter">Full-text filter</param>
/// <returns></returns>
public List<Consumer> getConsumers (bool relations, string filter) {
// create path and map variables
var path = "/consumers".Replace("{format}","json");
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
string paramStr = null;
if (relations != null){
paramStr = (relations != null && relations is DateTime) ? ((DateTime)(object)relations).ToString("u") : Convert.ToString(relations);
queryParams.Add("relations", paramStr);
}
if (filter != null){
paramStr = (filter != null && filter is DateTime) ? ((DateTime)(object)filter).ToString("u") : Convert.ToString(filter);
queryParams.Add("filter", paramStr);
}
try {
var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
if(response != null){
return (List<Consumer>) ApiClient.deserialize(response, typeof(List<Consumer>));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Create a new User Group
/// </summary>
/// <param name="body">Message-Body</param>
/// <returns></returns>
public Consumer createConsumer (Consumer body) {
// create path and map variables
var path = "/consumers".Replace("{format}","json");
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams);
if(response != null){
return (Consumer) ApiClient.deserialize(response, typeof(Consumer));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Read a User Group by a given ID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relations">If set to true, all relations of the Fact Sheet are fetched as well. Fetching all relations can be slower. Default: false.</param>
/// <returns></returns>
public Consumer getConsumer (string ID, bool relations) {
// create path and map variables
var path = "/consumers/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
if (relations != null){
paramStr = (relations != null && relations is DateTime) ? ((DateTime)(object)relations).ToString("u") : Convert.ToString(relations);
queryParams.Add("relations", paramStr);
}
try {
var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
if(response != null){
return (Consumer) ApiClient.deserialize(response, typeof(Consumer));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Update a User Group by a given ID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="body">Message-Body</param>
/// <returns></returns>
public Consumer updateConsumer (string ID, Consumer body) {
// create path and map variables
var path = "/consumers/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams);
if(response != null){
return (Consumer) ApiClient.deserialize(response, typeof(Consumer));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Delete a User Group by a given ID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <returns></returns>
public void deleteConsumer (string ID) {
// create path and map variables
var path = "/consumers/{ID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return ;
}
else {
throw ex;
}
}
}
/// <summary>
/// Read all of relation
/// </summary>
/// <param name="ID">Unique ID</param>
/// <returns></returns>
public List<ServiceHasConsumer> getServiceHasConsumers (string ID) {
// create path and map variables
var path = "/consumers/{ID}/serviceHasConsumers".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
if(response != null){
return (List<ServiceHasConsumer>) ApiClient.deserialize(response, typeof(List<ServiceHasConsumer>));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Create a new relation
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="body">Message-Body</param>
/// <returns></returns>
public ServiceHasConsumer createServiceHasConsumer (string ID, Consumer body) {
// create path and map variables
var path = "/consumers/{ID}/serviceHasConsumers".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "POST", queryParams, body, headerParams);
if(response != null){
return (ServiceHasConsumer) ApiClient.deserialize(response, typeof(ServiceHasConsumer));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Read by relationID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relationID">Unique ID of the Relation</param>
/// <returns></returns>
public ServiceHasConsumer getServiceHasConsumer (string ID, string relationID) {
// create path and map variables
var path = "/consumers/{ID}/serviceHasConsumers/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null || relationID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "GET", queryParams, null, headerParams);
if(response != null){
return (ServiceHasConsumer) ApiClient.deserialize(response, typeof(ServiceHasConsumer));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Update relation by a given relationID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relationID">Unique ID of the Relation</param>
/// <param name="body">Message-Body</param>
/// <returns></returns>
public ServiceHasConsumer updateServiceHasConsumer (string ID, string relationID, Consumer body) {
// create path and map variables
var path = "/consumers/{ID}/serviceHasConsumers/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null || relationID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "PUT", queryParams, body, headerParams);
if(response != null){
return (ServiceHasConsumer) ApiClient.deserialize(response, typeof(ServiceHasConsumer));
}
else {
return null;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return null;
}
else {
throw ex;
}
}
}
/// <summary>
/// Delete relation by a given relationID
/// </summary>
/// <param name="ID">Unique ID</param>
/// <param name="relationID">Unique ID of the Relation</param>
/// <returns></returns>
public void deleteServiceHasConsumer (string ID, string relationID) {
// create path and map variables
var path = "/consumers/{ID}/serviceHasConsumers/{relationID}".Replace("{format}","json").Replace("{" + "ID" + "}", apiClient.escapeString(ID.ToString())).Replace("{" + "relationID" + "}", apiClient.escapeString(relationID.ToString()));
// query params
var queryParams = new Dictionary<String, String>();
var headerParams = new Dictionary<String, String>();
// verify required params are set
if (ID == null || relationID == null ) {
throw new ApiException(400, "missing required params");
}
string paramStr = null;
try {
var response = apiClient.invokeAPI(path, "DELETE", queryParams, null, headerParams);
if(response != null){
return ;
}
else {
return ;
}
} catch (ApiException ex) {
if(ex.ErrorCode == 404) {
return ;
}
else {
throw ex;
}
}
}
}
}
| |
using Codecov.Services.ContinuousIntegrationServers;
using FluentAssertions;
using Moq;
using Xunit;
namespace Codecov.Tests.Services.ContiniousIntegrationServers
{
public class TravisTests
{
[Fact]
public void Branch_Should_Be_Empty_String_When_Environment_Variable_Does_Not_Exits()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var travis = new Travis(ev.Object);
// When
var branch = travis.Branch;
// Then
branch.Should().BeEmpty();
}
[Fact]
public void Branch_Should_Be_Set_When_Environment_Variable_Exits()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS_BRANCH")).Returns("develop");
var travis = new Travis(ev.Object);
// When
var branch = travis.Branch;
// Then
branch.Should().Be("develop");
}
[Fact]
public void Build_Should_Be_Empty_String_When_Environment_Variable_Does_Not_Exits()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var travis = new Travis(ev.Object);
// When
var build = travis.Build;
// Then
build.Should().BeEmpty();
}
[Fact]
public void Build_Should_Be_Set_When_Environment_Variable_Exits()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS_JOB_NUMBER")).Returns("5.2");
var travis = new Travis(ev.Object);
// When
var build = travis.Build;
// Then
build.Should().Be("5.2");
}
[Fact]
public void BuildUrl_Should_Be_Empty_String_When_Environment_Variables_Do_Not_Exist()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var travis = new Travis(ev.Object);
// When
var buildUrl = travis.BuildUrl;
// Then
buildUrl.Should().BeEmpty();
}
[Fact]
public void BuildUrl_Should_Not_Be_Empty_String_When_Environment_Variable_Exist()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS_JOB_WEB_URL")).Returns("https://travis-ci.org/some-job");
var travis = new Travis(ev.Object);
// When
var buildUrl = travis.BuildUrl;
// Then
buildUrl.Should().Be("https://travis-ci.org/some-job");
}
[Fact]
public void Commit_Should_Be_Empty_String_When_Environment_Variable_Does_Not_Exits()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var travis = new Travis(ev.Object);
// When
var commit = travis.Commit;
// Then
commit.Should().BeEmpty();
}
[Fact]
public void Commit_Should_Be_Set_When_Environment_Variable_Exits()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS_COMMIT")).Returns("123");
var travis = new Travis(ev.Object);
// When
var commit = travis.Commit;
// Then
commit.Should().Be("123");
}
[Theory, InlineData(null, null), InlineData("", ""), InlineData("True", null), InlineData("True", ""), InlineData(null, "True"), InlineData("", "True"), InlineData("true", "True"), InlineData("True", "true"), InlineData("False", "True"), InlineData("True", "False"), InlineData("False", "False"), InlineData("foo", "bar")]
public void Detecter_Should_Be_False_When_Travis_Environment_Variable_Or_Ci_Environment_Variable_Does_Not_Exit_And_Both_Are_Not_Equal_To_True(string travisData, string ciData)
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS")).Returns(travisData);
ev.Setup(s => s.GetEnvironmentVariable("CI")).Returns(ciData);
var travis = new Travis(ev.Object);
// When
var detecter = travis.Detecter;
// Then
detecter.Should().BeFalse();
}
[Theory]
[InlineData("True", "True")]
[InlineData("true", "true")]
public void Detecter_Should_Be_True_When_Travis_Environment_Variable_And_Ci_Environment_Variable_Exist_And_Both_Are_Equal_To_True(string travisData, string ciData)
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS")).Returns(travisData);
ev.Setup(s => s.GetEnvironmentVariable("CI")).Returns(ciData);
var travis = new Travis(ev.Object);
// When
var detecter = travis.Detecter;
// Then
detecter.Should().BeTrue();
}
[Fact]
public void Job_Should_Be_Empty_String_When_Environment_Variables_Do_Not_Exit()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var travis = new Travis(ev.Object);
// When
var job = travis.Job;
// Then
job.Should().BeEmpty();
}
[Fact]
public void Job_Should_Not_Be_Empty_String_When_Environment_Variables_Exit()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS_JOB_ID")).Returns("15657");
var travis = new Travis(ev.Object);
// When
var job = travis.Job;
// Then
job.Should().Be("15657");
}
[Fact]
public void Pr_Should_Be_Empty_String_When_Environment_Variable_Does_Not_Exits()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var travis = new Travis(ev.Object);
// When
var pr = travis.Pr;
// Then
pr.Should().BeEmpty();
}
[Fact]
public void Pr_Should_Be_Set_When_Environment_Variable_Exits()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS_PULL_REQUEST")).Returns("123");
var travis = new Travis(ev.Object);
// When
var pr = travis.Pr;
// Then
pr.Should().Be("123");
}
[Fact]
public void Slug_Should_Be_Empty_String_When_Environment_Variable_Does_Not_Exits()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var travis = new Travis(ev.Object);
// When
var slug = travis.Slug;
// Then
slug.Should().BeEmpty();
}
[Fact]
public void Slug_Should_Be_Set_When_Environment_Variable_Exits()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS_REPO_SLUG")).Returns("foo/bar");
var travis = new Travis(ev.Object);
// When
var slug = travis.Slug;
// Then
slug.Should().Be("foo/bar");
}
[Fact]
public void Tag_Should_Empty_String_When_Environment_Variable_Does_Not_Exist()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
var travis = new Travis(ev.Object);
// When
var tag = travis.Tag;
// THen
tag.Should().BeEmpty();
}
[Fact]
public void Tag_Should_Not_Be_Empty_String_When_Environment_Variable_Exist()
{
// Given
var ev = new Mock<IEnviornmentVariables>();
ev.Setup(s => s.GetEnvironmentVariable("TRAVIS_TAG")).Returns("v1.2.4");
var travis = new Travis(ev.Object);
// When
var tag = travis.Tag;
// Then
tag.Should().Be("v1.2.4");
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
#if NET472
using System.Runtime.Remoting;
#endif
using Fody;
using Mono.Cecil;
using Mono.Cecil.Pdb;
using Mono.Cecil.Rocks;
using FieldAttributes = Mono.Cecil.FieldAttributes;
using TypeAttributes = Mono.Cecil.TypeAttributes;
public partial class InnerWeaver :
MarshalByRefObject,
IInnerWeaver
{
public string ProjectDirectoryPath { get; set; } = null!;
public string ProjectFilePath { get; set; } = null!;
public string? DocumentationFilePath { get; set; }
public string AssemblyFilePath { get; set; } = null!;
public string SolutionDirectoryPath { get; set; } = null!;
public string References { get; set; } = null!;
public List<WeaverEntry> Weavers { get; set; } = null!;
public string? KeyFilePath { get; set; }
public bool SignAssembly { get; set; }
public bool DelaySign { get; set; }
public ILogger Logger { get; set; } = null!;
public string IntermediateDirectoryPath { get; set; } = null!;
public List<string> ReferenceCopyLocalPaths { get; set; } = null!;
public List<string> DefineConstants { get; set; } = null!;
#if (NETSTANDARD)
public IsolatedAssemblyLoadContext LoadContext { get; set; } = null!;
#endif
bool cancelRequested;
List<WeaverHolder> weaverInstances = new List<WeaverHolder>();
Action? cancelDelegate;
public IAssemblyResolver assemblyResolver = null!;
Assembly? CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var assemblyName = new AssemblyName(args.Name).Name;
if (assemblyName == "FodyHelpers")
{
return typeof(BaseModuleWeaver).Assembly;
}
if (assemblyName == "Mono.Cecil")
{
return typeof(ModuleDefinition).Assembly;
}
if (assemblyName == "Mono.Cecil.Rocks")
{
return typeof(MethodBodyRocks).Assembly;
}
if (assemblyName == "Mono.Cecil.Pdb")
{
return typeof(PdbReaderProvider).Assembly;
}
foreach (var weaverPath in Weavers.Select(x => x.AssemblyPath))
{
var directoryName = Path.GetDirectoryName(weaverPath);
var assemblyFileName = $"{assemblyName}.dll";
var assemblyPath = Path.Combine(directoryName, assemblyFileName);
if (!File.Exists(assemblyPath))
{
continue;
}
try
{
return LoadFromFile(assemblyPath);
}
catch (Exception exception)
{
var message = $"Failed to load '{assemblyPath}'. Going to swallow and continue to let other AssemblyResolve events to attempt to resolve. Exception:{exception}";
Logger.LogWarning(message);
}
}
return null;
}
public TypeCache TypeCache = null!;
public void Execute()
{
ResolveEventHandler assemblyResolve = CurrentDomain_AssemblyResolve;
try
{
AppDomain.CurrentDomain.AssemblyResolve += assemblyResolve;
SplitUpReferences();
assemblyResolver = new AssemblyResolver(Logger, SplitReferences);
ReadModule();
var weavingInfoClassName = GetWeavingInfoClassName();
if (ModuleDefinition.Types.Any(x => x.Name == weavingInfoClassName))
{
Logger.LogWarning($"The assembly has already been processed by Fody. Weaving aborted. Path: {AssemblyFilePath}");
return;
}
TypeCache = new TypeCache(assemblyResolver.Resolve);
InitialiseWeavers();
ValidatePackageReferenceSettings(weaverInstances, Logger);
TypeCache.BuildAssembliesToScan(weaverInstances.Select(x => x.Instance));
InitialiseTypeSystem();
ExecuteWeavers();
AddWeavingInfo();
FindStrongNameKey();
WriteModule();
ModuleDefinition?.Dispose();
ExecuteAfterWeavers();
DisposeWeavers();
}
catch (Exception exception)
{
Logger.LogException(exception);
}
finally
{
AppDomain.CurrentDomain.AssemblyResolve -= assemblyResolve;
ModuleDefinition?.Dispose();
assemblyResolver?.Dispose();
}
}
public void Cancel()
{
cancelRequested = true;
cancelDelegate?.Invoke();
}
void InitialiseWeavers()
{
foreach (var weaverConfig in Weavers)
{
if (cancelRequested)
{
return;
}
var weaverHolder = InitialiseWeaver(weaverConfig);
if (weaverHolder != null)
{
weaverInstances.Add(weaverHolder);
}
}
}
WeaverHolder? InitialiseWeaver(WeaverEntry weaverConfig)
{
Logger.LogDebug($"Weaver '{weaverConfig.AssemblyPath}'.");
Logger.LogDebug(" Initializing weaver");
var assembly = LoadWeaverAssembly(weaverConfig.AssemblyPath);
var weaverType = assembly.FindType(weaverConfig.TypeName);
if (weaverType == null)
{
Logger.LogError($"Could not find weaver type {weaverConfig.TypeName} in {weaverConfig.WeaverName}");
return null;
}
var delegateHolder = weaverType.GetDelegateHolderFromCache();
var weaverInstance = delegateHolder();
var weaverHolder = new WeaverHolder(weaverInstance, weaverConfig);
if (FodyVersion.WeaverRequiresUpdate(assembly, out var referencedVersion))
{
Logger.LogWarning($"Weavers should reference at least the current major version of Fody (version {FodyVersion.Major}). The weaver in {assembly.GetName().Name} references version {referencedVersion}. This may result in incompatibilities at build time such as MissingMethodException being thrown.", "FodyVersionMismatch");
weaverHolder.IsUsingOldFodyVersion = true;
}
weaverHolder.FodyVersion = referencedVersion;
SetProperties(weaverConfig, weaverInstance);
return weaverHolder;
}
void ExecuteWeavers()
{
foreach (var weaver in weaverInstances)
{
if (cancelRequested)
{
return;
}
try
{
cancelDelegate = weaver.Instance.Cancel;
Logger.SetCurrentWeaverName(weaver.Config.ElementName);
var startNew = Stopwatch.StartNew();
Logger.LogInfo("Executing weaver");
Logger.LogDebug($"Configuration source: {weaver.Config.ConfigurationSource}");
try
{
weaver.Instance.Execute();
}
catch (WeavingException)
{
throw;
}
catch (MissingMemberException exception) when (weaver.IsUsingOldFodyVersion)
{
throw new WeavingException($"Failed to execute weaver {weaver.Config.AssemblyPath} due to a MissingMemberException. Message: {exception.Message}. This is likely due to the weaver referencing an old version ({weaver.FodyVersion}) of Fody.");
}
catch (FileNotFoundException exception) when (exception.Message.Contains(nameof(ValueTuple)))
{
throw new Exception($@"Failed to execute weaver {weaver.Config.AssemblyPath} due to a failure to load ValueTuple.
This is a known issue with in dotnet (https://github.com/dotnet/runtime/issues/27533).
The recommended work around is to avoid using ValueTuple inside a weaver.", exception);
}
catch (Exception exception)
{
throw new Exception($"Failed to execute weaver {weaver.Config.AssemblyPath}", exception);
}
Logger.LogDebug($"Finished '{weaver.Config.ElementName}' in {startNew.ElapsedMilliseconds}ms");
ReferenceCleaner.CleanReferences(ModuleDefinition, weaver.Instance, Logger.LogDebug);
}
finally
{
cancelDelegate = null;
Logger.ClearWeaverName();
}
}
}
void AddWeavingInfo()
{
if (cancelRequested)
{
return;
}
Logger.LogDebug("Adding weaving info");
var startNew = Stopwatch.StartNew();
const TypeAttributes typeAttributes = TypeAttributes.NotPublic | TypeAttributes.Class;
var typeDefinition = new TypeDefinition(null, GetWeavingInfoClassName(), typeAttributes, TypeSystem.ObjectReference);
ModuleDefinition.Types.Add(typeDefinition);
AddVersionField(typeof(IInnerWeaver).Assembly, "FodyVersion", typeDefinition);
foreach (var weaver in weaverInstances)
{
var configAssembly = weaver.Instance.GetType().Assembly;
var name = weaver.Config.ElementName.Replace(".", string.Empty);
AddVersionField(configAssembly, name, typeDefinition);
}
Logger.LogDebug($"Finished in {startNew.ElapsedMilliseconds}ms");
}
string GetWeavingInfoClassName()
{
var classPrefix = ModuleDefinition.Assembly.Name.Name.Replace(".", "");
return $"{classPrefix}_ProcessedByFody";
}
void AddVersionField(Assembly assembly, string name, TypeDefinition typeDefinition)
{
var weaverVersion = "0.0.0.0";
var attrs = assembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute));
var fileVersionAttribute = (AssemblyFileVersionAttribute?)attrs.FirstOrDefault();
if (fileVersionAttribute != null)
{
weaverVersion = fileVersionAttribute.Version;
}
const FieldAttributes fieldAttributes = FieldAttributes.Assembly |
FieldAttributes.Literal |
FieldAttributes.Static |
FieldAttributes.HasDefault;
var field = new FieldDefinition(name, fieldAttributes, TypeSystem.StringReference)
{
Constant = weaverVersion
};
typeDefinition.Fields.Add(field);
}
void ExecuteAfterWeavers()
{
foreach (var weaver in weaverInstances)
{
if (cancelRequested)
{
return;
}
try
{
Logger.SetCurrentWeaverName(weaver.Config.ElementName);
var stopwatch = Stopwatch.StartNew();
Logger.LogDebug("Executing After Weaver");
weaver.Instance.AfterWeaving();
Logger.LogDebug($"Finished '{weaver.Config.ElementName}' in {stopwatch.ElapsedMilliseconds}ms");
}
finally
{
Logger.ClearWeaverName();
}
}
}
void DisposeWeavers()
{
foreach (var disposable in weaverInstances
.Select(x => x.Instance)
.OfType<IDisposable>())
{
disposable.Dispose();
}
}
public sealed override object? InitializeLifetimeService()
{
// Returning null designates an infinite non-expiring lease.
// We must therefore ensure that RemotingServices.Disconnect() is called when
// it's no longer needed otherwise there will be a memory leak.
return null;
}
public void Dispose()
{
#if NET472
//Disconnects the remoting channel(s) of this object and all nested objects.
RemotingServices.Disconnect(this);
#endif
}
}
| |
// "Therefore those skilled at the unorthodox
// are infinite as heaven and earth,
// inexhaustible as the great rivers.
// When they come to an end,
// they begin again,
// like the days and months;
// they die and are reborn,
// like the four seasons."
//
// - Sun Tsu,
// "The Art of War"
using System;
namespace MetroFramework.Drawing.Html.Adapters.Entities
{
/// <summary>
/// Stores a set of four floating-point numbers that represent the location and size of a rectangle.
/// </summary>
public struct RRect
{
#region Fields and Consts
/// <summary>
/// Represents an instance of the <see cref="RRect" /> class with its members uninitialized.
/// </summary>
public static readonly RRect Empty = new RRect();
private double _height;
private double _width;
private double _x;
private double _y;
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="RRect" /> class with the specified location and size.
/// </summary>
/// <param name="x">The x-coordinate of the upper-left corner of the rectangle. </param>
/// <param name="y">The y-coordinate of the upper-left corner of the rectangle. </param>
/// <param name="width">The width of the rectangle. </param>
/// <param name="height">The height of the rectangle. </param>
public RRect(double x, double y, double width, double height)
{
_x = x;
_y = y;
_width = width;
_height = height;
}
/// <summary>
/// Initializes a new instance of the <see cref="RRect" /> class with the specified location and size.
/// </summary>
/// <param name="location">A <see cref="RPoint" /> that represents the upper-left corner of the rectangular region.</param>
/// <param name="size">A <see cref="RSize" /> that represents the width and height of the rectangular region.</param>
public RRect(RPoint location, RSize size)
{
_x = location.X;
_y = location.Y;
_width = size.Width;
_height = size.Height;
}
/// <summary>
/// Gets or sets the coordinates of the upper-left corner of this <see cref="RRect" /> structure.
/// </summary>
/// <returns>A <see cref="RPoint" /> that represents the upper-left corner of this <see cref="RRect" /> structure.</returns>
public RPoint Location
{
get { return new RPoint(X, Y); }
set
{
X = value.X;
Y = value.Y;
}
}
/// <summary>
/// Gets or sets the size of this <see cref="RRect" />.
/// </summary>
/// <returns>A <see cref="RSize" /> that represents the width and height of this <see cref="RRect" /> structure.</returns>
public RSize Size
{
get { return new RSize(Width, Height); }
set
{
Width = value.Width;
Height = value.Height;
}
}
/// <summary>
/// Gets or sets the x-coordinate of the upper-left corner of this <see cref="RRect" /> structure.
/// </summary>
/// <returns>
/// The x-coordinate of the upper-left corner of this <see cref="RRect" /> structure.
/// </returns>
public double X
{
get { return _x; }
set { _x = value; }
}
/// <summary>
/// Gets or sets the y-coordinate of the upper-left corner of this <see cref="RRect" /> structure.
/// </summary>
/// <returns>
/// The y-coordinate of the upper-left corner of this <see cref="RRect" /> structure.
/// </returns>
public double Y
{
get { return _y; }
set { _y = value; }
}
/// <summary>
/// Gets or sets the width of this <see cref="RRect" /> structure.
/// </summary>
/// <returns>
/// The width of this <see cref="RRect" /> structure.
/// </returns>
public double Width
{
get { return _width; }
set { _width = value; }
}
/// <summary>
/// Gets or sets the height of this <see cref="RRect" /> structure.
/// </summary>
/// <returns>
/// The height of this <see cref="RRect" /> structure.
/// </returns>
public double Height
{
get { return _height; }
set { _height = value; }
}
/// <summary>
/// Gets the x-coordinate of the left edge of this <see cref="RRect" /> structure.
/// </summary>
/// <returns>
/// The x-coordinate of the left edge of this <see cref="RRect" /> structure.
/// </returns>
public double Left
{
get { return X; }
}
/// <summary>
/// Gets the y-coordinate of the top edge of this <see cref="RRect" /> structure.
/// </summary>
/// <returns>
/// The y-coordinate of the top edge of this <see cref="RRect" /> structure.
/// </returns>
public double Top
{
get { return Y; }
}
/// <summary>
/// Gets the x-coordinate that is the sum of <see cref="RRect.X" /> and
/// <see
/// cref="RRect.Width" />
/// of this <see cref="RRect" /> structure.
/// </summary>
/// <returns>
/// The x-coordinate that is the sum of <see cref="RRect.X" /> and
/// <see
/// cref="RRect.Width" />
/// of this <see cref="RRect" /> structure.
/// </returns>
public double Right
{
get { return X + Width; }
}
/// <summary>
/// Gets the y-coordinate that is the sum of <see cref="RRect.Y" /> and
/// <see
/// cref="RRect.Height" />
/// of this <see cref="RRect" /> structure.
/// </summary>
/// <returns>
/// The y-coordinate that is the sum of <see cref="RRect.Y" /> and
/// <see
/// cref="RRect.Height" />
/// of this <see cref="RRect" /> structure.
/// </returns>
public double Bottom
{
get { return Y + Height; }
}
/// <summary>
/// Tests whether the <see cref="RRect.Width" /> or
/// <see
/// cref="RRect.Height" />
/// property of this <see cref="RRect" /> has a value of zero.
/// </summary>
/// <returns>
/// This property returns true if the <see cref="RRect.Width" /> or
/// <see
/// cref="RRect.Height" />
/// property of this <see cref="RRect" /> has a value of zero; otherwise, false.
/// </returns>
public bool IsEmpty
{
get
{
if (Width > 0.0)
return Height <= 0.0;
else
return true;
}
}
/// <summary>
/// Tests whether two <see cref="RRect" /> structures have equal location and size.
/// </summary>
/// <returns>
/// This operator returns true if the two specified <see cref="RRect" /> structures have equal
/// <see cref="RRect.X" />, <see cref="RRect.Y" />, <see cref="RRect.Width" />, and <see cref="RRect.Height" /> properties.
/// </returns>
/// <param name="left">
/// The <see cref="RRect" /> structure that is to the left of the equality operator.
/// </param>
/// <param name="right">
/// The <see cref="RRect" /> structure that is to the right of the equality operator.
/// </param>
public static bool operator ==(RRect left, RRect right)
{
if (Math.Abs(left.X - right.X) < 0.001 && Math.Abs(left.Y - right.Y) < 0.001 && Math.Abs(left.Width - right.Width) < 0.001)
return Math.Abs(left.Height - right.Height) < 0.001;
else
return false;
}
/// <summary>
/// Tests whether two <see cref="RRect" /> structures differ in location or size.
/// </summary>
/// <returns>
/// This operator returns true if any of the <see cref="RRect.X" /> ,
/// <see cref="RRect.Y" />, <see cref="RRect.Width" />, or <see cref="RRect.Height" />
/// properties of the two <see cref="RRect" /> structures are unequal; otherwise false.
/// </returns>
/// <param name="left">
/// The <see cref="RRect" /> structure that is to the left of the inequality operator.
/// </param>
/// <param name="right">
/// The <see cref="RRect" /> structure that is to the right of the inequality operator.
/// </param>
public static bool operator !=(RRect left, RRect right)
{
return !(left == right);
}
/// <summary>
/// Creates a <see cref="RRect" /> structure with upper-left corner and lower-right corner at the specified locations.
/// </summary>
/// <returns>
/// The new <see cref="RRect" /> that this method creates.
/// </returns>
/// <param name="left">The x-coordinate of the upper-left corner of the rectangular region. </param>
/// <param name="top">The y-coordinate of the upper-left corner of the rectangular region. </param>
/// <param name="right">The x-coordinate of the lower-right corner of the rectangular region. </param>
/// <param name="bottom">The y-coordinate of the lower-right corner of the rectangular region. </param>
public static RRect FromLTRB(double left, double top, double right, double bottom)
{
return new RRect(left, top, right - left, bottom - top);
}
/// <summary>
/// Tests whether <paramref name="obj" /> is a <see cref="RRect" /> with the same location and size of this
/// <see cref="RRect" />.
/// </summary>
/// <returns>
/// This method returns true if <paramref name="obj" /> is a <see cref="RRect" /> and its X, Y, Width, and Height properties are equal to the corresponding properties of this
/// <see cref="RRect" />; otherwise, false.
/// </returns>
/// <param name="obj">
/// The <see cref="T:System.Object" /> to test.
/// </param>
public override bool Equals(object obj)
{
if (!(obj is RRect))
return false;
var rectangleF = (RRect)obj;
if (Math.Abs(rectangleF.X - X) < 0.001 && Math.Abs(rectangleF.Y - Y) < 0.001 && Math.Abs(rectangleF.Width - Width) < 0.001)
return Math.Abs(rectangleF.Height - Height) < 0.001;
else
return false;
}
/// <summary>
/// Determines if the specified point is contained within this <see cref="RRect" /> structure.
/// </summary>
/// <returns>
/// This method returns true if the point defined by <paramref name="x" /> and <paramref name="y" /> is contained within this
/// <see cref="RRect" />
/// structure; otherwise false.
/// </returns>
/// <param name="x">The x-coordinate of the point to test. </param>
/// <param name="y">The y-coordinate of the point to test. </param>
public bool Contains(double x, double y)
{
if (X <= x && x < X + Width && Y <= y)
return y < Y + Height;
else
return false;
}
/// <summary>
/// Determines if the specified point is contained within this <see cref="RRect" /> structure.
/// </summary>
/// <returns>
/// This method returns true if the point represented by the <paramref name="pt" /> parameter is contained within this
/// <see cref="RRect" />
/// structure; otherwise false.
/// </returns>
/// <param name="pt">The <see cref="RPoint" /> to test.</param>
public bool Contains(RPoint pt)
{
return Contains(pt.X, pt.Y);
}
/// <summary>
/// Determines if the rectangular region represented by <paramref name="rect" /> is entirely contained within this
/// <see cref="RRect" />
/// structure.
/// </summary>
/// <returns>
/// This method returns true if the rectangular region represented by <paramref name="rect" /> is entirely contained within the rectangular region represented by this
/// <see cref="RRect" />
/// ; otherwise false.
/// </returns>
/// <param name="rect">
/// The <see cref="RRect" /> to test.
/// </param>
public bool Contains(RRect rect)
{
if (X <= rect.X && rect.X + rect.Width <= X + Width && Y <= rect.Y)
return rect.Y + rect.Height <= Y + Height;
else
return false;
}
/// <summary>
/// Inflates this <see cref="RRect" /> structure by the specified amount.
/// </summary>
/// <param name="x">
/// The amount to inflate this <see cref="RRect" /> structure horizontally.
/// </param>
/// <param name="y">
/// The amount to inflate this <see cref="RRect" /> structure vertically.
/// </param>
public void Inflate(double x, double y)
{
X -= x;
Y -= y;
Width += 2f * x;
Height += 2f * y;
}
/// <summary>
/// Inflates this <see cref="RRect" /> by the specified amount.
/// </summary>
/// <param name="size">The amount to inflate this rectangle. </param>
public void Inflate(RSize size)
{
Inflate(size.Width, size.Height);
}
/// <summary>
/// Creates and returns an inflated copy of the specified <see cref="RRect" /> structure. The copy is inflated by the specified amount. The original rectangle remains unmodified.
/// </summary>
/// <returns>
/// The inflated <see cref="RRect" />.
/// </returns>
/// <param name="rect">
/// The <see cref="RRect" /> to be copied. This rectangle is not modified.
/// </param>
/// <param name="x">The amount to inflate the copy of the rectangle horizontally. </param>
/// <param name="y">The amount to inflate the copy of the rectangle vertically. </param>
public static RRect Inflate(RRect rect, double x, double y)
{
RRect rectangleF = rect;
rectangleF.Inflate(x, y);
return rectangleF;
}
/// <summary>
/// Replaces this <see cref="RRect" /> structure with the intersection of itself and the specified
/// <see
/// cref="RRect" />
/// structure.
/// </summary>
/// <param name="rect">The rectangle to intersect. </param>
public void Intersect(RRect rect)
{
RRect rectangleF = Intersect(rect, this);
X = rectangleF.X;
Y = rectangleF.Y;
Width = rectangleF.Width;
Height = rectangleF.Height;
}
/// <summary>
/// Returns a <see cref="RRect" /> structure that represents the intersection of two rectangles. If there is no intersection, and empty
/// <see
/// cref="RRect" />
/// is returned.
/// </summary>
/// <returns>
/// A third <see cref="RRect" /> structure the size of which represents the overlapped area of the two specified rectangles.
/// </returns>
/// <param name="a">A rectangle to intersect. </param>
/// <param name="b">A rectangle to intersect. </param>
public static RRect Intersect(RRect a, RRect b)
{
double x = Math.Max(a.X, b.X);
double num1 = Math.Min(a.X + a.Width, b.X + b.Width);
double y = Math.Max(a.Y, b.Y);
double num2 = Math.Min(a.Y + a.Height, b.Y + b.Height);
if (num1 >= x && num2 >= y)
return new RRect(x, y, num1 - x, num2 - y);
else
return Empty;
}
/// <summary>
/// Determines if this rectangle intersects with <paramref name="rect" />.
/// </summary>
/// <returns>
/// This method returns true if there is any intersection.
/// </returns>
/// <param name="rect">The rectangle to test. </param>
public bool IntersectsWith(RRect rect)
{
if (rect.X < X + Width && X < rect.X + rect.Width && rect.Y < Y + Height)
return Y < rect.Y + rect.Height;
else
return false;
}
/// <summary>
/// Creates the smallest possible third rectangle that can contain both of two rectangles that form a union.
/// </summary>
/// <returns>
/// A third <see cref="RRect" /> structure that contains both of the two rectangles that form the union.
/// </returns>
/// <param name="a">A rectangle to union. </param>
/// <param name="b">A rectangle to union. </param>
public static RRect Union(RRect a, RRect b)
{
double x = Math.Min(a.X, b.X);
double num1 = Math.Max(a.X + a.Width, b.X + b.Width);
double y = Math.Min(a.Y, b.Y);
double num2 = Math.Max(a.Y + a.Height, b.Y + b.Height);
return new RRect(x, y, num1 - x, num2 - y);
}
/// <summary>
/// Adjusts the location of this rectangle by the specified amount.
/// </summary>
/// <param name="pos">The amount to offset the location. </param>
public void Offset(RPoint pos)
{
Offset(pos.X, pos.Y);
}
/// <summary>
/// Adjusts the location of this rectangle by the specified amount.
/// </summary>
/// <param name="x">The amount to offset the location horizontally. </param>
/// <param name="y">The amount to offset the location vertically. </param>
public void Offset(double x, double y)
{
X += x;
Y += y;
}
/// <summary>
/// Gets the hash code for this <see cref="RRect" /> structure. For information about the use of hash codes, see Object.GetHashCode.
/// </summary>
/// <returns>The hash code for this <see cref="RRect" /></returns>
public override int GetHashCode()
{
return (int)(uint)X ^ ((int)(uint)Y << 13 | (int)((uint)Y >> 19)) ^ ((int)(uint)Width << 26 | (int)((uint)Width >> 6)) ^ ((int)(uint)Height << 7 | (int)((uint)Height >> 25));
}
/// <summary>
/// Converts the Location and Size of this <see cref="RRect" /> to a human-readable string.
/// </summary>
/// <returns>
/// A string that contains the position, width, and height of this <see cref="RRect" /> structure for example, "{X=20, Y=20, Width=100, Height=50}".
/// </returns>
public override string ToString()
{
return "{X=" + X + ",Y=" + Y + ",Width=" + Width + ",Height=" + Height + "}";
}
}
}
| |
// 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.Runtime.InteropServices;
internal static partial class Interop
{
/// <summary>Common Unix errno error codes.</summary>
internal enum Error
{
// These values were defined in src/Native/System.Native/fxerrno.h
//
// They compare against values obtaied via Interop.Sys.GetLastError() not Marshal.GetLastWin32Error()
// which obtains the raw errno that varies between unixes. The strong typing as an enum is meant to
// prevent confusing the two. Casting to or from int is suspect. Use GetLastErrorInfo() if you need to
// correlate these to the underlying platform values or obtain the corresponding error message.
//
SUCCESS = 0,
E2BIG = 0x10001, // Argument list too long.
EACCES = 0x10002, // Permission denied.
EADDRINUSE = 0x10003, // Address in use.
EADDRNOTAVAIL = 0x10004, // Address not available.
EAFNOSUPPORT = 0x10005, // Address family not supported.
EAGAIN = 0x10006, // Resource unavailable, try again (same value as EWOULDBLOCK),
EALREADY = 0x10007, // Connection already in progress.
EBADF = 0x10008, // Bad file descriptor.
EBADMSG = 0x10009, // Bad message.
EBUSY = 0x1000A, // Device or resource busy.
ECANCELED = 0x1000B, // Operation canceled.
ECHILD = 0x1000C, // No child processes.
ECONNABORTED = 0x1000D, // Connection aborted.
ECONNREFUSED = 0x1000E, // Connection refused.
ECONNRESET = 0x1000F, // Connection reset.
EDEADLK = 0x10010, // Resource deadlock would occur.
EDESTADDRREQ = 0x10011, // Destination address required.
EDOM = 0x10012, // Mathematics argument out of domain of function.
EDQUOT = 0x10013, // Reserved.
EEXIST = 0x10014, // File exists.
EFAULT = 0x10015, // Bad address.
EFBIG = 0x10016, // File too large.
EHOSTUNREACH = 0x10017, // Host is unreachable.
EIDRM = 0x10018, // Identifier removed.
EILSEQ = 0x10019, // Illegal byte sequence.
EINPROGRESS = 0x1001A, // Operation in progress.
EINTR = 0x1001B, // Interrupted function.
EINVAL = 0x1001C, // Invalid argument.
EIO = 0x1001D, // I/O error.
EISCONN = 0x1001E, // Socket is connected.
EISDIR = 0x1001F, // Is a directory.
ELOOP = 0x10020, // Too many levels of symbolic links.
EMFILE = 0x10021, // File descriptor value too large.
EMLINK = 0x10022, // Too many links.
EMSGSIZE = 0x10023, // Message too large.
EMULTIHOP = 0x10024, // Reserved.
ENAMETOOLONG = 0x10025, // Filename too long.
ENETDOWN = 0x10026, // Network is down.
ENETRESET = 0x10027, // Connection aborted by network.
ENETUNREACH = 0x10028, // Network unreachable.
ENFILE = 0x10029, // Too many files open in system.
ENOBUFS = 0x1002A, // No buffer space available.
ENODEV = 0x1002C, // No such device.
ENOENT = 0x1002D, // No such file or directory.
ENOEXEC = 0x1002E, // Executable file format error.
ENOLCK = 0x1002F, // No locks available.
ENOLINK = 0x10030, // Reserved.
ENOMEM = 0x10031, // Not enough space.
ENOMSG = 0x10032, // No message of the desired type.
ENOPROTOOPT = 0x10033, // Protocol not available.
ENOSPC = 0x10034, // No space left on device.
ENOSYS = 0x10037, // Function not supported.
ENOTCONN = 0x10038, // The socket is not connected.
ENOTDIR = 0x10039, // Not a directory or a symbolic link to a directory.
ENOTEMPTY = 0x1003A, // Directory not empty.
ENOTRECOVERABLE = 0x1003B, // State not recoverable.
ENOTSOCK = 0x1003C, // Not a socket.
ENOTSUP = 0x1003D, // Not supported (same value as EOPNOTSUP).
ENOTTY = 0x1003E, // Inappropriate I/O control operation.
ENXIO = 0x1003F, // No such device or address.
EOVERFLOW = 0x10040, // Value too large to be stored in data type.
EOWNERDEAD = 0x10041, // Previous owner died.
EPERM = 0x10042, // Operation not permitted.
EPIPE = 0x10043, // Broken pipe.
EPROTO = 0x10044, // Protocol error.
EPROTONOSUPPORT = 0x10045, // Protocol not supported.
EPROTOTYPE = 0x10046, // Protocol wrong type for socket.
ERANGE = 0x10047, // Result too large.
EROFS = 0x10048, // Read-only file system.
ESPIPE = 0x10049, // Invalid seek.
ESRCH = 0x1004A, // No such process.
ESTALE = 0x1004B, // Reserved.
ETIMEDOUT = 0x1004D, // Connection timed out.
ETXTBSY = 0x1004E, // Text file busy.
EXDEV = 0x1004F, // Cross-device link.
// POSIX permits these to have the same value and we make them always equal so
// that CoreFX cannot introduce a dependency on distinguishing between them that
// would not work on all platforms.
EOPNOTSUPP = ENOTSUP, // Operation not supported on socket
EWOULDBLOCK = EAGAIN, // Operation would block
}
// Represents a platform-agnostic Error and underlying platform-specific errno
internal struct ErrorInfo
{
private Error _error;
private int _rawErrno;
internal ErrorInfo(int errno)
{
_error = Interop.Sys.ConvertErrorPlatformToPal(errno);
_rawErrno = errno;
}
internal ErrorInfo(Error error)
{
_error = error;
_rawErrno = -1;
}
internal Error Error
{
get { return _error; }
}
internal int RawErrno
{
get { return _rawErrno == -1 ? (_rawErrno = Interop.Sys.ConvertErrorPalToPlatform(_error)) : _rawErrno; }
}
internal string GetErrorMessage()
{
return Interop.Sys.StrError(RawErrno);
}
public override string ToString()
{
return string.Format(
"RawErrno: {0} Error: {1} GetErrorMessage: {2}", // No localization required; text is member names used for debugging purposes
RawErrno, Error, GetErrorMessage());
}
}
internal partial class Sys
{
internal static Error GetLastError()
{
return ConvertErrorPlatformToPal(Marshal.GetLastWin32Error());
}
internal static ErrorInfo GetLastErrorInfo()
{
return new ErrorInfo(Marshal.GetLastWin32Error());
}
internal static unsafe string StrError(int platformErrno)
{
int maxBufferLength = 1024; // should be long enough for most any UNIX error
byte* buffer = stackalloc byte[maxBufferLength];
byte* message = StrErrorR(platformErrno, buffer, maxBufferLength);
if (message == null)
{
// This means the buffer was not large enough, but still contains
// as much of the error message as possible and is guaranteed to
// be null-terminated. We're not currently resizing/retrying because
// maxBufferLength is large enough in practice, but we could do
// so here in the future if necessary.
message = buffer;
}
return Marshal.PtrToStringAnsi((IntPtr)message);
}
[DllImport(Libraries.SystemNative)]
internal static extern Error ConvertErrorPlatformToPal(int platformErrno);
[DllImport(Libraries.SystemNative)]
internal static extern int ConvertErrorPalToPlatform(Error error);
[DllImport(Libraries.SystemNative)]
private static unsafe extern byte* StrErrorR(int platformErrno, byte* buffer, int bufferSize);
}
}
// NOTE: extension method can't be nested inside Interop class.
internal static class InteropErrorExtensions
{
// Intended usage is e.g. Interop.Error.EFAIL.Info() for brevity
// vs. new Interop.ErrorInfo(Interop.Error.EFAIL) for synthesizing
// errors. Errors originated from the system should be obtained
// via GetLastErrorInfo(), not GetLastError().Info() as that will
// convert twice, which is not only inefficient but also lossy if
// we ever encounter a raw errno that no equivalent in the Error
// enum.
public static Interop.ErrorInfo Info(this Interop.Error error)
{
return new Interop.ErrorInfo(error);
}
}
| |
namespace android.graphics.drawable
{
[global::MonoJavaBridge.JavaClass()]
public partial class ShapeDrawable : android.graphics.drawable.Drawable
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ShapeDrawable()
{
InitJNI();
}
protected ShapeDrawable(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
[global::MonoJavaBridge.JavaClass(typeof(global::android.graphics.drawable.ShapeDrawable.ShaderFactory_))]
public abstract partial class ShaderFactory : java.lang.Object
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ShaderFactory()
{
InitJNI();
}
protected ShaderFactory(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _resize4185;
public abstract global::android.graphics.Shader resize(int arg0, int arg1);
internal static global::MonoJavaBridge.MethodId _ShaderFactory4186;
public ShaderFactory() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.ShapeDrawable.ShaderFactory.staticClass, global::android.graphics.drawable.ShapeDrawable.ShaderFactory._ShaderFactory4186);
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.drawable.ShapeDrawable.ShaderFactory.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/ShapeDrawable$ShaderFactory"));
global::android.graphics.drawable.ShapeDrawable.ShaderFactory._resize4185 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.ShaderFactory.staticClass, "resize", "(II)Landroid/graphics/Shader;");
global::android.graphics.drawable.ShapeDrawable.ShaderFactory._ShaderFactory4186 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.ShaderFactory.staticClass, "<init>", "()V");
}
}
[global::MonoJavaBridge.JavaProxy(typeof(global::android.graphics.drawable.ShapeDrawable.ShaderFactory))]
public sealed partial class ShaderFactory_ : android.graphics.drawable.ShapeDrawable.ShaderFactory
{
internal new static global::MonoJavaBridge.JniGlobalHandle staticClass;
static ShaderFactory_()
{
InitJNI();
}
internal ShaderFactory_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env)
{
}
internal static global::MonoJavaBridge.MethodId _resize4187;
public override global::android.graphics.Shader resize(int arg0, int arg1)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.ShaderFactory_._resize4187, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.graphics.Shader;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.ShaderFactory_.staticClass, global::android.graphics.drawable.ShapeDrawable.ShaderFactory_._resize4187, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1))) as android.graphics.Shader;
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.drawable.ShapeDrawable.ShaderFactory_.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/ShapeDrawable$ShaderFactory"));
global::android.graphics.drawable.ShapeDrawable.ShaderFactory_._resize4187 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.ShaderFactory_.staticClass, "resize", "(II)Landroid/graphics/Shader;");
}
}
internal static global::MonoJavaBridge.MethodId _inflate4188;
public override void inflate(android.content.res.Resources arg0, org.xmlpull.v1.XmlPullParser arg1, android.util.AttributeSet arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._inflate4188, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._inflate4188, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _draw4189;
public override void draw(android.graphics.Canvas arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._draw4189, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._draw4189, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getChangingConfigurations4190;
public override int getChangingConfigurations()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._getChangingConfigurations4190);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._getChangingConfigurations4190);
}
internal static global::MonoJavaBridge.MethodId _setDither4191;
public override void setDither(bool arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._setDither4191, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._setDither4191, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setAlpha4192;
public override void setAlpha(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._setAlpha4192, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._setAlpha4192, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setColorFilter4193;
public override void setColorFilter(android.graphics.ColorFilter arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._setColorFilter4193, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._setColorFilter4193, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getOpacity4194;
public override int getOpacity()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._getOpacity4194);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._getOpacity4194);
}
internal static global::MonoJavaBridge.MethodId _onBoundsChange4195;
protected override void onBoundsChange(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._onBoundsChange4195, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._onBoundsChange4195, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getIntrinsicWidth4196;
public override int getIntrinsicWidth()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._getIntrinsicWidth4196);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._getIntrinsicWidth4196);
}
internal static global::MonoJavaBridge.MethodId _getIntrinsicHeight4197;
public override int getIntrinsicHeight()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallIntMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._getIntrinsicHeight4197);
else
return @__env.CallNonVirtualIntMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._getIntrinsicHeight4197);
}
internal static global::MonoJavaBridge.MethodId _getPadding4198;
public override bool getPadding(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._getPadding4198, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._getPadding4198, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _mutate4199;
public override global::android.graphics.drawable.Drawable mutate()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._mutate4199)) as android.graphics.drawable.Drawable;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._mutate4199)) as android.graphics.drawable.Drawable;
}
internal static global::MonoJavaBridge.MethodId _getConstantState4200;
public override global::android.graphics.drawable.Drawable.ConstantState getConstantState()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._getConstantState4200)) as android.graphics.drawable.Drawable.ConstantState;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._getConstantState4200)) as android.graphics.drawable.Drawable.ConstantState;
}
internal static global::MonoJavaBridge.MethodId _onDraw4201;
protected virtual void onDraw(android.graphics.drawable.shapes.Shape arg0, android.graphics.Canvas arg1, android.graphics.Paint arg2)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._onDraw4201, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._onDraw4201, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2));
}
internal static global::MonoJavaBridge.MethodId _setPadding4202;
public virtual void setPadding(android.graphics.Rect arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._setPadding4202, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._setPadding4202, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setPadding4203;
public virtual void setPadding(int arg0, int arg1, int arg2, int arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._setPadding4203, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._setPadding4203, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _getPaint4204;
public virtual global::android.graphics.Paint getPaint()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._getPaint4204)) as android.graphics.Paint;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._getPaint4204)) as android.graphics.Paint;
}
internal static global::MonoJavaBridge.MethodId _setShape4205;
public virtual void setShape(android.graphics.drawable.shapes.Shape arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._setShape4205, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._setShape4205, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _inflateTag4206;
protected virtual bool inflateTag(java.lang.String arg0, android.content.res.Resources arg1, org.xmlpull.v1.XmlPullParser arg2, android.util.AttributeSet arg3)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return @__env.CallBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._inflateTag4206, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
else
return @__env.CallNonVirtualBooleanMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._inflateTag4206, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg3));
}
internal static global::MonoJavaBridge.MethodId _getShape4207;
public virtual global::android.graphics.drawable.shapes.Shape getShape()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._getShape4207)) as android.graphics.drawable.shapes.Shape;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._getShape4207)) as android.graphics.drawable.shapes.Shape;
}
internal static global::MonoJavaBridge.MethodId _setShaderFactory4208;
public virtual void setShaderFactory(android.graphics.drawable.ShapeDrawable.ShaderFactory arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._setShaderFactory4208, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._setShaderFactory4208, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _getShaderFactory4209;
public virtual global::android.graphics.drawable.ShapeDrawable.ShaderFactory getShaderFactory()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallObjectMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._getShaderFactory4209)) as android.graphics.drawable.ShapeDrawable.ShaderFactory;
else
return global::MonoJavaBridge.JavaBridge.WrapJavaObject(@__env.CallNonVirtualObjectMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._getShaderFactory4209)) as android.graphics.drawable.ShapeDrawable.ShaderFactory;
}
internal static global::MonoJavaBridge.MethodId _setIntrinsicWidth4210;
public virtual void setIntrinsicWidth(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._setIntrinsicWidth4210, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._setIntrinsicWidth4210, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _setIntrinsicHeight4211;
public virtual void setIntrinsicHeight(int arg0)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
if (!IsClrObject)
@__env.CallVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable._setIntrinsicHeight4211, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
else
@__env.CallNonVirtualVoidMethod(this.JvmHandle, global::android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._setIntrinsicHeight4211, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
}
internal static global::MonoJavaBridge.MethodId _ShapeDrawable4212;
public ShapeDrawable() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._ShapeDrawable4212);
Init(@__env, handle);
}
internal static global::MonoJavaBridge.MethodId _ShapeDrawable4213;
public ShapeDrawable(android.graphics.drawable.shapes.Shape arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv)
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(android.graphics.drawable.ShapeDrawable.staticClass, global::android.graphics.drawable.ShapeDrawable._ShapeDrawable4213, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0));
Init(@__env, handle);
}
private static void InitJNI()
{
global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv;
global::android.graphics.drawable.ShapeDrawable.staticClass = @__env.NewGlobalRef(@__env.FindClass("android/graphics/drawable/ShapeDrawable"));
global::android.graphics.drawable.ShapeDrawable._inflate4188 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "inflate", "(Landroid/content/res/Resources;Lorg/xmlpull/v1/XmlPullParser;Landroid/util/AttributeSet;)V");
global::android.graphics.drawable.ShapeDrawable._draw4189 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "draw", "(Landroid/graphics/Canvas;)V");
global::android.graphics.drawable.ShapeDrawable._getChangingConfigurations4190 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "getChangingConfigurations", "()I");
global::android.graphics.drawable.ShapeDrawable._setDither4191 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "setDither", "(Z)V");
global::android.graphics.drawable.ShapeDrawable._setAlpha4192 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "setAlpha", "(I)V");
global::android.graphics.drawable.ShapeDrawable._setColorFilter4193 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "setColorFilter", "(Landroid/graphics/ColorFilter;)V");
global::android.graphics.drawable.ShapeDrawable._getOpacity4194 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "getOpacity", "()I");
global::android.graphics.drawable.ShapeDrawable._onBoundsChange4195 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "onBoundsChange", "(Landroid/graphics/Rect;)V");
global::android.graphics.drawable.ShapeDrawable._getIntrinsicWidth4196 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "getIntrinsicWidth", "()I");
global::android.graphics.drawable.ShapeDrawable._getIntrinsicHeight4197 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "getIntrinsicHeight", "()I");
global::android.graphics.drawable.ShapeDrawable._getPadding4198 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "getPadding", "(Landroid/graphics/Rect;)Z");
global::android.graphics.drawable.ShapeDrawable._mutate4199 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "mutate", "()Landroid/graphics/drawable/Drawable;");
global::android.graphics.drawable.ShapeDrawable._getConstantState4200 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "getConstantState", "()Landroid/graphics/drawable/Drawable$ConstantState;");
global::android.graphics.drawable.ShapeDrawable._onDraw4201 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "onDraw", "(Landroid/graphics/drawable/shapes/Shape;Landroid/graphics/Canvas;Landroid/graphics/Paint;)V");
global::android.graphics.drawable.ShapeDrawable._setPadding4202 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "setPadding", "(Landroid/graphics/Rect;)V");
global::android.graphics.drawable.ShapeDrawable._setPadding4203 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "setPadding", "(IIII)V");
global::android.graphics.drawable.ShapeDrawable._getPaint4204 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "getPaint", "()Landroid/graphics/Paint;");
global::android.graphics.drawable.ShapeDrawable._setShape4205 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "setShape", "(Landroid/graphics/drawable/shapes/Shape;)V");
global::android.graphics.drawable.ShapeDrawable._inflateTag4206 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "inflateTag", "(Ljava/lang/String;Landroid/content/res/Resources;Lorg/xmlpull/v1/XmlPullParser;Landroid/util/AttributeSet;)Z");
global::android.graphics.drawable.ShapeDrawable._getShape4207 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "getShape", "()Landroid/graphics/drawable/shapes/Shape;");
global::android.graphics.drawable.ShapeDrawable._setShaderFactory4208 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "setShaderFactory", "(Landroid/graphics/drawable/ShapeDrawable$ShaderFactory;)V");
global::android.graphics.drawable.ShapeDrawable._getShaderFactory4209 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "getShaderFactory", "()Landroid/graphics/drawable/ShapeDrawable$ShaderFactory;");
global::android.graphics.drawable.ShapeDrawable._setIntrinsicWidth4210 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "setIntrinsicWidth", "(I)V");
global::android.graphics.drawable.ShapeDrawable._setIntrinsicHeight4211 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "setIntrinsicHeight", "(I)V");
global::android.graphics.drawable.ShapeDrawable._ShapeDrawable4212 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "<init>", "()V");
global::android.graphics.drawable.ShapeDrawable._ShapeDrawable4213 = @__env.GetMethodIDNoThrow(global::android.graphics.drawable.ShapeDrawable.staticClass, "<init>", "(Landroid/graphics/drawable/shapes/Shape;)V");
}
}
}
| |
/*
* 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.
*/
namespace Apache.Ignite.Core.Tests.Process
{
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Apache.Ignite.Core.Impl.Common;
/// <summary>
/// Defines forked Ignite node.
/// </summary>
public class IgniteProcess
{
/** Executable file name. */
private static readonly string ExeName = "Apache.Ignite.exe";
/** Executable process name. */
private static readonly string ExeProcName = ExeName.Substring(0, ExeName.LastIndexOf('.'));
/** Executable configuration file name. */
private static readonly string ExeCfgName = ExeName + ".config";
/** Executable backup configuration file name. */
private static readonly string ExeCfgBakName = ExeCfgName + ".bak";
/** Directory where binaries are stored. */
private static readonly string ExeDir;
/** Full path to executable. */
private static readonly string ExePath;
/** Full path to executable configuration file. */
private static readonly string ExeCfgPath;
/** Full path to executable configuration file backup. */
private static readonly string ExeCfgBakPath;
/** Default process output reader. */
private static readonly IIgniteProcessOutputReader DfltOutReader = new IgniteProcessConsoleOutputReader();
/** Process. */
private readonly Process _proc;
/// <summary>
/// Static initializer.
/// </summary>
static IgniteProcess()
{
// 1. Locate executable file and related stuff.
DirectoryInfo dir = new FileInfo(new Uri(typeof(IgniteProcess).Assembly.CodeBase).LocalPath).Directory;
// ReSharper disable once PossibleNullReferenceException
ExeDir = dir.FullName;
var exe = dir.GetFiles(ExeName);
if (exe.Length == 0)
throw new Exception(ExeName + " is not found in test output directory: " + dir.FullName);
ExePath = exe[0].FullName;
var exeCfg = dir.GetFiles(ExeCfgName);
if (exeCfg.Length == 0)
throw new Exception(ExeCfgName + " is not found in test output directory: " + dir.FullName);
ExeCfgPath = exeCfg[0].FullName;
ExeCfgBakPath = Path.Combine(ExeDir, ExeCfgBakName);
File.Delete(ExeCfgBakPath);
}
/// <summary>
/// Save current configuration to backup.
/// </summary>
public static void SaveConfigurationBackup()
{
File.Copy(ExeCfgPath, ExeCfgBakPath, true);
}
/// <summary>
/// Restore configuration from backup.
/// </summary>
public static void RestoreConfigurationBackup()
{
File.Copy(ExeCfgBakPath, ExeCfgPath, true);
}
/// <summary>
/// Replace application configuration with another one.
/// </summary>
/// <param name="relPath">Path to config relative to executable directory.</param>
public static void ReplaceConfiguration(string relPath)
{
File.Copy(Path.Combine(ExeDir, relPath), ExeCfgPath, true);
}
/// <summary>
/// Kill all Ignite processes.
/// </summary>
public static void KillAll()
{
foreach (Process proc in Process.GetProcesses())
{
if (proc.ProcessName.Equals(ExeProcName))
{
proc.Kill();
proc.WaitForExit();
}
}
}
/// <summary>
/// Construector.
/// </summary>
/// <param name="args">Arguments</param>
public IgniteProcess(params string[] args) : this(DfltOutReader, args) { }
/// <summary>
/// Construector.
/// </summary>
/// <param name="outReader">Output reader.</param>
/// <param name="args">Arguments.</param>
public IgniteProcess(IIgniteProcessOutputReader outReader, params string[] args)
{
// Add test dll path
args = args.Concat(new[] {"-assembly=" + GetType().Assembly.Location}).ToArray();
_proc = Start(ExePath, IgniteHome.Resolve(null), outReader, args);
}
/// <summary>
/// Starts a grid process.
/// </summary>
/// <param name="exePath">Exe path.</param>
/// <param name="ggHome">Ignite home.</param>
/// <param name="outReader">Output reader.</param>
/// <param name="args">Arguments.</param>
/// <returns>Started process.</returns>
public static Process Start(string exePath, string ggHome, IIgniteProcessOutputReader outReader = null,
params string[] args)
{
Debug.Assert(!string.IsNullOrEmpty(exePath));
// 1. Define process start configuration.
var sb = new StringBuilder();
foreach (string arg in args)
sb.Append('\"').Append(arg).Append("\" ");
var procStart = new ProcessStartInfo
{
FileName = exePath,
Arguments = sb.ToString(),
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
if (ggHome != null)
procStart.EnvironmentVariables[IgniteHome.EnvIgniteHome] = ggHome;
procStart.EnvironmentVariables[Classpath.EnvIgniteNativeTestClasspath] = "true";
var workDir = Path.GetDirectoryName(exePath);
if (workDir != null)
procStart.WorkingDirectory = workDir;
Console.WriteLine("About to run Apache.Ignite.exe process [exePath=" + exePath + ", arguments=" + sb + ']');
// 2. Start.
var proc = Process.Start(procStart);
Debug.Assert(proc != null);
// 3. Attach output readers to avoid hangs.
AttachProcessConsoleReader(proc, outReader);
return proc;
}
/// <summary>
/// Attaches the process console reader.
/// </summary>
public static void AttachProcessConsoleReader(Process proc, IIgniteProcessOutputReader outReader = null)
{
outReader = outReader ?? DfltOutReader;
Attach(proc, proc.StandardOutput, outReader, false);
Attach(proc, proc.StandardError, outReader, true);
}
/// <summary>
/// Whether the process is still alive.
/// </summary>
public bool Alive
{
get { return !_proc.HasExited; }
}
/// <summary>
/// Gets the process.
/// </summary>
public string GetInfo()
{
return Alive
? string.Format("Id={0}, Alive={1}", _proc.Id, Alive)
: string.Format("Id={0}, Alive={1}, ExitCode={2}, ExitTime={3}",
_proc.Id, Alive, _proc.ExitCode, _proc.ExitTime);
}
/// <summary>
/// Kill process.
/// </summary>
public void Kill()
{
_proc.Kill();
}
/// <summary>
/// Suspends the process.
/// </summary>
public void Suspend()
{
_proc.Suspend();
}
/// <summary>
/// Resumes the process.
/// </summary>
public void Resume()
{
_proc.Resume();
}
/// <summary>
/// Join process.
/// </summary>
/// <returns>Exit code.</returns>
public int Join()
{
_proc.WaitForExit();
return _proc.ExitCode;
}
/// <summary>
/// Join process with timeout.
/// </summary>
/// <param name="timeout">Timeout in milliseconds.</param>
/// <param name="exitCode">Exit code.</param>
/// <returns><c>True</c> if process exit occurred before timeout.</returns>
public bool Join(int timeout, out int exitCode)
{
if (_proc.WaitForExit(timeout))
{
exitCode = _proc.ExitCode;
return true;
}
exitCode = 0;
return false;
}
/// <summary>
/// Attach output reader to the process.
/// </summary>
/// <param name="proc">Process.</param>
/// <param name="reader">Process stream reader.</param>
/// <param name="outReader">Output reader.</param>
/// <param name="err">Whether this is error stream.</param>
private static void Attach(Process proc, StreamReader reader, IIgniteProcessOutputReader outReader, bool err)
{
new Thread(() =>
{
while (!proc.HasExited)
outReader.OnOutput(proc, reader.ReadLine(), err);
}) {IsBackground = true}.Start();
}
}
}
| |
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using FullSerializer;
namespace ModelLoaderFileExplorer {
public class ModelData {
public string name;
public bool isPrivate;
public float unitSize;
public int cpuCoresCount;
public float cpuHz;
public int hddBaysCount;
public int memorySpeed;
public List<PairData> memoryCapacity;
public string raid;
public List<PairData> hdd;
public List<PairData> network;
public List<string> gpu;
public DateTime timeStamp;
public float fileSize;
public string details;
public string modelFile;
public string modelUrl;
public string modelPath;
public string objectId;
public string username;
private static readonly fsSerializer _serializer = new fsSerializer();
public ModelData () {
memoryCapacity = new List<PairData>();
hdd = new List<PairData>();
network = new List<PairData>();
gpu = new List<string>();
timeStamp = DateTime.Now;
}
public ModelData (string name,
bool isPrivate,
float unitSize,
int cpuCoresCount,
float cpuHz,
int hddBaysCount,
int memorySpeed,
List<PairData> memoryCapacity,
string raid,
List<PairData> hdd,
List<PairData> network,
List<string> gpu,
float fileSize,
string details,
DateTime timeStamp) {
this.name = name;
this.isPrivate = isPrivate;
this.unitSize = unitSize;
this.cpuCoresCount = cpuCoresCount;
this.cpuHz = cpuHz;
this.hddBaysCount = hddBaysCount;
this.memorySpeed = memorySpeed;
this.memoryCapacity = memoryCapacity;
this.raid = raid;
this.hdd = hdd;
this.network = network;
this.gpu = gpu;
this.fileSize = fileSize;
this.details = details;
this.timeStamp = timeStamp;
}
public override string ToString () {
string memoryCapacityString = GetListString<PairData>(memoryCapacity);
string hddString = GetListString<PairData>(hdd);
string networkString = GetListString<PairData>(network);
string gpuString = GetListString<String>(gpu);
return string.Format ("[ModelData] \n" +
" Name: {0} \n" +
" Unit Size: {1} \n" +
" CPU Cores Count: {2} \n" +
" CPU Hz: {3} \n" +
" HDD Bays Count: {4} \n" +
" Memory Speed: {5} \n" +
" Memory Caacity: {6} \n" +
" RAID: {7} \n" +
" HDD: {8} \n" +
" Network: {9} \n" +
" GPU: {10} \n" +
" \n" +
" File Size: {11} \n" +
" Details: {12} \n" +
" Time Stamp: {13} \n" +
" Is Private: {14} \n",
name,
unitSize,
cpuCoresCount,
cpuHz,
hddBaysCount,
memorySpeed,
memoryCapacityString,
raid,
hddString,
networkString,
gpuString,
fileSize,
details,
timeStamp.ToString(),
isPrivate);
}
public void Serialize () {
fsData data;
_serializer.TrySerialize<ModelData>(this, out data).AssertSuccessWithoutWarnings();
PersistanceManager.StoreLocalModelData(name, fsJsonPrinter.PrettyJson(data), modelPath);
}
public void MakeCloud () {
CloudData.SaveInCloud(this, () => {
Debug.Log("MakeCould: Success");
},
(string s) => {
Debug.Log("MakeCould: Failed");
Debug.Log("Exception: " + s);
});
}
public void AddToUser () {
objectId = null;
CloudData.SaveInCloud(this, () => {
Debug.Log("Save In Cloud: Success");
},
(string s) => {
Debug.Log("Save In Cloud: Failed");
Debug.Log("Exception: " + s);
});
}
public static ModelData Deserialize (string content) {
fsData data = fsJsonParser.Parse(content);
ModelData modelData = null;
_serializer.TryDeserialize(data, ref modelData).AssertSuccessWithoutWarnings();
return modelData;
}
private static string GetListString<T> (List<T> objList) {
string result = "";
foreach (T obj in objList) {
result += " " + obj.ToString() + "\n";
}
return result;
}
}
public struct PairData {
public int count;
public int data;
public PairData (int count, int data) {
this.count = count;
this.data = data;
}
public override string ToString (){
return count + " x " + data;
}
public static int[] ToArrayOfInts (List<PairData> datas) {
var arr = new int[2 * datas.Count];
for (int i=0; i<datas.Count; i++) {
arr[2*i] = datas[i].count;
arr[2*i+1] = datas[i].data;
}
return arr;
}
public static List<PairData> FromArrOfIntsToList (int[] arr) {
var list = new List<PairData>();
for (int i=0; i<arr.Length; i+=2) {
int count = arr[i];
int data = arr[i+1];
list.Add(new PairData(count, data));
}
return list;
}
public static List<PairData> FromListOfIntsToList (IList<int> listInt) {
var list = new List<PairData>();
for (int i=0; i<listInt.Count; i+=2) {
int count = listInt[i];
int data = listInt[i+1];
list.Add(new PairData(count, data));
}
return list;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using mshtml;
using OpenLiveWriter.Api;
using OpenLiveWriter.Extensibility.BlogClient;
namespace OpenLiveWriter.Extensibility.ImageEditing
{
public enum ImageDecoratorInvocationSource { Unknown, InitialInsert, Resize, Reset, ImagePropertiesEditor, Command, TiltPreview };
public enum ImageEmbedType { Embedded, Linked };
/// <summary>
/// Provides runtime context information and callbacks related to the image that a decorator is modifying.
/// </summary>
public interface ImageDecoratorContext
{
/// <summary>
/// The raw image that is being decorated.
/// </summary>
Bitmap Image { get; set; }
/// <summary>
/// The size of the border margins applied to the image.
/// </summary>
ImageBorderMargin BorderMargin { get; set; }
/// <summary>
/// The settings for the decorator.
/// </summary>
IProperties Settings { get; }
/// <summary>
/// The options for the current blog client
/// </summary>
IEditorOptions EditorOptions { get; }
/// <summary>
/// Returns the manner in which the current image is embedded into the post document.
/// </summary>
ImageEmbedType ImageEmbedType { get; }
/// <summary>
/// The img HTML element associated with the image being decorated.
/// </summary>
IHTMLElement ImgElement { get; }
/// <summary>
/// Returns a hint about the reason the image decoration was triggered.
/// </summary>
ImageDecoratorInvocationSource InvocationSource { get; }
/// <summary>
/// The rotation of the image with respect to the original source image.
/// </summary>
RotateFlipType ImageRotation { get; }
/// <summary>
/// The URI of the original source image.
/// </summary>
Uri SourceImageUri { get; }
float? EnforcedAspectRatio { get; }
}
/// <summary>
/// An ImageBorderMargin serves two purposes. It notes the current
/// amount of margin that has actually been applied to an image, and
/// it also keeps track of the calculations that were used to come
/// up with that amount of margin. The calculations are necessary to
/// determine how much border margin would be applied to the same image
/// at other sizes.
/// </summary>
public class ImageBorderMargin
{
private readonly int _width;
private readonly int _height;
private readonly List<BorderCalculation> _calculations;
public ImageBorderMargin(int width, int height, BorderCalculation calculation)
{
_width = width;
_height = height;
_calculations = new List<BorderCalculation>();
_calculations.Add(calculation);
}
public ImageBorderMargin(ImageBorderMargin existingBorder, int width, int height, BorderCalculation calculation)
{
_width = width + existingBorder.Width;
_height = height + existingBorder.Height;
_calculations = new List<BorderCalculation>(existingBorder._calculations);
_calculations.Add(calculation);
}
#region Property names
private const string WIDTH = "Width";
private const string HEIGHT = "Height";
private const string COUNT = "CalcCount";
private const string CALC = "Calc";
private const string WIDTH_ADD = "WidthAdd";
private const string HEIGHT_ADD = "HeightAdd";
private const string WIDTH_FACTOR = "WidthFactor";
private const string HEIGHT_FACTOR = "HeightFactor";
#endregion
public ImageBorderMargin(IProperties properties)
{
_width = properties.GetInt(WIDTH, 0);
_height = properties.GetInt(HEIGHT, 0);
int calcCount = properties.GetInt(COUNT, 0);
_calculations = new List<BorderCalculation>(calcCount);
for (int i = 0; i < calcCount; i++)
{
string prefix = CALC + i.ToString(CultureInfo.InvariantCulture);
_calculations.Add(new BorderCalculation(
properties.GetInt(prefix + WIDTH_ADD, 0),
properties.GetInt(prefix + HEIGHT_ADD, 0),
properties.GetFloat(prefix + WIDTH_FACTOR, 1f),
properties.GetFloat(prefix + HEIGHT_FACTOR, 1f)));
}
}
public void Save(IProperties properties)
{
properties.RemoveAll();
properties.SetInt(WIDTH, _width);
properties.SetInt(HEIGHT, _height);
properties.SetInt(COUNT, _calculations.Count);
for (int i = 0; i < _calculations.Count; i++)
{
BorderCalculation calc = _calculations[i];
string prefix = CALC + i.ToString(CultureInfo.InvariantCulture);
properties.SetInt(prefix + WIDTH_ADD, calc.WidthAdd);
properties.SetInt(prefix + HEIGHT_ADD, calc.HeightAdd);
properties.SetFloat(prefix + WIDTH_FACTOR, calc.WidthFactor);
properties.SetFloat(prefix + HEIGHT_FACTOR, calc.HeightFactor);
}
}
public int Width
{
get { return _width; }
}
public int Height
{
get { return _height; }
}
/// <summary>
/// Create a blank ImageBorderMargin.
/// </summary>
public static ImageBorderMargin Empty
{
get { return new ImageBorderMargin(0, 0, new BorderCalculation(0, 0, 1f, 1f)); }
}
public Size CalculateImageSize(Size imageSize)
{
foreach (BorderCalculation calc in _calculations)
imageSize = calc.ForwardCalculation(imageSize);
return imageSize;
}
public Size ReverseCalculateImageSize(Size imageSize)
{
for (int i = _calculations.Count - 1; i >= 0; i--)
{
imageSize = _calculations[i].ReverseCalculation(imageSize);
}
return imageSize;
}
}
public class BorderCalculation
{
private readonly int _widthAdd = 0;
private readonly int _heightAdd = 0;
private readonly float _widthFactor = 1f;
private readonly float _heightFactor = 1f;
public BorderCalculation(int widthAdd, int heightAdd, float widthFactor, float heightFactor)
{
_widthAdd = widthAdd;
_heightAdd = heightAdd;
_widthFactor = widthFactor;
_heightFactor = heightFactor;
}
public BorderCalculation(int widthAdd, int heightAdd)
{
_widthAdd = widthAdd;
_heightAdd = heightAdd;
}
public BorderCalculation(float widthFactor, float heightFactor)
{
_widthFactor = widthFactor;
_heightFactor = heightFactor;
}
internal int WidthAdd
{
get { return _widthAdd; }
}
internal int HeightAdd
{
get { return _heightAdd; }
}
internal float WidthFactor
{
get { return _widthFactor; }
}
internal float HeightFactor
{
get { return _heightFactor; }
}
public Size ForwardCalculation(Size size)
{
size.Width += _widthAdd;
size.Width = (int)(Math.Round(size.Width * _widthFactor));
size.Height += _heightAdd;
size.Height = (int)(Math.Round(size.Height * _heightFactor));
return size;
}
public Size ReverseCalculation(Size size)
{
size.Width = (int)(Math.Round(size.Width / _widthFactor));
size.Width -= _widthAdd;
size.Height = (int)(Math.Round(size.Height / _heightFactor));
size.Height -= _heightAdd;
return size;
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Net.Http.Headers;
using System.Diagnostics.Contracts;
using System.Text;
namespace System.Net.Http
{
[SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix",
Justification = "Represents a multipart/* content. Even if a collection of HttpContent is stored, " +
"suffix Collection is not appropriate.")]
public class MultipartContent : HttpContent, IEnumerable<HttpContent>
{
#region Fields
private const string crlf = "\r\n";
private List<HttpContent> _nestedContent;
private string _boundary;
// Temp context for serialization.
private int _nextContentIndex;
private Stream _outputStream;
private TaskCompletionSource<Object> _tcs;
#endregion Fields
#region Construction
public MultipartContent()
: this("mixed", GetDefaultBoundary())
{ }
public MultipartContent(string subtype)
: this(subtype, GetDefaultBoundary())
{ }
public MultipartContent(string subtype, string boundary)
{
if (string.IsNullOrWhiteSpace(subtype))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "subtype");
}
Contract.EndContractBlock();
ValidateBoundary(boundary);
_boundary = boundary;
string quotedBoundary = boundary;
if (!quotedBoundary.StartsWith("\"", StringComparison.Ordinal))
{
quotedBoundary = "\"" + quotedBoundary + "\"";
}
MediaTypeHeaderValue contentType = new MediaTypeHeaderValue("multipart/" + subtype);
contentType.Parameters.Add(new NameValueHeaderValue("boundary", quotedBoundary));
Headers.ContentType = contentType;
_nestedContent = new List<HttpContent>();
}
private static void ValidateBoundary(string boundary)
{
// NameValueHeaderValue is too restrictive for boundary.
// Instead validate it ourselves and then quote it.
if (string.IsNullOrWhiteSpace(boundary))
{
throw new ArgumentException(SR.net_http_argument_empty_string, "boundary");
}
// RFC 2046 Section 5.1.1
// boundary := 0*69<bchars> bcharsnospace
// bchars := bcharsnospace / " "
// bcharsnospace := DIGIT / ALPHA / "'" / "(" / ")" / "+" / "_" / "," / "-" / "." / "/" / ":" / "=" / "?"
if (boundary.Length > 70)
{
throw new ArgumentOutOfRangeException("boundary", boundary,
string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_content_field_too_long, 70));
}
// Cannot end with space.
if (boundary.EndsWith(" ", StringComparison.Ordinal))
{
throw new ArgumentException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), "boundary");
}
Contract.EndContractBlock();
string allowedMarks = @"'()+_,-./:=? ";
foreach (char ch in boundary)
{
if (('0' <= ch && ch <= '9') || // Digit.
('a' <= ch && ch <= 'z') || // alpha.
('A' <= ch && ch <= 'Z') || // ALPHA.
(allowedMarks.IndexOf(ch) >= 0)) // Marks.
{
// Valid.
}
else
{
throw new ArgumentException(string.Format(System.Globalization.CultureInfo.InvariantCulture, SR.net_http_headers_invalid_value, boundary), "boundary");
}
}
}
private static string GetDefaultBoundary()
{
return Guid.NewGuid().ToString();
}
public virtual void Add(HttpContent content)
{
if (content == null)
{
throw new ArgumentNullException("content");
}
Contract.EndContractBlock();
_nestedContent.Add(content);
}
#endregion Construction
#region Dispose
protected override void Dispose(bool disposing)
{
if (disposing)
{
foreach (HttpContent content in _nestedContent)
{
content.Dispose();
}
_nestedContent.Clear();
}
base.Dispose(disposing);
}
#endregion Dispose
#region IEnumerable<HttpContent> Members
public IEnumerator<HttpContent> GetEnumerator()
{
return _nestedContent.GetEnumerator();
}
#endregion
#region IEnumerable Members
Collections.IEnumerator Collections.IEnumerable.GetEnumerator()
{
return _nestedContent.GetEnumerator();
}
#endregion
#region Serialization
// for-each content
// write "--" + boundary
// for-each content header
// write header: header-value
// write content.CopyTo[Async]
// write "--" + boundary + "--"
// Can't be canceled directly by the user. If the overall request is canceled
// then the stream will be closed an an exception thrown.
protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
{
Debug.Assert(stream != null);
Debug.Assert(_outputStream == null, "Opperation already in progress");
Debug.Assert(_tcs == null, "Opperation already in progress");
Debug.Assert(_nextContentIndex == 0, "Opperation already in progress");
// Keep a local copy in case the operation completes and cleans up synchronously.
TaskCompletionSource<Object> localTcs = new TaskCompletionSource<Object>();
_tcs = localTcs;
_outputStream = stream;
_nextContentIndex = 0;
// Start Boundary, chain everything else.
EncodeStringToStreamAsync(_outputStream, "--" + _boundary + crlf)
.ContinueWithStandard(WriteNextContentHeadersAsync);
return localTcs.Task;
}
private void WriteNextContentHeadersAsync(Task task)
{
if (task.IsFaulted)
{
HandleAsyncException("WriteNextContentHeadersAsync", task.Exception.GetBaseException());
return;
}
try
{
// Base case, no more content, finish.
if (_nextContentIndex >= _nestedContent.Count)
{
WriteTerminatingBoundaryAsync();
return;
}
string internalBoundary = crlf + "--" + _boundary + crlf;
StringBuilder output = new StringBuilder();
if (_nextContentIndex == 0)
{
// First time, don't write dividing boundary.
}
else
{
output.Append(internalBoundary);
}
HttpContent content = _nestedContent[_nextContentIndex];
// Headers
foreach (KeyValuePair<string, IEnumerable<string>> headerPair in content.Headers)
{
output.Append(headerPair.Key + ": " + string.Join(", ", headerPair.Value) + crlf);
}
output.Append(crlf); // Extra CRLF to end headers (even if there are no headers).
EncodeStringToStreamAsync(_outputStream, output.ToString())
.ContinueWithStandard(WriteNextContentAsync);
}
catch (Exception ex)
{
HandleAsyncException("WriteNextContentHeadersAsync", ex);
}
}
private void WriteNextContentAsync(Task task)
{
if (task.IsFaulted)
{
HandleAsyncException("WriteNextContentAsync", task.Exception.GetBaseException());
return;
}
try
{
HttpContent content = _nestedContent[_nextContentIndex];
_nextContentIndex++; // Next call will operate on the next content object.
content.CopyToAsync(_outputStream)
.ContinueWithStandard(WriteNextContentHeadersAsync);
}
catch (Exception ex)
{
HandleAsyncException("WriteNextContentAsync", ex);
}
}
// Final step, write the footer boundary.
private void WriteTerminatingBoundaryAsync()
{
try
{
EncodeStringToStreamAsync(_outputStream, crlf + "--" + _boundary + "--" + crlf)
.ContinueWithStandard(task =>
{
if (task.IsFaulted)
{
HandleAsyncException("WriteTerminatingBoundaryAsync", task.Exception.GetBaseException());
return;
}
TaskCompletionSource<object> lastTcs = CleanupAsync();
lastTcs.TrySetResult(null); // This was the final opperation.
});
}
catch (Exception ex)
{
HandleAsyncException("WriteTerminatingBoundaryAsync", ex);
}
}
private static Task EncodeStringToStreamAsync(Stream stream, string input)
{
byte[] buffer = HttpRuleParser.DefaultHttpEncoding.GetBytes(input);
return stream.WriteAsync(buffer, 0, buffer.Length);
}
private TaskCompletionSource<object> CleanupAsync()
{
Contract.Requires(_tcs != null, "Operation already cleaned up");
TaskCompletionSource<object> toReturn = _tcs;
_outputStream = null;
_nextContentIndex = 0;
_tcs = null;
return toReturn;
}
private void HandleAsyncException(string method, Exception ex)
{
if (NetEventSource.Log.IsEnabled()) NetEventSource.Exception(NetEventSource.ComponentType.Http, this, method, ex);
TaskCompletionSource<object> lastTcs = CleanupAsync();
lastTcs.TrySetException(ex);
}
protected internal override bool TryComputeLength(out long length)
{
long currentLength = 0;
long internalBoundaryLength = GetEncodedLength(crlf + "--" + _boundary + crlf);
// Start Boundary.
currentLength += GetEncodedLength("--" + _boundary + crlf);
bool first = true;
foreach (HttpContent content in _nestedContent)
{
if (first)
{
first = false; // First boundary already written.
}
else
{
// Internal Boundary.
currentLength += internalBoundaryLength;
}
// Headers.
foreach (KeyValuePair<string, IEnumerable<string>> headerPair in content.Headers)
{
currentLength += GetEncodedLength(headerPair.Key + ": " + string.Join(", ", headerPair.Value) + crlf);
}
currentLength += crlf.Length;
// Content.
long tempContentLength = 0;
if (!content.TryComputeLength(out tempContentLength))
{
length = 0;
return false;
}
currentLength += tempContentLength;
}
// Terminating boundary.
currentLength += GetEncodedLength(crlf + "--" + _boundary + "--" + crlf);
length = currentLength;
return true;
}
private static int GetEncodedLength(string input)
{
return HttpRuleParser.DefaultHttpEncoding.GetByteCount(input);
}
#endregion Serialization
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using OpenSim.Framework;
using OpenSim.Server.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Reflection;
namespace OpenSim.Services.ProfilesService
{
public class UserProfilesService : UserProfilesServiceBase, IUserProfilesService
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private IAuthenticationService authService;
private IUserAccountService userAccounts;
public UserProfilesService(IConfigSource config, string configName) :
base(config, configName)
{
IConfig Config = config.Configs[configName];
if (Config == null)
{
m_log.Warn("[PROFILES]: No configuration found!");
return;
}
Object[] args = null;
args = new Object[] { config };
string accountService = Config.GetString("UserAccountService", String.Empty);
if (accountService != string.Empty)
userAccounts = ServerUtils.LoadPlugin<IUserAccountService>(accountService, args);
args = new Object[] { config };
string authServiceConfig = Config.GetString("AuthenticationServiceModule", String.Empty);
if (accountService != string.Empty)
authService = ServerUtils.LoadPlugin<IAuthenticationService>(authServiceConfig, args);
}
#region Classifieds
public OSD AvatarClassifiedsRequest(UUID creatorId)
{
OSDArray records = ProfilesData.GetClassifiedRecords(creatorId);
return records;
}
public bool ClassifiedDelete(UUID recordId)
{
if (ProfilesData.DeleteClassifiedRecord(recordId))
return true;
return false;
}
public bool ClassifiedInfoRequest(ref UserClassifiedAdd ad, ref string result)
{
if (ProfilesData.GetClassifiedInfo(ref ad, ref result))
return true;
return false;
}
public bool ClassifiedUpdate(UserClassifiedAdd ad, ref string result)
{
if (!ProfilesData.UpdateClassifiedRecord(ad, ref result))
{
return false;
}
result = "success";
return true;
}
#endregion Classifieds
#region Picks
public OSD AvatarPicksRequest(UUID creatorId)
{
OSDArray records = ProfilesData.GetAvatarPicks(creatorId);
return records;
}
public bool PickInfoRequest(ref UserProfilePick pick, ref string result)
{
pick = ProfilesData.GetPickInfo(pick.CreatorId, pick.PickId);
result = "OK";
return true;
}
public bool PicksDelete(UUID pickId)
{
return ProfilesData.DeletePicksRecord(pickId);
}
public bool PicksUpdate(ref UserProfilePick pick, ref string result)
{
return ProfilesData.UpdatePicksRecord(pick);
}
#endregion Picks
#region Notes
public bool AvatarNotesRequest(ref UserProfileNotes note)
{
return ProfilesData.GetAvatarNotes(ref note);
}
public bool NotesUpdate(ref UserProfileNotes note, ref string result)
{
return ProfilesData.UpdateAvatarNotes(ref note, ref result);
}
#endregion Notes
#region Profile Properties
public bool AvatarPropertiesRequest(ref UserProfileProperties prop, ref string result)
{
return ProfilesData.GetAvatarProperties(ref prop, ref result);
}
public bool AvatarPropertiesUpdate(ref UserProfileProperties prop, ref string result)
{
return ProfilesData.UpdateAvatarProperties(ref prop, ref result);
}
#endregion Profile Properties
#region Interests
public bool AvatarInterestsUpdate(UserProfileProperties prop, ref string result)
{
return ProfilesData.UpdateAvatarInterests(prop, ref result);
}
#endregion Interests
#region User Preferences
public bool UserPreferencesRequest(ref UserPreferences pref, ref string result)
{
if (string.IsNullOrEmpty(pref.EMail))
{
UserAccount account = new UserAccount();
if (userAccounts is UserAccountService.UserAccountService)
{
try
{
account = userAccounts.GetUserAccount(UUID.Zero, pref.UserId);
if (string.IsNullOrEmpty(account.Email))
{
result = "No Email address on record!";
return false;
}
else
pref.EMail = account.Email;
}
catch
{
m_log.Info("[PROFILES]: UserAccountService Exception: Could not get user account");
result = "Missing Email address!";
return false;
}
}
else
{
m_log.Info("[PROFILES]: UserAccountService: Could not get user account");
result = "Missing Email address!";
return false;
}
}
return ProfilesData.GetUserPreferences(ref pref, ref result);
}
public bool UserPreferencesUpdate(ref UserPreferences pref, ref string result)
{
if (string.IsNullOrEmpty(pref.EMail))
{
UserAccount account = new UserAccount();
if (userAccounts is UserAccountService.UserAccountService)
{
try
{
account = userAccounts.GetUserAccount(UUID.Zero, pref.UserId);
if (string.IsNullOrEmpty(account.Email))
{
result = "No Email address on record!";
return false;
}
else
pref.EMail = account.Email;
}
catch
{
m_log.Info("[PROFILES]: UserAccountService Exception: Could not get user account");
result = "Missing Email address!";
return false;
}
}
else
{
m_log.Info("[PROFILES]: UserAccountService: Could not get user account");
result = "Missing Email address!";
return false;
}
}
return ProfilesData.UpdateUserPreferences(ref pref, ref result);
}
#endregion User Preferences
#region Utility
public OSD AvatarImageAssetsRequest(UUID avatarId)
{
OSDArray records = ProfilesData.GetUserImageAssets(avatarId);
return records;
}
#endregion Utility
#region UserData
public bool RequestUserAppData(ref UserAppData prop, ref string result)
{
return ProfilesData.GetUserAppData(ref prop, ref result);
}
public bool SetUserAppData(UserAppData prop, ref string result)
{
return true;
}
#endregion UserData
}
}
| |
/*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Threading;
using OpenMetaverse;
using log4net;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Framework.Console;
using OpenSim.Region.Framework.Interfaces;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Region.Framework.Scenes
{
public abstract class SceneBase : IScene
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
#pragma warning disable 414
private static readonly string LogHeader = "[SCENE]";
#pragma warning restore 414
#region Events
public event restart OnRestart;
#endregion
#region Fields
public string Name { get { return RegionInfo.RegionName; } }
public IConfigSource Config
{
get { return GetConfig(); }
}
protected virtual IConfigSource GetConfig()
{
return null;
}
/// <value>
/// All the region modules attached to this scene.
/// </value>
public Dictionary<string, IRegionModuleBase> RegionModules
{
get { return m_regionModules; }
}
private Dictionary<string, IRegionModuleBase> m_regionModules = new Dictionary<string, IRegionModuleBase>();
/// <value>
/// The module interfaces available from this scene.
/// </value>
protected Dictionary<Type, List<object>> ModuleInterfaces = new Dictionary<Type, List<object>>();
/// <summary>
/// These two objects hold the information about any formats used
/// by modules that hold agent specific data.
/// </summary>
protected List<UUID> FormatsOffered = new List<UUID>();
protected Dictionary<object, List<UUID>> FormatsWanted = new Dictionary<object, List<UUID>>();
protected Dictionary<string, object> ModuleAPIMethods = new Dictionary<string, object>();
/// <value>
/// The module commanders available from this scene
/// </value>
protected Dictionary<string, ICommander> m_moduleCommanders = new Dictionary<string, ICommander>();
/// <value>
/// Registered classes that are capable of creating entities.
/// </value>
protected Dictionary<PCode, IEntityCreator> m_entityCreators = new Dictionary<PCode, IEntityCreator>();
/// <summary>
/// The last allocated local prim id. When a new local id is requested, the next number in the sequence is
/// dispensed.
/// </summary>
protected uint m_lastAllocatedLocalId = 720000;
private readonly Mutex _primAllocateMutex = new Mutex(false);
protected readonly ClientManager m_clientManager = new ClientManager();
public bool LoginsEnabled
{
get
{
return m_loginsEnabled;
}
set
{
if (m_loginsEnabled != value)
{
m_loginsEnabled = value;
EventManager.TriggerRegionLoginsStatusChange(this);
}
}
}
private bool m_loginsEnabled;
public bool Ready
{
get
{
return m_ready;
}
set
{
if (m_ready != value)
{
m_ready = value;
EventManager.TriggerRegionReadyStatusChange(this);
}
}
}
private bool m_ready;
public float TimeDilation
{
get { return 1.0f; }
}
public ITerrainChannel Heightmap;
/// <value>
/// Allows retrieval of land information for this scene.
/// </value>
public ILandChannel LandChannel;
/// <value>
/// Manage events that occur in this scene (avatar movement, script rez, etc.). Commonly used by region modules
/// to subscribe to scene events.
/// </value>
public EventManager EventManager
{
get { return m_eventManager; }
}
protected EventManager m_eventManager;
protected ScenePermissions m_permissions;
public ScenePermissions Permissions
{
get { return m_permissions; }
}
/* Used by the loadbalancer plugin on GForge */
protected RegionStatus m_regStatus;
public RegionStatus RegionStatus
{
get { return m_regStatus; }
set { m_regStatus = value; }
}
#endregion
public SceneBase(RegionInfo regInfo)
{
RegionInfo = regInfo;
}
#region Update Methods
/// <summary>
/// Called to update the scene loop by a number of frames and until shutdown.
/// </summary>
/// <param name="frames">
/// Number of frames to update. Exits on shutdown even if there are frames remaining.
/// If -1 then updates until shutdown.
/// </param>
/// <returns>true if update completed within minimum frame time, false otherwise.</returns>
public abstract bool Update(int frames);
#endregion
#region Terrain Methods
/// <summary>
/// Loads the World heightmap
/// </summary>
public abstract void LoadWorldMap();
/// <summary>
/// Send the region heightmap to the client
/// </summary>
/// <param name="RemoteClient">Client to send to</param>
public virtual void SendLayerData(IClientAPI RemoteClient)
{
// RemoteClient.SendLayerData(Heightmap.GetFloatsSerialised());
ITerrainModule terrModule = RequestModuleInterface<ITerrainModule>();
if (terrModule != null)
{
terrModule.PushTerrain(RemoteClient);
}
}
#endregion
#region Add/Remove Agent/Avatar
public abstract ISceneAgent AddNewAgent(IClientAPI client, PresenceType type);
public abstract bool CloseAgent(UUID agentID, bool force);
public bool TryGetScenePresence(UUID agentID, out object scenePresence)
{
scenePresence = null;
ScenePresence sp = null;
if (TryGetScenePresence(agentID, out sp))
{
scenePresence = sp;
return true;
}
return false;
}
/// <summary>
/// Try to get a scene presence from the scene
/// </summary>
/// <param name="agentID"></param>
/// <param name="scenePresence">null if there is no scene presence with the given agent id</param>
/// <returns>true if there was a scene presence with the given id, false otherwise.</returns>
public abstract bool TryGetScenePresence(UUID agentID, out ScenePresence scenePresence);
#endregion
/// <summary>
///
/// </summary>
/// <returns></returns>
public virtual RegionInfo RegionInfo { get; private set; }
#region admin stuff
public abstract void OtherRegionUp(GridRegion otherRegion);
public virtual string GetSimulatorVersion()
{
return "OpenSimulator Server";
}
#endregion
#region Shutdown
/// <summary>
/// Tidy before shutdown
/// </summary>
public virtual void Close()
{
try
{
EventManager.TriggerShutdown();
}
catch (Exception e)
{
m_log.Error(string.Format("[SCENE]: SceneBase.cs: Close() - Failed with exception ", e));
}
}
#endregion
/// <summary>
/// Returns a new unallocated local ID
/// </summary>
/// <returns>A brand new local ID</returns>
public uint AllocateLocalId()
{
uint myID;
_primAllocateMutex.WaitOne();
myID = ++m_lastAllocatedLocalId;
_primAllocateMutex.ReleaseMutex();
return myID;
}
#region Module Methods
/// <summary>
/// Add a region-module to this scene. TODO: This will replace AddModule in the future.
/// </summary>
/// <param name="name"></param>
/// <param name="module"></param>
public void AddRegionModule(string name, IRegionModuleBase module)
{
if (!RegionModules.ContainsKey(name))
{
RegionModules.Add(name, module);
}
}
public void RemoveRegionModule(string name)
{
RegionModules.Remove(name);
}
/// <summary>
/// Register a module commander.
/// </summary>
/// <param name="commander"></param>
public void RegisterModuleCommander(ICommander commander)
{
lock (m_moduleCommanders)
{
m_moduleCommanders.Add(commander.Name, commander);
}
}
/// <summary>
/// Unregister a module commander and all its commands
/// </summary>
/// <param name="name"></param>
public void UnregisterModuleCommander(string name)
{
lock (m_moduleCommanders)
{
ICommander commander;
if (m_moduleCommanders.TryGetValue(name, out commander))
m_moduleCommanders.Remove(name);
}
}
/// <summary>
/// Get a module commander
/// </summary>
/// <param name="name"></param>
/// <returns>The module commander, null if no module commander with that name was found</returns>
public ICommander GetCommander(string name)
{
lock (m_moduleCommanders)
{
if (m_moduleCommanders.ContainsKey(name))
return m_moduleCommanders[name];
}
return null;
}
public Dictionary<string, ICommander> GetCommanders()
{
return m_moduleCommanders;
}
public List<UUID> GetFormatsOffered()
{
List<UUID> ret = new List<UUID>(FormatsOffered);
return ret;
}
protected void CheckAndAddAgentDataFormats(object mod)
{
if (!(mod is IAgentStatefulModule))
return;
IAgentStatefulModule m = (IAgentStatefulModule)mod;
List<UUID> renderFormats = m.GetRenderStateFormats();
List<UUID> acceptFormats = m.GetAcceptStateFormats();
foreach (UUID render in renderFormats)
{
if (!(FormatsOffered.Contains(render)))
FormatsOffered.Add(render);
}
if (acceptFormats.Count == 0)
return;
if (FormatsWanted.ContainsKey(mod))
return;
FormatsWanted[mod] = acceptFormats;
}
/// <summary>
/// Register an interface to a region module. This allows module methods to be called directly as
/// well as via events. If there is already a module registered for this interface, it is not replaced
/// (is this the best behaviour?)
/// </summary>
/// <param name="mod"></param>
public void RegisterModuleInterface<M>(M mod)
{
// m_log.DebugFormat("[SCENE BASE]: Registering interface {0}", typeof(M));
List<Object> l = null;
if (!ModuleInterfaces.TryGetValue(typeof(M), out l))
{
l = new List<Object>();
ModuleInterfaces.Add(typeof(M), l);
}
if (l.Count > 0)
return;
l.Add(mod);
CheckAndAddAgentDataFormats(mod);
if (mod is IEntityCreator)
{
IEntityCreator entityCreator = (IEntityCreator)mod;
foreach (PCode pcode in entityCreator.CreationCapabilities)
{
m_entityCreators[pcode] = entityCreator;
}
}
}
public void UnregisterModuleInterface<M>(M mod)
{
// We can't unregister agent stateful modules because
// that would require much more data to be held about formats
// and would make that code slower and less efficient.
// No known modules are unregistered anyway, ever, unless
// the simulator shuts down anyway.
if (mod is IAgentStatefulModule)
return;
List<Object> l;
if (ModuleInterfaces.TryGetValue(typeof(M), out l))
{
if (l.Remove(mod))
{
if (mod is IEntityCreator)
{
IEntityCreator entityCreator = (IEntityCreator)mod;
foreach (PCode pcode in entityCreator.CreationCapabilities)
{
m_entityCreators[pcode] = null;
}
}
}
}
}
public void StackModuleInterface<M>(M mod)
{
List<Object> l;
if (ModuleInterfaces.ContainsKey(typeof(M)))
l = ModuleInterfaces[typeof(M)];
else
l = new List<Object>();
if (l.Contains(mod))
return;
l.Add(mod);
CheckAndAddAgentDataFormats(mod);
if (mod is IEntityCreator)
{
IEntityCreator entityCreator = (IEntityCreator)mod;
foreach (PCode pcode in entityCreator.CreationCapabilities)
{
m_entityCreators[pcode] = entityCreator;
}
}
ModuleInterfaces[typeof(M)] = l;
}
/// <summary>
/// For the given interface, retrieve the region module which implements it.
/// </summary>
/// <returns>null if there is no registered module implementing that interface</returns>
public T RequestModuleInterface<T>()
{
if (ModuleInterfaces.ContainsKey(typeof(T)) &&
(ModuleInterfaces[typeof(T)].Count > 0))
return (T)ModuleInterfaces[typeof(T)][0];
else
return default(T);
}
/// <summary>
/// For the given interface, retrieve an array of region modules that implement it.
/// </summary>
/// <returns>an empty array if there are no registered modules implementing that interface</returns>
public T[] RequestModuleInterfaces<T>()
{
if (ModuleInterfaces.ContainsKey(typeof(T)))
{
List<T> ret = new List<T>();
foreach (Object o in ModuleInterfaces[typeof(T)])
ret.Add((T)o);
return ret.ToArray();
}
else
{
return new T[] {};
}
}
#endregion
/// <summary>
/// Call this from a region module to add a command to the OpenSim console.
/// </summary>
/// <param name="mod"></param>
/// <param name="command"></param>
/// <param name="shorthelp"></param>
/// <param name="longhelp"></param>
/// <param name="callback"></param>
public void AddCommand(IRegionModuleBase module, string command, string shorthelp, string longhelp, CommandDelegate callback)
{
AddCommand(module, command, shorthelp, longhelp, string.Empty, callback);
}
/// <summary>
/// Call this from a region module to add a command to the OpenSim console.
/// </summary>
/// <param name="mod">
/// The use of IRegionModuleBase is a cheap trick to get a different method signature,
/// though all new modules should be using interfaces descended from IRegionModuleBase anyway.
/// </param>
/// <param name="category">
/// Category of the command. This is the section under which it will appear when the user asks for help
/// </param>
/// <param name="command"></param>
/// <param name="shorthelp"></param>
/// <param name="longhelp"></param>
/// <param name="callback"></param>
public void AddCommand(
string category, IRegionModuleBase module, string command, string shorthelp, string longhelp, CommandDelegate callback)
{
AddCommand(category, module, command, shorthelp, longhelp, string.Empty, callback);
}
/// <summary>
/// Call this from a region module to add a command to the OpenSim console.
/// </summary>
/// <param name="mod"></param>
/// <param name="command"></param>
/// <param name="shorthelp"></param>
/// <param name="longhelp"></param>
/// <param name="descriptivehelp"></param>
/// <param name="callback"></param>
public void AddCommand(IRegionModuleBase module, string command, string shorthelp, string longhelp, string descriptivehelp, CommandDelegate callback)
{
string moduleName = "";
if (module != null)
moduleName = module.Name;
AddCommand(moduleName, module, command, shorthelp, longhelp, descriptivehelp, callback);
}
/// <summary>
/// Call this from a region module to add a command to the OpenSim console.
/// </summary>
/// <param name="category">
/// Category of the command. This is the section under which it will appear when the user asks for help
/// </param>
/// <param name="mod"></param>
/// <param name="command"></param>
/// <param name="shorthelp"></param>
/// <param name="longhelp"></param>
/// <param name="descriptivehelp"></param>
/// <param name="callback"></param>
public void AddCommand(
string category, IRegionModuleBase module, string command,
string shorthelp, string longhelp, string descriptivehelp, CommandDelegate callback)
{
if (MainConsole.Instance == null)
return;
bool shared = false;
if (module != null)
shared = module is ISharedRegionModule;
MainConsole.Instance.Commands.AddCommand(
category, shared, command, shorthelp, longhelp, descriptivehelp, callback);
}
public virtual ISceneObject DeserializeObject(string representation)
{
return null;
}
public virtual bool AllowScriptCrossings
{
get { return false; }
}
public virtual void Start()
{
}
public void Restart()
{
// This has to be here to fire the event
restart handlerPhysicsCrash = OnRestart;
if (handlerPhysicsCrash != null)
handlerPhysicsCrash(RegionInfo);
}
public abstract bool CheckClient(UUID agentID, System.Net.IPEndPoint ep);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.