context stringlengths 2.52k 185k | gt stringclasses 1 value |
|---|---|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Xunit;
namespace System.Tests
{
public static class BitConverterTests
{
[Fact]
public static unsafe void IsLittleEndian()
{
short s = 1;
Assert.Equal(BitConverter.IsLittleEndian, *((byte*)&s) == 1);
}
[Fact]
public static void ValueArgumentNull()
{
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToBoolean(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToChar(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToDouble(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToInt16(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToInt32(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToInt64(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToSingle(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToUInt16(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToUInt32(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToUInt64(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToString(null));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToString(null, 0));
Assert.Throws<ArgumentNullException>("value", () => BitConverter.ToString(null, 0, 0));
}
[Fact]
public static void StartIndexBeyondLength()
{
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], 1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[1], 2));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], 2));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToChar(new byte[2], 3));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], 8));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToDouble(new byte[8], 9));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], 2));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt16(new byte[2], 3));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], 4));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt32(new byte[4], 5));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], 8));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToInt64(new byte[8], 9));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], 4));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToSingle(new byte[4], 5));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], 2));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt16(new byte[2], 3));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], 4));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt32(new byte[4], 5));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], 8));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToUInt64(new byte[8], 9));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], -1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 1));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 2));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], -1, 0));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 1, 0));
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToString(new byte[1], 2, 0));
Assert.Throws<ArgumentOutOfRangeException>("length", () => BitConverter.ToString(new byte[1], 0, -1));
}
[Fact]
public static void StartIndexPlusNeededLengthTooLong()
{
Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => BitConverter.ToBoolean(new byte[0], 0));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToChar(new byte[2], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToDouble(new byte[8], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToInt16(new byte[2], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToInt32(new byte[4], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToInt64(new byte[8], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToSingle(new byte[4], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToUInt16(new byte[2], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToUInt32(new byte[4], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToUInt64(new byte[8], 1));
Assert.Throws<ArgumentException>("value", () => BitConverter.ToString(new byte[2], 1, 2));
}
[Fact]
public static void DoubleToInt64Bits()
{
Double input = 123456.3234;
Int64 result = BitConverter.DoubleToInt64Bits(input);
Assert.Equal(4683220267154373240L, result);
Double roundtripped = BitConverter.Int64BitsToDouble(result);
Assert.Equal(input, roundtripped);
}
[Fact]
public static void RoundtripBoolean()
{
Byte[] bytes = BitConverter.GetBytes(true);
Assert.Equal(1, bytes.Length);
Assert.Equal(1, bytes[0]);
Assert.True(BitConverter.ToBoolean(bytes, 0));
bytes = BitConverter.GetBytes(false);
Assert.Equal(1, bytes.Length);
Assert.Equal(0, bytes[0]);
Assert.False(BitConverter.ToBoolean(bytes, 0));
}
[Fact]
public static void RoundtripChar()
{
Char input = 'A';
Byte[] expected = { 0x41, 0 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToChar, input, expected);
}
[Fact]
public static void RoundtripDouble()
{
Double input = 123456.3234;
Byte[] expected = { 0x78, 0x7a, 0xa5, 0x2c, 0x05, 0x24, 0xfe, 0x40 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToDouble, input, expected);
}
[Fact]
public static void RoundtripSingle()
{
Single input = 8392.34f;
Byte[] expected = { 0x5c, 0x21, 0x03, 0x46 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToSingle, input, expected);
}
[Fact]
public static void RoundtripInt16()
{
Int16 input = 0x1234;
Byte[] expected = { 0x34, 0x12 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToInt16, input, expected);
}
[Fact]
public static void RoundtripInt32()
{
Int32 input = 0x12345678;
Byte[] expected = { 0x78, 0x56, 0x34, 0x12 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToInt32, input, expected);
}
[Fact]
public static void RoundtripInt64()
{
Int64 input = 0x0123456789abcdef;
Byte[] expected = { 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToInt64, input, expected);
}
[Fact]
public static void RoundtripUInt16()
{
UInt16 input = 0x1234;
Byte[] expected = { 0x34, 0x12 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToUInt16, input, expected);
}
[Fact]
public static void RoundtripUInt32()
{
UInt32 input = 0x12345678;
Byte[] expected = { 0x78, 0x56, 0x34, 0x12 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToUInt32, input, expected);
}
[Fact]
public static void RoundtripUInt64()
{
UInt64 input = 0x0123456789abcdef;
Byte[] expected = { 0xef, 0xcd, 0xab, 0x89, 0x67, 0x45, 0x23, 0x01 };
VerifyRoundtrip(BitConverter.GetBytes, BitConverter.ToUInt64, input, expected);
}
[Fact]
public static void RoundtripString()
{
Byte[] bytes = { 0x12, 0x34, 0x56, 0x78, 0x9a };
Assert.Equal("12-34-56-78-9A", BitConverter.ToString(bytes));
Assert.Equal("56-78-9A", BitConverter.ToString(bytes, 2));
Assert.Equal("56", BitConverter.ToString(bytes, 2, 1));
Assert.Equal(String.Empty, BitConverter.ToString(new byte[0]));
}
[Fact]
public static void ToString_ByteArrayTooLong_Throws()
{
byte[] arr;
try
{
arr = new byte[int.MaxValue / 3 + 1];
}
catch (OutOfMemoryException)
{
// Exit out of the test if we don't have an enough contiguous memory
// available to create a big enough array.
return;
}
Assert.Throws<ArgumentOutOfRangeException>("length", () => BitConverter.ToString(arr));
}
private static void VerifyRoundtrip<TInput>(Func<TInput, Byte[]> getBytes, Func<Byte[], int, TInput> convertBack, TInput input, Byte[] expectedBytes)
{
Byte[] bytes = getBytes(input);
Assert.Equal(expectedBytes.Length, bytes.Length);
if (!BitConverter.IsLittleEndian)
{
Array.Reverse(expectedBytes);
}
Assert.Equal(expectedBytes, bytes);
Assert.Equal(input, convertBack(bytes, 0));
// Also try unaligned startIndex
byte[] longerBytes = new byte[bytes.Length + 1];
longerBytes[0] = 0;
Array.Copy(bytes, 0, longerBytes, 1, bytes.Length);
Assert.Equal(input, convertBack(longerBytes, 1));
}
}
}
| |
using System;
using System.Diagnostics;
using System.IO;
using System.Collections;
namespace OTFontFile
{
// The OTFont class encapsulates the Offset table and its directory entries for a font.
public class OTFont
{
/***************
* constructors
*/
public OTFont()
{
// this constructor is for creating fonts in memory
// as opposed to reading a font from a file
m_File = null;
MemBasedTables = new ArrayList();
m_OutlineType = OutlineType.OUTLINE_INVALID;
m_OffsetTable = new OffsetTable(new OTFixed(1,0), 0);
}
public OTFont(OTFile f)
{
m_File = f;
m_FontFileNumber = 0;
m_OffsetTable = null;
m_maxpNumGlyphs = 0;
m_arrUnicodeToGlyph_3_0 = null;
m_arrUnicodeToGlyph_3_1 = null;
m_arrUnicodeToGlyph_3_10 = null;
m_bContainsMsSymbolEncodedCmap = false;
}
public OTFont(OTFile f, uint FontFileNumber, OffsetTable ot, OutlineType outlineType)
{
m_File = f;
m_FontFileNumber = FontFileNumber;
m_OffsetTable = ot;
m_OutlineType = outlineType;
m_maxpNumGlyphs = 0;
m_arrUnicodeToGlyph_3_0 = null;
m_arrUnicodeToGlyph_3_1 = null;
m_arrUnicodeToGlyph_3_10 = null;
m_bContainsMsSymbolEncodedCmap = false;
}
/************************
* public static methods
*/
/// <summary>Return a new OTFont by reading a single font from an
/// OTFile starting at a given file position.
/// <p/>
/// The type of the font is set by determining whether there is
/// a 'glyf' table or a 'CFF ' table.
/// </summary>
public static OTFont ReadFont(OTFile file, uint FontFileNumber, uint filepos)
{
OTFont f = null;
OffsetTable ot = ReadOffsetTable(file, filepos);
if (ot != null)
{
if (ot.numTables == ot.DirectoryEntries.Count)
{
OutlineType olt = OutlineType.OUTLINE_INVALID;
for (int i = 0; i<ot.DirectoryEntries.Count; i++)
{
DirectoryEntry temp = (DirectoryEntry)ot.DirectoryEntries[i];
string sTable = (string)temp.tag;
if (sTable == "CFF ")
{
olt = OutlineType.OUTLINE_POSTSCRIPT;
break;
}
else if (sTable == "glyf")
{
olt = OutlineType.OUTLINE_TRUETYPE;
break;
}
}
f = new OTFont(file, FontFileNumber, ot, olt);
}
}
return f;
}
/*****************
* public methods
*/
///
/// <summary>Calculate the check sum for the font as the
/// sum of the checksums of the offset table, directory entries, and
/// each table.
/// </summary>
public uint CalcChecksum()
{
uint sum = 0;
sum += m_OffsetTable.CalcOffsetTableChecksum();
sum += m_OffsetTable.CalcDirectoryEntriesChecksum();
if (m_OffsetTable != null)
{
for (int i = 0; i<m_OffsetTable.DirectoryEntries.Count; i++)
{
DirectoryEntry de = (DirectoryEntry)m_OffsetTable.DirectoryEntries[i];
OTTable table = GetTable(de);
uint calcChecksum = 0;
if (table != null)
{
calcChecksum = table.CalcChecksum();
}
sum += calcChecksum;
}
}
return sum;
}
/// <summary>Return the ith table in the directory entries,
/// or null if there is no such entry.
/// </summary>
public OTTable GetTable(ushort i)
{
OTTable table = null;
DirectoryEntry de = GetDirectoryEntry(i);
if (de != null)
{
table = GetTable(de);
}
return table;
}
/// <summary>Return the first table with tag == <c>tag</c>
/// or null if there is no such table.
/// </summary>
public OTTable GetTable(OTTag tag)
{
OTTable table = null;
// find the directory entry in this font that matches the tag
DirectoryEntry de = GetDirectoryEntry(tag);
if (de != null)
{
table = GetTable(de);
}
return table;
}
/// <summary>Return the ith directory entry,
/// or null if there is no such entry.
/// </summary>
public DirectoryEntry GetDirectoryEntry(ushort i)
{
DirectoryEntry de = null;
if (m_OffsetTable != null)
{
if (i<m_OffsetTable.numTables)
{
de = (DirectoryEntry)m_OffsetTable.DirectoryEntries[i];
}
}
return de;
}
/// <summary>Return the first directory entry with
/// tag == <c>tag</c>
/// or null if there is no such entry.
/// </summary>
public DirectoryEntry GetDirectoryEntry(OTTag tag)
{
Debug.Assert(m_OffsetTable != null);
DirectoryEntry de = null;
if (m_OffsetTable != null)
{
for (int i = 0; i<m_OffsetTable.DirectoryEntries.Count; i++)
{
DirectoryEntry temp = (DirectoryEntry)m_OffsetTable.DirectoryEntries[i];
if (temp.tag == tag)
{
de = temp;
break;
}
}
}
return de;
}
/// <summary>Accessor for <c>m_file</c></summary>
public OTFile GetFile()
{
return m_File;
}
/// <summary>Accessor for <c>m_FontFileNumber</c></summary>
public uint GetFontIndexInFile()
{
return m_FontFileNumber;
}
/// <summary>Accessor for <c>m_OffstTable.numTables</c>, or 0
/// if no offset table yet.
/// </summary>
public ushort GetNumTables()
{
ushort nTables = 0;
if (m_OffsetTable != null)
{
nTables = m_OffsetTable.numTables;
}
return nTables;
}
/// <summary>Accessor for <c>m_OffstTable</c></summary>
public OffsetTable GetOffsetTable()
{
return m_OffsetTable;
}
/// <summary>Get font name from "name" table, or <c>null</c> if
/// no "name" table yet.</summary>
public string GetFontName()
{
string sName = null;
Table_name nameTable = (Table_name)GetTable("name");
if (nameTable != null)
{
sName = nameTable.GetNameString();
}
return sName;
}
/// <summary>Get font version from "name" table, or <c>null</c> if
/// no "name" table yet.</summary>
public string GetFontVersion()
{
string sVersion = null;
Table_name nameTable = (Table_name)GetTable("name");
if (nameTable != null)
{
sVersion = nameTable.GetVersionString();
}
return sVersion;
}
/// <summary>Get modified date from "name" table, or <c>1/1/1904</c> if
/// no "name" table yet.</summary>
public DateTime GetFontModifiedDate()
{
// default to Jan 1, 1904 if unavailable
DateTime dt = new DateTime(1904, 1, 1);
try
{
Table_head headTable = (Table_head)GetTable("head");
if (headTable != null)
{
dt = headTable.GetModifiedDateTime();
}
}
catch
{
}
return dt;
}
/// <summary>Add a new table to an non-file based table. Table cannot
/// already exist in the font.
/// </summary>
public void AddTable(OTTable t)
{
if (m_File != null)
{
throw new ApplicationException("attempted to add a table to a file-based OTFont object");
}
if (GetDirectoryEntry(t.m_tag) != null)
{
throw new ArgumentException("the specified table already exists in the font");
}
// build a new directory entry
DirectoryEntry de = new DirectoryEntry();
de.tag = new OTTag(t.m_tag.GetBytes());
de.checkSum = t.CalcChecksum();
de.offset = 0; // this value won't get fixed up until the font is written
de.length = t.GetLength();
// add the directory entry
m_OffsetTable.DirectoryEntries.Add(de);
m_OffsetTable.numTables++;
// add the table to the list of tables in memory
MemBasedTables.Add(t);
// special handling for certain tables
string sTable = (string)t.m_tag;
if (sTable == "CFF ")
{
m_OutlineType = OutlineType.OUTLINE_POSTSCRIPT;
}
else if (sTable == "glyf")
{
m_OutlineType = OutlineType.OUTLINE_TRUETYPE;
}
}
/// <summary>Rmove a table to an non-file based table. Throws
/// exception if table is not in font.
/// </summary>
public void RemoveTable(OTTag tag)
{
if (m_File != null)
{
throw new ApplicationException("attempted to remove a table from a file-based OTFont object");
}
if (GetDirectoryEntry(tag) == null)
{
throw new ArgumentException("the specified table doesn't doesn't exist in the font");
}
// remove the directory entry
for (int i=0; i<m_OffsetTable.DirectoryEntries.Count; i++)
{
DirectoryEntry de = (DirectoryEntry)m_OffsetTable.DirectoryEntries[i];
if (tag == de.tag)
{
m_OffsetTable.DirectoryEntries.RemoveAt(i);
m_OffsetTable.numTables--;
break;
}
}
// remove the table from the list of tables in memory
for (int i=0; i<MemBasedTables.Count; i++)
{
OTTable t = (OTTable)MemBasedTables[i];
if (tag == t.m_tag)
{
MemBasedTables.RemoveAt(i);
break;
}
}
string sTable = (string)tag;
if (sTable == "CFF ")
{
m_OutlineType = OutlineType.OUTLINE_INVALID;
}
else if (sTable == "glyf")
{
m_OutlineType = OutlineType.OUTLINE_INVALID;
}
}
/*******************************
* public methods
* that cache information
* from various tables
*/
public bool ContainsPostScriptOutlines()
{
if (m_OutlineType == OutlineType.OUTLINE_POSTSCRIPT)
return true;
else
return false;
}
public bool ContainsTrueTypeOutlines()
{
if (m_OutlineType == OutlineType.OUTLINE_TRUETYPE)
return true;
else
return false;
}
public ushort GetMaxpNumGlyphs()
{
// this routine caches the maxp.numGlyphs value for better performance
if (m_maxpNumGlyphs == 0)
{
Table_maxp maxpTable = (Table_maxp)GetTable("maxp");
if (maxpTable != null)
{
m_maxpNumGlyphs = maxpTable.NumGlyphs;
}
else
{
throw new InvalidOperationException("maxp table missing or invalid");
}
}
return m_maxpNumGlyphs;
}
public uint FastMapUnicodeToGlyphID(char c)
{
// this routine caches the windows unicode cmap for better performance
// but uses 256K of heap
uint glyphID = 0xffffffff;
if (m_arrUnicodeToGlyph_3_1 == null)
{
m_arrUnicodeToGlyph_3_1 = new uint[0x00010000];
for (uint i=0; i<=0xffff; i++)
{
m_arrUnicodeToGlyph_3_1[i] = 0;
}
Table_cmap cmapTable = (Table_cmap)GetTable("cmap");
if (cmapTable != null)
{
Table_cmap.EncodingTableEntry eteUni = cmapTable.GetEncodingTableEntry(3,1);
if (eteUni != null)
{
Table_cmap.Subtable st = cmapTable.GetSubtable(eteUni);
if (st != null)
{
byte [] buf = new byte[2];
for (ushort i=0; i<0xffff; i++)
{
buf[0] = (byte)i;
buf[1] = (byte)(i>>8);
uint g = st.MapCharToGlyph(buf, 0);
if (g!=0)
{
// BEWARE: Some bad fonts have the glyph ID greater than # of glyphs
// and we're not throwing it out here!
m_arrUnicodeToGlyph_3_1[i] = g;
}
}
}
}
}
}
Debug.Assert(m_arrUnicodeToGlyph_3_1 != null);
if (m_arrUnicodeToGlyph_3_1 != null)
{
glyphID = m_arrUnicodeToGlyph_3_1[c];
}
return glyphID;
}
public uint FastMapUnicode32ToGlyphID(uint c)
{
// this routine caches the windows 3,10 cmap for better performance
// but might use tons of heap
uint glyphID = 0xffffffff;
if (m_arrUnicodeToGlyph_3_10 == null)
{
Table_cmap cmapTable = (Table_cmap)GetTable("cmap");
if (cmapTable != null)
{
Table_cmap.Format12 subtable = (Table_cmap.Format12)cmapTable.GetSubtable(3,10);
Table_cmap.Format12.Group g = subtable.GetGroup(subtable.nGroups-1);
uint nArraySize = g.endCharCode + 1;
m_arrUnicodeToGlyph_3_10 = new uint[nArraySize];
for (uint i=0; i<nArraySize; i++)
{
m_arrUnicodeToGlyph_3_10[i] = 0;
}
for (uint nGroup = 0; nGroup<subtable.nGroups; nGroup++)
{
g = subtable.GetGroup(nGroup);
for (uint i=0; i<=g.endCharCode-g.startCharCode; i++)
{
m_arrUnicodeToGlyph_3_10[g.startCharCode + i] = g.startGlyphID + i;
}
}
}
}
Debug.Assert(m_arrUnicodeToGlyph_3_10 != null);
if (m_arrUnicodeToGlyph_3_10 != null)
{
glyphID = m_arrUnicodeToGlyph_3_10[c];
}
return glyphID;
}
public char MapGlyphIDToUnicode(uint nGlyphID, char Start)
{
char unicode = (char)0xffff; // return this (illegal) char on failure
for (char c=Start; c<0xffff; c++)
{
uint g = FastMapUnicodeToGlyphID(c);
if (g == nGlyphID)
{
unicode = c;
break;
}
}
return unicode;
}
public uint MapGlyphIDToUnicode32(uint nGlyphID, uint Start)
{
uint uni32 = 0xffffffff; // return this (illegal) char on failure
FastMapUnicode32ToGlyphID(0); // force the map to be calculated
for (uint c=Start; c<m_arrUnicodeToGlyph_3_10.Length; c++)
{
uint g = FastMapUnicode32ToGlyphID(c);
if (g == nGlyphID)
{
uni32 = c;
break;
}
}
return uni32;
}
bool bCheckedForSymbolCmap = false;
public bool ContainsMsSymbolEncodedCmap()
{
if (!bCheckedForSymbolCmap)
{
Table_cmap cmapTable = (Table_cmap)GetTable("cmap");
if (cmapTable != null)
{
Table_cmap.EncodingTableEntry eteUni = cmapTable.GetEncodingTableEntry(3,0);
if (eteUni != null)
{
m_bContainsMsSymbolEncodedCmap = true;
}
}
bCheckedForSymbolCmap = true;
}
return m_bContainsMsSymbolEncodedCmap;
}
public bool ContainsSymbolsOnly()
{
// check for a 3,0 cmap, if found then it's a symbol only font
bool bSymbolOnly = ContainsMsSymbolEncodedCmap();
// if it didn't contain a 3,0 cmap, then check for unicode symbols in the font
if (!bSymbolOnly)
{
int nUnicodeSymbols = 0;
for (ushort c=0xf000; c<= 0xf0ff; c++)
{
uint nGlyphID = 0;
try
{
nGlyphID = FastMapUnicodeToGlyphID((char)c);
}
catch
{
}
if (nGlyphID != 0)
{
nUnicodeSymbols++;
}
}
if (GetTable("maxp") != null)
{
if (nUnicodeSymbols == GetMaxpNumGlyphs())
{
bSymbolOnly = true;
}
}
}
return bSymbolOnly;
}
public bool ContainsLatinOnly()
{
bool bLatinOnly = true;
// check for a 3,0 cmap, if found then it's a symbol only font
if (ContainsMsSymbolEncodedCmap()) bLatinOnly = false;
if (bLatinOnly)
{
// unicode ranges Basic Latin, Latin-1 Supplement, Latin Extended-A and LatinExtended-B range from 0 to 0x024f
FastMapUnicodeToGlyphID(' '); // force the cmap to be cached
for (uint i=0x0250; i<0xffff; i++)
{
if (m_arrUnicodeToGlyph_3_1[i] != 0)
{
bLatinOnly = false;
break;
}
}
}
return bLatinOnly;
}
/******************
* protected methods
*/
protected static OffsetTable ReadOffsetTable(OTFile file, uint filepos)
{
// read the Offset Table from the file
const int SIZEOF_OFFSETTABLE = 12;
OffsetTable ot = null;
// read the offset table
MBOBuffer buf = file.ReadPaddedBuffer(filepos, SIZEOF_OFFSETTABLE);
if (buf != null)
{
if (OTFile.IsValidSfntVersion(buf.GetUint(0)))
{
ot = new OffsetTable(buf);
}
}
// now read the directory entries
if (ot != null)
{
const int SIZEOF_DIRECTORYENTRY = 16;
for (int i=0; i<ot.numTables; i++)
{
uint dirFilePos = (uint)(filepos+SIZEOF_OFFSETTABLE+i*SIZEOF_DIRECTORYENTRY);
MBOBuffer DirEntBuf = file.ReadPaddedBuffer(dirFilePos, SIZEOF_DIRECTORYENTRY);
if (DirEntBuf != null)
{
DirectoryEntry de = new DirectoryEntry(DirEntBuf);
ot.DirectoryEntries.Add(de);
}
else
{
Debug.Assert(false);
break;
}
}
}
return ot;
}
protected OTTable GetTable(DirectoryEntry de)
{
OTTable table = null;
if (m_File != null)
{
// get the table from OTFile's table manager
table = m_File.GetTableManager().GetTable(this, de);
}
else
{
// get the table from the list in memory
for (int i=0; i<MemBasedTables.Count; i++)
{
OTTable t = (OTTable)MemBasedTables[i];
if (de.tag == t.m_tag)
{
table = t;
break;
}
}
}
return table;
}
/**************
* member data
*/
public enum OutlineType
{
OUTLINE_INVALID,
OUTLINE_TRUETYPE,
OUTLINE_POSTSCRIPT
}
protected OTFile m_File;
protected uint m_FontFileNumber; // 0 if ttf, else number of font in ttc, starting at 0
protected OffsetTable m_OffsetTable;
protected OutlineType m_OutlineType;
protected ushort m_maxpNumGlyphs;
protected uint [] m_arrUnicodeToGlyph_3_0;
protected uint [] m_arrUnicodeToGlyph_3_1;
protected uint [] m_arrUnicodeToGlyph_3_10;
protected bool m_bContainsMsSymbolEncodedCmap;
protected ArrayList MemBasedTables; // this list is used when building a font in memory
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Data.Common;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace System.Data.SqlClient
{
internal class TdsParserStateObjectNative : TdsParserStateObject
{
private SNIHandle _sessionHandle = null; // the SNI handle we're to work on
private SNIPacket _sniPacket = null; // Will have to re-vamp this for MARS
internal SNIPacket _sniAsyncAttnPacket = null; // Packet to use to send Attn
private readonly WritePacketCache _writePacketCache = new WritePacketCache(); // Store write packets that are ready to be re-used
public TdsParserStateObjectNative(TdsParser parser) : base(parser) { }
private GCHandle _gcHandle; // keeps this object alive until we're closed.
private Dictionary<IntPtr, SNIPacket> _pendingWritePackets = new Dictionary<IntPtr, SNIPacket>(); // Stores write packets that have been sent to SNI, but have not yet finished writing (i.e. we are waiting for SNI's callback)
internal TdsParserStateObjectNative(TdsParser parser, TdsParserStateObject physicalConnection, bool async) :
base(parser, physicalConnection, async)
{
}
internal SNIHandle Handle => _sessionHandle;
internal override uint Status => _sessionHandle != null ? _sessionHandle.Status : TdsEnums.SNI_UNINITIALIZED;
internal override SessionHandle SessionHandle => SessionHandle.FromNativeHandle(_sessionHandle);
protected override void CreateSessionHandle(TdsParserStateObject physicalConnection, bool async)
{
Debug.Assert(physicalConnection is TdsParserStateObjectNative, "Expected a stateObject of type " + this.GetType());
TdsParserStateObjectNative nativeSNIObject = physicalConnection as TdsParserStateObjectNative;
SNINativeMethodWrapper.ConsumerInfo myInfo = CreateConsumerInfo(async);
_sessionHandle = new SNIHandle(myInfo, nativeSNIObject.Handle);
}
private SNINativeMethodWrapper.ConsumerInfo CreateConsumerInfo(bool async)
{
SNINativeMethodWrapper.ConsumerInfo myInfo = new SNINativeMethodWrapper.ConsumerInfo();
Debug.Assert(_outBuff.Length == _inBuff.Length, "Unexpected unequal buffers.");
myInfo.defaultBufferSize = _outBuff.Length; // Obtain packet size from outBuff size.
if (async)
{
myInfo.readDelegate = SNILoadHandle.SingletonInstance.ReadAsyncCallbackDispatcher;
myInfo.writeDelegate = SNILoadHandle.SingletonInstance.WriteAsyncCallbackDispatcher;
_gcHandle = GCHandle.Alloc(this, GCHandleType.Normal);
myInfo.key = (IntPtr)_gcHandle;
}
return myInfo;
}
internal override void CreatePhysicalSNIHandle(string serverName, bool ignoreSniOpenTimeout, long timerExpire, out byte[] instanceName, ref byte[] spnBuffer, bool flushCache, bool async, bool fParallel, bool isIntegratedSecurity)
{
// We assume that the loadSSPILibrary has been called already. now allocate proper length of buffer
spnBuffer = null;
if (isIntegratedSecurity)
{
// now allocate proper length of buffer
spnBuffer = new byte[SNINativeMethodWrapper.SniMaxComposedSpnLength];
}
SNINativeMethodWrapper.ConsumerInfo myInfo = CreateConsumerInfo(async);
// Translate to SNI timeout values (Int32 milliseconds)
long timeout;
if (long.MaxValue == timerExpire)
{
timeout = int.MaxValue;
}
else
{
timeout = ADP.TimerRemainingMilliseconds(timerExpire);
if (timeout > int.MaxValue)
{
timeout = int.MaxValue;
}
else if (0 > timeout)
{
timeout = 0;
}
}
_sessionHandle = new SNIHandle(myInfo, serverName, spnBuffer, ignoreSniOpenTimeout, checked((int)timeout), out instanceName, flushCache, !async, fParallel);
}
protected override uint SNIPacketGetData(PacketHandle packet, byte[] _inBuff, ref uint dataSize)
{
Debug.Assert(packet.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer");
return SNINativeMethodWrapper.SNIPacketGetData(packet.NativePointer, _inBuff, ref dataSize);
}
protected override bool CheckPacket(PacketHandle packet, TaskCompletionSource<object> source)
{
Debug.Assert(packet.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer");
IntPtr ptr = packet.NativePointer;
return IntPtr.Zero == ptr || IntPtr.Zero != ptr && source != null;
}
public void ReadAsyncCallback(IntPtr key, IntPtr packet, uint error) => ReadAsyncCallback(key, packet, error);
public void WriteAsyncCallback(IntPtr key, IntPtr packet, uint sniError) => WriteAsyncCallback(key, packet, sniError);
protected override void RemovePacketFromPendingList(PacketHandle ptr)
{
Debug.Assert(ptr.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer");
IntPtr pointer = ptr.NativePointer;
SNIPacket recoveredPacket;
lock (_writePacketLockObject)
{
if (_pendingWritePackets.TryGetValue(pointer, out recoveredPacket))
{
_pendingWritePackets.Remove(pointer);
_writePacketCache.Add(recoveredPacket);
}
#if DEBUG
else
{
Debug.Fail("Removing a packet from the pending list that was never added to it");
}
#endif
}
}
internal override void Dispose()
{
SafeHandle packetHandle = _sniPacket;
SafeHandle sessionHandle = _sessionHandle;
SafeHandle asyncAttnPacket = _sniAsyncAttnPacket;
_sniPacket = null;
_sessionHandle = null;
_sniAsyncAttnPacket = null;
DisposeCounters();
if (null != sessionHandle || null != packetHandle)
{
packetHandle?.Dispose();
asyncAttnPacket?.Dispose();
if (sessionHandle != null)
{
sessionHandle.Dispose();
DecrementPendingCallbacks(true); // Will dispose of GC handle.
}
}
DisposePacketCache();
}
protected override void FreeGcHandle(int remaining, bool release)
{
if ((0 == remaining || release) && _gcHandle.IsAllocated)
{
_gcHandle.Free();
}
}
internal override bool IsFailedHandle() => _sessionHandle.Status != TdsEnums.SNI_SUCCESS;
internal override PacketHandle ReadSyncOverAsync(int timeoutRemaining, out uint error)
{
SNIHandle handle = Handle;
if (handle == null)
{
throw ADP.ClosedConnectionError();
}
IntPtr readPacketPtr = IntPtr.Zero;
error = SNINativeMethodWrapper.SNIReadSyncOverAsync(handle, ref readPacketPtr, GetTimeoutRemaining());
return PacketHandle.FromNativePointer(readPacketPtr);
}
protected override PacketHandle EmptyReadPacket => PacketHandle.FromNativePointer(default);
internal override bool IsPacketEmpty(PacketHandle readPacket)
{
Debug.Assert(readPacket.Type == PacketHandle.NativePointerType || readPacket.Type == 0, "unexpected packet type when requiring NativePointer");
return IntPtr.Zero == readPacket.NativePointer;
}
internal override void ReleasePacket(PacketHandle syncReadPacket)
{
Debug.Assert(syncReadPacket.Type == PacketHandle.NativePointerType, "unexpected packet type when requiring NativePointer");
SNINativeMethodWrapper.SNIPacketRelease(syncReadPacket.NativePointer);
}
internal override uint CheckConnection()
{
SNIHandle handle = Handle;
return handle == null ? TdsEnums.SNI_SUCCESS : SNINativeMethodWrapper.SNICheckConnection(handle);
}
internal override PacketHandle ReadAsync(SessionHandle handle, out uint error)
{
Debug.Assert(handle.Type == SessionHandle.NativeHandleType, "unexpected handle type when requiring NativePointer");
IntPtr readPacketPtr = IntPtr.Zero;
error = SNINativeMethodWrapper.SNIReadAsync(handle.NativeHandle, ref readPacketPtr);
return PacketHandle.FromNativePointer(readPacketPtr);
}
internal override PacketHandle CreateAndSetAttentionPacket()
{
SNIHandle handle = Handle;
SNIPacket attnPacket = new SNIPacket(handle);
_sniAsyncAttnPacket = attnPacket;
SetPacketData(PacketHandle.FromNativePacket(attnPacket), SQL.AttentionHeader, TdsEnums.HEADER_LEN);
return PacketHandle.FromNativePacket(attnPacket);
}
internal override uint WritePacket(PacketHandle packet, bool sync)
{
Debug.Assert(packet.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePacket");
return SNINativeMethodWrapper.SNIWritePacket(Handle, packet.NativePacket, sync);
}
internal override PacketHandle AddPacketToPendingList(PacketHandle packetToAdd)
{
Debug.Assert(packetToAdd.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePacket");
SNIPacket packet = packetToAdd.NativePacket;
Debug.Assert(packet == _sniPacket, "Adding a packet other than the current packet to the pending list");
_sniPacket = null;
IntPtr pointer = packet.DangerousGetHandle();
lock (_writePacketLockObject)
{
_pendingWritePackets.Add(pointer, packet);
}
return PacketHandle.FromNativePointer(pointer);
}
internal override bool IsValidPacket(PacketHandle packetPointer)
{
Debug.Assert(packetPointer.Type == PacketHandle.NativePointerType || packetPointer.Type==PacketHandle.NativePacketType, "unexpected packet type when requiring NativePointer");
return (
(packetPointer.Type == PacketHandle.NativePointerType && packetPointer.NativePointer != IntPtr.Zero)
||
(packetPointer.Type == PacketHandle.NativePacketType && packetPointer.NativePacket != null)
);
}
internal override PacketHandle GetResetWritePacket()
{
if (_sniPacket != null)
{
SNINativeMethodWrapper.SNIPacketReset(Handle, SNINativeMethodWrapper.IOType.WRITE, _sniPacket, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI);
}
else
{
lock (_writePacketLockObject)
{
_sniPacket = _writePacketCache.Take(Handle);
}
}
return PacketHandle.FromNativePacket(_sniPacket);
}
internal override void ClearAllWritePackets()
{
if (_sniPacket != null)
{
_sniPacket.Dispose();
_sniPacket = null;
}
lock (_writePacketLockObject)
{
Debug.Assert(_pendingWritePackets.Count == 0 && _asyncWriteCount == 0, "Should not clear all write packets if there are packets pending");
_writePacketCache.Clear();
}
}
internal override void SetPacketData(PacketHandle packet, byte[] buffer, int bytesUsed)
{
Debug.Assert(packet.Type == PacketHandle.NativePacketType, "unexpected packet type when requiring NativePacket");
SNINativeMethodWrapper.SNIPacketSetData(packet.NativePacket, buffer, bytesUsed);
}
internal override uint SniGetConnectionId(ref Guid clientConnectionId)
=> SNINativeMethodWrapper.SniGetConnectionId(Handle, ref clientConnectionId);
internal override uint DisabeSsl()
=> SNINativeMethodWrapper.SNIRemoveProvider(Handle, SNINativeMethodWrapper.ProviderEnum.SSL_PROV);
internal override uint EnableMars(ref uint info)
=> SNINativeMethodWrapper.SNIAddProvider(Handle, SNINativeMethodWrapper.ProviderEnum.SMUX_PROV, ref info);
internal override uint EnableSsl(ref uint info)
{
// Add SSL (Encryption) SNI provider.
return SNINativeMethodWrapper.SNIAddProvider(Handle, SNINativeMethodWrapper.ProviderEnum.SSL_PROV, ref info);
}
internal override uint SetConnectionBufferSize(ref uint unsignedPacketSize)
=> SNINativeMethodWrapper.SNISetInfo(Handle, SNINativeMethodWrapper.QTypes.SNI_QUERY_CONN_BUFSIZE, ref unsignedPacketSize);
internal override uint GenerateSspiClientContext(byte[] receivedBuff, uint receivedLength, ref byte[] sendBuff, ref uint sendLength, byte[] _sniSpnBuffer)
=> SNINativeMethodWrapper.SNISecGenClientContext(Handle, receivedBuff, receivedLength, sendBuff, ref sendLength, _sniSpnBuffer);
internal override uint WaitForSSLHandShakeToComplete()
=> SNINativeMethodWrapper.SNIWaitForSSLHandshakeToComplete(Handle, GetTimeoutRemaining());
internal override void DisposePacketCache()
{
lock (_writePacketLockObject)
{
_writePacketCache.Dispose();
// Do not set _writePacketCache to null, just in case a WriteAsyncCallback completes after this point
}
}
internal sealed class WritePacketCache : IDisposable
{
private bool _disposed;
private Stack<SNIPacket> _packets;
public WritePacketCache()
{
_disposed = false;
_packets = new Stack<SNIPacket>();
}
public SNIPacket Take(SNIHandle sniHandle)
{
SNIPacket packet;
if (_packets.Count > 0)
{
// Success - reset the packet
packet = _packets.Pop();
SNINativeMethodWrapper.SNIPacketReset(sniHandle, SNINativeMethodWrapper.IOType.WRITE, packet, SNINativeMethodWrapper.ConsumerNumber.SNI_Consumer_SNI);
}
else
{
// Failed to take a packet - create a new one
packet = new SNIPacket(sniHandle);
}
return packet;
}
public void Add(SNIPacket packet)
{
if (!_disposed)
{
_packets.Push(packet);
}
else
{
// If we're disposed, then get rid of any packets added to us
packet.Dispose();
}
}
public void Clear()
{
while (_packets.Count > 0)
{
_packets.Pop().Dispose();
}
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
Clear();
}
}
}
}
}
| |
namespace Ioke.Lang {
using System;
using System.Globalization;
using Ioke.Math;
public class Decimal : IokeData {
private readonly BigDecimal value;
public static BigDecimal GetValue(object number) {
return ((Decimal)IokeObject.dataOf(number)).value;
}
public Decimal(string textRepresentation) {
this.value = new BigDecimal(textRepresentation).stripTrailingZeros();
}
public Decimal(BigDecimal value) {
this.value = value;
}
public static Decimal CreateDecimal(string val) {
return new Decimal(val);
}
public static Decimal CreateDecimal(RatNum val) {
return new Decimal(new BigDecimal(val.longValue()));
}
public static Decimal CreateDecimal(BigDecimal val) {
return new Decimal(val);
}
public string AsNativeString() {
string s = value.toPlainString();
if(s.IndexOf('.') != -1) {
if(s[s.Length-1] == '0' && s.IndexOf('e') == -1 && s.IndexOf('E') == -1) {
int end = s.Length-1;
while(s[end] == '0' && s[end-1] != '.') end--;
if(s[end-1] == '.') end++;
return s.Substring(0, end);
}
} else {
if(s.IndexOf('e') == -1 && s.IndexOf('E') == -1) {
return s + ".0";
}
}
return s;
}
public override string ToString() {
return AsNativeString();
}
public override string ToString(IokeObject obj) {
return AsNativeString();
}
public override IokeObject ConvertToDecimal(IokeObject self, IokeObject m, IokeObject context, bool signalCondition) {
return self;
}
public static string GetInspect(object on) {
return ((Decimal)(IokeObject.dataOf(on))).Inspect(on);
}
public string Inspect(object obj) {
return AsNativeString();
}
public override void Init(IokeObject obj) {
Runtime runtime = obj.runtime;
obj.Kind = "Number Decimal";
runtime.Decimal = obj;
obj.RegisterMethod(runtime.NewNativeMethod("returns true if the left hand side decimal is equal to the right hand side decimal.",
new TypeCheckingNativeMethod("==", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(runtime.Decimal)
.WithRequiredPositional("other")
.Arguments,
(method, on, args, keywords, context, message) => {
Decimal d = (Decimal)IokeObject.dataOf(on);
object other = args[0];
return ((other is IokeObject) &&
(IokeObject.dataOf(other) is Decimal)
&& ((on == context.runtime.Decimal && other == on) ||
d.value.Equals(((Decimal)IokeObject.dataOf(other)).value))) ? context.runtime.True : context.runtime.False;
})));
obj.RegisterMethod(runtime.NewNativeMethod("Returns a text representation of the object",
new TypeCheckingNativeMethod.WithNoArguments("asText", obj,
(method, on, args, keywords, context, message) => {
return runtime.NewText(on.ToString());
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns the square root of the receiver. this should return the same result as calling ** with 0.5",
new TypeCheckingNativeMethod.WithNoArguments("sqrt", obj,
(method, on, args, keywords, context, message) => {
BigDecimal value = ((Decimal)IokeObject.dataOf(on)).value;
if(value.CompareTo(BigDecimal.ZERO) < 1) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"Arithmetic"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
context.runtime.ErrorCondition(condition);
}
return runtime.NewDecimal(new BigSquareRoot().Get(value));
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a text inspection of the object",
new TypeCheckingNativeMethod.WithNoArguments("inspect", obj,
(method, on, args, keywords, context, message) => {
return method.runtime.NewText(Decimal.GetInspect(on));
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("Returns a brief text inspection of the object",
new TypeCheckingNativeMethod.WithNoArguments("notice", obj,
(method, on, args, keywords, context, message) => {
return method.runtime.NewText(Decimal.GetInspect(on));
})));
obj.RegisterMethod(obj.runtime.NewNativeMethod("returns a hash for the decimal number",
new NativeMethod.WithNoArguments("hash", (method, context, message, on, outer) => {
outer.ArgumentsDefinition.CheckArgumentCount(context, message, on);
return context.runtime.NewNumber(Decimal.GetValue(on).GetHashCode());
})));
obj.RegisterMethod(runtime.NewNativeMethod("compares this number against the argument, true if this number is the same, otherwise false",
new TypeCheckingNativeMethod("==", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("other")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
if(IokeObject.dataOf(arg) is Number) {
return (Decimal.GetValue(on).CompareTo(Number.GetValue(arg).AsBigDecimal()) == 0) ? context.runtime.True : context.runtime.False;
} else if(IokeObject.dataOf(arg) is Decimal) {
return (Decimal.GetValue(on).CompareTo(Decimal.GetValue(arg)) == 0) ? context.runtime.True : context.runtime.False;
} else {
return context.runtime.False;
}
})));
obj.RegisterMethod(runtime.NewNativeMethod("compares this number against the argument, returning -1, 0 or 1 based on which one is larger. if the argument is a rational, it will be converted into a form suitable for comparing against a decimal, and then compared. if the argument is neither a Rational nor a Decimal, it tries to call asDecimal, and if that doesn't work it returns nil.",
new TypeCheckingNativeMethod("<=>", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("other")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(data is Number) {
return context.runtime.NewNumber(Decimal.GetValue(on).CompareTo(Number.GetValue(arg).AsBigDecimal()));
} else {
if(!(data is Decimal)) {
arg = IokeObject.ConvertToDecimal(arg, message, context, false);
if(!(IokeObject.dataOf(arg) is Decimal)) {
// Can't compare, so bail out
return context.runtime.nil;
}
}
if(on == context.runtime.Decimal || arg == context.runtime.Decimal) {
if(arg == on) {
return context.runtime.NewNumber(0);
}
return context.runtime.nil;
}
return context.runtime.NewNumber(Decimal.GetValue(on).CompareTo(Decimal.GetValue(arg)));
}
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns the difference between this number and the argument. if the argument is a rational, it will be converted into a form suitable for subtracting against a decimal, and then subtracted. if the argument is neither a Rational nor a Decimal, it tries to call asDecimal, and if that fails it signals a condition.",
new TypeCheckingNativeMethod("-", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("subtrahend")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(data is Number) {
return context.runtime.NewDecimal(Decimal.GetValue(on).subtract(Number.GetValue(arg).AsBigDecimal()));
} else {
if(!(data is Decimal)) {
arg = IokeObject.ConvertToDecimal(arg, message, context, true);
}
return context.runtime.NewDecimal(Decimal.GetValue(on).subtract(Decimal.GetValue(arg)));
}
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns the sum of this number and the argument. if the argument is a rational, it will be converted into a form suitable for addition against a decimal, and then added. if the argument is neither a Rational nor a Decimal, it tries to call asDecimal, and if that fails it signals a condition.",
new TypeCheckingNativeMethod("+", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("addend")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(data is Number) {
return context.runtime.NewDecimal(Decimal.GetValue(on).add(Number.GetValue(arg).AsBigDecimal()));
} else {
if(!(data is Decimal)) {
arg = IokeObject.ConvertToDecimal(arg, message, context, true);
}
return context.runtime.NewDecimal(Decimal.GetValue(on).add(Decimal.GetValue(arg)));
}
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns the product of this number and the argument. if the argument is a rational, the receiver will be converted into a form suitable for multiplying against a decimal, and then multiplied. if the argument is neither a Rational nor a Decimal, it tries to call asDecimal, and if that fails it signals a condition.",
new TypeCheckingNativeMethod("*", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("multiplier")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(data is Number) {
return context.runtime.NewDecimal(Decimal.GetValue(on).multiply(Number.GetValue(arg).AsBigDecimal()));
} else {
if(!(data is Decimal)) {
arg = IokeObject.ConvertToDecimal(arg, message, context, true);
}
return context.runtime.NewDecimal(Decimal.GetValue(on).multiply(Decimal.GetValue(arg)));
}
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns this number to the power of the argument (which has to be an integer)",
new TypeCheckingNativeMethod("**", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("exponent")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(!(data is Number)) {
arg = IokeObject.ConvertToRational(arg, message, context, true);
}
return context.runtime.NewDecimal(Decimal.GetValue(on).pow(Number.IntValue(arg).intValue()));
})));
obj.RegisterMethod(runtime.NewNativeMethod("returns the quotient of this number and the argument.",
new TypeCheckingNativeMethod("/", TypeCheckingArgumentsDefinition.builder()
.ReceiverMustMimic(obj)
.WithRequiredPositional("divisor")
.Arguments,
(method, on, args, keywords, context, message) => {
object arg = args[0];
IokeData data = IokeObject.dataOf(arg);
if(data is Number) {
return context.runtime.NewDecimal(Decimal.GetValue(on).divide(Number.GetValue(arg).AsBigDecimal()));
} else {
if(!(data is Decimal)) {
arg = IokeObject.ConvertToDecimal(arg, message, context, true);
}
while(Decimal.GetValue(arg).CompareTo(BigDecimal.ZERO) == 0) {
IokeObject condition = IokeObject.As(IokeObject.GetCellChain(context.runtime.Condition,
message,
context,
"Error",
"Arithmetic",
"DivisionByZero"), context).Mimic(message, context);
condition.SetCell("message", message);
condition.SetCell("context", context);
condition.SetCell("receiver", on);
object[] newCell = new object[]{arg};
context.runtime.WithRestartReturningArguments(()=>{context.runtime.ErrorCondition(condition);},
context,
new IokeObject.UseValue("newValue", newCell));
arg = newCell[0];
}
BigDecimal result = null;
try {
result = Decimal.GetValue(on).divide(Decimal.GetValue(arg), BigDecimal.ROUND_UNNECESSARY);
} catch(System.ArithmeticException) {
result = Decimal.GetValue(on).divide(Decimal.GetValue(arg), MathContext.DECIMAL128);
}
return context.runtime.NewDecimal(result);
}
})));
}
}
}
| |
/*
Copyright 2006 - 2010 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
using System.Data;
using System.Drawing;
using System.Collections;
using System.Windows.Forms;
using System.ComponentModel;
namespace UPnPAuthor
{
/// <summary>
/// Summary description for ComplexItem.
/// </summary>
public class ComplexItem : System.Windows.Forms.UserControl
{
private System.Windows.Forms.TextBox variableName;
private System.Windows.Forms.PictureBox iconBox;
private System.Windows.Forms.ImageList actionImageList;
private System.Windows.Forms.Button upButton;
private System.Windows.Forms.Button downButton;
private System.ComponentModel.IContainer components;
private int min = 1;
private string max = "";
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton maxOccur_UNBOUNDED;
private System.Windows.Forms.RadioButton maxOccur_FIXED;
private System.Windows.Forms.TextBox maxOccurTextBox;
private System.Windows.Forms.ComboBox variableType;
private Container parent;
public OpenSource.UPnP.UPnPComplexType.Field GetFieldInfo()
{
OpenSource.UPnP.UPnPComplexType.Field f = new OpenSource.UPnP.UPnPComplexType.Field();
f.Name = variableName.Text;
f.Type = variableType.SelectedItem.ToString();
f.MinOccurs = this.MinOccurs.ToString();
f.MaxOccurs = this.MaxOccurs;
if(variableType.SelectedIndex>9)
{
// Complex Type
f.TypeNS = ((OpenSource.UPnP.UPnPComplexType)variableType.SelectedItem).Name_NAMESPACE;
}
else
{
// XSD Type
f.TypeNS = "http://www.w3.org/2001/XMLSchema";
}
return(f);
}
public ComplexItem(Container p, OpenSource.UPnP.UPnPComplexType[] typeList)
{
// This call is required by the Windows.Forms Form Designer.
InitializeComponent();
// TODO: Add any initialization after the InitializeComponent call
iconBox.Image = actionImageList.Images[0];
parent = p;
variableType.SelectedIndex = 0;
foreach(OpenSource.UPnP.UPnPComplexType ct in typeList)
{
variableType.Items.Add(ct);
}
}
public int MinOccurs
{
get
{
return(min);
}
}
public string MaxOccurs
{
get
{
return(max);
}
}
public string VariableName
{
get
{
return(variableName.Text);
}
}
// public ArrayList DataStructure
// {
// get
// {
// }
// }
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(ComplexItem));
this.variableName = new System.Windows.Forms.TextBox();
this.variableType = new System.Windows.Forms.ComboBox();
this.iconBox = new System.Windows.Forms.PictureBox();
this.actionImageList = new System.Windows.Forms.ImageList(this.components);
this.upButton = new System.Windows.Forms.Button();
this.downButton = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.maxOccurTextBox = new System.Windows.Forms.TextBox();
this.maxOccur_FIXED = new System.Windows.Forms.RadioButton();
this.maxOccur_UNBOUNDED = new System.Windows.Forms.RadioButton();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// variableName
//
this.variableName.Location = new System.Drawing.Point(72, 8);
this.variableName.Name = "variableName";
this.variableName.Size = new System.Drawing.Size(320, 20);
this.variableName.TabIndex = 0;
this.variableName.Text = "";
//
// variableType
//
this.variableType.Items.AddRange(new object[] {
"string",
"boolean",
"decimal",
"float",
"double",
"duration",
"dateTime",
"time",
"date",
"anyURI"});
this.variableType.Location = new System.Drawing.Point(72, 32);
this.variableType.Name = "variableType";
this.variableType.Size = new System.Drawing.Size(320, 21);
this.variableType.TabIndex = 1;
//
// iconBox
//
this.iconBox.Location = new System.Drawing.Point(8, 8);
this.iconBox.Name = "iconBox";
this.iconBox.Size = new System.Drawing.Size(48, 24);
this.iconBox.TabIndex = 2;
this.iconBox.TabStop = false;
this.iconBox.DoubleClick += new System.EventHandler(this.iconBox_DoubleClick);
//
// actionImageList
//
this.actionImageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth24Bit;
this.actionImageList.ImageSize = new System.Drawing.Size(41, 18);
this.actionImageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("actionImageList.ImageStream")));
this.actionImageList.TransparentColor = System.Drawing.Color.White;
//
// upButton
//
this.upButton.Image = ((System.Drawing.Image)(resources.GetObject("upButton.Image")));
this.upButton.Location = new System.Drawing.Point(4, 36);
this.upButton.Name = "upButton";
this.upButton.Size = new System.Drawing.Size(24, 22);
this.upButton.TabIndex = 3;
this.upButton.Text = "button1";
this.upButton.Click += new System.EventHandler(this.upButton_Click);
//
// downButton
//
this.downButton.Image = ((System.Drawing.Image)(resources.GetObject("downButton.Image")));
this.downButton.Location = new System.Drawing.Point(32, 36);
this.downButton.Name = "downButton";
this.downButton.Size = new System.Drawing.Size(24, 22);
this.downButton.TabIndex = 4;
this.downButton.Text = "button2";
this.downButton.Click += new System.EventHandler(this.downButton_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.maxOccurTextBox);
this.groupBox1.Controls.Add(this.maxOccur_FIXED);
this.groupBox1.Controls.Add(this.maxOccur_UNBOUNDED);
this.groupBox1.Location = new System.Drawing.Point(416, 1);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(104, 56);
this.groupBox1.TabIndex = 5;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "MaxOccurs";
//
// maxOccurTextBox
//
this.maxOccurTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 6.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.maxOccurTextBox.Location = new System.Drawing.Point(24, 32);
this.maxOccurTextBox.Name = "maxOccurTextBox";
this.maxOccurTextBox.Size = new System.Drawing.Size(56, 18);
this.maxOccurTextBox.TabIndex = 2;
this.maxOccurTextBox.Text = "1";
//
// maxOccur_FIXED
//
this.maxOccur_FIXED.Checked = true;
this.maxOccur_FIXED.Location = new System.Drawing.Point(8, 33);
this.maxOccur_FIXED.Name = "maxOccur_FIXED";
this.maxOccur_FIXED.Size = new System.Drawing.Size(16, 16);
this.maxOccur_FIXED.TabIndex = 1;
this.maxOccur_FIXED.TabStop = true;
this.maxOccur_FIXED.Text = "radioButton2";
this.maxOccur_FIXED.CheckedChanged += new System.EventHandler(this.maxOccur_FIXED_CheckedChanged);
//
// maxOccur_UNBOUNDED
//
this.maxOccur_UNBOUNDED.Location = new System.Drawing.Point(8, 16);
this.maxOccur_UNBOUNDED.Name = "maxOccur_UNBOUNDED";
this.maxOccur_UNBOUNDED.Size = new System.Drawing.Size(88, 16);
this.maxOccur_UNBOUNDED.TabIndex = 0;
this.maxOccur_UNBOUNDED.Text = "Unbounded";
this.maxOccur_UNBOUNDED.CheckedChanged += new System.EventHandler(this.maxOccur_UNBOUNDED_CheckedChanged);
//
// ComplexItem
//
this.BackColor = System.Drawing.SystemColors.ControlLight;
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.downButton);
this.Controls.Add(this.upButton);
this.Controls.Add(this.iconBox);
this.Controls.Add(this.variableType);
this.Controls.Add(this.variableName);
this.Name = "ComplexItem";
this.Size = new System.Drawing.Size(528, 64);
this.groupBox1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private void ToggleIcon()
{
if(min==1)
{
min=0;
iconBox.Image=actionImageList.Images[1];
}
else
{
min=1;
iconBox.Image=actionImageList.Images[0];
}
}
private void iconBox_DoubleClick(object sender, System.EventArgs e)
{
ToggleIcon();
}
private void upButton_Click(object sender, System.EventArgs e)
{
parent.moveUp(this);
}
private void downButton_Click(object sender, System.EventArgs e)
{
parent.moveDown(this);
}
private void maxOccur_UNBOUNDED_CheckedChanged(object sender, System.EventArgs e)
{
if(maxOccur_UNBOUNDED.Checked)
{
max = "unbounded";
}
}
private void maxOccur_FIXED_CheckedChanged(object sender, System.EventArgs e)
{
if(maxOccur_FIXED.Checked)
{
max = maxOccurTextBox.Text;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Security;
using System.Windows;
using System.Windows.Threading;
using DevExpress.Mvvm.Native;
using System.Windows.Interop;
using DevExpress.Mvvm.UI.Native;
namespace DevExpress.Mvvm.UI {
public enum SplashScreenLocation {
CenterContainer,
CenterWindow
}
public enum SplashScreenLock {
None,
InputOnly,
Full,
LoadingContent
}
public enum SplashScreenClosingMode {
Default,
OnParentClosed,
ManualOnly
}
enum AsyncInvokeMode {
AllowSyncInvoke,
AsyncOnly
}
enum SplashScreenArrangeMode {
Default,
ArrangeOnStartupOnly,
Skip
}
public class SplashScreenOwner {
public DependencyObject Owner { get; private set; }
public SplashScreenOwner(DependencyObject owner) {
if(owner == null)
throw new ArgumentNullException("Owner");
Owner = owner;
}
internal WindowContainer CreateOwnerContainer(WindowStartupLocation splashScreenStartupLocation) {
WindowContainer result = null;
if(splashScreenStartupLocation == WindowStartupLocation.CenterOwner)
result = new WindowArrangerContainer(Owner, SplashScreenLocation.CenterWindow) { ArrangeMode = SplashScreenArrangeMode.ArrangeOnStartupOnly };
if(result == null || !result.IsInitialized)
result = new WindowContainer(Owner);
return result;
}
}
internal class WindowLocker {
readonly SplashScreenLock lockMode;
WindowContainer Container { get; set; }
public WindowLocker(WindowContainer container, SplashScreenLock lockMode) {
Container = container;
this.lockMode = lockMode;
if(!Container.IsInitialized)
Container.Initialized += OnOwnerInitialized;
else
Initialize();
}
public void Release(bool activateWindowIfNeeded) {
if(Container == null)
return;
Container.Initialized -= OnOwnerInitialized;
var container = Container;
Container = null;
if(container.Window == null || lockMode == SplashScreenLock.None)
return;
SplashScreenHelper.InvokeAsync(container.Window, () => {
if(activateWindowIfNeeded && !SplashScreenHelper.ApplicationHasActiveWindow())
container.ActivateWindow();
SplashScreenHelper.UnlockWindow(container);
}, DispatcherPriority.Render);
}
void OnOwnerInitialized(object sender, EventArgs e) {
((WindowContainer)sender).Initialized -= OnOwnerInitialized;
Initialize();
}
void Initialize() {
if(Container != null)
SplashScreenHelper.InvokeAsync(Container.Window, () => SplashScreenHelper.LockWindow(Container, lockMode), DispatcherPriority.Send, AsyncInvokeMode.AllowSyncInvoke);
}
}
internal class WindowArranger : WindowRelationInfo {
new public WindowArrangerContainer Parent { get { return base.Parent as WindowArrangerContainer; } }
FrameworkElement ParentContainer { get { return Parent.WindowObject as FrameworkElement; } }
SplashScreenLocation childLocation;
Rect lastChildPos = Rect.Empty;
Rect lastParentPos = Rect.Empty;
Rect nextParentPos = Rect.Empty;
bool isParentClosed;
SplashScreenArrangeMode arrangeMode;
bool SkipArrange { get { return IsReleased || arrangeMode == SplashScreenArrangeMode.Skip; } }
bool IsArrangeValid { get { return nextParentPos == lastParentPos && lastChildPos.Width == Child.Window.ActualWidth && lastChildPos.Height == Child.Window.ActualHeight; } }
protected internal WindowArranger(WindowArrangerContainer parent, SplashScreenLocation childLocation, SplashScreenArrangeMode arrangeMode)
: base(parent) {
this.childLocation = childLocation;
this.arrangeMode = arrangeMode;
}
protected override void ChildAttachedOverride() {
Child.Window.WindowStartupLocation = WindowStartupLocation.Manual;
}
protected override void CompleteInitializationOverride() {
if(Child.Window.Dispatcher.CheckAccess()) {
nextParentPos = childLocation == SplashScreenLocation.CenterContainer ? Parent.ControlStartupPosition : Parent.WindowStartupPosition;
UpdateChildPosition();
}
SplashScreenHelper.InvokeAsync(Parent.Window, () => UpdateNextParentRectAndChildPosition(true), DispatcherPriority.Normal, AsyncInvokeMode.AllowSyncInvoke);
}
protected override void SubscribeChildEventsOverride() {
Child.Window.SizeChanged += ChildSizeChanged;
Child.Window.ContentRendered += ChildSizeChanged;
}
protected override void UnsubscribeChildEventsOverride() {
Child.Window.SizeChanged -= ChildSizeChanged;
Child.Window.ContentRendered -= ChildSizeChanged;
}
protected override void SubscribeParentEventsOverride() {
if(Parent.Window != null) {
Parent.Window.LocationChanged += OnParentSizeOrPositionChanged;
Parent.Window.SizeChanged += OnParentSizeOrPositionChanged;
}
if(childLocation == SplashScreenLocation.CenterContainer && ParentContainer != null && Parent.Window != ParentContainer) {
ParentContainer.SizeChanged += OnParentSizeOrPositionChanged;
ParentContainer.LayoutUpdated += OnParentSizeOrPositionChanged;
}
}
protected override void UnsubscribeParentEventsOverride() {
if(Parent.Window != null) {
Parent.Window.LocationChanged -= OnParentSizeOrPositionChanged;
Parent.Window.SizeChanged -= OnParentSizeOrPositionChanged;
}
if(childLocation == SplashScreenLocation.CenterContainer && ParentContainer != null && Parent.Window != ParentContainer) {
try {
ParentContainer.SizeChanged -= OnParentSizeOrPositionChanged;
ParentContainer.LayoutUpdated -= OnParentSizeOrPositionChanged;
} catch { }
}
}
protected override void OnParentClosed(object sender, EventArgs e) {
isParentClosed = true;
base.OnParentClosed(sender, e);
}
void OnParentSizeOrPositionChanged(object sender, EventArgs e) {
if(SkipArrange)
return;
UpdateNextParentRectAndChildPosition(false);
}
void ChildSizeChanged(object sender, EventArgs e) {
if(SkipArrange)
return;
if(!Parent.IsInitialized || Child.Window == null ||
(lastChildPos.Width == Child.Window.ActualWidth && lastChildPos.Height == Child.Window.ActualHeight))
return;
if(lastParentPos.IsEmpty)
SplashScreenHelper.InvokeAsync(Parent, () => UpdateNextParentRectAndChildPosition(true), DispatcherPriority.Normal, AsyncInvokeMode.AllowSyncInvoke);
else
UpdateChildPosition();
}
void UpdateNextParentRectAndChildPosition(bool skipSizeCheck) {
if(SkipArrange || !Parent.IsInitialized)
return;
nextParentPos = isParentClosed
? Rect.Empty
: childLocation == SplashScreenLocation.CenterContainer ? Parent.GetControlRect() : Parent.GetWindowRect();
if(!skipSizeCheck && lastParentPos == nextParentPos || nextParentPos.IsEmpty)
return;
SplashScreenHelper.InvokeAsync(Child, () => UpdateChildPosition(), DispatcherPriority.Normal, AsyncInvokeMode.AllowSyncInvoke);
}
void UpdateChildPosition() {
if(SkipArrange || Child == null || !Child.IsInitialized || IsArrangeValid)
return;
if(arrangeMode == SplashScreenArrangeMode.ArrangeOnStartupOnly && lastParentPos != Rect.Empty && lastParentPos != nextParentPos) {
arrangeMode = SplashScreenArrangeMode.Skip;
return;
}
Rect bounds = nextParentPos;
var window = Child.Window;
if(!IsZero(window.ActualWidth) && !IsZero(window.ActualHeight)) {
window.Left = (int)(bounds.X + (bounds.Width - window.ActualWidth) * 0.5);
window.Top = (int)(bounds.Y + (bounds.Height - window.ActualHeight) * 0.5);
lastChildPos = new Rect(window.Left, window.Top, window.Width, window.Height);
}
lastParentPos = bounds;
}
static bool IsZero(double value) {
return value == 0d || double.IsNaN(value);
}
}
internal class WindowRelationInfo {
public WindowContainer Parent { get; private set; }
public WindowContainer Child { get; private set; }
public bool IsInitialized { get; private set; }
public bool IsReleased { get; private set; }
protected internal WindowRelationInfo(WindowContainer parent) {
if(parent == null)
throw new ArgumentNullException("Parent");
Parent = parent;
CompleteContainerInitialization(Parent);
}
public void AttachChild(Window child) {
if(Child != null)
throw new ArgumentException("Child property is already set");
Child = new WindowContainer(child);
ChildAttachedOverride();
CompleteContainerInitialization(Child);
}
public virtual void Release() {
if(IsReleased)
return;
IsReleased = true;
UnsubscribeChildEvents();
UnsubscribeParentEvents();
Child.Initialized -= OnContainerInitialized;
Parent.Initialized -= OnContainerInitialized;
Child = null;
Parent = null;
}
protected virtual void SubscribeParentEventsOverride() { }
protected virtual void SubscribeChildEventsOverride() { }
protected virtual void UnsubscribeParentEventsOverride() { }
protected virtual void UnsubscribeChildEventsOverride() { }
protected virtual void CompleteInitializationOverride() { }
protected virtual void ChildAttachedOverride() { }
protected virtual void OnParentClosed(object sender, EventArgs e) {
ParentClosed.Do(x => x(this, EventArgs.Empty));
}
#region Initialization
void OnContainerInitialized(object sender, EventArgs e) {
((WindowContainer)sender).Initialized -= OnContainerInitialized;
CompleteContainerInitialization((WindowContainer)sender);
}
void CompleteContainerInitialization(WindowContainer container) {
if(!container.IsInitialized) {
container.Initialized += OnContainerInitialized;
return;
}
if(container == Parent)
SubscribeParentEvents();
else
SubscribeChildEvents();
CompleteInitialization();
}
void CompleteInitialization() {
if(IsReleased || IsInitialized || Child == null || Child.Handle == IntPtr.Zero || Parent.Handle == IntPtr.Zero)
return;
CompleteInitializationOverride();
SplashScreenHelper.InvokeAsync(Child, SetChildParent);
IsInitialized = true;
}
void SetChildParent() {
if(IsReleased)
return;
SplashScreenHelper.SetParent(Child.Window, Parent.Handle);
}
#endregion
void SubscribeChildEvents() {
if(Child == null || Child.Window == null)
return;
Child.Window.Closed += OnChildClosed;
SubscribeChildEventsOverride();
}
void UnsubscribeChildEvents() {
if(Child == null || Child.Window == null)
return;
Child.Window.Closed -= OnChildClosed;
UnsubscribeChildEventsOverride();
}
void OnChildClosed(object sender, EventArgs e) {
UnsubscribeChildEvents();
}
void SubscribeParentEvents() {
if(Parent == null)
return;
Parent.Window.Closed += OnParentClosed;
SubscribeParentEventsOverride();
}
void UnsubscribeParentEvents() {
if(Parent == null || Parent.Window == null)
return;
Parent.Window.Closed -= OnParentClosed;
UnsubscribeParentEventsOverride();
}
public event EventHandler ParentClosed;
}
internal class WindowArrangerContainer : WindowContainer {
public Rect ControlStartupPosition { get; private set; }
public Rect WindowStartupPosition { get; private set; }
public SplashScreenArrangeMode ArrangeMode { get; set; }
SplashScreenLocation arrangeLocation;
public WindowArrangerContainer(DependencyObject parentObject, SplashScreenLocation arrangeLocation)
: base(parentObject) {
this.arrangeLocation = arrangeLocation;
}
public override WindowRelationInfo CreateOwnerContainer() {
return new WindowArranger(this, arrangeLocation, ArrangeMode);
}
public Rect GetWindowRect() {
return Window == null || !Window.IsLoaded ? Rect.Empty : LayoutHelper.GetScreenRect(Window);
}
public Rect GetControlRect() {
return !(WindowObject as FrameworkElement).Return(x => x.IsLoaded, () => false) || PresentationSource.FromDependencyObject(WindowObject) == null
? Rect.Empty
: LayoutHelper.GetScreenRect(WindowObject as FrameworkElement);
}
protected override void CompleteInitializationOverride() {
ControlStartupPosition = GetControlRect();
WindowStartupPosition = GetWindowRect();
}
}
internal class WindowContainer {
public DependencyObject WindowObject { get; private set; }
public Window Window { get; private set; }
public IntPtr Handle { get; private set; }
public bool IsInitialized { get; private set; }
public WindowContainer(DependencyObject windowObject) {
if(windowObject == null)
throw new ArgumentNullException("WindowObject");
WindowObject = windowObject;
Initialize();
}
public virtual WindowRelationInfo CreateOwnerContainer() {
return new WindowRelationInfo(this);
}
public void ActivateWindow() {
SplashScreenHelper.InvokeAsync(this, ActivateWindowCore, DispatcherPriority.Send, AsyncInvokeMode.AllowSyncInvoke);
}
protected virtual void CompleteInitializationOverride() { }
void ActivateWindowCore() {
if(Window != null && !Window.IsActive && Window.IsVisible && !SplashScreenHelper.ApplicationHasActiveWindow())
Window.Activate();
}
void Initialize() {
CompleteInitialization();
if(IsInitialized)
return;
if(!(WindowObject as FrameworkElement).Return(x => x.IsLoaded, () => true))
(WindowObject as FrameworkElement).Loaded += OnControlLoaded;
}
void CompleteInitialization() {
if(IsInitialized)
return;
Window window = (WindowObject as Window) ?? Window.GetWindow(WindowObject);
if(window == null)
return;
WindowInteropHelper helper = new WindowInteropHelper(window);
helper.EnsureHandle();
Window = window;
Handle = helper.Handle;
CompleteInitializationOverride();
IsInitialized = true;
Initialized.Do(x => x(this, EventArgs.Empty));
}
void OnControlLoaded(object sender, RoutedEventArgs e) {
(sender as FrameworkElement).Loaded -= OnControlLoaded;
Initialize();
}
public event EventHandler Initialized;
}
static class SplashScreenHelper {
[DllImport("user32.dll")]
static extern bool EnableWindow(IntPtr hWnd, bool bEnable);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, IntPtr dwNewLong);
[DllImport("user32.dll", SetLastError = true)]
static extern int GetWindowLong(IntPtr hWnd, int nIndex);
[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
const int WS_EX_TRANSPARENT = 0x00000020;
const int GWL_EXSTYLE = (-20);
const int GWL_HWNDPARENT = -8;
static object locker = new object();
static Dictionary<IntPtr, WindowLockInfo> lockedWindowsDict = new Dictionary<IntPtr, WindowLockInfo>();
class WindowLockInfo {
public int LockCounter { get; set; }
public SplashScreenLock LockMode { get; private set; }
public bool IsHitTestVisible { get; private set; }
public WindowLockInfo(int lockCounter, SplashScreenLock lockMode, bool isHitTestVisible) {
LockCounter = lockCounter;
LockMode = lockMode;
IsHitTestVisible = isHitTestVisible;
}
}
public static void InvokeAsync(WindowContainer container, Action action, DispatcherPriority priority = DispatcherPriority.Normal, AsyncInvokeMode mode = AsyncInvokeMode.AsyncOnly) {
if(container != null)
InvokeAsync(container.Window, action, priority, mode);
}
public static void InvokeAsync(DispatcherObject dispatcherObject, Action action, DispatcherPriority priority = DispatcherPriority.Normal, AsyncInvokeMode mode = AsyncInvokeMode.AsyncOnly) {
if(dispatcherObject == null || dispatcherObject.Dispatcher == null)
return;
if(mode == AsyncInvokeMode.AllowSyncInvoke && dispatcherObject.Dispatcher.CheckAccess())
action.Invoke();
else
dispatcherObject.Dispatcher.BeginInvoke(action, priority);
}
public static T FindParameter<T>(object parameter, T fallbackValue = default(T)) {
if(parameter is T)
return (T)parameter;
if(parameter is object[])
foreach(object val in (object[])parameter)
if(val is T)
return (T)val;
return fallbackValue;
}
public static IList<T> FindParameters<T>(object parameter) {
if(parameter is T)
return new List<T>() { (T)parameter };
var result = new List<T>();
if(parameter is object[])
foreach(object val in (object[])parameter)
if(val is T)
result.Add((T)val);
return result.Count > 0 ? result : null;
}
[SecuritySafeCritical]
public static void SetParent(Window window, IntPtr parentHandle) {
if(window.IsVisible) {
SetWindowLong(new WindowInteropHelper(window).Handle, GWL_HWNDPARENT, parentHandle);
} else {
WindowInteropHelper windowInteropHelper = new WindowInteropHelper(window);
windowInteropHelper.Owner = parentHandle;
}
}
public static bool ApplicationHasActiveWindow() {
return GetApplicationActiveWindow(false) != null;
}
public static Window GetApplicationActiveWindow(bool mainWindowIfNull) {
if(Application.Current == null || !Application.Current.Dispatcher.CheckAccess())
return null;
foreach(Window window in Application.Current.Windows)
if(window.Dispatcher.CheckAccess() && window.IsActive)
return window;
return mainWindowIfNull ? Application.Current.Return(x => x.MainWindow, null) : null;
}
[SecuritySafeCritical]
static void SetWindowEnabled(IntPtr windowHandle, bool isEnabled) {
if(windowHandle == IntPtr.Zero)
return;
EnableWindow(windowHandle, isEnabled);
}
[SecuritySafeCritical]
public static bool PatchWindowStyle(Window window) {
var wndHelper = new WindowInteropHelper(window);
if(wndHelper.Handle == IntPtr.Zero)
return false;
int exStyle = GetWindowLong(wndHelper.Handle, GWL_EXSTYLE);
SetWindowLong(wndHelper.Handle, GWL_EXSTYLE, exStyle | WS_EX_TRANSPARENT);
return true;
}
#region Lock logic
public static void LockWindow(WindowContainer container, SplashScreenLock lockMode) {
if(container == null || container.Handle == IntPtr.Zero || lockMode == SplashScreenLock.None)
return;
IntPtr handle = container.Handle;
lock(locker) {
WindowLockInfo lockInfo;
if(!lockedWindowsDict.TryGetValue(handle, out lockInfo))
lockedWindowsDict.Add(handle, (lockInfo = new WindowLockInfo(1, lockMode, container.Window.IsHitTestVisible)));
else
++lockInfo.LockCounter;
if(lockInfo.LockCounter == 1)
DisableWindow(container, lockMode);
}
}
public static void UnlockWindow(WindowContainer container) {
if(container.Handle == IntPtr.Zero)
return;
IntPtr handle = container.Handle;
lock(locker) {
WindowLockInfo lockInfo;
if(!lockedWindowsDict.TryGetValue(handle, out lockInfo))
return;
if(--lockInfo.LockCounter == 0) {
lockedWindowsDict.Remove(handle);
EnableWindow(container, lockInfo);
}
}
}
static void DisableWindow(WindowContainer container, SplashScreenLock lockMode) {
if(lockMode == SplashScreenLock.Full)
SplashScreenHelper.SetWindowEnabled(container.Handle, false);
else if(lockMode == SplashScreenLock.InputOnly) {
container.Window.IsHitTestVisible = false;
container.Window.PreviewKeyDown += OnWindowKeyDown;
} else if(lockMode == SplashScreenLock.LoadingContent) {
FrameworkElement content = container.WindowObject as FrameworkElement;
if(content != null) {
content.PreviewKeyDown -= OnWindowKeyDown;
content.IsHitTestVisible = false;
}
}
}
static void EnableWindow(WindowContainer container, WindowLockInfo lockInfo) {
if(lockInfo.LockMode == SplashScreenLock.Full)
SplashScreenHelper.SetWindowEnabled(container.Handle, true);
else if(lockInfo.LockMode == SplashScreenLock.InputOnly) {
container.Window.IsHitTestVisible = lockInfo.IsHitTestVisible;
container.Window.PreviewKeyDown -= OnWindowKeyDown;
} else if(lockInfo.LockMode == SplashScreenLock.LoadingContent) {
FrameworkElement content = container.WindowObject as FrameworkElement;
if(content != null) {
content.PreviewKeyDown -= OnWindowKeyDown;
content.IsHitTestVisible = lockInfo.IsHitTestVisible;
}
}
}
static void OnWindowKeyDown(object sender, System.Windows.Input.KeyEventArgs e) {
e.Handled = true;
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.Shared.Extensions;
namespace Microsoft.CodeAnalysis.CodeRefactorings.UseNamedArguments
{
internal abstract class AbstractUseNamedArgumentsCodeRefactoringProvider : CodeRefactoringProvider
{
protected interface IAnalyzer
{
Task ComputeRefactoringsAsync(
CodeRefactoringContext context, SyntaxNode root, CancellationToken cancellationToken);
}
protected abstract class Analyzer<TBaseArgumentSyntax, TSimpleArgumentSyntax, TArgumentListSyntax> : IAnalyzer
where TBaseArgumentSyntax : SyntaxNode
where TSimpleArgumentSyntax : TBaseArgumentSyntax
where TArgumentListSyntax : SyntaxNode
{
public async Task ComputeRefactoringsAsync(
CodeRefactoringContext context, SyntaxNode root, CancellationToken cancellationToken)
{
if (context.Span.Length > 0)
{
return;
}
var position = context.Span.Start;
var token = root.FindToken(position);
if (token.Span.Start == position &&
IsCloseParenOrComma(token))
{
token = token.GetPreviousToken();
if (token.Span.End != position)
{
return;
}
}
var argument = root.FindNode(token.Span).FirstAncestorOrSelfUntil<TBaseArgumentSyntax>(node => node is TArgumentListSyntax) as TSimpleArgumentSyntax;
if (argument == null)
{
return;
}
if (!IsPositionalArgument(argument))
{
return;
}
// Arguments can be arbitrarily large. Only offer this feature if the caret is on hte
// line that the argument starts on.
var document = context.Document;
var sourceText = await document.GetTextAsync(cancellationToken).ConfigureAwait(false);
var argumentStartLine = sourceText.Lines.GetLineFromPosition(argument.Span.Start).LineNumber;
var caretLine = sourceText.Lines.GetLineFromPosition(position).LineNumber;
if (argumentStartLine != caretLine)
{
return;
}
var receiver = GetReceiver(argument);
if (receiver == null)
{
return;
}
if (receiver.ContainsDiagnostics)
{
return;
}
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var symbol = semanticModel.GetSymbolInfo(receiver, cancellationToken).Symbol;
if (symbol == null)
{
return;
}
var parameters = symbol.GetParameters();
if (parameters.IsDefaultOrEmpty)
{
return;
}
var argumentList = argument.Parent as TArgumentListSyntax;
if (argumentList == null)
{
return;
}
var arguments = GetArguments(argumentList);
var argumentCount = arguments.Count;
var argumentIndex = arguments.IndexOf(argument);
if (argumentIndex >= parameters.Length)
{
return;
}
if (!IsLegalToAddNamedArguments(parameters, argumentCount))
{
return;
}
for (var i = argumentIndex; i < argumentCount; i++)
{
if (!(arguments[i] is TSimpleArgumentSyntax))
{
return;
}
}
var argumentName = parameters[argumentIndex].Name;
context.RegisterRefactoring(
new MyCodeAction(
string.Format(FeaturesResources.Add_argument_name_0, argumentName),
c => AddNamedArgumentsAsync(root, document, argument, parameters, argumentIndex)));
}
private Task<Document> AddNamedArgumentsAsync(
SyntaxNode root,
Document document,
TSimpleArgumentSyntax firstArgument,
ImmutableArray<IParameterSymbol> parameters,
int index)
{
var argumentList = (TArgumentListSyntax)firstArgument.Parent;
var newArgumentList = GetOrSynthesizeNamedArguments(parameters, argumentList, index);
var newRoot = root.ReplaceNode(argumentList, newArgumentList);
return Task.FromResult(document.WithSyntaxRoot(newRoot));
}
private TArgumentListSyntax GetOrSynthesizeNamedArguments(
ImmutableArray<IParameterSymbol> parameters, TArgumentListSyntax argumentList, int index)
{
var arguments = GetArguments(argumentList);
var namedArguments = arguments
.Select((argument, i) => i >= index && argument is TSimpleArgumentSyntax s && IsPositionalArgument(s)
? WithName(s, parameters[i].Name).WithTriviaFrom(argument)
: argument);
return WithArguments(argumentList, namedArguments, arguments.GetSeparators());
}
protected abstract TArgumentListSyntax WithArguments(
TArgumentListSyntax argumentList, IEnumerable<TBaseArgumentSyntax> namedArguments, IEnumerable<SyntaxToken> separators);
protected abstract bool IsCloseParenOrComma(SyntaxToken token);
protected abstract bool IsLegalToAddNamedArguments(ImmutableArray<IParameterSymbol> parameters, int argumentCount);
protected abstract TSimpleArgumentSyntax WithName(TSimpleArgumentSyntax argument, string name);
protected abstract bool IsPositionalArgument(TSimpleArgumentSyntax argument);
protected abstract SeparatedSyntaxList<TBaseArgumentSyntax> GetArguments(TArgumentListSyntax argumentList);
protected abstract SyntaxNode GetReceiver(SyntaxNode argument);
}
private readonly IAnalyzer _argumentAnalyzer;
private readonly IAnalyzer _attributeArgumentAnalyzer;
protected AbstractUseNamedArgumentsCodeRefactoringProvider(
IAnalyzer argumentAnalyzer,
IAnalyzer attributeArgumentAnalyzer)
{
_argumentAnalyzer = argumentAnalyzer;
_attributeArgumentAnalyzer = attributeArgumentAnalyzer;
}
public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context)
{
var document = context.Document;
if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles)
{
return;
}
var cancellationToken = context.CancellationToken;
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
await _argumentAnalyzer.ComputeRefactoringsAsync(
context, root, cancellationToken).ConfigureAwait(false);
if (_attributeArgumentAnalyzer != null)
{
await _attributeArgumentAnalyzer.ComputeRefactoringsAsync(
context, root, cancellationToken).ConfigureAwait(false);
}
}
private class MyCodeAction : CodeAction.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument)
{
}
}
}
}
| |
using System;
using System.Linq;
using System.Threading;
using Microsoft.Deployment.WindowsInstaller;
using WixSharp.CommonTasks;
using WixSharp.UI.ManagedUI;
using System.Diagnostics;
using WixSharp.UI.Forms;
using System.Xml.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
namespace WixSharp
{
/// <summary>
/// Implements as standard dialog-based MSI embedded UI.
/// <para>
/// This class allows defining separate sequences of UI dialogs for 'install'
/// and 'modify' MSI executions. The dialog sequence can contain any mixture
/// of built-in standard dialogs and/or custom dialogs (Form inherited from <see cref="T:WixSharp.UI.Forms.ManagedForm"/>).
/// </para>
/// </summary>
/// <example>The following is an example of installing <c>MyLibrary.dll</c> assembly and registering it in GAC.
/// <code>
/// ...
/// project.ManagedUI = new ManagedUI();
/// project.ManagedUI.InstallDialogs.Add(Dialogs.Welcome)
/// .Add(Dialogs.Licence)
/// .Add(Dialogs.SetupType)
/// .Add(Dialogs.Features)
/// .Add(Dialogs.InstallDir)
/// .Add(Dialogs.Progress)
/// .Add(Dialogs.Exit);
///
/// project.ManagedUI.ModifyDialogs.Add(Dialogs.MaintenanceType)
/// .Add(Dialogs.Features)
/// .Add(Dialogs.Progress)
/// .Add(Dialogs.Exit);
///
/// </code>
/// </example>
public class ManagedUI : IManagedUI, IEmbeddedUI
{
/// <summary>
/// The default implementation of ManagedUI. It implements all major dialogs of a typical MSI UI.
/// </summary>
static public ManagedUI Default = new ManagedUI
{
InstallDialogs = new ManagedDialogs()
.Add<WelcomeDialog>()
.Add<LicenceDialog>()
.Add<SetupTypeDialog>()
.Add<FeaturesDialog>()
.Add<InstallDirDialog>()
.Add<ProgressDialog>()
.Add<ExitDialog>(),
ModifyDialogs = new ManagedDialogs()
.Add<MaintenanceTypeDialog>()
.Add<FeaturesDialog>()
.Add<ProgressDialog>()
.Add<ExitDialog>()
};
/// <summary>
/// The default implementation of ManagedUI with no UI dialogs.
/// </summary>
static public ManagedUI Empty = new ManagedUI();
/// <summary>
/// Initializes a new instance of the <see cref="ManagedUI"/> class.
/// </summary>
public ManagedUI()
{
InstallDialogs = new ManagedDialogs();
ModifyDialogs = new ManagedDialogs();
}
/// <summary>
/// This method is called (indirectly) by Wix# compiler just before building the MSI. It allows embedding UI specific resources (e.g. license file, properties)
/// into the MSI.
/// </summary>
/// <param name="project">The project.</param>
public void BeforeBuild(ManagedProject project)
{
var file = LocalizationFileFor(project);
ValidateUITextFile(file);
project.AddBinary(new Binary(new Id("WixSharp_UIText"), file));
project.AddBinary(new Binary(new Id("WixSharp_LicenceFile"), LicenceFileFor(project)));
project.AddBinary(new Binary(new Id("WixUI_Bmp_Dialog"), DialogBitmapFileFor(project)));
project.AddBinary(new Binary(new Id("WixUI_Bmp_Banner"), DialogBannerFileFor(project)));
}
/// <summary>
/// Validates the UI text file (localization file) for being compatible with ManagedUI.
/// </summary>
/// <param name="file">The file.</param>
/// <param name="throwOnError">if set to <c>true</c> [throw on error].</param>
/// <returns></returns>
public static bool ValidateUITextFile(string file, bool throwOnError = true)
{
try
{
var data = new ResourcesData();
data.InitFromWxl(System.IO.File.ReadAllBytes(file));
}
catch (Exception e)
{
//may need to do extra logging; not important for now
if (throwOnError)
throw new Exception("Localization file is incompatible with ManagedUI.", e);
else
return false;
}
return true;
}
/// <summary>
/// Gets or sets the id of the 'installdir' (destination folder) directory. It is the directory,
/// which is bound to the input UI elements of the Browse dialog (e.g. WiX BrowseDlg, Wix# InstallDirDialog).
/// </summary>
/// <value>
/// The install dir identifier.
/// </value>
public string InstallDirId { get; set; }
internal string LocalizationFileFor(Project project)
{
return UIExtensions.UserOrDefaultContentOf(project.LocalizationFile, project.SourceBaseDir, project.OutDir, project.Name + ".wxl", Resources.WixUI_en_us);
}
internal string LicenceFileFor(Project project)
{
return UIExtensions.UserOrDefaultContentOf(project.LicenceFile, project.SourceBaseDir, project.OutDir, project.Name + ".licence.rtf", Resources.WixSharp_LicenceFile);
}
internal string DialogBitmapFileFor(Project project)
{
return UIExtensions.UserOrDefaultContentOf(project.BackgroundImage, project.SourceBaseDir, project.OutDir, project.Name + ".dialog_bmp.png", Resources.WixUI_Bmp_Dialog);
}
internal string DialogBannerFileFor(Project project)
{
return UIExtensions.UserOrDefaultContentOf(project.BannerImage, project.SourceBaseDir, project.OutDir, project.Name + ".dialog_banner.png", Resources.WixUI_Bmp_Banner);
}
/// <summary>
/// Sequence of the dialogs to be displayed during the installation of the product.
/// </summary>
public ManagedDialogs InstallDialogs { get; set; }
/// <summary>
/// Sequence of the dialogs to be displayed during the customization of the installed product.
/// </summary>
public ManagedDialogs ModifyDialogs { get; set; }
/// <summary>
/// A window icon that appears in the left top corner of the UI shell window.
/// </summary>
public string Icon { get; set; }
ManualResetEvent uiExitEvent = new ManualResetEvent(false);
IUIContainer shell;
void ReadDialogs(Session session)
{
InstallDialogs.Clear()
.AddRange(ManagedProject.ReadDialogs(session.Property("WixSharp_InstallDialogs")));
ModifyDialogs.Clear()
.AddRange(ManagedProject.ReadDialogs(session.Property("WixSharp_ModifyDialogs")));
}
Mutex cancelRequest = null;
/// <summary>
/// Initializes the specified session.
/// </summary>
/// <param name="session">The session.</param>
/// <param name="resourcePath">The resource path.</param>
/// <param name="uiLevel">The UI level.</param>
/// <returns></returns>
/// <exception cref="Microsoft.Deployment.WindowsInstaller.InstallCanceledException"></exception>
public bool Initialize(Session session, string resourcePath, ref InstallUIOptions uiLevel)
{
//System.Diagnostics.Debugger.Launch();
if (session != null && (session.IsUninstalling() || uiLevel.IsBasic()))
return false; //use built-in MSI basic UI
string upgradeCode = session["UpgradeCode"];
using (cancelRequest)
{
try
{
ReadDialogs(session);
var startEvent = new ManualResetEvent(false);
var uiThread = new Thread(() =>
{
session["WIXSHARP_MANAGED_UI"] = System.Reflection.Assembly.GetExecutingAssembly().ToString();
shell = new UIShell(); //important to create the instance in the same thread that call ShowModal
shell.ShowModal(new MsiRuntime(session)
{
StartExecute = () => startEvent.Set(),
CancelExecute = () =>
{
// NOTE: IEmbeddedUI interface has no way to cancel the installation, which has been started
// (e.g. ProgressDialog is displayed). What is even worse is that UI can pass back to here
// a signal the user pressed 'Cancel' but nothing we can do with it. Install is already started
// and session object is now invalid.
// To solve this we use this work around - set a unique "cancel request mutex" form here
// and ManagedProjectActions.CancelRequestHandler built-in CA will pick the request and yield
// return code UserExit.
cancelRequest = new Mutex(true, "WIXSHARP_UI_CANCEL_REQUEST." + upgradeCode);
}
},
this);
uiExitEvent.Set();
});
uiThread.SetApartmentState(ApartmentState.STA);
uiThread.Start();
int waitResult = WaitHandle.WaitAny(new[] { startEvent, uiExitEvent });
if (waitResult == 1)
{
//UI exited without starting the install. Cancel the installation.
throw new InstallCanceledException();
}
else
{
// Start the installation with a silenced internal UI.
// This "embedded external UI" will handle message types except for source resolution.
uiLevel = InstallUIOptions.NoChange | InstallUIOptions.SourceResolutionOnly;
shell.OnExecuteStarted();
return true;
}
}
catch (Exception e)
{
session.Log("Cannot attach ManagedUI: " + e);
throw;
}
}
}
/// <summary>
/// Processes information and progress messages sent to the user interface.
/// </summary>
/// <param name="messageType">Message type.</param>
/// <param name="messageRecord">Record that contains message data.</param>
/// <param name="buttons">Message buttons.</param>
/// <param name="icon">Message box icon.</param>
/// <param name="defaultButton">Message box default button.</param>
/// <returns>
/// Result of processing the message.
/// </returns>
/// <remarks>
/// <p>
/// Win32 MSI API:
/// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/embeddeduihandler.asp">EmbeddedUIHandler</a></p>
/// </remarks>
public MessageResult ProcessMessage(InstallMessage messageType, Record messageRecord, MessageButtons buttons, MessageIcon icon, MessageDefaultButton defaultButton)
{
return shell.ProcessMessage(messageType, messageRecord, buttons, icon, defaultButton);
}
/// <summary>
/// Shuts down the embedded UI at the end of the installation.
/// </summary>
/// <remarks>
/// If the installation was canceled during initialization, this method will not be called.
/// If the installation was canceled or failed at any later point, this method will be called at the end.
/// <p>
/// Win32 MSI API:
/// <a href="http://msdn.microsoft.com/library/en-us/msi/setup/shutdownembeddedui.asp">ShutdownEmbeddedUI</a></p>
/// </remarks>
public void Shutdown()
{
shell.OnExecuteComplete();
uiExitEvent.WaitOne();
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Globalization;
namespace Ripper
{
partial class Login
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region 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(Login));
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.GuestLogin = new System.Windows.Forms.CheckBox();
this.ForumList = new System.Windows.Forms.ComboBox();
this.label4 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.ForumUrl = new System.Windows.Forms.TextBox();
this.label5 = new System.Windows.Forms.Label();
this.LanuageSelector = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.LoginButton = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.PasswordField = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.UserNameField = new System.Windows.Forms.TextBox();
this.timer1 = new System.Timers.Timer();
this.groupBox1.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.timer1)).BeginInit();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.GuestLogin);
this.groupBox1.Controls.Add(this.ForumList);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.label6);
this.groupBox1.Controls.Add(this.ForumUrl);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.LanuageSelector);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.LoginButton);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.PasswordField);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Controls.Add(this.UserNameField);
this.groupBox1.Location = new System.Drawing.Point(8, 16);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(376, 304);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Provide Login Credentials for the Forums";
this.groupBox1.UseCompatibleTextRendering = true;
//
// GuestLogin
//
this.GuestLogin.AutoSize = true;
this.GuestLogin.Location = new System.Drawing.Point(102, 78);
this.GuestLogin.Name = "GuestLogin";
this.GuestLogin.Size = new System.Drawing.Size(92, 17);
this.GuestLogin.TabIndex = 17;
this.GuestLogin.Text = "Guest Access";
this.GuestLogin.UseVisualStyleBackColor = true;
this.GuestLogin.CheckedChanged += new System.EventHandler(this.GuestLogin_CheckedChanged);
//
// ForumList
//
this.ForumList.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.ForumList.IntegralHeight = false;
this.ForumList.ItemHeight = 13;
this.ForumList.Items.AddRange(new object[] {
"<Select a Forum>",
"ViperGirls Forums",
"Sexy and Funny Forums",
"Scanlover Forums",
"Big Naturals Only",
"The phun.org forum",
"<Other - Enter URL bellow>"});
this.ForumList.Location = new System.Drawing.Point(102, 109);
this.ForumList.Name = "ForumList";
this.ForumList.Size = new System.Drawing.Size(246, 21);
this.ForumList.TabIndex = 2;
this.ForumList.SelectedIndexChanged += new System.EventHandler(this.ForumSelectedIndexChanged);
//
// label4
//
this.label4.AutoSize = true;
this.label4.Location = new System.Drawing.Point(6, 143);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(64, 13);
this.label4.TabIndex = 16;
this.label4.Text = "Forum URL:";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Location = new System.Drawing.Point(6, 112);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(72, 13);
this.label6.TabIndex = 15;
this.label6.Text = "Select Forum:";
//
// ForumUrl
//
this.ForumUrl.Location = new System.Drawing.Point(102, 144);
this.ForumUrl.Name = "ForumUrl";
this.ForumUrl.Size = new System.Drawing.Size(246, 20);
this.ForumUrl.TabIndex = 3;
//
// label5
//
this.label5.Location = new System.Drawing.Point(114, 273);
this.label5.MaximumSize = new System.Drawing.Size(0, 13);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(120, 13);
this.label5.TabIndex = 13;
this.label5.Text = "label5";
this.label5.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.label5.UseCompatibleTextRendering = true;
//
// LanuageSelector
//
this.LanuageSelector.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.LanuageSelector.Items.AddRange(new object[] {
"German",
"French",
"English"});
this.LanuageSelector.Location = new System.Drawing.Point(240, 270);
this.LanuageSelector.MaximumSize = new System.Drawing.Size(121, 0);
this.LanuageSelector.Name = "LanuageSelector";
this.LanuageSelector.Size = new System.Drawing.Size(121, 21);
this.LanuageSelector.TabIndex = 6;
this.LanuageSelector.SelectedIndexChanged += new System.EventHandler(this.LanuageSelectorIndexChanged);
//
// label3
//
this.label3.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.ForeColor = System.Drawing.Color.Red;
this.label3.Location = new System.Drawing.Point(9, 213);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(339, 24);
this.label3.TabIndex = 5;
this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// LoginButton
//
this.LoginButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.LoginButton.Image = ((System.Drawing.Image)(resources.GetObject("LoginButton.Image")));
this.LoginButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.LoginButton.Location = new System.Drawing.Point(102, 170);
this.LoginButton.Name = "LoginButton";
this.LoginButton.Size = new System.Drawing.Size(246, 40);
this.LoginButton.TabIndex = 5;
this.LoginButton.Text = "Login";
this.LoginButton.UseCompatibleTextRendering = true;
this.LoginButton.Click += new System.EventHandler(this.LoginBtnClick);
//
// label2
//
this.label2.Location = new System.Drawing.Point(6, 54);
this.label2.MaximumSize = new System.Drawing.Size(87, 16);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(87, 16);
this.label2.TabIndex = 3;
this.label2.Text = "Password :";
this.label2.UseCompatibleTextRendering = true;
//
// PasswordField
//
this.PasswordField.Location = new System.Drawing.Point(102, 51);
this.PasswordField.MaximumSize = new System.Drawing.Size(246, 20);
this.PasswordField.Name = "PasswordField";
this.PasswordField.PasswordChar = '*';
this.PasswordField.Size = new System.Drawing.Size(246, 20);
this.PasswordField.TabIndex = 1;
//
// label1
//
this.label1.Location = new System.Drawing.Point(6, 22);
this.label1.MaximumSize = new System.Drawing.Size(87, 16);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(87, 16);
this.label1.TabIndex = 1;
this.label1.Text = "User Name :";
this.label1.UseCompatibleTextRendering = true;
//
// UserNameField
//
this.UserNameField.Location = new System.Drawing.Point(102, 19);
this.UserNameField.MaximumSize = new System.Drawing.Size(246, 20);
this.UserNameField.Name = "UserNameField";
this.UserNameField.Size = new System.Drawing.Size(246, 20);
this.UserNameField.TabIndex = 0;
//
// timer1
//
this.timer1.Interval = 400D;
this.timer1.SynchronizingObject = this;
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.Timer1Elapsed);
//
// Login
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(394, 332);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Login";
this.Text = "Login";
this.Load += new System.EventHandler(this.LoginLoad);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.timer1)).EndInit();
this.ResumeLayout(false);
}
#endregion
private GroupBox groupBox1;
private TextBox UserNameField;
private Label label1;
private Label label2;
private TextBox PasswordField;
private Button LoginButton;
private Label label3;
private System.Timers.Timer timer1;
private ComboBox LanuageSelector;
private Label label5;
private Label label6;
private TextBox ForumUrl;
private Label label4;
private ComboBox ForumList;
private CheckBox GuestLogin;
}
}
| |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
#pragma warning disable 1634, 1691
namespace System.ServiceModel.Web
{
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net;
using System.Runtime.Serialization.Json;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Syndication;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using System.ServiceModel.Dispatcher;
public class WebOperationContext : IExtension<OperationContext>
{
internal static readonly string DefaultTextMediaType = "text/plain";
internal static readonly string DefaultJsonMediaType = JsonGlobals.applicationJsonMediaType;
internal static readonly string DefaultXmlMediaType = "application/xml";
internal static readonly string DefaultAtomMediaType = "application/atom+xml";
internal static readonly string DefaultStreamMediaType = WebHttpBehavior.defaultStreamContentType;
OperationContext operationContext;
public WebOperationContext(OperationContext operationContext)
{
if (operationContext == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("operationContext");
}
this.operationContext = operationContext;
#pragma warning disable 56506 // [....], operationContext.Extensions is never null
if (operationContext.Extensions.Find<WebOperationContext>() == null)
{
operationContext.Extensions.Add(this);
}
#pragma warning enable 56506
}
public static WebOperationContext Current
{
get
{
if (OperationContext.Current == null)
{
return null;
}
WebOperationContext existing = OperationContext.Current.Extensions.Find<WebOperationContext>();
if (existing != null)
{
return existing;
}
return new WebOperationContext(OperationContext.Current);
}
}
public IncomingWebRequestContext IncomingRequest
{
get { return new IncomingWebRequestContext(this.operationContext); }
}
public IncomingWebResponseContext IncomingResponse
{
get { return new IncomingWebResponseContext(this.operationContext); }
}
public OutgoingWebRequestContext OutgoingRequest
{
get { return new OutgoingWebRequestContext(this.operationContext); }
}
public OutgoingWebResponseContext OutgoingResponse
{
get { return new OutgoingWebResponseContext(this.operationContext); }
}
public void Attach(OperationContext owner)
{
}
public void Detach(OperationContext owner)
{
}
public Message CreateJsonResponse<T>(T instance)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
return CreateJsonResponse<T>(instance, serializer);
}
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "CreateJsonMessage requires the DataContractJsonSerializer. Allowing the base type XmlObjectSerializer would let deveopers supply a non-Json Serializer.")]
public Message CreateJsonResponse<T>(T instance, DataContractJsonSerializer serializer)
{
if (serializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
}
Message message = Message.CreateMessage(MessageVersion.None, (string)null, instance, serializer);
message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.JsonProperty);
AddContentType(WebOperationContext.DefaultJsonMediaType, this.OutgoingResponse.BindingWriteEncoding);
return message;
}
public Message CreateXmlResponse<T>(T instance)
{
System.Runtime.Serialization.DataContractSerializer serializer = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
return CreateXmlResponse(instance, serializer);
}
public Message CreateXmlResponse<T>(T instance, System.Runtime.Serialization.XmlObjectSerializer serializer)
{
if (serializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
}
Message message = Message.CreateMessage(MessageVersion.None, (string)null, instance, serializer);
message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.XmlProperty);
AddContentType(WebOperationContext.DefaultXmlMediaType, this.OutgoingResponse.BindingWriteEncoding);
return message;
}
public Message CreateXmlResponse<T>(T instance, XmlSerializer serializer)
{
if (serializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
}
Message message = Message.CreateMessage(MessageVersion.None, (string)null, new XmlSerializerBodyWriter(instance, serializer));
message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.XmlProperty);
AddContentType(WebOperationContext.DefaultXmlMediaType, this.OutgoingResponse.BindingWriteEncoding);
return message;
}
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Other XNode derived types such as XAttribute don't make sense in this context, so we are not using the XNode base type.")]
public Message CreateXmlResponse(XDocument document)
{
if (document == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("document");
}
Message message;
if (document.FirstNode == null)
{
message = Message.CreateMessage(MessageVersion.None, (string)null);
}
else
{
message = Message.CreateMessage(MessageVersion.None, (string)null, document.CreateReader());
}
message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.XmlProperty);
AddContentType(WebOperationContext.DefaultXmlMediaType, this.OutgoingResponse.BindingWriteEncoding);
return message;
}
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Other XNode derived types such as XAttribute don't make sense in this context, so we are not using the XNode base type.")]
public Message CreateXmlResponse(XElement element)
{
if (element == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("element");
}
Message message = Message.CreateMessage(MessageVersion.None, (string)null, element.CreateReader());
message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.XmlProperty);
AddContentType(WebOperationContext.DefaultXmlMediaType, this.OutgoingResponse.BindingWriteEncoding);
return message;
}
public Message CreateAtom10Response(SyndicationItem item)
{
if (item == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("item");
}
Message message = Message.CreateMessage(MessageVersion.None, (string)null, item.GetAtom10Formatter());
message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.XmlProperty);
AddContentType(WebOperationContext.DefaultAtomMediaType, this.OutgoingResponse.BindingWriteEncoding);
return message;
}
public Message CreateAtom10Response(SyndicationFeed feed)
{
if (feed == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("feed");
}
Message message = Message.CreateMessage(MessageVersion.None, (string)null, feed.GetAtom10Formatter());
message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.XmlProperty);
AddContentType(WebOperationContext.DefaultAtomMediaType, this.OutgoingResponse.BindingWriteEncoding);
return message;
}
public Message CreateAtom10Response(ServiceDocument document)
{
if (document == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("document");
}
Message message = Message.CreateMessage(MessageVersion.None, (string)null, document.GetFormatter());
message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.XmlProperty);
AddContentType(WebOperationContext.DefaultAtomMediaType, this.OutgoingResponse.BindingWriteEncoding);
return message;
}
public Message CreateTextResponse(string text)
{
return CreateTextResponse(text, WebOperationContext.DefaultTextMediaType, Encoding.UTF8);
}
public Message CreateTextResponse(string text, string contentType)
{
return CreateTextResponse(text, contentType, Encoding.UTF8);
}
public Message CreateTextResponse(string text, string contentType, Encoding encoding)
{
if (text == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("text");
}
if (contentType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contentType");
}
if (encoding == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoding");
}
Message message = new HttpStreamMessage(StreamBodyWriter.CreateStreamBodyWriter((stream) =>
{
byte[] preamble = encoding.GetPreamble();
if (preamble.Length > 0)
{
stream.Write(preamble, 0, preamble.Length);
}
byte[] bytes = encoding.GetBytes(text);
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
}));
message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.RawProperty);
AddContentType(contentType, null);
return message;
}
public Message CreateTextResponse(Action<TextWriter> textWriter, string contentType)
{
Encoding encoding = this.OutgoingResponse.BindingWriteEncoding;
if (encoding == null)
{
encoding = Encoding.UTF8;
}
return CreateTextResponse(textWriter, contentType, encoding);
}
public Message CreateTextResponse(Action<TextWriter> textWriter, string contentType, Encoding encoding)
{
if (textWriter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("textWriter");
}
if (contentType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contentType");
}
if (encoding == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("encoding");
}
Message message = new HttpStreamMessage(StreamBodyWriter.CreateStreamBodyWriter((stream) =>
{
using (TextWriter writer = new StreamWriter(stream, encoding))
{
textWriter(writer);
}
}));
message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.RawProperty);
AddContentType(contentType, null);
return message;
}
public Message CreateStreamResponse(Stream stream, string contentType)
{
if (stream == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("stream");
}
if (contentType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contentType");
}
Message message = ByteStreamMessage.CreateMessage(stream);
message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.RawProperty);
AddContentType(contentType, null);
return message;
}
[SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Using the StreamBodyWriter type instead of the BodyWriter type for discoverability. The StreamBodyWriter provides a helpful overload of the OnWriteBodyContents method that takes a Stream")]
public Message CreateStreamResponse(StreamBodyWriter bodyWriter, string contentType)
{
if (bodyWriter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("bodyWriter");
}
if (contentType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contentType");
}
Message message = new HttpStreamMessage(bodyWriter);
message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.RawProperty);
AddContentType(contentType, null);
return message;
}
public Message CreateStreamResponse(Action<Stream> streamWriter, string contentType)
{
if (streamWriter == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("streamWriter");
}
if (contentType == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contentType");
}
Message message = new HttpStreamMessage(StreamBodyWriter.CreateStreamBodyWriter(streamWriter));
message.Properties.Add(WebBodyFormatMessageProperty.Name, WebBodyFormatMessageProperty.RawProperty);
AddContentType(contentType, null);
return message;
}
public UriTemplate GetUriTemplate(string operationName)
{
if (String.IsNullOrEmpty(operationName))
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("operationName");
}
WebHttpDispatchOperationSelector selector = OperationContext.Current.EndpointDispatcher.DispatchRuntime.OperationSelector as WebHttpDispatchOperationSelector;
if (selector == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperWarning(new InvalidOperationException(SR2.GetString(SR2.OperationSelectorNotWebSelector, typeof(WebHttpDispatchOperationSelector))));
}
return selector.GetUriTemplate(operationName);
}
void AddContentType(string contentType, Encoding encoding)
{
if (string.IsNullOrEmpty(this.OutgoingResponse.ContentType))
{
if (encoding != null)
{
contentType = WebMessageEncoderFactory.GetContentType(contentType, encoding);
}
this.OutgoingResponse.ContentType = contentType;
}
}
class XmlSerializerBodyWriter : BodyWriter
{
object instance;
XmlSerializer serializer;
public XmlSerializerBodyWriter(object instance, XmlSerializer serializer)
: base(false)
{
if (instance == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("instance");
}
if (serializer == null)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
}
this.instance = instance;
this.serializer = serializer;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
serializer.Serialize(writer, instance);
}
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.OsConfig.V1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedOsConfigServiceClientSnippets
{
/// <summary>Snippet for ExecutePatchJob</summary>
public void ExecutePatchJobRequestObject()
{
// Snippet: ExecutePatchJob(ExecutePatchJobRequest, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
ExecutePatchJobRequest request = new ExecutePatchJobRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
Description = "",
PatchConfig = new PatchConfig(),
Duration = new Duration(),
DryRun = false,
InstanceFilter = new PatchInstanceFilter(),
DisplayName = "",
Rollout = new PatchRollout(),
};
// Make the request
PatchJob response = osConfigServiceClient.ExecutePatchJob(request);
// End snippet
}
/// <summary>Snippet for ExecutePatchJobAsync</summary>
public async Task ExecutePatchJobRequestObjectAsync()
{
// Snippet: ExecutePatchJobAsync(ExecutePatchJobRequest, CallSettings)
// Additional: ExecutePatchJobAsync(ExecutePatchJobRequest, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
ExecutePatchJobRequest request = new ExecutePatchJobRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
Description = "",
PatchConfig = new PatchConfig(),
Duration = new Duration(),
DryRun = false,
InstanceFilter = new PatchInstanceFilter(),
DisplayName = "",
Rollout = new PatchRollout(),
};
// Make the request
PatchJob response = await osConfigServiceClient.ExecutePatchJobAsync(request);
// End snippet
}
/// <summary>Snippet for GetPatchJob</summary>
public void GetPatchJobRequestObject()
{
// Snippet: GetPatchJob(GetPatchJobRequest, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
GetPatchJobRequest request = new GetPatchJobRequest
{
PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"),
};
// Make the request
PatchJob response = osConfigServiceClient.GetPatchJob(request);
// End snippet
}
/// <summary>Snippet for GetPatchJobAsync</summary>
public async Task GetPatchJobRequestObjectAsync()
{
// Snippet: GetPatchJobAsync(GetPatchJobRequest, CallSettings)
// Additional: GetPatchJobAsync(GetPatchJobRequest, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
GetPatchJobRequest request = new GetPatchJobRequest
{
PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"),
};
// Make the request
PatchJob response = await osConfigServiceClient.GetPatchJobAsync(request);
// End snippet
}
/// <summary>Snippet for GetPatchJob</summary>
public void GetPatchJob()
{
// Snippet: GetPatchJob(string, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/patchJobs/[PATCH_JOB]";
// Make the request
PatchJob response = osConfigServiceClient.GetPatchJob(name);
// End snippet
}
/// <summary>Snippet for GetPatchJobAsync</summary>
public async Task GetPatchJobAsync()
{
// Snippet: GetPatchJobAsync(string, CallSettings)
// Additional: GetPatchJobAsync(string, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/patchJobs/[PATCH_JOB]";
// Make the request
PatchJob response = await osConfigServiceClient.GetPatchJobAsync(name);
// End snippet
}
/// <summary>Snippet for GetPatchJob</summary>
public void GetPatchJobResourceNames()
{
// Snippet: GetPatchJob(PatchJobName, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
PatchJobName name = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]");
// Make the request
PatchJob response = osConfigServiceClient.GetPatchJob(name);
// End snippet
}
/// <summary>Snippet for GetPatchJobAsync</summary>
public async Task GetPatchJobResourceNamesAsync()
{
// Snippet: GetPatchJobAsync(PatchJobName, CallSettings)
// Additional: GetPatchJobAsync(PatchJobName, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
PatchJobName name = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]");
// Make the request
PatchJob response = await osConfigServiceClient.GetPatchJobAsync(name);
// End snippet
}
/// <summary>Snippet for CancelPatchJob</summary>
public void CancelPatchJobRequestObject()
{
// Snippet: CancelPatchJob(CancelPatchJobRequest, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
CancelPatchJobRequest request = new CancelPatchJobRequest
{
PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"),
};
// Make the request
PatchJob response = osConfigServiceClient.CancelPatchJob(request);
// End snippet
}
/// <summary>Snippet for CancelPatchJobAsync</summary>
public async Task CancelPatchJobRequestObjectAsync()
{
// Snippet: CancelPatchJobAsync(CancelPatchJobRequest, CallSettings)
// Additional: CancelPatchJobAsync(CancelPatchJobRequest, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
CancelPatchJobRequest request = new CancelPatchJobRequest
{
PatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"),
};
// Make the request
PatchJob response = await osConfigServiceClient.CancelPatchJobAsync(request);
// End snippet
}
/// <summary>Snippet for ListPatchJobs</summary>
public void ListPatchJobsRequestObject()
{
// Snippet: ListPatchJobs(ListPatchJobsRequest, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
ListPatchJobsRequest request = new ListPatchJobsRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
Filter = "",
};
// Make the request
PagedEnumerable<ListPatchJobsResponse, PatchJob> response = osConfigServiceClient.ListPatchJobs(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (PatchJob item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPatchJobsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchJob item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchJob> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchJob item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchJobsAsync</summary>
public async Task ListPatchJobsRequestObjectAsync()
{
// Snippet: ListPatchJobsAsync(ListPatchJobsRequest, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
ListPatchJobsRequest request = new ListPatchJobsRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListPatchJobsResponse, PatchJob> response = osConfigServiceClient.ListPatchJobsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PatchJob item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPatchJobsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchJob item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchJob> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchJob item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchJobs</summary>
public void ListPatchJobs()
{
// Snippet: ListPatchJobs(string, string, int?, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
// Make the request
PagedEnumerable<ListPatchJobsResponse, PatchJob> response = osConfigServiceClient.ListPatchJobs(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (PatchJob item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPatchJobsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchJob item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchJob> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchJob item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchJobsAsync</summary>
public async Task ListPatchJobsAsync()
{
// Snippet: ListPatchJobsAsync(string, string, int?, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
// Make the request
PagedAsyncEnumerable<ListPatchJobsResponse, PatchJob> response = osConfigServiceClient.ListPatchJobsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PatchJob item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPatchJobsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchJob item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchJob> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchJob item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchJobs</summary>
public void ListPatchJobsResourceNames()
{
// Snippet: ListPatchJobs(ProjectName, string, int?, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
// Make the request
PagedEnumerable<ListPatchJobsResponse, PatchJob> response = osConfigServiceClient.ListPatchJobs(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (PatchJob item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPatchJobsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchJob item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchJob> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchJob item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchJobsAsync</summary>
public async Task ListPatchJobsResourceNamesAsync()
{
// Snippet: ListPatchJobsAsync(ProjectName, string, int?, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListPatchJobsResponse, PatchJob> response = osConfigServiceClient.ListPatchJobsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PatchJob item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPatchJobsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchJob item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchJob> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchJob item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchJobInstanceDetails</summary>
public void ListPatchJobInstanceDetailsRequestObject()
{
// Snippet: ListPatchJobInstanceDetails(ListPatchJobInstanceDetailsRequest, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
ListPatchJobInstanceDetailsRequest request = new ListPatchJobInstanceDetailsRequest
{
ParentAsPatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"),
Filter = "",
};
// Make the request
PagedEnumerable<ListPatchJobInstanceDetailsResponse, PatchJobInstanceDetails> response = osConfigServiceClient.ListPatchJobInstanceDetails(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (PatchJobInstanceDetails item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPatchJobInstanceDetailsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchJobInstanceDetails item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchJobInstanceDetails> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchJobInstanceDetails item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchJobInstanceDetailsAsync</summary>
public async Task ListPatchJobInstanceDetailsRequestObjectAsync()
{
// Snippet: ListPatchJobInstanceDetailsAsync(ListPatchJobInstanceDetailsRequest, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
ListPatchJobInstanceDetailsRequest request = new ListPatchJobInstanceDetailsRequest
{
ParentAsPatchJobName = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]"),
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListPatchJobInstanceDetailsResponse, PatchJobInstanceDetails> response = osConfigServiceClient.ListPatchJobInstanceDetailsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PatchJobInstanceDetails item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPatchJobInstanceDetailsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchJobInstanceDetails item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchJobInstanceDetails> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchJobInstanceDetails item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchJobInstanceDetails</summary>
public void ListPatchJobInstanceDetails()
{
// Snippet: ListPatchJobInstanceDetails(string, string, int?, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/patchJobs/[PATCH_JOB]";
// Make the request
PagedEnumerable<ListPatchJobInstanceDetailsResponse, PatchJobInstanceDetails> response = osConfigServiceClient.ListPatchJobInstanceDetails(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (PatchJobInstanceDetails item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPatchJobInstanceDetailsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchJobInstanceDetails item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchJobInstanceDetails> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchJobInstanceDetails item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchJobInstanceDetailsAsync</summary>
public async Task ListPatchJobInstanceDetailsAsync()
{
// Snippet: ListPatchJobInstanceDetailsAsync(string, string, int?, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]/patchJobs/[PATCH_JOB]";
// Make the request
PagedAsyncEnumerable<ListPatchJobInstanceDetailsResponse, PatchJobInstanceDetails> response = osConfigServiceClient.ListPatchJobInstanceDetailsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PatchJobInstanceDetails item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPatchJobInstanceDetailsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchJobInstanceDetails item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchJobInstanceDetails> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchJobInstanceDetails item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchJobInstanceDetails</summary>
public void ListPatchJobInstanceDetailsResourceNames()
{
// Snippet: ListPatchJobInstanceDetails(PatchJobName, string, int?, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
PatchJobName parent = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]");
// Make the request
PagedEnumerable<ListPatchJobInstanceDetailsResponse, PatchJobInstanceDetails> response = osConfigServiceClient.ListPatchJobInstanceDetails(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (PatchJobInstanceDetails item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPatchJobInstanceDetailsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchJobInstanceDetails item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchJobInstanceDetails> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchJobInstanceDetails item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchJobInstanceDetailsAsync</summary>
public async Task ListPatchJobInstanceDetailsResourceNamesAsync()
{
// Snippet: ListPatchJobInstanceDetailsAsync(PatchJobName, string, int?, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
PatchJobName parent = PatchJobName.FromProjectPatchJob("[PROJECT]", "[PATCH_JOB]");
// Make the request
PagedAsyncEnumerable<ListPatchJobInstanceDetailsResponse, PatchJobInstanceDetails> response = osConfigServiceClient.ListPatchJobInstanceDetailsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PatchJobInstanceDetails item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPatchJobInstanceDetailsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchJobInstanceDetails item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchJobInstanceDetails> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchJobInstanceDetails item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for CreatePatchDeployment</summary>
public void CreatePatchDeploymentRequestObject()
{
// Snippet: CreatePatchDeployment(CreatePatchDeploymentRequest, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
CreatePatchDeploymentRequest request = new CreatePatchDeploymentRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
PatchDeploymentId = "",
PatchDeployment = new PatchDeployment(),
};
// Make the request
PatchDeployment response = osConfigServiceClient.CreatePatchDeployment(request);
// End snippet
}
/// <summary>Snippet for CreatePatchDeploymentAsync</summary>
public async Task CreatePatchDeploymentRequestObjectAsync()
{
// Snippet: CreatePatchDeploymentAsync(CreatePatchDeploymentRequest, CallSettings)
// Additional: CreatePatchDeploymentAsync(CreatePatchDeploymentRequest, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
CreatePatchDeploymentRequest request = new CreatePatchDeploymentRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
PatchDeploymentId = "",
PatchDeployment = new PatchDeployment(),
};
// Make the request
PatchDeployment response = await osConfigServiceClient.CreatePatchDeploymentAsync(request);
// End snippet
}
/// <summary>Snippet for CreatePatchDeployment</summary>
public void CreatePatchDeployment()
{
// Snippet: CreatePatchDeployment(string, PatchDeployment, string, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
PatchDeployment patchDeployment = new PatchDeployment();
string patchDeploymentId = "";
// Make the request
PatchDeployment response = osConfigServiceClient.CreatePatchDeployment(parent, patchDeployment, patchDeploymentId);
// End snippet
}
/// <summary>Snippet for CreatePatchDeploymentAsync</summary>
public async Task CreatePatchDeploymentAsync()
{
// Snippet: CreatePatchDeploymentAsync(string, PatchDeployment, string, CallSettings)
// Additional: CreatePatchDeploymentAsync(string, PatchDeployment, string, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
PatchDeployment patchDeployment = new PatchDeployment();
string patchDeploymentId = "";
// Make the request
PatchDeployment response = await osConfigServiceClient.CreatePatchDeploymentAsync(parent, patchDeployment, patchDeploymentId);
// End snippet
}
/// <summary>Snippet for CreatePatchDeployment</summary>
public void CreatePatchDeploymentResourceNames()
{
// Snippet: CreatePatchDeployment(ProjectName, PatchDeployment, string, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
PatchDeployment patchDeployment = new PatchDeployment();
string patchDeploymentId = "";
// Make the request
PatchDeployment response = osConfigServiceClient.CreatePatchDeployment(parent, patchDeployment, patchDeploymentId);
// End snippet
}
/// <summary>Snippet for CreatePatchDeploymentAsync</summary>
public async Task CreatePatchDeploymentResourceNamesAsync()
{
// Snippet: CreatePatchDeploymentAsync(ProjectName, PatchDeployment, string, CallSettings)
// Additional: CreatePatchDeploymentAsync(ProjectName, PatchDeployment, string, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
PatchDeployment patchDeployment = new PatchDeployment();
string patchDeploymentId = "";
// Make the request
PatchDeployment response = await osConfigServiceClient.CreatePatchDeploymentAsync(parent, patchDeployment, patchDeploymentId);
// End snippet
}
/// <summary>Snippet for GetPatchDeployment</summary>
public void GetPatchDeploymentRequestObject()
{
// Snippet: GetPatchDeployment(GetPatchDeploymentRequest, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
GetPatchDeploymentRequest request = new GetPatchDeploymentRequest
{
PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"),
};
// Make the request
PatchDeployment response = osConfigServiceClient.GetPatchDeployment(request);
// End snippet
}
/// <summary>Snippet for GetPatchDeploymentAsync</summary>
public async Task GetPatchDeploymentRequestObjectAsync()
{
// Snippet: GetPatchDeploymentAsync(GetPatchDeploymentRequest, CallSettings)
// Additional: GetPatchDeploymentAsync(GetPatchDeploymentRequest, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
GetPatchDeploymentRequest request = new GetPatchDeploymentRequest
{
PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"),
};
// Make the request
PatchDeployment response = await osConfigServiceClient.GetPatchDeploymentAsync(request);
// End snippet
}
/// <summary>Snippet for GetPatchDeployment</summary>
public void GetPatchDeployment()
{
// Snippet: GetPatchDeployment(string, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/patchDeployments/[PATCH_DEPLOYMENT]";
// Make the request
PatchDeployment response = osConfigServiceClient.GetPatchDeployment(name);
// End snippet
}
/// <summary>Snippet for GetPatchDeploymentAsync</summary>
public async Task GetPatchDeploymentAsync()
{
// Snippet: GetPatchDeploymentAsync(string, CallSettings)
// Additional: GetPatchDeploymentAsync(string, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/patchDeployments/[PATCH_DEPLOYMENT]";
// Make the request
PatchDeployment response = await osConfigServiceClient.GetPatchDeploymentAsync(name);
// End snippet
}
/// <summary>Snippet for GetPatchDeployment</summary>
public void GetPatchDeploymentResourceNames()
{
// Snippet: GetPatchDeployment(PatchDeploymentName, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
PatchDeploymentName name = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]");
// Make the request
PatchDeployment response = osConfigServiceClient.GetPatchDeployment(name);
// End snippet
}
/// <summary>Snippet for GetPatchDeploymentAsync</summary>
public async Task GetPatchDeploymentResourceNamesAsync()
{
// Snippet: GetPatchDeploymentAsync(PatchDeploymentName, CallSettings)
// Additional: GetPatchDeploymentAsync(PatchDeploymentName, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
PatchDeploymentName name = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]");
// Make the request
PatchDeployment response = await osConfigServiceClient.GetPatchDeploymentAsync(name);
// End snippet
}
/// <summary>Snippet for ListPatchDeployments</summary>
public void ListPatchDeploymentsRequestObject()
{
// Snippet: ListPatchDeployments(ListPatchDeploymentsRequest, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
ListPatchDeploymentsRequest request = new ListPatchDeploymentsRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
};
// Make the request
PagedEnumerable<ListPatchDeploymentsResponse, PatchDeployment> response = osConfigServiceClient.ListPatchDeployments(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (PatchDeployment item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPatchDeploymentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchDeployment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchDeployment> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchDeployment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchDeploymentsAsync</summary>
public async Task ListPatchDeploymentsRequestObjectAsync()
{
// Snippet: ListPatchDeploymentsAsync(ListPatchDeploymentsRequest, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
ListPatchDeploymentsRequest request = new ListPatchDeploymentsRequest
{
ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
};
// Make the request
PagedAsyncEnumerable<ListPatchDeploymentsResponse, PatchDeployment> response = osConfigServiceClient.ListPatchDeploymentsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PatchDeployment item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPatchDeploymentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchDeployment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchDeployment> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchDeployment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchDeployments</summary>
public void ListPatchDeployments()
{
// Snippet: ListPatchDeployments(string, string, int?, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
// Make the request
PagedEnumerable<ListPatchDeploymentsResponse, PatchDeployment> response = osConfigServiceClient.ListPatchDeployments(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (PatchDeployment item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPatchDeploymentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchDeployment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchDeployment> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchDeployment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchDeploymentsAsync</summary>
public async Task ListPatchDeploymentsAsync()
{
// Snippet: ListPatchDeploymentsAsync(string, string, int?, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "projects/[PROJECT]";
// Make the request
PagedAsyncEnumerable<ListPatchDeploymentsResponse, PatchDeployment> response = osConfigServiceClient.ListPatchDeploymentsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PatchDeployment item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPatchDeploymentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchDeployment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchDeployment> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchDeployment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchDeployments</summary>
public void ListPatchDeploymentsResourceNames()
{
// Snippet: ListPatchDeployments(ProjectName, string, int?, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
// Make the request
PagedEnumerable<ListPatchDeploymentsResponse, PatchDeployment> response = osConfigServiceClient.ListPatchDeployments(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (PatchDeployment item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListPatchDeploymentsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchDeployment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchDeployment> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchDeployment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListPatchDeploymentsAsync</summary>
public async Task ListPatchDeploymentsResourceNamesAsync()
{
// Snippet: ListPatchDeploymentsAsync(ProjectName, string, int?, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
// Make the request
PagedAsyncEnumerable<ListPatchDeploymentsResponse, PatchDeployment> response = osConfigServiceClient.ListPatchDeploymentsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((PatchDeployment item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListPatchDeploymentsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (PatchDeployment item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<PatchDeployment> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (PatchDeployment item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for DeletePatchDeployment</summary>
public void DeletePatchDeploymentRequestObject()
{
// Snippet: DeletePatchDeployment(DeletePatchDeploymentRequest, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
DeletePatchDeploymentRequest request = new DeletePatchDeploymentRequest
{
PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"),
};
// Make the request
osConfigServiceClient.DeletePatchDeployment(request);
// End snippet
}
/// <summary>Snippet for DeletePatchDeploymentAsync</summary>
public async Task DeletePatchDeploymentRequestObjectAsync()
{
// Snippet: DeletePatchDeploymentAsync(DeletePatchDeploymentRequest, CallSettings)
// Additional: DeletePatchDeploymentAsync(DeletePatchDeploymentRequest, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
DeletePatchDeploymentRequest request = new DeletePatchDeploymentRequest
{
PatchDeploymentName = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]"),
};
// Make the request
await osConfigServiceClient.DeletePatchDeploymentAsync(request);
// End snippet
}
/// <summary>Snippet for DeletePatchDeployment</summary>
public void DeletePatchDeployment()
{
// Snippet: DeletePatchDeployment(string, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
string name = "projects/[PROJECT]/patchDeployments/[PATCH_DEPLOYMENT]";
// Make the request
osConfigServiceClient.DeletePatchDeployment(name);
// End snippet
}
/// <summary>Snippet for DeletePatchDeploymentAsync</summary>
public async Task DeletePatchDeploymentAsync()
{
// Snippet: DeletePatchDeploymentAsync(string, CallSettings)
// Additional: DeletePatchDeploymentAsync(string, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "projects/[PROJECT]/patchDeployments/[PATCH_DEPLOYMENT]";
// Make the request
await osConfigServiceClient.DeletePatchDeploymentAsync(name);
// End snippet
}
/// <summary>Snippet for DeletePatchDeployment</summary>
public void DeletePatchDeploymentResourceNames()
{
// Snippet: DeletePatchDeployment(PatchDeploymentName, CallSettings)
// Create client
OsConfigServiceClient osConfigServiceClient = OsConfigServiceClient.Create();
// Initialize request argument(s)
PatchDeploymentName name = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]");
// Make the request
osConfigServiceClient.DeletePatchDeployment(name);
// End snippet
}
/// <summary>Snippet for DeletePatchDeploymentAsync</summary>
public async Task DeletePatchDeploymentResourceNamesAsync()
{
// Snippet: DeletePatchDeploymentAsync(PatchDeploymentName, CallSettings)
// Additional: DeletePatchDeploymentAsync(PatchDeploymentName, CancellationToken)
// Create client
OsConfigServiceClient osConfigServiceClient = await OsConfigServiceClient.CreateAsync();
// Initialize request argument(s)
PatchDeploymentName name = PatchDeploymentName.FromProjectPatchDeployment("[PROJECT]", "[PATCH_DEPLOYMENT]");
// Make the request
await osConfigServiceClient.DeletePatchDeploymentAsync(name);
// End snippet
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#region Fast Binary format
/*
.----------.--------------. .----------.---------.
struct hierarchy | struct | BT_STOP_BASE |...| struct | BT_STOP |
'----------'--------------' '----------'---------'
.----------.----------. .----------.
struct | field | field |...| field |
'----------'----------' '----------'
.------.----.----------.
field | type | id | value |
'------'----'----------'
.---.---.---.---.---.---.---.---. i - id bits
type | 0 | 0 | 0 | t | t | t | t | t | t - type bits
'---'---'---'---'---'---'---'---' v - value bits
4 0
id .---. .---.---. .---.
| i |...| i | i |...| i |
'---' '---'---' '---'
7 0 15 8
.---.---.---.---.---.---.---.---.
value bool | | | | | | | | v |
'---'---'---'---'---'---'---'---'
0
integer, little endian
float, double
.-------.------------.
string, wstring | count | characters |
'-------'------------'
count variable encoded uint32 count of 1-byte (for
string) or 2-byte (for wstring) Unicode code
units
characters 1-byte UTF-8 code units (for string) or 2-byte
UTF-16LE code units (for wstring)
.-------.-------.-------.
blob, list, set, | type | count | items |
vector, nullable '-------'-------'-------'
.---.---.---.---.---.---.---.---.
type | | | | t | t | t | t | t |
'---'---'---'---'---'---'---'---'
4 0
count variable uint32 count of items
items each item encoded according to its type
.----------.------------.-------.-----.-------.
map | key type | value type | count | key | value |
'----------'------------'-------'-----'-------'
.---.---.---.---.---.---.---.---.
key type, | | | | t | t | t | t | t |
value type '---'---'---'---'---'---'---'---'
4 0
count variable encoded uint32 count of {key,mapped} pairs
key, mapped each item encoded according to its type
variable uint32
.---.---. .---..---.---. .---..---.---. .---..---.---. .---..---.---.---.---. .---.
| 1 | v |...| v || 1 | v |...| v || 1 | v |...| v || 1 | v |...| v || 0 | 0 | 0 | v |...| v |
'---'---' '---''---'---' '---''---'---' '---''---'---' '---''---'---'---'---' '---'
6 0 13 7 20 14 27 21 31 28
1 to 5 bytes, high bit of every byte indicates if there is another byte
*/
#endregion
namespace Bond.Protocols
{
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
using Bond.IO;
/// <summary>
/// Writer for the Fast Binary tagged protocol
/// </summary>
/// <typeparam name="O">Implementation of IOutputStream interface</typeparam>
[Reader(typeof(FastBinaryReader<>))]
public struct FastBinaryWriter<O> : IProtocolWriter
where O : IOutputStream
{
const ushort Magic = (ushort)ProtocolType.FAST_PROTOCOL;
readonly O output;
readonly ushort version;
/// <summary>
/// Create an instance of FastBinaryWriter
/// </summary>
/// <param name="output">Serialized payload output</param>
/// <param name="version">Protocol version</param>
public FastBinaryWriter(O output, ushort version = 1)
{
this.output = output;
this.version = version;
}
/// <summary>
/// Write protocol magic number and version
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteVersion()
{
output.WriteUInt16(Magic);
output.WriteUInt16(version);
}
#region Complex types
/// <summary>
/// Start writing a struct
/// </summary>
/// <param name="metadata">Schema metadata</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteStructBegin(Metadata metadata)
{}
/// <summary>
/// Start writing a base struct
/// </summary>
/// <param name="metadata">Base schema metadata</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBaseBegin(Metadata metadata)
{}
/// <summary>
/// End writing a struct
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteStructEnd()
{
output.WriteUInt8((Byte)BondDataType.BT_STOP);
}
/// <summary>
/// End writing a base struct
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBaseEnd()
{
output.WriteUInt8((Byte)BondDataType.BT_STOP_BASE);
}
/// <summary>
/// Start writing a field
/// </summary>
/// <param name="type">Type of the field</param>
/// <param name="id">Identifier of the field</param>
/// <param name="metadata">Metadata of the field</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFieldBegin(BondDataType type, ushort id, Metadata metadata)
{
output.WriteUInt8((byte) type);
output.WriteUInt16(id);
}
/// <summary>
/// Indicate that field was omitted because it was set to its default value
/// </summary>
/// <param name="dataType">Type of the field</param>
/// <param name="id">Identifier of the field</param>
/// <param name="metadata">Metadata of the field</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFieldOmitted(BondDataType dataType, ushort id, Metadata metadata)
{}
/// <summary>
/// End writing a field
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFieldEnd()
{}
/// <summary>
/// Start writing a list or set container
/// </summary>
/// <param name="count">Number of elements in the container</param>
/// <param name="elementType">Type of the elements</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteContainerBegin(int count, BondDataType elementType)
{
output.WriteUInt8((byte)elementType);
output.WriteVarUInt32((uint)count);
}
/// <summary>
/// Start writing a map container
/// </summary>
/// <param name="count">Number of elements in the container</param>
/// <param name="keyType">Type of the keys</param>
/// /// <param name="valueType">Type of the values</param>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteContainerBegin(int count, BondDataType keyType, BondDataType valueType)
{
output.WriteUInt8((byte)keyType);
output.WriteUInt8((byte)valueType);
output.WriteVarUInt32((uint)count);
}
/// <summary>
/// End writing a container
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteContainerEnd()
{}
/// <summary>
/// Write array of bytes verbatim
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBytes(ArraySegment<byte> data)
{
output.WriteBytes(data);
}
#endregion
#region Primitive types
/// <summary>
/// Write an UInt8
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt8(Byte value)
{
output.WriteUInt8(value);
}
/// <summary>
/// Write an UInt16
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt16(UInt16 value)
{
output.WriteUInt16(value);
}
/// <summary>
/// Write an UInt16
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt32(UInt32 value)
{
output.WriteUInt32(value);
}
/// <summary>
/// Write an UInt64
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteUInt64(UInt64 value)
{
output.WriteUInt64(value);
}
/// <summary>
/// Write an Int8
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt8(SByte value)
{
output.WriteUInt8((Byte)value);
}
/// <summary>
/// Write an Int16
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt16(Int16 value)
{
output.WriteUInt16((ushort)value);
}
/// <summary>
/// Write an Int32
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt32(Int32 value)
{
output.WriteUInt32((uint)value);
}
/// <summary>
/// Write an Int64
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteInt64(Int64 value)
{
output.WriteUInt64((ulong)value);
}
/// <summary>
/// Write a float
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteFloat(float value)
{
output.WriteFloat(value);
}
/// <summary>
/// Write a double
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteDouble(double value)
{
output.WriteDouble(value);
}
/// <summary>
/// Write a bool
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteBool(bool value)
{
output.WriteUInt8((byte)(value ? 1 : 0));
}
/// <summary>
/// Write a UTF-8 string
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteString(string value)
{
if (value.Length == 0)
{
output.WriteVarUInt32(0);
}
else
{
var size = Encoding.UTF8.GetByteCount(value);
output.WriteVarUInt32((UInt32)size);
output.WriteString(Encoding.UTF8, value, size);
}
}
/// <summary>
/// Write a UTF-16 string
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void WriteWString(string value)
{
if (value.Length == 0)
{
output.WriteVarUInt32(0);
}
else
{
int byteSize = checked(value.Length * 2);
output.WriteVarUInt32((UInt32)value.Length);
output.WriteString(Encoding.Unicode, value, byteSize);
}
}
#endregion
}
/// <summary>
/// Reader for the Fast Binary tagged protocol
/// </summary>
/// <typeparam name="I">Implementation of IInputStream interface</typeparam>
public struct FastBinaryReader<I> : IClonableTaggedProtocolReader, ICloneable<FastBinaryReader<I>>
where I : IInputStream, ICloneable<I>
{
readonly I input;
/// <summary>
/// Create an instance of FastBinaryReader
/// </summary>
/// <param name="input">Input payload</param>
/// <param name="version">Protocol version</param>
public FastBinaryReader(I input, ushort version = 1)
{
this.input = input;
}
/// <summary>
/// Clone the reader
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
FastBinaryReader<I> ICloneable<FastBinaryReader<I>>.Clone()
{
return new FastBinaryReader<I>(input.Clone());
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
IClonableTaggedProtocolReader ICloneable<IClonableTaggedProtocolReader>.Clone()
{
return (this as ICloneable<FastBinaryReader<I>>).Clone();
}
#region Complex types
/// <summary>
/// Start reading a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadStructBegin()
{ }
/// <summary>
/// Start reading a base of a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadBaseBegin()
{ }
/// <summary>
/// End reading a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadStructEnd()
{ }
/// <summary>
/// End reading a base of a struct
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadBaseEnd()
{ }
/// <summary>
/// Start reading a field
/// </summary>
/// <param name="type">An out parameter set to the field type
/// or BT_STOP/BT_STOP_BASE if there is no more fields in current struct/base</param>
/// <param name="id">Out parameter set to the field identifier</param>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadFieldBegin(out BondDataType type, out ushort id)
{
type = (BondDataType)input.ReadUInt8();
if (type != BondDataType.BT_STOP && type != BondDataType.BT_STOP_BASE)
id = input.ReadUInt16();
else
id = 0;
}
/// <summary>
/// End reading a field
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadFieldEnd()
{ }
/// <summary>
/// Start reading a list or set container
/// </summary>
/// <param name="count">An out parameter set to number of items in the container</param>
/// <param name="elementType">An out parameter set to type of container elements</param>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadContainerBegin(out int count, out BondDataType elementType)
{
elementType = (BondDataType)input.ReadUInt8();
count = checked((int)input.ReadVarUInt32());
}
/// <summary>
/// Start reading a map container
/// </summary>
/// <param name="count">An out parameter set to number of items in the container</param>
/// <param name="keyType">An out parameter set to the type of map keys</param>
/// <param name="valueType">An out parameter set to the type of map values</param>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadContainerBegin(out int count, out BondDataType keyType, out BondDataType valueType)
{
keyType = (BondDataType)input.ReadUInt8();
valueType = (BondDataType)input.ReadUInt8();
count = checked((int)input.ReadVarUInt32());
}
/// <summary>
/// End reading a container
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReadContainerEnd()
{ }
#endregion
#region Primitive types
/// <summary>
/// Read an UInt8
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public byte ReadUInt8()
{
return input.ReadUInt8();
}
/// <summary>
/// Read an UInt16
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ushort ReadUInt16()
{
return input.ReadUInt16();
}
/// <summary>
/// Read an UInt32
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public uint ReadUInt32()
{
return input.ReadUInt32();
}
/// <summary>
/// Read an UInt64
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public UInt64 ReadUInt64()
{
return input.ReadUInt64();
}
/// <summary>
/// Read an Int8
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public sbyte ReadInt8()
{
return (sbyte)input.ReadUInt8();
}
/// <summary>
/// Read an Int16
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public short ReadInt16()
{
return (short)input.ReadUInt16();
}
/// <summary>
/// Read an Int32
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ReadInt32()
{
return (int)input.ReadUInt32();
}
/// <summary>
/// Read an Int64
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public long ReadInt64()
{
return (long)input.ReadUInt64();
}
/// <summary>
/// Read a bool
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool ReadBool()
{
return input.ReadUInt8() != 0;
}
/// <summary>
/// Read a float
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public float ReadFloat()
{
return input.ReadFloat();
}
/// <summary>
/// Read a double
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public double ReadDouble()
{
return input.ReadDouble();
}
/// <summary>
/// Read a UTF-8 string
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public String ReadString()
{
var length = checked((int)input.ReadVarUInt32());
return length == 0 ? string.Empty : input.ReadString(Encoding.UTF8, length);
}
/// <summary>
/// Read a UTF-16 string
/// </summary>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string ReadWString()
{
var length = checked((int)(input.ReadVarUInt32() * 2));
return length == 0 ? string.Empty : input.ReadString(Encoding.Unicode, length);
}
/// <summary>
/// Read an array of bytes verbatim
/// </summary>
/// <param name="count">Number of bytes to read</param>
/// <exception cref="EndOfStreamException"/>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ArraySegment<byte> ReadBytes(int count)
{
return input.ReadBytes(count);
}
#endregion
#region Skip
/// <summary>
/// Skip a value of specified type
/// </summary>
/// <param name="type">Type of the value to skip</param>
/// <exception cref="EndOfStreamException"/>
public void Skip(BondDataType type)
{
switch (type)
{
case (BondDataType.BT_BOOL):
case (BondDataType.BT_UINT8):
case (BondDataType.BT_INT8):
input.SkipBytes(sizeof(byte));
break;
case (BondDataType.BT_UINT16):
case (BondDataType.BT_INT16):
input.SkipBytes(sizeof(ushort));
break;
case (BondDataType.BT_UINT32):
case (BondDataType.BT_INT32):
input.SkipBytes(sizeof(uint));
break;
case (BondDataType.BT_FLOAT):
input.SkipBytes(sizeof(float));
break;
case (BondDataType.BT_DOUBLE):
input.SkipBytes(sizeof(double));
break;
case (BondDataType.BT_UINT64):
case (BondDataType.BT_INT64):
input.SkipBytes(sizeof(ulong));
break;
case (BondDataType.BT_STRING):
input.SkipBytes(checked(((int)input.ReadVarUInt32())));
break;
case (BondDataType.BT_WSTRING):
input.SkipBytes(checked((int)(input.ReadVarUInt32()) * 2));
break;
case BondDataType.BT_LIST:
case BondDataType.BT_SET:
SkipContainer();
break;
case BondDataType.BT_MAP:
SkipMap();
break;
case BondDataType.BT_STRUCT:
SkipStruct();
break;
default:
Throw.InvalidBondDataType(type);
break;
}
}
void SkipContainer()
{
BondDataType elementType;
int count;
ReadContainerBegin(out count, out elementType);
switch (elementType)
{
case BondDataType.BT_BOOL:
case BondDataType.BT_INT8:
case BondDataType.BT_UINT8:
input.SkipBytes(count);
break;
case (BondDataType.BT_UINT16):
case (BondDataType.BT_INT16):
input.SkipBytes(checked(count * sizeof(ushort)));
break;
case (BondDataType.BT_UINT32):
case (BondDataType.BT_INT32):
input.SkipBytes(checked(count * sizeof(uint)));
break;
case (BondDataType.BT_UINT64):
case (BondDataType.BT_INT64):
input.SkipBytes(checked(count * sizeof(ulong)));
break;
case BondDataType.BT_FLOAT:
input.SkipBytes(checked(count * sizeof(float)));
break;
case BondDataType.BT_DOUBLE:
input.SkipBytes(checked(count * sizeof(double)));
break;
default:
while (0 <= --count)
{
Skip(elementType);
}
break;
}
}
void SkipMap()
{
BondDataType keyType;
BondDataType valueType;
int count;
ReadContainerBegin(out count, out keyType, out valueType);
while (0 <= --count)
{
Skip(keyType);
Skip(valueType);
}
}
void SkipStruct()
{
while (true)
{
BondDataType type;
ushort id;
ReadFieldBegin(out type, out id);
if (type == BondDataType.BT_STOP_BASE) continue;
if (type == BondDataType.BT_STOP) break;
Skip(type);
}
}
#endregion
}
}
| |
using System;
using GitTools.Testing;
using GitVersionCore.Tests.Helpers;
using NUnit.Framework;
using Shouldly;
namespace GitVersionCore.Tests.IntegrationTests
{
[TestFixture]
public class DocumentationSamples : TestBase
{
[Test]
public void GitFlowFeatureBranch()
{
using var fixture = new EmptyRepositoryFixture();
fixture.SequenceDiagram.Participant("master");
fixture.SequenceDiagram.Participant("develop");
// GitFlow setup
fixture.Repository.MakeACommit();
fixture.ApplyTag("1.2.0");
fixture.BranchTo("develop");
// Branch to develop
fixture.MakeACommit();
fixture.AssertFullSemver("1.3.0-alpha.1");
// Open Pull Request
fixture.BranchTo("feature/myfeature", "feature");
fixture.SequenceDiagram.Activate("feature/myfeature");
fixture.AssertFullSemver("1.3.0-myfeature.1+1");
fixture.MakeACommit();
fixture.AssertFullSemver("1.3.0-myfeature.1+2");
// Merge into develop
fixture.Checkout("develop");
fixture.MergeNoFF("feature/myfeature");
fixture.SequenceDiagram.Destroy("feature/myfeature");
fixture.SequenceDiagram.NoteOver("Feature branches should\r\n" +
"be deleted once merged", "feature/myfeature");
fixture.AssertFullSemver("1.3.0-alpha.3");
Console.WriteLine(fixture.SequenceDiagram.GetDiagram());
}
[Test]
public void GitFlowPullRequestBranch()
{
using var fixture = new EmptyRepositoryFixture();
fixture.SequenceDiagram.Participant("master");
fixture.SequenceDiagram.Participant("develop");
// GitFlow setup
fixture.Repository.MakeACommit();
fixture.ApplyTag("1.2.0");
fixture.BranchTo("develop");
// Branch to develop
fixture.MakeACommit();
fixture.AssertFullSemver("1.3.0-alpha.1");
// Open Pull Request
fixture.BranchTo("pull/2/merge", "pr");
fixture.SequenceDiagram.Activate("pull/2/merge");
fixture.AssertFullSemver("1.3.0-PullRequest0002.1");
fixture.MakeACommit();
fixture.AssertFullSemver("1.3.0-PullRequest0002.2");
// Merge into develop
fixture.Checkout("develop");
fixture.MergeNoFF("pull/2/merge");
fixture.SequenceDiagram.Destroy("pull/2/merge");
fixture.SequenceDiagram.NoteOver("Feature branches/pr's should\r\n" +
"be deleted once merged", "pull/2/merge");
fixture.AssertFullSemver("1.3.0-alpha.3");
Console.WriteLine(fixture.SequenceDiagram.GetDiagram());
}
[Test]
public void GitFlowHotfixBranch()
{
using var fixture = new EmptyRepositoryFixture();
fixture.SequenceDiagram.Participant("develop");
fixture.SequenceDiagram.Participant("master");
fixture.Repository.MakeACommit();
fixture.ApplyTag("1.2.0");
// Create hotfix branch
fixture.Checkout("master");
fixture.BranchTo("hotfix/1.2.1", "hotfix");
fixture.SequenceDiagram.Activate("hotfix/1.2.1");
fixture.MakeACommit();
fixture.MakeACommit();
fixture.AssertFullSemver("1.2.1-beta.1+2");
// Apply beta.1 tag should be exact tag
fixture.ApplyTag("1.2.1-beta.1");
fixture.AssertFullSemver("1.2.1-beta.1");
fixture.Checkout("master");
fixture.MergeNoFF("hotfix/1.2.1");
fixture.SequenceDiagram.Destroy("hotfix/1.2.1");
fixture.SequenceDiagram.NoteOver("Hotfix branches are deleted once merged", "hotfix/1.2.1");
fixture.ApplyTag("1.2.1");
Console.WriteLine(fixture.SequenceDiagram.GetDiagram());
}
[Test]
public void GitFlowMinorRelease()
{
using var fixture = new EmptyRepositoryFixture();
fixture.SequenceDiagram.Participant("master");
fixture.SequenceDiagram.Participant("develop");
// GitFlow setup
fixture.Repository.MakeACommit();
fixture.ApplyTag("1.2.1");
// GitFlow setup
fixture.BranchTo("develop");
fixture.MakeACommit();
// Create release branch
fixture.BranchTo("release/1.3.0", "release");
fixture.SequenceDiagram.Activate("release/1.3.0");
fixture.AssertFullSemver("1.3.0-beta.1+0");
// Make another commit on develop
fixture.Checkout("develop");
fixture.MakeACommit();
fixture.AssertFullSemver("1.4.0-alpha.1");
// Make a commit to release-1.3.0
fixture.Checkout("release/1.3.0");
fixture.MakeACommit();
fixture.AssertFullSemver("1.3.0-beta.1+1");
// Apply beta.1 tag should be exact tag
fixture.ApplyTag("1.3.0-beta.1");
fixture.AssertFullSemver("1.3.0-beta.1");
// Make a commit after a tag should bump up the beta
fixture.MakeACommit();
fixture.AssertFullSemver("1.3.0-beta.2+2");
// Complete release
fixture.Checkout("master");
fixture.MergeNoFF("release/1.3.0");
fixture.Checkout("develop");
fixture.MergeNoFF("release/1.3.0");
fixture.SequenceDiagram.Destroy("release/1.3.0");
fixture.SequenceDiagram.NoteOver("Release branches are deleted once merged", "release/1.3.0");
fixture.Checkout("master");
fixture.ApplyTag("1.3.0");
fixture.AssertFullSemver("1.3.0");
// Not 0 for commit count as we can't know the increment rules of the merged branch
fixture.Checkout("develop");
fixture.AssertFullSemver("1.4.0-alpha.4");
Console.WriteLine(fixture.SequenceDiagram.GetDiagram());
}
[Test]
public void GitFlowMajorRelease()
{
using var fixture = new EmptyRepositoryFixture();
fixture.SequenceDiagram.Participant("master");
fixture.SequenceDiagram.Participant("develop");
fixture.Repository.MakeACommit();
fixture.ApplyTag("1.3.0");
// GitFlow setup
fixture.BranchTo("develop");
fixture.MakeACommit();
// Create release branch
fixture.BranchTo("release/2.0.0", "release");
fixture.SequenceDiagram.Activate("release/2.0.0");
fixture.AssertFullSemver("2.0.0-beta.1+0");
// Make another commit on develop
fixture.Checkout("develop");
fixture.MakeACommit();
fixture.AssertFullSemver("2.1.0-alpha.1");
// Make a commit to release-2.0.0
fixture.Checkout("release/2.0.0");
fixture.MakeACommit();
fixture.AssertFullSemver("2.0.0-beta.1+1");
// Apply beta.1 tag should be exact tag
fixture.ApplyTag("2.0.0-beta.1");
fixture.AssertFullSemver("2.0.0-beta.1");
// Make a commit after a tag should bump up the beta
fixture.MakeACommit();
fixture.AssertFullSemver("2.0.0-beta.2+2");
// Complete release
fixture.Checkout("master");
fixture.MergeNoFF("release/2.0.0");
fixture.Checkout("develop");
fixture.MergeNoFF("release/2.0.0");
fixture.SequenceDiagram.Destroy("release/2.0.0");
fixture.SequenceDiagram.NoteOver("Release branches are deleted once merged", "release/2.0.0");
fixture.Checkout("master");
fixture.AssertFullSemver("2.0.0+0");
fixture.ApplyTag("2.0.0");
fixture.AssertFullSemver("2.0.0");
// Not 0 for commit count as we can't know the increment rules of the merged branch
fixture.Checkout("develop");
fixture.AssertFullSemver("2.1.0-alpha.4");
Console.WriteLine(fixture.SequenceDiagram.GetDiagram());
}
[Test]
public void GitFlowSupportHotfixRelease()
{
using var fixture = new EmptyRepositoryFixture();
fixture.SequenceDiagram.Participant("develop");
fixture.SequenceDiagram.Participant("master");
fixture.Repository.MakeACommit();
fixture.ApplyTag("1.3.0");
// GitFlow setup
fixture.Repository.MakeACommit();
fixture.BranchTo("develop");
fixture.SequenceDiagram.NoteOver("Create 2.0.0 release and complete", "develop", "master");
fixture.Checkout("master");
fixture.ApplyTag("2.0.0");
// Create hotfix branch
fixture.Checkout("1.3.0");
fixture.BranchToFromTag("support/1.x", "1.3.0", "master", "support");
fixture.MakeACommit();
fixture.AssertFullSemver("1.3.1+1");
fixture.BranchTo("hotfix/1.3.1", "hotfix2");
fixture.SequenceDiagram.Activate("hotfix/1.3.1");
fixture.MakeACommit();
fixture.MakeACommit();
fixture.AssertFullSemver("1.3.1-beta.1+3");
// Apply beta.1 tag should be exact tag
fixture.ApplyTag("1.3.1-beta.1");
fixture.AssertFullSemver("1.3.1-beta.1");
fixture.Checkout("support/1.x");
fixture.MergeNoFF("hotfix/1.3.1");
fixture.SequenceDiagram.Destroy("hotfix/1.3.1");
fixture.SequenceDiagram.NoteOver("Hotfix branches are deleted once merged", "hotfix/1.3.1");
fixture.AssertFullSemver("1.3.1+4");
fixture.ApplyTag("1.3.1");
fixture.AssertFullSemver("1.3.1");
Console.WriteLine(fixture.SequenceDiagram.GetDiagram());
}
[Test]
public void GitFlowSupportMinorRelease()
{
using var fixture = new EmptyRepositoryFixture();
fixture.SequenceDiagram.Participant("develop");
fixture.SequenceDiagram.Participant("master");
fixture.Repository.MakeACommit();
fixture.ApplyTag("1.3.0");
// GitFlow setup
fixture.Repository.MakeACommit();
fixture.BranchTo("develop");
fixture.SequenceDiagram.NoteOver("Create 2.0.0 release and complete", "develop", "master");
fixture.Checkout("master");
fixture.ApplyTag("2.0.0");
// Create hotfix branch
fixture.Checkout("1.3.0");
fixture.BranchToFromTag("support/1.x", "1.3.0", "master", "support");
fixture.SequenceDiagram.NoteOver("Create 1.3.1 release and complete", "master", "support/1.x");
fixture.Repository.MakeACommit();
fixture.ApplyTag("1.3.1");
fixture.BranchTo("release/1.4.0", "supportRelease");
fixture.SequenceDiagram.Activate("release/1.4.0");
fixture.MakeACommit();
fixture.MakeACommit();
fixture.AssertFullSemver("1.4.0-beta.1+2");
// Apply beta.1 tag should be exact tag
fixture.ApplyTag("1.4.0-beta.1");
fixture.AssertFullSemver("1.4.0-beta.1");
fixture.Checkout("support/1.x");
fixture.MergeNoFF("release/1.4.0");
fixture.SequenceDiagram.Destroy("release/1.4.0");
fixture.SequenceDiagram.NoteOver("Release branches are deleted once merged", "release/1.4.0");
fixture.AssertFullSemver("1.4.0+0");
fixture.ApplyTag("1.4.0");
fixture.AssertFullSemver("1.4.0");
Console.WriteLine(fixture.SequenceDiagram.GetDiagram());
}
[Test]
public void GitHubFlowFeatureBranch()
{
using var fixture = new EmptyRepositoryFixture();
fixture.SequenceDiagram.Participant("master");
// GitFlow setup
fixture.Repository.MakeACommit();
fixture.ApplyTag("1.2.0");
// Branch to develop
fixture.MakeACommit();
fixture.AssertFullSemver("1.2.1+1");
// Open Pull Request
fixture.BranchTo("feature/myfeature", "feature");
fixture.SequenceDiagram.Activate("feature/myfeature");
fixture.AssertFullSemver("1.2.1-myfeature.1+1");
fixture.MakeACommit();
fixture.AssertFullSemver("1.2.1-myfeature.1+2");
// Merge into master
fixture.Checkout("master");
fixture.MergeNoFF("feature/myfeature");
fixture.SequenceDiagram.Destroy("feature/myfeature");
fixture.SequenceDiagram.NoteOver("Feature branches should\r\n" +
"be deleted once merged", "feature/myfeature");
fixture.AssertFullSemver("1.2.1+3");
}
[Test]
public void GitHubFlowPullRequestBranch()
{
using var fixture = new EmptyRepositoryFixture();
fixture.SequenceDiagram.Participant("master");
// GitFlow setup
fixture.Repository.MakeACommit();
fixture.ApplyTag("1.2.0");
// Branch to develop
fixture.MakeACommit();
fixture.AssertFullSemver("1.2.1+1");
// Open Pull Request
fixture.BranchTo("pull/2/merge", "pr");
fixture.SequenceDiagram.Activate("pull/2/merge");
fixture.AssertFullSemver("1.2.1-PullRequest0002.1");
fixture.MakeACommit();
fixture.AssertFullSemver("1.2.1-PullRequest0002.2");
// Merge into master
fixture.Checkout("master");
fixture.MergeNoFF("pull/2/merge");
fixture.SequenceDiagram.Destroy("pull/2/merge");
fixture.SequenceDiagram.NoteOver("Feature branches/pr's should\r\n" +
"be deleted once merged", "pull/2/merge");
fixture.AssertFullSemver("1.2.1+3");
}
[Test]
public void GitHubFlowMajorRelease()
{
using var fixture = new EmptyRepositoryFixture();
fixture.SequenceDiagram.Participant("master");
fixture.Repository.MakeACommit();
fixture.ApplyTag("1.3.0");
// Create release branch
fixture.BranchTo("release/2.0.0", "release");
fixture.SequenceDiagram.Activate("release/2.0.0");
fixture.MakeACommit();
fixture.AssertFullSemver("2.0.0-beta.1+1");
fixture.MakeACommit();
fixture.AssertFullSemver("2.0.0-beta.1+2");
// Apply beta.1 tag should be exact tag
fixture.ApplyTag("2.0.0-beta.1");
fixture.AssertFullSemver("2.0.0-beta.1");
// test that the CommitsSinceVersionSource should still return commit count
var version = fixture.GetVersion();
version.CommitsSinceVersionSource.ShouldBe("2");
// Make a commit after a tag should bump up the beta
fixture.MakeACommit();
fixture.AssertFullSemver("2.0.0-beta.2+3");
// Complete release
fixture.Checkout("master");
fixture.MergeNoFF("release/2.0.0");
fixture.SequenceDiagram.Destroy("release/2.0.0");
fixture.SequenceDiagram.NoteOver("Release branches are deleted once merged", "release/2.0.0");
fixture.AssertFullSemver("2.0.0+0");
fixture.ApplyTag("2.0.0");
fixture.AssertFullSemver("2.0.0");
fixture.MakeACommit();
fixture.Repository.DumpGraph();
fixture.AssertFullSemver("2.0.1+1");
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
namespace Metaheuristics
{
public static class QAPUtils
{
public static double Fitness(QAPInstance instance, int[] assignment)
{
double cost = 0;
for (int i = 0; i < instance.NumberFacilities; i++) {
for (int j = 0; j < instance.NumberFacilities; j++) {
cost += instance.Distances[i,j] * instance.Flows[assignment[i],assignment[j]];
}
}
return cost;
}
public static int[] RandomSolution(QAPInstance instance)
{
int[] solution = new int[instance.NumberFacilities];
List<int> facilities = new List<int>();
for (int facility = 0; facility < instance.NumberFacilities; facility++) {
facilities.Add(facility);
}
for (int i = 0; i < instance.NumberFacilities; i++) {
int facilityIndex = Statistics.RandomDiscreteUniform(0, facilities.Count - 1);
int facility = facilities[facilityIndex];
facilities.RemoveAt(facilityIndex);
solution[i] = facility;
}
return solution;
}
public static int[] GetNeighbor(QAPInstance instance, int[] solution)
{
int[] neighbor = new int[instance.NumberFacilities];
int a = Statistics.RandomDiscreteUniform(0, solution.Length - 1);
int b = a;
while (b == a) {
b = Statistics.RandomDiscreteUniform(0, solution.Length - 1);
}
for (int i = 0; i < solution.Length; i++) {
if (i == a) {
neighbor[i] = solution[b];
}
else if (i == b) {
neighbor[i] = solution[a];
}
else {
neighbor[i] = solution[i];
}
}
return neighbor;
}
public static void Repair(QAPInstance instance, int[] individual)
{
int facilitiesCount = 0;
bool[] facilitiesUsed = new bool[instance.NumberFacilities];
bool[] facilitiesRepeated = new bool[instance.NumberFacilities];
// Get information to decide if the individual is valid.
for (int i = 0; i < instance.NumberFacilities; i++) {
if (!facilitiesUsed[individual[i]]) {
facilitiesCount += 1;
facilitiesUsed[individual[i]] = true;
}
else {
facilitiesRepeated[i] = true;
}
}
// If the individual is invalid, make it valid.
if (facilitiesCount != instance.NumberFacilities) {
for (int i = 0; i < facilitiesRepeated.Length; i++) {
if (facilitiesRepeated[i]) {
int count = Statistics.RandomDiscreteUniform(1, instance.NumberFacilities - facilitiesCount);
for (int f = 0; f < facilitiesUsed.Length; f++) {
if (!facilitiesUsed[f]) {
count -= 1;
if (count == 0) {
individual[i] = f;
facilitiesRepeated[i] = false;
facilitiesUsed[f] = true;
facilitiesCount += 1;
break;
}
}
}
}
}
}
}
// Implementation of the 2-opt (first improvement) local search algorithm.
public static void LocalSearch2OptFirst(QAPInstance instance, int[] assignment)
{
int tmp;
double currentFitness, bestFitness;
bestFitness = Fitness(instance, assignment);
for (int j = 1; j < assignment.Length; j++) {
for (int i = 0; i < j; i++) {
// Swap the items.
tmp = assignment[j];
assignment[j] = assignment[i];
assignment[i] = tmp;
// Evaluate the fitness of this new solution.
currentFitness = Fitness(instance, assignment);
if (currentFitness < bestFitness) {
return;
}
// Undo the swap.
tmp = assignment[j];
assignment[j] = assignment[i];
assignment[i] = tmp;
}
}
}
// Implementation of the 2-opt (best improvement) local search algorithm.
public static void LocalSearch2OptBest(QAPInstance instance, int[] assignment)
{
int tmp;
int firstSwapItem = 0, secondSwapItem = 0;
double currentFitness, bestFitness;
bestFitness = Fitness(instance, assignment);
for (int j = 1; j < assignment.Length; j++) {
for (int i = 0; i < j; i++) {
// Swap the items.
tmp = assignment[j];
assignment[j] = assignment[i];
assignment[i] = tmp;
// Evaluate the fitness of this new solution.
currentFitness = Fitness(instance, assignment);
if (currentFitness < bestFitness) {
firstSwapItem = j;
secondSwapItem = i;
bestFitness = currentFitness;
}
// Undo the swap.
tmp = assignment[j];
assignment[j] = assignment[i];
assignment[i] = tmp;
}
}
// Use the best assignment.
if (firstSwapItem != secondSwapItem) {
tmp = assignment[firstSwapItem];
assignment[firstSwapItem] = assignment[secondSwapItem];
assignment[secondSwapItem] = tmp;
}
}
// Implementation of the Tabu Movement of two movements.
public static Tuple<int, int> GetTabu(int[] source, int[] destiny)
{
Tuple<int, int> tabu = new Tuple<int, int>(-1, -1);
for (int i = 0; i < source.Length; i++) {
if (source[i] != destiny[i]) {
tabu.Val1 = Math.Min(source[i],destiny[i]);
tabu.Val2 = Math.Max(source[i],destiny[i]);
break;
}
}
return tabu;
}
// Implementation of the GRC solution's construction algorithm.
public static int[] GRCSolution(QAPInstance instance, double rclThreshold)
{
int numFacilities = instance.NumberFacilities;
int[] assigment = new int[numFacilities];
int totalFacilities = numFacilities;
int index = 0;
double best = 0;
double cost = 0;
int facility = 0;
// Restricted Candidate List.
SortedList<double, int> rcl = new SortedList<double, int>();
// Available cities.
bool[] assigned = new bool[numFacilities];
assigment[0] = Statistics.RandomDiscreteUniform(0, numFacilities-1);
assigned[assigment[0]] = true;
index++;
numFacilities --;
while (numFacilities > 0) {
rcl = new SortedList<double, int>();
for (int i = 0; i < totalFacilities; i++) {
if (!assigned[i]) {
cost = 0;
for (int j = 0; j < index; j++) {
cost += instance.Distances[j,index] * instance.Flows[assigment[j],i];
}
if(rcl.Count == 0) {
best = cost;
rcl.Add(cost, i);
}
else if( cost < best) {
// The new assignment is the new best;
best = cost;
for (int j = rcl.Count-1; j > 0; j--) {
if (rcl.Keys[j] > rclThreshold * best) {
rcl.RemoveAt(j);
}
else {
break;
}
}
rcl.Add(cost, i);
}
else if (cost < rclThreshold * best) {
// The new assigment is a mostly good candidate.
rcl.Add(cost, i);
}
}
}
facility = rcl.Values[Statistics.RandomDiscreteUniform(0, rcl.Count-1)];
assigned[facility] = true;
assigment[index] = facility;
index++;
numFacilities--;
}
return assigment;
}
public static double Distance(QAPInstance instance, int[] a, int[] b)
{
double distance = 0;
for (int i = 0; i < a.Length; i++) {
if (a[i] != b[i]) {
distance += 1;
}
}
return distance;
}
public static void PerturbateSolution(int[] solution, int perturbations)
{
int point1 = 0;
int point2 = 0;
int tmp = 0;
for (int i = 0; i < perturbations; i++) {
point1 = Statistics.RandomDiscreteUniform(0, solution.Length -1 );
point2 = Statistics.RandomDiscreteUniform(0, solution.Length -1 );
tmp = solution[point1];
solution[point1] = solution[point2];
solution[point2] = tmp;
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Diagnostics;
using Microsoft.Extensions.Logging;
namespace Microsoft.AspNetCore.Mvc.Razor
{
internal static class MvcRazorLoggerExtensions
{
private static readonly double TimestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency;
private static readonly Action<ILogger, string, Exception?> _generatedCodeToAssemblyCompilationStart;
private static readonly Action<ILogger, string, double, Exception?> _generatedCodeToAssemblyCompilationEnd;
private static readonly Action<ILogger, string, Exception?> _viewCompilerStartCodeGeneration;
private static readonly Action<ILogger, string, double, Exception?> _viewCompilerEndCodeGeneration;
private static readonly Action<ILogger, string, Exception?> _viewCompilerLocatedCompiledView;
private static readonly Action<ILogger, Exception?> _viewCompilerNoCompiledViewsFound;
private static readonly Action<ILogger, string, Exception?> _viewCompilerLocatedCompiledViewForPath;
private static readonly Action<ILogger, string, Exception?> _viewCompilerCouldNotFindFileToCompileForPath;
private static readonly Action<ILogger, string, Exception?> _viewCompilerFoundFileToCompileForPath;
private static readonly Action<ILogger, string, Exception?> _viewCompilerInvalidatingCompiledFile;
private static readonly Action<ILogger, string, string?, Exception?> _viewLookupCacheMiss;
private static readonly Action<ILogger, string, string?, Exception?> _viewLookupCacheHit;
private static readonly Action<ILogger, string, Exception?> _precompiledViewFound;
private static readonly Action<ILogger, string, Exception?> _tagHelperComponentInitialized;
private static readonly Action<ILogger, string, Exception?> _tagHelperComponentProcessed;
private static readonly LogDefineOptions SkipEnabledCheckLogOptions = new() { SkipEnabledCheck = true };
static MvcRazorLoggerExtensions()
{
_viewCompilerStartCodeGeneration = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(1, "ViewCompilerStartCodeGeneration"),
"Code generation for the Razor file at '{FilePath}' started.");
_viewCompilerEndCodeGeneration = LoggerMessage.Define<string, double>(
LogLevel.Debug,
new EventId(2, "ViewCompilerEndCodeGeneration"),
"Code generation for the Razor file at '{FilePath}' completed in {ElapsedMilliseconds}ms.",
SkipEnabledCheckLogOptions);
_viewCompilerLocatedCompiledView = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(3, "ViewCompilerLocatedCompiledView"),
"Initializing Razor view compiler with compiled view: '{ViewName}'.");
_viewCompilerNoCompiledViewsFound = LoggerMessage.Define(
LogLevel.Debug,
new EventId(4, "ViewCompilerNoCompiledViewsFound"),
"Initializing Razor view compiler with no compiled views.");
_viewCompilerLocatedCompiledViewForPath = LoggerMessage.Define<string>(
LogLevel.Trace,
new EventId(5, "ViewCompilerLocatedCompiledViewForPath"),
"Located compiled view for view at path '{Path}'.");
// 6, ViewCompilerRecompilingCompiledView - removed
_viewCompilerCouldNotFindFileToCompileForPath = LoggerMessage.Define<string>(
LogLevel.Trace,
new EventId(7, "ViewCompilerCouldNotFindFileAtPath"),
"Could not find a file for view at path '{Path}'.");
_viewCompilerFoundFileToCompileForPath = LoggerMessage.Define<string>(
LogLevel.Trace,
new EventId(8, "ViewCompilerFoundFileToCompile"),
"Found file at path '{Path}'.");
_viewCompilerInvalidatingCompiledFile = LoggerMessage.Define<string>(
LogLevel.Trace,
new EventId(9, "ViewCompilerInvalidingCompiledFile"),
"Invalidating compiled view at path '{Path}' with a file since the checksum did not match.");
_viewLookupCacheMiss = LoggerMessage.Define<string, string?>(
LogLevel.Debug,
new EventId(1, "ViewLookupCacheMiss"),
"View lookup cache miss for view '{ViewName}' in controller '{ControllerName}'.");
_viewLookupCacheHit = LoggerMessage.Define<string, string?>(
LogLevel.Debug,
new EventId(2, "ViewLookupCacheHit"),
"View lookup cache hit for view '{ViewName}' in controller '{ControllerName}'.");
_precompiledViewFound = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(3, "PrecompiledViewFound"),
"Using precompiled view for '{RelativePath}'.");
_generatedCodeToAssemblyCompilationStart = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(1, "GeneratedCodeToAssemblyCompilationStart"),
"Compilation of the generated code for the Razor file at '{FilePath}' started.");
_generatedCodeToAssemblyCompilationEnd = LoggerMessage.Define<string, double>(
LogLevel.Debug,
new EventId(2, "GeneratedCodeToAssemblyCompilationEnd"),
"Compilation of the generated code for the Razor file at '{FilePath}' completed in {ElapsedMilliseconds}ms.",
SkipEnabledCheckLogOptions);
_tagHelperComponentInitialized = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(2, "TagHelperComponentInitialized"),
"Tag helper component '{ComponentName}' initialized.",
SkipEnabledCheckLogOptions);
_tagHelperComponentProcessed = LoggerMessage.Define<string>(
LogLevel.Debug,
new EventId(3, "TagHelperComponentProcessed"),
"Tag helper component '{ComponentName}' processed.",
SkipEnabledCheckLogOptions);
}
public static void ViewCompilerStartCodeGeneration(this ILogger logger, string filePath)
{
_viewCompilerStartCodeGeneration(logger, filePath, null);
}
public static void ViewCompilerEndCodeGeneration(this ILogger logger, string filePath, long startTimestamp)
{
// Don't log if logging wasn't enabled at start of request as time will be wildly wrong.
if (startTimestamp != 0 && logger.IsEnabled(LogLevel.Debug))
{
var currentTimestamp = Stopwatch.GetTimestamp();
var elapsed = new TimeSpan((long)(TimestampToTicks * (currentTimestamp - startTimestamp)));
_viewCompilerEndCodeGeneration(logger, filePath, elapsed.TotalMilliseconds, null);
}
}
public static void ViewCompilerLocatedCompiledView(this ILogger logger, string view)
{
_viewCompilerLocatedCompiledView(logger, view, null);
}
public static void ViewCompilerNoCompiledViewsFound(this ILogger logger)
{
_viewCompilerNoCompiledViewsFound(logger, null);
}
public static void ViewCompilerLocatedCompiledViewForPath(this ILogger logger, string path)
{
_viewCompilerLocatedCompiledViewForPath(logger, path, null);
}
public static void ViewCompilerCouldNotFindFileAtPath(this ILogger logger, string path)
{
_viewCompilerCouldNotFindFileToCompileForPath(logger, path, null);
}
public static void ViewCompilerFoundFileToCompile(this ILogger logger, string path)
{
_viewCompilerFoundFileToCompileForPath(logger, path, null);
}
public static void ViewCompilerInvalidingCompiledFile(this ILogger logger, string path)
{
_viewCompilerInvalidatingCompiledFile(logger, path, null);
}
public static void ViewLookupCacheMiss(this ILogger logger, string viewName, string? controllerName)
{
_viewLookupCacheMiss(logger, viewName, controllerName, null);
}
public static void ViewLookupCacheHit(this ILogger logger, string viewName, string? controllerName)
{
_viewLookupCacheHit(logger, viewName, controllerName, null);
}
public static void PrecompiledViewFound(this ILogger logger, string relativePath)
{
_precompiledViewFound(logger, relativePath, null);
}
public static void GeneratedCodeToAssemblyCompilationStart(this ILogger logger, string filePath)
{
_generatedCodeToAssemblyCompilationStart(logger, filePath, null);
}
public static void TagHelperComponentInitialized(this ILogger logger, string componentName)
{
_tagHelperComponentInitialized(logger, componentName, null);
}
public static void TagHelperComponentProcessed(this ILogger logger, string componentName)
{
_tagHelperComponentProcessed(logger, componentName, null);
}
public static void GeneratedCodeToAssemblyCompilationEnd(this ILogger logger, string filePath, long startTimestamp)
{
// Don't log if logging wasn't enabled at start of request as time will be wildly wrong.
if (startTimestamp != 0 && logger.IsEnabled(LogLevel.Debug))
{
var currentTimestamp = Stopwatch.GetTimestamp();
var elapsed = new TimeSpan((long)(TimestampToTicks * (currentTimestamp - startTimestamp)));
_generatedCodeToAssemblyCompilationEnd(logger, filePath, elapsed.TotalMilliseconds, null);
}
}
}
}
| |
/*
Copyright 2019 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.Linq;
using System.Text;
using System.Threading.Tasks;
using ArcGIS.Desktop.Framework;
using ArcGIS.Desktop.Framework.Contracts;
using ArcGIS.Desktop.Mapping.Controls;
using ArcGIS.Desktop.Mapping;
using ArcGIS.Core.CIM;
using ArcGIS.Desktop.Mapping.Events;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using System.Windows.Input;
namespace QueryBuilderControl
{
internal class DefinitionQueryDockPaneViewModel : DockPane
{
private const string _dockPaneID = "QueryBuilderControl_DefinitionQueryDockPane";
private string _origExpression;
protected DefinitionQueryDockPaneViewModel() { }
/// <summary>
/// Show the DockPane.
/// </summary>
internal static void Show()
{
DockPane pane = FrameworkApplication.DockPaneManager.Find(_dockPaneID);
if (pane == null)
return;
pane.Activate();
var vm = pane as DefinitionQueryDockPaneViewModel;
if (vm != null && MapView.Active != null)
{
vm.ClearControlProperties();
vm.BuildControlProperties(MapView.Active);
}
}
private bool _subscribed = false;
/// <summary>
/// When visibility of dockpane changes, subscribe or unsubscribe from events.
/// </summary>
/// <param name="isVisible">is the dockpane visible?</param>
protected override void OnShow(bool isVisible)
{
if (isVisible)
{
if (!_subscribed)
{
_subscribed = true;
// connect to events
ArcGIS.Desktop.Mapping.Events.TOCSelectionChangedEvent.Subscribe(OnSelectedLayersChanged);
ArcGIS.Desktop.Core.Events.ProjectClosingEvent.Subscribe(OnProjectClosing);
}
}
else
{
if (_subscribed)
{
_subscribed = false;
// unsubscribe from events
ArcGIS.Desktop.Mapping.Events.TOCSelectionChangedEvent.Unsubscribe(OnSelectedLayersChanged);
ArcGIS.Desktop.Core.Events.ProjectClosingEvent.Unsubscribe(OnProjectClosing);
}
}
base.OnShow(isVisible);
}
#region Properties
/// <summary>
/// Gets and sets the QueryBuilderControlProperties to bind to the QueryBuilderControl.
/// </summary>
private QueryBuilderControlProperties _props = null;
public QueryBuilderControlProperties ControlProperties
{
get { return _props; }
set { SetProperty(ref _props, value); }
}
/// <summary>
/// Gets and sets the query expression in the QueryBuilderControl.
/// </summary>
private string _expression = string.Empty;
public string Expression
{
get { return _expression; }
set { _expression = value; } // doesn't bind in xaml so no need to worry about NotifyPropertyChanged
}
/// <summary>
/// Gets and sets the name of currently selected mapMember.
/// </summary>
private string _mapMemberName;
public string MapMemberName
{
get { return _mapMemberName; }
set { SetProperty(ref _mapMemberName, value); }
}
/// <summary>
/// Gets the Apply command to write query definition to mapMember.
/// </summary>
private RelayCommand _applyCommand;
public ICommand ApplyCommand
{
get
{
if (_applyCommand == null)
_applyCommand = new RelayCommand(() => SaveChanges(), CanSaveChanges);
return _applyCommand;
}
}
#endregion
#region Events
/// <summary>
/// Event handler for ProjectClosing event.
/// </summary>
/// <param name="args">The ProjectClosing arguments.</param>
/// <returns></returns>
private Task OnProjectClosing(ArcGIS.Desktop.Core.Events.ProjectClosingEventArgs args)
{
// if already cancelled, ignore
if (args.Cancel)
return Task.CompletedTask;
// save current changes
SaveChanges();
// reset the control
ClearControlProperties();
return Task.CompletedTask;
}
/// <summary>
/// Event handler for TOCSelectionChangedEvent event
/// </summary>
/// <param name="args">The event arguments.</param>
private void OnSelectedLayersChanged(MapViewEventArgs args)
{
// save current changes
SaveChanges();
// set up for the next selected mapMember
BuildControlProperties(args.MapView);
}
#endregion
/// <summary>
/// Build a QueryBuilderControlProperties for the specified mapView. Finds the first BasicFeatureLayer or StandAloneTable highlighted in the TOC.
/// </summary>
/// <param name="mapView">a mapView.</param>
private void BuildControlProperties(MapView mapView)
{
MapMember mapMember = null;
if (mapView != null)
{
// only interested in basicFeatureLayers ... they are the ones with definition queries
var selectedTOCLayers = mapView.GetSelectedLayers().OfType<BasicFeatureLayer>();
var selectedTOCTables = mapView.GetSelectedStandaloneTables();
// take layers over tables... but only take the first
if (selectedTOCLayers.Count() > 0)
mapMember = selectedTOCLayers.First();
else if (selectedTOCTables.Count() > 0)
mapMember = selectedTOCTables.First();
}
// build the control properties
BuildControlProperties(mapMember);
}
/// <summary>
/// Initialize a QueryBuilderControlProperties with the specified mapMember. Use the current definition query of that mapMember (if it exists) to extend the
/// initialization.
/// </summary>
/// <param name="mapMember">MapMember to initialize the QueryBuilderControlProperties. </param>
private void BuildControlProperties(MapMember mapMember)
{
// find the current definition query for the mapMember
string expression = "";
BasicFeatureLayer fLayer = mapMember as BasicFeatureLayer;
StandaloneTable table = mapMember as StandaloneTable;
if (fLayer != null)
expression = fLayer.DefinitionQuery;
else if (table != null)
expression = table.DefinitionQuery;
// create it
var props = new QueryBuilderControlProperties()
{
MapMember = mapMember,
Expression = expression,
};
// set the binding properties
this.ControlProperties = props;
MapMemberName = mapMember?.Name ?? "";
// keep track of the original expression
_origExpression = expression;
}
/// <summary>
/// Use a null mapMember to reset the QueryBuilderControlProperties.
/// </summary>
private void ClearControlProperties()
{
// reset the control
MapMember mapMember = null;
BuildControlProperties(mapMember);
}
/// <summary>
/// Has the current expression been altered?
/// </summary>
/// <returns>true if the current expression has been altered. False otherwise.</returns>
private bool CanSaveChanges()
{
string newExpression = Expression ?? "";
return (string.Compare(_origExpression, newExpression) != 0);
}
/// <summary>
/// Saves the current expression to the appropriate mapMember according to user response.
/// </summary>
private void SaveChanges()
{
// get the new expression
string newExpression = Expression ?? "";
// is it different?
if (string.Compare(_origExpression, newExpression) != 0)
{
if (ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Expression has changed. Do you wish to save it?", "Definition Query", System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question) == System.Windows.MessageBoxResult.Yes)
{
// update internal var
_origExpression = newExpression;
var fLayer = ControlProperties.MapMember as BasicFeatureLayer;
var table = ControlProperties.MapMember as StandaloneTable;
// update mapMember definition query
QueuedTask.Run(() =>
{
if (fLayer != null)
fLayer.SetDefinitionQuery(newExpression);
else if (table != null)
table.SetDefinitionQuery(newExpression);
});
}
}
}
}
/// <summary>
/// Button implementation to show the DockPane.
/// </summary>
internal class DefinitionQueryDockPane_ShowButton : Button
{
protected override void OnClick()
{
DefinitionQueryDockPaneViewModel.Show();
}
}
}
| |
// Copyright 2018 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 Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.Tasks.Offline;
using Esri.ArcGISRuntime.UI;
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace ArcGISRuntime.WPF.Samples.ExportTiles
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Export tiles",
category: "Layers",
description: "Download tiles to a local tile cache file stored on the device.",
instructions: "Pan and zoom into the desired area, making sure the area is within the red boundary. Click the 'Export tiles' button to start the process. On successful completion you will see a preview of the downloaded tile package.",
tags: new[] { "cache", "download", "export", "local", "offline", "package", "tiles" })]
public partial class ExportTiles
{
// URL to the service tiles will be exported from.
private Uri _serviceUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/World_Street_Map/MapServer");
public ExportTiles()
{
InitializeComponent();
// Call a function to set up the map.
Initialize();
}
private async void Initialize()
{
try
{
// Create the tile layer.
ArcGISTiledLayer myLayer = new ArcGISTiledLayer(_serviceUri);
// Load the layer.
await myLayer.LoadAsync();
// Create the basemap with the layer.
Map myMap = new Map(new Basemap(myLayer))
{
// Set the min and max scale - export task fails if the scale is too big or small.
MaxScale = 5000000,
MinScale = 10000000
};
// Assign the map to the mapview.
MyMapView.Map = myMap;
// Create a new symbol for the extent graphic.
// This is the red box that visualizes the extent for which tiles will be exported.
SimpleLineSymbol myExtentSymbol = new SimpleLineSymbol(SimpleLineSymbolStyle.Solid, Color.Red, 2);
// Create graphics overlay for the extent graphic and apply a renderer.
GraphicsOverlay extentOverlay = new GraphicsOverlay
{
Renderer = new SimpleRenderer(myExtentSymbol)
};
// Add the overlay to the view.
MyMapView.GraphicsOverlays.Add(extentOverlay);
// Subscribe to changes in the mapview's viewpoint so the preview box can be kept in position.
MyMapView.ViewpointChanged += MyMapView_ViewpointChanged;
// Update the graphic - needed in case the user decides not to interact before pressing the button.
UpdateMapExtentGraphic();
// Enable the export button.
MyExportButton.IsEnabled = true;
// Set viewpoint of the map.
MyMapView.SetViewpoint(new Viewpoint(-4.853791, 140.983598, myMap.MinScale));
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void MyMapView_ViewpointChanged(object sender, EventArgs e)
{
UpdateMapExtentGraphic();
}
/// <summary>
/// Function used to keep the overlaid preview area marker in position.
/// This is called by MyMapView_ViewpointChanged every time the user pans/zooms
/// and updates the red box graphic to outline 80% of the current view.
/// </summary>
private void UpdateMapExtentGraphic()
{
// Return if mapview is null.
if (MyMapView == null) { return; }
// Get the new viewpoint.
Viewpoint myViewPoint = MyMapView.GetCurrentViewpoint(ViewpointType.BoundingGeometry);
// Return if viewpoint is null.
if (myViewPoint == null) { return; }
// Get the updated extent for the new viewpoint.
Envelope extent = myViewPoint.TargetGeometry as Envelope;
// Return if extent is null.
if (extent == null) { return; }
// Create an envelope that is a bit smaller than the extent.
EnvelopeBuilder envelopeBldr = new EnvelopeBuilder(extent);
envelopeBldr.Expand(0.80);
// Get the (only) graphics overlay in the map view.
GraphicsOverlay extentOverlay = MyMapView.GraphicsOverlays.FirstOrDefault();
// Return if the extent overlay is null.
if (extentOverlay == null) { return; }
// Get the extent graphic.
Graphic extentGraphic = extentOverlay.Graphics.FirstOrDefault();
// Create the extent graphic and add it to the overlay if it doesn't exist.
if (extentGraphic == null)
{
extentGraphic = new Graphic(envelopeBldr.ToGeometry());
extentOverlay.Graphics.Add(extentGraphic);
}
else
{
// Otherwise, simply update the graphic's geometry.
extentGraphic.Geometry = envelopeBldr.ToGeometry();
}
}
private async Task StartExport()
{
// Get the parameters for the job.
ExportTileCacheParameters parameters = GetExportParameters();
// Create the task.
ExportTileCacheTask exportTask = await ExportTileCacheTask.CreateAsync(_serviceUri);
// Get the tile cache path.
string tilePath = Path.Combine(Environment.ExpandEnvironmentVariables("%TEMP%"), Path.GetTempFileName() + ".tpk");
// Create the export job.
ExportTileCacheJob job = exportTask.ExportTileCache(parameters, tilePath);
// Start the export job.
job.Start();
// Wait for the job to complete.
TileCache resultTileCache = await job.GetResultAsync();
// Do the rest of the work.
await HandleExportCompleted(job, resultTileCache);
}
private async Task HandleExportCompleted(ExportTileCacheJob job, TileCache cache)
{
if (job.Status == Esri.ArcGISRuntime.Tasks.JobStatus.Succeeded)
{
// Show the exported tiles on the preview map.
await UpdatePreviewMap(cache);
// Show the preview window.
MyPreviewMapView.Visibility = Visibility.Visible;
// Show the 'close preview' button.
MyClosePreviewButton.Visibility = Visibility.Visible;
// Hide the 'export tiles' button.
MyExportButton.Visibility = Visibility.Collapsed;
// Hide the progress bar.
MyProgressBar.Visibility = Visibility.Collapsed;
}
else if (job.Status == Esri.ArcGISRuntime.Tasks.JobStatus.Failed)
{
// Notify the user.
MessageBox.Show("Job failed");
// Hide the progress bar.
MyProgressBar.Visibility = Visibility.Collapsed;
}
}
private ExportTileCacheParameters GetExportParameters()
{
// Create a new ExportTileCacheParameters instance.
ExportTileCacheParameters parameters = new ExportTileCacheParameters();
// Get the (only) graphics overlay in the map view.
GraphicsOverlay extentOverlay = MyMapView.GraphicsOverlays.First();
// Get the area selection graphic's extent.
Graphic extentGraphic = extentOverlay.Graphics.First();
// Set the area for the export.
parameters.AreaOfInterest = extentGraphic.Geometry;
// Set the highest possible export quality.
parameters.CompressionQuality = 100;
// Add level IDs 1-9.
// Note: Failing to add at least one Level ID will result in job failure.
for (int x = 1; x < 10; x++)
{
parameters.LevelIds.Add(x);
}
// Return the parameters.
return parameters;
}
private async Task UpdatePreviewMap(TileCache cache)
{
// Load the cache.
await cache.LoadAsync();
// Create a tile layer from the tile cache.
ArcGISTiledLayer myLayer = new ArcGISTiledLayer(cache);
// Show the layer in a new map.
MyPreviewMapView.Map = new Map(new Basemap(myLayer));
}
private async void MyExportButton_Click(object sender, RoutedEventArgs e)
{
try
{
// Show the progress bar.
MyProgressBar.Visibility = Visibility.Visible;
// Hide the preview window.
MyPreviewMapView.Visibility = Visibility.Collapsed;
// Hide the 'close preview' button.
MyClosePreviewButton.Visibility = Visibility.Collapsed;
// Show the 'export tiles' button.
MyExportButton.Visibility = Visibility.Visible;
// Disable the 'export tiles' button.
MyExportButton.IsEnabled = false;
// Start the export.
await StartExport();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void ClosePreview_Click(object sender, RoutedEventArgs e)
{
// Hide the preview map.
MyPreviewMapView.Visibility = Visibility.Collapsed;
// Hide the close preview button.
MyClosePreviewButton.Visibility = Visibility.Collapsed;
// Show the 'export tiles' button.
MyExportButton.Visibility = Visibility.Visible;
// Re-enable the export button.
MyExportButton.IsEnabled = true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using AxiomCoders.PdfTemplateEditor.EditorStuff;
using AxiomCoders.PdfTemplateEditor.Common;
using AxiomCoders.PdfTemplateEditor.Forms;
using System.Windows.Forms;
using System.Drawing;
using System.Xml;
using System.Drawing.Design;
using System.Diagnostics;
namespace AxiomCoders.PdfTemplateEditor.EditorItems
{
[Serializable, System.Reflection.Obfuscation(Exclude = true)]
public class BorderEditor : UITypeEditor
{
BorderPropertyForm editorDialog;
public static Balloon parentBalloon;
public BorderEditor()
{
}
public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
{
editorDialog = new BorderPropertyForm();
editorDialog.SourceBalloon = parentBalloon;
if(DialogResult.OK == editorDialog.ShowDialog())
{
value = true;
EditorController.Instance.ProjectSaved = false;
}else
{
value = false;
}
//value = "Border properties...";
EditorController.Instance.EditorViewer.RefreshView();
return value;// base.EditValue(context, provider, value);
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
}
[System.Reflection.Obfuscation(Exclude = true)]
public abstract class Balloon : EditorItem, DynamicEditorItemInterface
{
private bool availableOnEveryPage = true;
private bool fillingGeneratesNew;
private int fillCapacity;
private bool canGrow = true;
private bool fitToContent = true;
private List<RectangleNormal> rectMatrix = new List<RectangleNormal>();
public RectangleNormal containerRect = new RectangleNormal();
public RectangleNormal positionRect = new RectangleNormal();
public BalloonBorders Borders;
/// <summary>
/// Fill Color for item
/// </summary>
private Color fillColor;
/// <summary>
/// Fill color for balloon
/// </summary>
[Browsable(true), DisplayName("Fill Color")]
public Color FillColor
{
get
{
return fillColor;
}
set
{
fillColor = value;
}
}
/// <summary>
/// balloon from which is this one created. Can be null. Used for preview mode
/// </summary>
private Balloon templateBalloon;
/// <summary>
/// balloon from which is this one created. Can be null. Used for preview mode
/// </summary>
public Balloon TemplateBalloon
{
get { return templateBalloon; }
set { templateBalloon = value; }
}
/// <summary>
/// Default constructor for balloon
/// </summary>
public Balloon()
{
isContainer = true;
fillingGeneratesNew = false;
this.cursor = Cursors.Default;
this.WidthInUnits = 3;
this.HeightInUnits = 3;
this.fillColor = Color.Transparent;
Borders.top = new BalloonBorder(BorderTypes.TOP_BORDER);
Borders.left = new BalloonBorder(BorderTypes.LEFT_BORDER);
Borders.bottom = new BalloonBorder(BorderTypes.BOTTOM_BORDER);
Borders.right = new BalloonBorder(BorderTypes.RIGHT_BORDER);
}
private string sourceDataStream = string.Empty;
[Browsable(true), DisplayName("Border Properties"), Category("Standard"), Description("Edit border properties"), EditorAttribute(typeof(BorderEditor), typeof(UITypeEditor))]
public string BorderProps
{
get
{
BorderEditor.parentBalloon = this;
return "Border properties...";
}
}
/// <summary>
/// Data stream that this balloon uses
/// </summary>
[Browsable(true), DisplayName("Data Stream"), Description("Source Data Stream name of item."), Category("Standard"), EditorAttribute(typeof(ComboBoxPropertyEditor), typeof(UITypeEditor))]
public string SourceDataStream
{
get
{
ComboBoxPropertyEditor.ItemList = null;
int tmpCount = EditorController.Instance.EditorProject.DataStreams.Count;
if(tmpCount > 0)
{
string[] tmpList = new string[tmpCount];
int i = 0;
foreach(DataStream tmpItem in EditorController.Instance.EditorProject.DataStreams)
{
tmpList[i] = tmpItem.Name;
i++;
}
ComboBoxPropertyEditor.ItemList = tmpList;
}
return sourceDataStream;
}
set
{
string tmpValue = this.sourceDataStream;
if(this is DynamicBalloon && this.Parent is DynamicBalloon)
{
DynamicBalloon tmpItem = (DynamicBalloon)this.Parent;
if(tmpItem.SourceDataStream == value)
{
MessageBox.Show("You can't put same data stream as it is on Items parent!", "Invalid value");
sourceDataStream = tmpValue;
}else{
sourceDataStream = value;
}
}else{
sourceDataStream = value;
}
}
}
[Browsable(false)]
public string SourceColumn
{
get
{
return string.Empty;
}
set
{
//sourceColumn = value;
}
}
public Balloon(string name, string dataStream)
{
this.Name = name;
this.SourceDataStream = dataStream;
}
protected override void CreateCommands()
{
base.CreateCommands();
if (dockPosition == DockingPosition.DOCK_NONE)
{
CommandItem command;
command = new MovingCommandItem(this);
this.commands.Add(command);
}
}
/// <summary>
/// Load balloon properties
/// </summary>
/// <param name="txR"></param>
public override void Load(System.Xml.XmlNode element)
{
base.Load(element);
XmlAttribute attr = (XmlAttribute)element.Attributes.GetNamedItem("DataStream");
if (attr != null)
{
this.SourceDataStream = attr.Value;
}
XmlNode node = element.SelectSingleNode("AvailableOnEveryPage");
if (node != null)
{
this.AvailableOnEveryPage = Convert.ToBoolean(node.Attributes["Value"].Value);
}
node = element.SelectSingleNode("FitToContent");
if (node != null)
{
this.FitToContent = Convert.ToBoolean(node.Attributes["Value"].Value);
}
node = element.SelectSingleNode("FillingGeneratesNew");
if (node != null)
{
this.FillingGeneratesNew = Convert.ToBoolean(node.Attributes["Value"].Value);
}
node = element.SelectSingleNode("FillCapacity");
if (node != null)
{
this.FillCapacity = Convert.ToInt32(node.Attributes["Value"].Value);
}
node = element.SelectSingleNode("CanGrow");
if (node != null)
{
this.CanGrow = Convert.ToBoolean(node.Attributes["Value"].Value);
}
// Load fill color
node = element.SelectSingleNode("FillColor");
if (node != null)
{
try
{
int r = Convert.ToInt32(node.Attributes["R"].Value);
int g = Convert.ToInt32(node.Attributes["G"].Value);
int b = Convert.ToInt32(node.Attributes["B"].Value);
int a = Convert.ToInt32(node.Attributes["A"].Value);
this.FillColor = Color.FromArgb(a, r, g, b);
}
catch { }
}
this.Borders.top.Load(element);
this.Borders.left.Load(element);
this.Borders.bottom.Load(element);
this.Borders.right.Load(element);
// EditorController.Instance.MainFormOfTheProject.AddNewEditorItemToList(this);
// Load items
node = element.SelectSingleNode("Items");
if (node != null)
{
foreach(XmlNode itemNode in node.ChildNodes)
{
if (itemNode.Name == "Item")
{
LoadItem(itemNode);
}
}
}
// Load other child balloons
node = element.SelectSingleNode("Balloons");
if (node != null)
{
foreach(XmlNode balloonNode in node.ChildNodes)
{
if (balloonNode.Name == "Balloon")
{
string tmpType;
tmpType = balloonNode.Attributes["Type"].Value;
if (tmpType == "Static")
{
StaticBalloon child = new StaticBalloon();
//child.Parent = this;
child.Load(balloonNode);
child.Parent = this;
//Children.Add(child);
}
else if (tmpType == "Dynamic")
{
DynamicBalloon child = new DynamicBalloon();
//child.Parent = this;
child.Load(balloonNode);
child.Parent = this;
//Children.Add(child);
}
}
}
}
}
/// <summary>
/// Load item from node
/// </summary>
/// <param name="itemNode"></param>
private void LoadItem(XmlNode itemNode)
{
string itemType = "";
if (itemNode.Attributes.Count > 0)
{
itemType = itemNode.Attributes["Type"].Value;
EditorItem newItem = ReportPage.CreateItemFromType(itemType);
//newItem.Parent = this;
newItem.Load(itemNode);
newItem.Parent = this;
//Children.Add(newItem);
}
}
/// <summary>
/// Save item
/// </summary>
/// <param name="txW"></param>
public override void SaveItem(XmlDocument doc, XmlElement element)
{
// save base attributes and child nodes
base.SaveItem(doc, element);
// save Type
XmlAttribute attr = doc.CreateAttribute("Type");
attr.Value = this is StaticBalloon ? "Static" : "Dynamic";
element.SetAttributeNode(attr);
attr = doc.CreateAttribute("Version");
attr.Value = "1.0";
element.SetAttributeNode(attr);
attr = doc.CreateAttribute("DataStream");
attr.Value = this.SourceDataStream;
element.SetAttributeNode(attr);
XmlElement el = doc.CreateElement("AvailableOnEveryPage");
attr = doc.CreateAttribute("Value");
attr.Value = AvailableOnEveryPage.ToString();
el.SetAttributeNode(attr);
element.AppendChild(el);
el = doc.CreateElement("FitToContent");
attr = doc.CreateAttribute("Value");
attr.Value = FitToContent.ToString();
el.SetAttributeNode(attr);
element.AppendChild(el);
el = doc.CreateElement("FillingGeneratesNew");
attr = doc.CreateAttribute("Value");
attr.Value = this.FillingGeneratesNew.ToString();
el.SetAttributeNode(attr);
element.AppendChild(el);
el = doc.CreateElement("FillCapacity");
attr = doc.CreateAttribute("Value");
attr.Value = this.FillCapacity.ToString();
el.SetAttributeNode(attr);
element.AppendChild(el);
el = doc.CreateElement("CanGrow");
attr = doc.CreateAttribute("Value");
attr.Value = this.CanGrow.ToString();
el.SetAttributeNode(attr);
element.AppendChild(el);
// FillColor
el = doc.CreateElement("FillColor");
attr = doc.CreateAttribute("R"); attr.Value = this.FillColor.R.ToString(); el.SetAttributeNode(attr);
attr = doc.CreateAttribute("G"); attr.Value = this.FillColor.G.ToString(); el.SetAttributeNode(attr);
attr = doc.CreateAttribute("B"); attr.Value = this.FillColor.B.ToString(); el.SetAttributeNode(attr);
attr = doc.CreateAttribute("A"); attr.Value = this.FillColor.A.ToString(); el.SetAttributeNode(attr);
element.AppendChild(el);
this.Borders.top.SaveItem(doc, element);
this.Borders.left.SaveItem(doc, element);
this.Borders.bottom.SaveItem(doc, element);
this.Borders.right.SaveItem(doc, element);
// save children items and child balloons
el = doc.CreateElement("Balloons");
foreach(EditorItem item in this.Children)
{
if (item is Balloon)
{
item.Save(doc, el);
}
}
element.AppendChild(el);
// save items
el = doc.CreateElement("Items");
foreach(EditorItem item in this.Children)
{
if (!(item is Balloon))
{
item.Save(doc, el);
}
}
element.AppendChild(el);
}
public Balloon sourceBallon = null;
/// <summary>
/// If this balloon should be used on all pages.
/// </summary>
[Browsable(true), DisplayName("Available On Every Page"), Description("If this balloon should be used on all pages.")]
public bool AvailableOnEveryPage
{
get
{
return availableOnEveryPage;
}
set
{
availableOnEveryPage = value;
}
}
/// <summary>
/// If this balloon should be used on all pages.
/// </summary>
[Browsable(true), DisplayName("Fit To Content"), Description("Should balloon size be auto-changed to size of its content during generating process.")]
public virtual bool FitToContent
{
get
{
return fitToContent;
}
set
{
fitToContent = value;
}
}
/// <summary>
/// If this balloon is filled with some other balloons then new balloon of this type will be generated.
/// </summary>
[Browsable(false), Description("If this balloon is filled with some other balloons then new balloon of this type will be generated.")]
public bool FillingGeneratesNew
{
get
{
return fillingGeneratesNew;
}
set
{
fillingGeneratesNew = value;
}
}
/// <summary>
/// If more than this number of dynamic balloons is reached balloon will try to generate another one, or stop dynamic generation, 0 = infinite.
/// </summary>
[Browsable(true), DisplayName("Fill Capacity"), Description("If more than this number of dynamic balloons is reached balloon will try to generate another one, or stop dynamic generation, 0 = infinite.")]
public int FillCapacity
{
get
{
return fillCapacity;
}
set
{
if (value < 0)
{
fillCapacity = 0;
}
else
{
fillCapacity = value;
}
}
}
/// <summary>
/// Count number of dynamic child balloons
/// </summary>
private int DynamicChildBalloons
{
get
{
// count child balloons
int childBalloons = 0;
foreach (EditorItem item in this.Children)
{
if (item is DynamicBalloon)
{
childBalloons++;
}
}
return childBalloons;
}
}
private int ChildBalloons
{
get
{
// count child balloons
int childBalloons = 0;
foreach (EditorItem item in this.Children)
{
if (item is Balloon)
{
childBalloons++;
}
}
return childBalloons;
}
}
/// <summary>
/// Is this balloon allowed to grow when there is no more place. Page is the only entity that cannot grow
/// </summary>
[Description("Is this balloon allowed to grow when there is no more place. Page is the only entity that cannot grow")]
public virtual bool CanGrow
{
get
{
if (canGrow)
{
if (this.FillCapacity <= 0 || DynamicChildBalloons <= this.FillCapacity)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
set
{
canGrow = value;
}
}
public bool GrowBalloon(Balloon generatedBalloon, float growDelta)
{
RectangleNormal rect1 = new RectangleNormal();
RectangleNormal rect2 = new RectangleNormal();
Debug.Assert(growDelta >= -Epsilon , "Grow Delta Should never be negative");
// check what generate algorithm is used and do logic from that
//if (generatedBalloon->generatingAlgorithm == GENERATING_ALGORITHM_RIGHT_BOTTOM)
{
// this means we can grow only on bottom. growDelta contains info how much we need to grow
// 1. Grow Parent if can grow
if(this.Parent != null)
{
// check if parent needs to grow at all
// rect of parent
rect1.top = 0;
rect1.left = 0;
rect1.right = this.Parent.WidthInPixels;
rect1.bottom = this.Parent.HeightInPixels;
//desired rect after growth. Growth to allow generatedBalloon to fall in
rect2.left = this.positionRect.left;
rect2.top = this.positionRect.top;
rect2.bottom = (rect2.top + this.HeightInPixels + growDelta);
rect2.right = (rect2.left + this.WidthInPixels);
if(rect1.Contains(rect2))
{
// check if we intersect some rectangle in rectMatrix and in case we do return false
foreach(RectangleNormal rect in this.Parent.rectMatrix)
{
// if rect.top != rect2.top && rect.left != rect2.left - or if this is not the same rect which already has taken place
// and if it does insterest something return false
if (!(System.Math.Abs(rect.top - rect2.top) < Epsilon &&
System.Math.Abs(rect.left - rect2.left) < Epsilon) &&
rect.Intersect(rect2))
{
return false;
}
}
// we don't need to grow parent just increase size of self
this.HeightInPixels += growDelta;
this.containerRect.bottom += growDelta;
}
else
{
// can parent grow at all
if(this.CanGrow)
{
// grow parent
if(this.Parent is Balloon)
{
Balloon parentBallon = (Balloon)this.Parent;
if(parentBallon.CanGrow && parentBallon.GrowBalloon(generatedBalloon, growDelta))
{
this.HeightInPixels += growDelta;
this.containerRect.bottom += growDelta;
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
// cannot increase size return FALSE
return false;
}
}
}
else
{
// no parent ... grow in height by required size.
this.HeightInPixels += growDelta;
this.containerRect.bottom += growDelta;
}
this.positionRect.bottom = rect2.bottom;
}
//if (generatedBalloon->generatingAlgorithm == GENERATING_ALGORITHM_BOTTOM_RIGHT)
//{
// // this means we can grow only on left
// // TODO: Not implemented yet
//}
return true;
}
/// <summary>
/// This will return real width of balloon considering its static ballon children
/// If FitToContent is false it will return real WidthInPixels value
/// </summary>
/// <returns></returns>
public float GetFitToContentWidthInPixels()
{
return this.WidthInPixels;
}
/// <summary>
/// This will return real height of balloon considering its static ballon children
/// </summary>
/// <returns></returns>
public float GetFitToContentHeightInPixels()
{
float res = 0;
float heightToAdd = 0;
if (this.FitToContent)
{
// if it is empty and has no other child balloons then result should be its own Width
if (this.ChildBalloons == 0)
{
res = this.HeightInPixels;
}
else
{
// count child static balloons and width should be the right most one
foreach (EditorItem item in this.Children)
{
if (item is StaticBalloon)
{
StaticBalloon sb = item as StaticBalloon;
// handle docking to get this information
if (sb.DockPosition == DockingPosition.DOCK_BOTTOM)
{
// static docked balloons are just adding additional minimal hight
heightToAdd += sb.HeightInPixels;
}
else
{
float tmpRes = sb.LocationInPixelsY + sb.GetFitToContentHeightInPixels();
if (tmpRes > res)
{
res = tmpRes;
}
}
}
}
}
}
else
{
// FitToContent is false, so just return HeightInPixels
res = this.HeightInPixels;
}
return res + heightToAdd;
}
/// <summary>
/// Adds new child to this balloon and performs resize if necessary.
///
/// </summary>
/// <param name="generatedBalloon">newly created balloon that needs to fit into this one</param>
/// <param name="staticBalloonFlag">this flag is true if generated balloon should be threated as static. if true
/// then it is put exactly where it should be. If this is true staticDockedBottomFlag is ignored</param>
/// <param name="staticDockedBottomFlag">Flag that tells if this should be threated as static bottom docked ballooon. </param>
/// <returns></returns>
public override bool AddChild(Balloon generatedBalloon, bool staticBalloonFlag, bool staticDockedBottomFlag)
{
RectangleNormal newRect = new RectangleNormal();
if(staticBalloonFlag)
{
// add it to the list
this.AddChildToList(generatedBalloon);
}
else
{
// if there is no room for another child here
if (this.FillCapacity > 0 && (this.DynamicChildBalloons + 1 > this.FillCapacity) && !staticDockedBottomFlag)
{
return false;
}
if(!this.GetNewRect(generatedBalloon, ref newRect))
{
if(this.CanGrow)
{
// we established that balloon need to grow to put this new one inside and determined ammount of grow
// we need to check if grow is allowed on parents side (maybe it is already taken on parents size and allocated in
// rect matrix. this is checked before grow
if(this.GrowBalloon(generatedBalloon, generatedBalloon.HeightInPixels - (this.HeightInPixels - newRect.top)))
{
return this.AddChild(generatedBalloon, staticBalloonFlag, staticDockedBottomFlag);
}
else
{
return false;
}
}
else
{
return false;
}
}
else
{
if (staticDockedBottomFlag && !this.FitToContent)
{
// in case this one is static docked bottom and we wont to put him on the bottom of this balloon
newRect.top = this.containerRect.bottom - (newRect.bottom - newRect.top);
newRect.bottom = this.containerRect.bottom;
generatedBalloon.WidthInPixels = newRect.right - newRect.left;
generatedBalloon.HeightInPixels = newRect.bottom - newRect.top;
generatedBalloon.positionRect.top = newRect.top;
generatedBalloon.positionRect.left = newRect.left;
generatedBalloon.containerRect = newRect;
}
else
{
generatedBalloon.WidthInPixels = newRect.right - newRect.left;
generatedBalloon.HeightInPixels = newRect.bottom - newRect.top;
generatedBalloon.positionRect.top = newRect.top;
generatedBalloon.positionRect.left = newRect.left;
generatedBalloon.containerRect = newRect;
}
this.AddChildToList(generatedBalloon);
}
// 1. ask for free space and get new rect for it
// 2. in case there is no space
// check for conditions to grow
// try to grow this balloon (also parents). Return which one failed growing if anyone failed and return FALSE
// if balloon grew goto 1.
// if cannot grow return false
// 3. in case there is enough space.
// move new balloon to the rect position and set position and sizes to structure
// add balloon to rect List and return true.
}
return true;
}
/// <summary>
/// Display item
/// </summary>
/// <param name="gc"></param>
public override void DisplayItem(Graphics gc)
{
using (SolidBrush brush = new SolidBrush(fillColor))
{
gc.FillRectangle(brush, 0, 0, (float)this.WidthInPixels, (float)this.HeightInPixels);
}
}
public void DrawBorders(Graphics gc)
{
this.Borders.top.Draw(this, gc);
this.Borders.left.Draw(this, gc);
this.Borders.bottom.Draw(this, gc);
this.Borders.right.Draw(this, gc);
}
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Fixtures.DateTimeOffset
{
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Models;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// A sample API that tests datetimeoffset usage for date-time
/// </summary>
public partial class SwaggerDateTimeOffsetClient : ServiceClient<SwaggerDateTimeOffsetClient>, ISwaggerDateTimeOffsetClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public System.Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Initializes a new instance of the SwaggerDateTimeOffsetClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SwaggerDateTimeOffsetClient(params DelegatingHandler[] handlers) : base(handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerDateTimeOffsetClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
public SwaggerDateTimeOffsetClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
Initialize();
}
/// <summary>
/// Initializes a new instance of the SwaggerDateTimeOffsetClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerDateTimeOffsetClient(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the SwaggerDateTimeOffsetClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="System.ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
public SwaggerDateTimeOffsetClient(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new System.ArgumentNullException("baseUri");
}
BaseUri = baseUri;
}
/// <summary>
/// An optional partial-method to perform custom initialization.
///</summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
BaseUri = new System.Uri("http://localhost:3000/api");
SerializationSettings = new JsonSerializerSettings
{
Formatting = Newtonsoft.Json.Formatting.Indented,
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc,
NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore,
ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
}
/// <summary>
/// Product Types
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Product>> GetProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "GetProduct", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("GET");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (responseCode != null)
{
if (_httpRequest.Headers.Contains("response-code"))
{
_httpRequest.Headers.Remove("response-code");
}
_httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = SafeJsonConvert.SerializeObject(product, SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Product>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Product Types
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Product>> PutProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PutProduct", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PUT");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (responseCode != null)
{
if (_httpRequest.Headers.Contains("response-code"))
{
_httpRequest.Headers.Remove("response-code");
}
_httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = SafeJsonConvert.SerializeObject(product, SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Product>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Product Types
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Product>> PostProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PostProduct", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("POST");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (responseCode != null)
{
if (_httpRequest.Headers.Contains("response-code"))
{
_httpRequest.Headers.Remove("response-code");
}
_httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = SafeJsonConvert.SerializeObject(product, SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Product>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
/// <summary>
/// Product Types
/// </summary>
/// <param name='responseCode'>
/// The desired returned status code
/// </param>
/// <param name='product'>
/// The only parameter
/// </param>
/// <param name='customHeaders'>
/// Headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <return>
/// A response object containing the response body and response headers.
/// </return>
public async Task<HttpOperationResponse<Product>> PatchProductWithHttpMessagesAsync(string responseCode = default(string), Product product = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken))
{
// Tracing
bool _shouldTrace = ServiceClientTracing.IsEnabled;
string _invocationId = null;
if (_shouldTrace)
{
_invocationId = ServiceClientTracing.NextInvocationId.ToString();
Dictionary<string, object> tracingParameters = new Dictionary<string, object>();
tracingParameters.Add("responseCode", responseCode);
tracingParameters.Add("product", product);
tracingParameters.Add("cancellationToken", cancellationToken);
ServiceClientTracing.Enter(_invocationId, this, "PatchProduct", tracingParameters);
}
// Construct URL
var _baseUrl = BaseUri.AbsoluteUri;
var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "datatypes").ToString();
// Create HTTP transport objects
var _httpRequest = new HttpRequestMessage();
HttpResponseMessage _httpResponse = null;
_httpRequest.Method = new HttpMethod("PATCH");
_httpRequest.RequestUri = new System.Uri(_url);
// Set Headers
if (responseCode != null)
{
if (_httpRequest.Headers.Contains("response-code"))
{
_httpRequest.Headers.Remove("response-code");
}
_httpRequest.Headers.TryAddWithoutValidation("response-code", responseCode);
}
if (customHeaders != null)
{
foreach(var _header in customHeaders)
{
if (_httpRequest.Headers.Contains(_header.Key))
{
_httpRequest.Headers.Remove(_header.Key);
}
_httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value);
}
}
// Serialize Request
string _requestContent = null;
if(product != null)
{
_requestContent = SafeJsonConvert.SerializeObject(product, SerializationSettings);
_httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8);
_httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8");
}
// Send Request
if (_shouldTrace)
{
ServiceClientTracing.SendRequest(_invocationId, _httpRequest);
}
cancellationToken.ThrowIfCancellationRequested();
_httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false);
if (_shouldTrace)
{
ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse);
}
HttpStatusCode _statusCode = _httpResponse.StatusCode;
cancellationToken.ThrowIfCancellationRequested();
string _responseContent = null;
if ((int)_statusCode != 200)
{
var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
try
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings);
if (_errorBody != null)
{
ex.Body = _errorBody;
}
}
catch (JsonException)
{
// Ignore the exception
}
ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent);
ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);
if (_shouldTrace)
{
ServiceClientTracing.Error(_invocationId, ex);
}
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw ex;
}
// Create Result
var _result = new HttpOperationResponse<Product>();
_result.Request = _httpRequest;
_result.Response = _httpResponse;
// Deserialize Response
if ((int)_statusCode == 200)
{
_responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
try
{
_result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, DeserializationSettings);
}
catch (JsonException ex)
{
_httpRequest.Dispose();
if (_httpResponse != null)
{
_httpResponse.Dispose();
}
throw new SerializationException("Unable to deserialize the response.", _responseContent, ex);
}
}
if (_shouldTrace)
{
ServiceClientTracing.Exit(_invocationId, _result);
}
return _result;
}
}
}
| |
using System;
using System.Linq;
using Shouldly;
using Spectre.Cli.Internal.Configuration;
using Spectre.Cli.Internal.Exceptions;
using Spectre.Cli.Internal.Modelling;
using Spectre.Cli.Tests.Data;
using Spectre.Cli.Tests.Data.Settings;
using Xunit;
namespace Spectre.Cli.Tests.Unit.Internal.Modelling
{
public sealed class CommandModelBuilderTests
{
[Fact]
public void Should_Set_Parents_Correctly()
{
// Given
var configurator = new Configurator(null);
configurator.AddBranch<AnimalSettings>("animal", animal =>
{
animal.AddBranch<MammalSettings>("mammal", mammal =>
{
mammal.AddCommand<DogCommand>("dog");
mammal.AddCommand<HorseCommand>("horse");
});
});
// When
var model = CommandModelBuilder.Build(configurator);
// Then
model.Commands.Count.ShouldBe(1);
model.Commands[0].As(animal =>
{
animal.Parent.ShouldBeNull();
animal.Children.Count.ShouldBe(1);
animal.Children[0].As(mammal =>
{
mammal.Parent.ShouldBe(animal);
mammal.Children.Count.ShouldBe(2);
mammal.Children[0].As(dog => dog.Parent.ShouldBe(mammal));
mammal.Children[1].As(horse => horse.Parent.ShouldBe(mammal));
});
});
}
[Fact]
public void Should_Set_Descriptions_For_Branches()
{
// Given
var configurator = new Configurator(null);
configurator.AddBranch<AnimalSettings>("animal", animal =>
{
animal.SetDescription("An animal");
animal.AddBranch<MammalSettings>("mammal", mammal =>
{
mammal.SetDescription("A mammal");
mammal.AddCommand<DogCommand>("dog");
mammal.AddCommand<HorseCommand>("horse");
});
});
// When
var model = CommandModelBuilder.Build(configurator);
// Then
model.Commands[0].As(animal =>
{
animal.Description.ShouldBe("An animal");
animal.Children[0].As(mammal => mammal.Description.ShouldBe("A mammal"));
});
}
[Fact]
public void Should_Set_TypeConverter_For_Options()
{
// Given
var configurator = new Configurator(null);
configurator.AddCommand<CatCommand>("cat");
// When
var model = CommandModelBuilder.Build(configurator);
// Then
model.Commands[0]
.GetOption(option => option.LongNames.Contains("agility", StringComparer.Ordinal))
.Converter.ConverterTypeName
.ShouldStartWith("Spectre.Cli.Tests.Data.Converters.CatAgilityConverter");
}
[Fact]
public void Should_Shadow_Options_Declared_In_Parent_Command_If_Settings_Are_Of_Same_Type()
{
// Given
var configurator = new Configurator(null);
configurator.AddBranch<MammalSettings>("mammal", mammal =>
{
mammal.AddCommand<HorseCommand>("horse");
});
// When
var model = CommandModelBuilder.Build(configurator);
// Then
model.Commands[0].As(mammal =>
{
mammal.GetOption(option => option.LongNames.Contains("name", StringComparer.Ordinal)).As(o1 =>
{
o1.ShouldNotBeNull();
o1.IsShadowed.ShouldBe(false);
});
mammal.Children[0].As(horse =>
{
horse.GetOption(option => option.LongNames.Contains("name", StringComparer.Ordinal)).As(o2 =>
{
o2.ShouldNotBeNull();
o2.IsShadowed.ShouldBe(true);
});
});
});
}
[Fact]
public void Should_Make_Shadowed_Options_Non_Required()
{
// Given
var configurator = new Configurator(null);
configurator.AddBranch<MammalSettings>("mammal", mammal =>
{
mammal.AddCommand<HorseCommand>("horse");
});
// When
var model = CommandModelBuilder.Build(configurator);
// Then
model.Commands[0].As(mammal =>
{
mammal.Children[0].As(horse =>
{
horse.GetOption(option => option.LongNames.Contains("name", StringComparer.Ordinal)).As(o2 =>
{
o2.ShouldNotBeNull();
o2.Required.ShouldBe(false);
});
});
});
}
[Fact]
public void Should_Set_Default_Value_For_Options()
{
// Given
var configurator = new Configurator(null);
configurator.AddCommand<CatCommand>("cat");
// When
var model = CommandModelBuilder.Build(configurator);
// Then
model.Commands[0]
.GetOption(option => option.LongNames.Contains("agility", StringComparer.Ordinal))
.DefaultValue.Value.ShouldBe(10);
}
[Fact]
public void Should_Generate_Correct_Model_For_Default_Command()
{
// Given
var configurator = new Configurator(null);
configurator.SetDefaultCommand<DogCommand>();
// When
var model = CommandModelBuilder.Build(configurator);
// Then
model.DefaultCommand.ShouldNotBeNull();
model.DefaultCommand.As(command =>
{
command.CommandType.ShouldBe<DogCommand>();
command.SettingsType.ShouldBe<DogSettings>();
command.Children.Count.ShouldBe(0);
command.Description.ShouldBe("The dog command.");
command.IsBranch.ShouldBeFalse();
command.Name.ShouldBe("__default_command");
command.Parent.ShouldBeNull();
});
}
/// <summary>
/// https://github.com/spectresystems/spectre.cli/wiki/Test-cases#test-case-1
/// </summary>
[Theory]
[EmbeddedResourceData("Spectre.Cli.Tests/Data/Resources/Models/case1.xml")]
public void Should_Generate_Correct_Model_For_Case_1(string expected)
{
// Given, When
var result = CommandModelSerializer.Serialize(config =>
{
config.AddBranch<AnimalSettings>("animal", animal =>
{
animal.AddBranch<MammalSettings>("mammal", mammal =>
{
mammal.AddCommand<DogCommand>("dog");
mammal.AddCommand<HorseCommand>("horse");
});
});
});
// Then
result.ShouldBe(expected);
}
/// <summary>
/// https://github.com/spectresystems/spectre.cli/wiki/Test-cases#test-case-2
/// </summary>
[Theory]
[EmbeddedResourceData("Spectre.Cli.Tests/Data/Resources/Models/case2.xml")]
public void Should_Generate_Correct_Model_For_Case_2(string expected)
{
// Given, When
var result = CommandModelSerializer.Serialize(config =>
{
config.AddCommand<DogCommand>("dog");
});
// Then
result.ShouldBe(expected);
}
/// <summary>
/// https://github.com/spectresystems/spectre.cli/wiki/Test-cases#test-case-3
/// </summary>
[Theory]
[EmbeddedResourceData("Spectre.Cli.Tests/Data/Resources/Models/case3.xml")]
public void Should_Generate_Correct_Model_For_Case_3(string expected)
{
// Given, When
var result = CommandModelSerializer.Serialize(config =>
{
config.AddBranch<AnimalSettings>("animal", animal =>
{
animal.AddCommand<DogCommand>("dog");
animal.AddCommand<HorseCommand>("horse");
});
});
// Then
result.ShouldBe(expected);
}
/// <summary>
/// https://github.com/spectresystems/spectre.cli/wiki/Test-cases#test-case-4
/// </summary>
[Theory]
[EmbeddedResourceData("Spectre.Cli.Tests/Data/Resources/Models/case4.xml")]
public void Should_Generate_Correct_Model_For_Case_4(string expected)
{
// Given, When
var result = CommandModelSerializer.Serialize(config =>
{
config.AddBranch<AnimalSettings>("animal", animal =>
{
animal.AddCommand<DogCommand>("dog");
});
});
// Then
result.ShouldBe(expected);
}
[Fact]
public void Should_Throw_If_Branch_Has_No_Children()
{
// Given
var configurator = new Configurator(null);
configurator.AddBranch<AnimalSettings>("animal", _ =>
{
});
// When
var result = Record.Exception(() => CommandModelBuilder.Build(configurator));
// Then
result.ShouldBeOfType<ConfigurationException>().And(exception =>
exception.Message.ShouldBe("The branch 'animal' does not define any commands."));
}
[Fact]
public void Should_Throw_If_No_Commands_Not_Default_Command_Have_Been_Configured()
{
// Given
var configurator = new Configurator(null);
// When
var result = Record.Exception(() => CommandModelBuilder.Build(configurator));
// Then
result.ShouldBeOfType<ConfigurationException>().And(exception =>
exception.Message.ShouldBe("No commands have been configured."));
}
[Fact]
public void Should_Not_Throw_If_No_Commands_Have_Been_Configured_But_A_Default_Command_Has()
{
// Given
var configurator = new Configurator(null);
configurator.SetDefaultCommand<DogCommand>();
// When
var result = CommandModelBuilder.Build(configurator);
// Then
result.DefaultCommand.ShouldNotBeNull();
}
}
}
| |
using J2N;
using YAF.Lucene.Net.Support;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
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.
*/
using Directory = YAF.Lucene.Net.Store.Directory;
/// <summary>
/// This class emulates the new Java 7 "Try-With-Resources" statement.
/// Remove once Lucene is on Java 7.
/// <para/>
/// @lucene.internal
/// </summary>
[ExceptionToClassNameConvention]
public sealed class IOUtils
{
/// <summary>
/// UTF-8 <see cref="Encoding"/> instance to prevent repeated
/// <see cref="Encoding.UTF8"/> lookups </summary>
[Obsolete("Use Encoding.UTF8 instead.")]
public static readonly Encoding CHARSET_UTF_8 = Encoding.UTF8;
/// <summary>
/// UTF-8 charset string.
/// <para/>Where possible, use <see cref="Encoding.UTF8"/> instead,
/// as using the <see cref="string"/> constant may slow things down. </summary>
/// <seealso cref="Encoding.UTF8"/>
public static readonly string UTF_8 = "UTF-8";
private IOUtils() // no instance
{
}
/// <summary>
/// <para>Disposes all given <c>IDisposable</c>s, suppressing all thrown exceptions. Some of the <c>IDisposable</c>s
/// may be <c>null</c>, they are ignored. After everything is disposed, method either throws <paramref name="priorException"/>,
/// if one is supplied, or the first of suppressed exceptions, or completes normally.</para>
/// <para>Sample usage:
/// <code>
/// IDisposable resource1 = null, resource2 = null, resource3 = null;
/// ExpectedException priorE = null;
/// try
/// {
/// resource1 = ...; resource2 = ...; resource3 = ...; // Acquisition may throw ExpectedException
/// ..do..stuff.. // May throw ExpectedException
/// }
/// catch (ExpectedException e)
/// {
/// priorE = e;
/// }
/// finally
/// {
/// IOUtils.CloseWhileHandlingException(priorE, resource1, resource2, resource3);
/// }
/// </code>
/// </para>
/// </summary>
/// <param name="priorException"> <c>null</c> or an exception that will be rethrown after method completion. </param>
/// <param name="objects"> Objects to call <see cref="IDisposable.Dispose()"/> on. </param>
[Obsolete("Use DisposeWhileHandlingException(Exception, params IDisposable[]) instead.")]
public static void CloseWhileHandlingException(Exception priorException, params IDisposable[] objects)
{
DisposeWhileHandlingException(priorException, objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary>
/// <seealso cref="DisposeWhileHandlingException(Exception, IDisposable[])"/>
[Obsolete("Use DisposeWhileHandlingException(Exception, IEnumerable<IDisposable>) instead.")]
public static void CloseWhileHandlingException(Exception priorException, IEnumerable<IDisposable> objects)
{
DisposeWhileHandlingException(priorException, objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s. Some of the
/// <see cref="IDisposable"/>s may be <c>null</c>; they are
/// ignored. After everything is closed, the method either
/// throws the first exception it hit while closing, or
/// completes normally if there were no exceptions.
/// </summary>
/// <param name="objects">
/// Objects to call <see cref="IDisposable.Dispose()"/> on </param>
[Obsolete("Use Dispose(params IDisposable[]) instead.")]
public static void Close(params IDisposable[] objects)
{
Dispose(objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s. </summary>
/// <seealso cref="Dispose(IDisposable[])"/>
[Obsolete("Use Dispose(IEnumerable<IDisposable>) instead.")]
public static void Close(IEnumerable<IDisposable> objects)
{
Dispose(objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions.
/// Some of the <see cref="IDisposable"/>s may be <c>null</c>, they are ignored.
/// </summary>
/// <param name="objects">
/// Objects to call <see cref="IDisposable.Dispose()"/> on </param>
[Obsolete("Use DisposeWhileHandlingException(params IDisposable[]) instead.")]
public static void CloseWhileHandlingException(params IDisposable[] objects)
{
DisposeWhileHandlingException(objects);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary>
/// <seealso cref="DisposeWhileHandlingException(IEnumerable{IDisposable})"/>
/// <seealso cref="DisposeWhileHandlingException(IDisposable[])"/>
[Obsolete("Use DisposeWhileHandlingException(IEnumerable<IDisposable>) instead.")]
public static void CloseWhileHandlingException(IEnumerable<IDisposable> objects)
{
DisposeWhileHandlingException(objects);
}
// LUCENENET specific - added overloads starting with Dispose... instead of Close...
/// <summary>
/// <para>Disposes all given <c>IDisposable</c>s, suppressing all thrown exceptions. Some of the <c>IDisposable</c>s
/// may be <c>null</c>, they are ignored. After everything is disposed, method either throws <paramref name="priorException"/>,
/// if one is supplied, or the first of suppressed exceptions, or completes normally.</para>
/// <para>Sample usage:
/// <code>
/// IDisposable resource1 = null, resource2 = null, resource3 = null;
/// ExpectedException priorE = null;
/// try
/// {
/// resource1 = ...; resource2 = ...; resource3 = ...; // Acquisition may throw ExpectedException
/// ..do..stuff.. // May throw ExpectedException
/// }
/// catch (ExpectedException e)
/// {
/// priorE = e;
/// }
/// finally
/// {
/// IOUtils.DisposeWhileHandlingException(priorE, resource1, resource2, resource3);
/// }
/// </code>
/// </para>
/// </summary>
/// <param name="priorException"> <c>null</c> or an exception that will be rethrown after method completion. </param>
/// <param name="objects"> Objects to call <see cref="IDisposable.Dispose()"/> on. </param>
public static void DisposeWhileHandlingException(Exception priorException, params IDisposable[] objects)
{
Exception th = null;
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception t)
{
AddSuppressed(priorException ?? th, t);
if (th == null)
{
th = t;
}
}
}
if (priorException != null)
{
throw priorException;
}
else
{
ReThrow(th);
}
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary>
/// <seealso cref="DisposeWhileHandlingException(Exception, IDisposable[])"/>
public static void DisposeWhileHandlingException(Exception priorException, IEnumerable<IDisposable> objects)
{
Exception th = null;
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception t)
{
AddSuppressed(priorException ?? th, t);
if (th == null)
{
th = t;
}
}
}
if (priorException != null)
{
throw priorException;
}
else
{
ReThrow(th);
}
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s. Some of the
/// <see cref="IDisposable"/>s may be <c>null</c>; they are
/// ignored. After everything is closed, the method either
/// throws the first exception it hit while closing, or
/// completes normally if there were no exceptions.
/// </summary>
/// <param name="objects">
/// Objects to call <see cref="IDisposable.Dispose()"/> on </param>
public static void Dispose(params IDisposable[] objects)
{
Exception th = null;
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception t)
{
AddSuppressed(th, t);
if (th == null)
{
th = t;
}
}
}
ReThrow(th);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s. </summary>
/// <seealso cref="Dispose(IDisposable[])"/>
public static void Dispose(IEnumerable<IDisposable> objects)
{
Exception th = null;
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception t)
{
AddSuppressed(th, t);
if (th == null)
{
th = t;
}
}
}
ReThrow(th);
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions.
/// Some of the <see cref="IDisposable"/>s may be <c>null</c>, they are ignored.
/// </summary>
/// <param name="objects">
/// Objects to call <see cref="IDisposable.Dispose()"/> on </param>
public static void DisposeWhileHandlingException(params IDisposable[] objects)
{
foreach (var o in objects)
{
try
{
if (o != null)
{
o.Dispose();
}
}
catch (Exception)
{
//eat it
}
}
}
/// <summary>
/// Disposes all given <see cref="IDisposable"/>s, suppressing all thrown exceptions. </summary>
/// <seealso cref="DisposeWhileHandlingException(IDisposable[])"/>
public static void DisposeWhileHandlingException(IEnumerable<IDisposable> objects)
{
foreach (IDisposable @object in objects)
{
try
{
if (@object != null)
{
@object.Dispose();
}
}
catch (Exception)
{
//eat it
}
}
}
/// <summary>
/// Since there's no C# equivalent of Java's Exception.AddSuppressed, we add the
/// suppressed exceptions to a data field via the
/// <see cref="ExceptionExtensions.AddSuppressed(Exception, Exception)"/> method.
/// <para/>
/// The exceptions can be retrieved by calling <see cref="ExceptionExtensions.GetSuppressed(Exception)"/>
/// or <see cref="ExceptionExtensions.GetSuppressedAsList(Exception)"/>.
/// </summary>
/// <param name="exception"> this exception should get the suppressed one added </param>
/// <param name="suppressed"> the suppressed exception </param>
private static void AddSuppressed(Exception exception, Exception suppressed)
{
if (exception != null && suppressed != null)
{
exception.AddSuppressed(suppressed);
}
}
/// <summary>
/// Wrapping the given <see cref="Stream"/> in a reader using a <see cref="Encoding"/>.
/// Unlike Java's defaults this reader will throw an exception if your it detects
/// the read charset doesn't match the expected <see cref="Encoding"/>.
/// <para/>
/// Decoding readers are useful to load configuration files, stopword lists or synonym files
/// to detect character set problems. However, its not recommended to use as a common purpose
/// reader.
/// </summary>
/// <param name="stream"> The stream to wrap in a reader </param>
/// <param name="charSet"> The expected charset </param>
/// <returns> A wrapping reader </returns>
public static TextReader GetDecodingReader(Stream stream, Encoding charSet)
{
return new StreamReader(stream, charSet);
}
/// <summary>
/// Opens a <see cref="TextReader"/> for the given <see cref="FileInfo"/> using a <see cref="Encoding"/>.
/// Unlike Java's defaults this reader will throw an exception if your it detects
/// the read charset doesn't match the expected <see cref="Encoding"/>.
/// <para/>
/// Decoding readers are useful to load configuration files, stopword lists or synonym files
/// to detect character set problems. However, its not recommended to use as a common purpose
/// reader. </summary>
/// <param name="file"> The file to open a reader on </param>
/// <param name="charSet"> The expected charset </param>
/// <returns> A reader to read the given file </returns>
public static TextReader GetDecodingReader(FileInfo file, Encoding charSet)
{
FileStream stream = null;
bool success = false;
try
{
stream = file.OpenRead();
TextReader reader = GetDecodingReader(stream, charSet);
success = true;
return reader;
}
finally
{
if (!success)
{
IOUtils.Dispose(stream);
}
}
}
/// <summary>
/// Opens a <see cref="TextReader"/> for the given resource using a <see cref="Encoding"/>.
/// Unlike Java's defaults this reader will throw an exception if your it detects
/// the read charset doesn't match the expected <see cref="Encoding"/>.
/// <para/>
/// Decoding readers are useful to load configuration files, stopword lists or synonym files
/// to detect character set problems. However, its not recommended to use as a common purpose
/// reader. </summary>
/// <param name="clazz"> The class used to locate the resource </param>
/// <param name="resource"> The resource name to load </param>
/// <param name="charSet"> The expected charset </param>
/// <returns> A reader to read the given file </returns>
public static TextReader GetDecodingReader(Type clazz, string resource, Encoding charSet)
{
Stream stream = null;
bool success = false;
try
{
stream = clazz.FindAndGetManifestResourceStream(resource);
TextReader reader = GetDecodingReader(stream, charSet);
success = true;
return reader;
}
finally
{
if (!success)
{
IOUtils.Dispose(stream);
}
}
}
/// <summary>
/// Deletes all given files, suppressing all thrown <see cref="Exception"/>s.
/// <para/>
/// Note that the files should not be <c>null</c>.
/// </summary>
public static void DeleteFilesIgnoringExceptions(Directory dir, params string[] files)
{
foreach (string name in files)
{
try
{
dir.DeleteFile(name);
}
catch (Exception)
{
// ignore
}
}
}
/// <summary>
/// Copy one file's contents to another file. The target will be overwritten
/// if it exists. The source must exist.
/// </summary>
public static void Copy(FileInfo source, FileInfo target)
{
FileStream fis = null;
FileStream fos = null;
try
{
fis = source.OpenRead();
fos = target.OpenWrite();
byte[] buffer = new byte[1024 * 8];
int len;
while ((len = fis.Read(buffer, 0, buffer.Length)) > 0)
{
fos.Write(buffer, 0, len);
}
}
finally
{
Dispose(fis, fos);
}
}
/// <summary>
/// Simple utilty method that takes a previously caught
/// <see cref="Exception"/> and rethrows either
/// <see cref="IOException"/> or an unchecked exception. If the
/// argument is <c>null</c> then this method does nothing.
/// </summary>
public static void ReThrow(Exception th)
{
if (th != null)
{
if (th is System.IO.IOException)
{
throw th;
}
ReThrowUnchecked(th);
}
}
/// <summary>
/// Simple utilty method that takes a previously caught
/// <see cref="Exception"/> and rethrows it as an unchecked exception.
/// If the argument is <c>null</c> then this method does nothing.
/// </summary>
public static void ReThrowUnchecked(Exception th)
{
if (th != null)
{
throw th;
}
}
// LUCENENET specific: Fsync is pointless in .NET, since we are
// calling FileStream.Flush(true) before the stream is disposed
// which means we never need it at the point in Java where it is called.
// /// <summary>
// /// Ensure that any writes to the given file is written to the storage device that contains it. </summary>
// /// <param name="fileToSync"> The file to fsync </param>
// /// <param name="isDir"> If <c>true</c>, the given file is a directory (we open for read and ignore <see cref="IOException"/>s,
// /// because not all file systems and operating systems allow to fsync on a directory) </param>
// public static void Fsync(string fileToSync, bool isDir)
// {
// // Fsync does not appear to function properly for Windows and Linux platforms. In Lucene version
// // they catch this in IOException branch and return if the call is for the directory.
// // In Lucene.Net the exception is UnauthorizedAccessException and is not handled by
// // IOException block. No need to even attempt to fsync, just return if the call is for directory
// if (isDir)
// {
// return;
// }
// var retryCount = 1;
// while (true)
// {
// FileStream file = null;
// bool success = false;
// try
// {
// // If the file is a directory we have to open read-only, for regular files we must open r/w for the fsync to have an effect.
// // See http://blog.httrack.com/blog/2013/11/15/everything-you-always-wanted-to-know-about-fsync/
// file = new FileStream(fileToSync,
// FileMode.Open, // We shouldn't create a file when syncing.
// // Java version uses FileChannel which doesn't create the file if it doesn't already exist,
// // so there should be no reason for attempting to create it in Lucene.Net.
// FileAccess.Write,
// FileShare.ReadWrite);
// //FileSupport.Sync(file);
// file.Flush(true);
// success = true;
// }
//#pragma warning disable 168
// catch (IOException e)
//#pragma warning restore 168
// {
// if (retryCount == 5)
// {
// throw;
// }
//#if !NETSTANDARD1_6
// try
// {
//#endif
// // Pause 5 msec
// Thread.Sleep(5);
//#if !NETSTANDARD1_6
// }
// catch (ThreadInterruptedException ie)
// {
// var ex = new ThreadInterruptedException(ie.ToString(), ie);
// ex.AddSuppressed(e);
// throw ex;
// }
//#endif
// }
// finally
// {
// if (file != null)
// {
// file.Dispose();
// }
// }
// if (success)
// {
// return;
// }
// retryCount++;
// }
// }
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace Serialize.Linq.Examples.RestApi.Areas.HelpPage
{
/// <summary>
/// This class will create an object of a given type and populate it with sample data.
/// </summary>
public class ObjectGenerator
{
private const int DefaultCollectionSize = 3;
private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator();
/// <summary>
/// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types:
/// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc.
/// Complex types: POCO types.
/// Nullables: <see cref="Nullable{T}"/>.
/// Arrays: arrays of simple types or complex types.
/// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/>
/// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc
/// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>.
/// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>.
/// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>.
/// </summary>
/// <param name="type">The type.</param>
/// <returns>An object of the given type.</returns>
public object GenerateObject(Type type)
{
return GenerateObject(type, new Dictionary<Type, object>());
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")]
private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
try
{
if (SimpleTypeObjectGenerator.CanGenerateObject(type))
{
return SimpleObjectGenerator.GenerateObject(type);
}
if (type.IsArray)
{
return GenerateArray(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsGenericType)
{
return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IDictionary))
{
return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IDictionary).IsAssignableFrom(type))
{
return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IList) ||
type == typeof(IEnumerable) ||
type == typeof(ICollection))
{
return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences);
}
if (typeof(IList).IsAssignableFrom(type))
{
return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences);
}
if (type == typeof(IQueryable))
{
return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences);
}
if (type.IsEnum)
{
return GenerateEnum(type);
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
}
catch
{
// Returns null if anything fails
return null;
}
return null;
}
private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences)
{
Type genericTypeDefinition = type.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
return GenerateNullable(type, createdObjectReferences);
}
if (genericTypeDefinition == typeof(KeyValuePair<,>))
{
return GenerateKeyValuePair(type, createdObjectReferences);
}
if (IsTuple(genericTypeDefinition))
{
return GenerateTuple(type, createdObjectReferences);
}
Type[] genericArguments = type.GetGenericArguments();
if (genericArguments.Length == 1)
{
if (genericTypeDefinition == typeof(IList<>) ||
genericTypeDefinition == typeof(IEnumerable<>) ||
genericTypeDefinition == typeof(ICollection<>))
{
Type collectionType = typeof(List<>).MakeGenericType(genericArguments);
return GenerateCollection(collectionType, collectionSize, createdObjectReferences);
}
if (genericTypeDefinition == typeof(IQueryable<>))
{
return GenerateQueryable(type, collectionSize, createdObjectReferences);
}
Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]);
if (closedCollectionType.IsAssignableFrom(type))
{
return GenerateCollection(type, collectionSize, createdObjectReferences);
}
}
if (genericArguments.Length == 2)
{
if (genericTypeDefinition == typeof(IDictionary<,>))
{
Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments);
return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences);
}
Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]);
if (closedDictionaryType.IsAssignableFrom(type))
{
return GenerateDictionary(type, collectionSize, createdObjectReferences);
}
}
if (type.IsPublic || type.IsNestedPublic)
{
return GenerateComplexObject(type, createdObjectReferences);
}
return null;
}
private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = type.GetGenericArguments();
object[] parameterValues = new object[genericArgs.Length];
bool failedToCreateTuple = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < genericArgs.Length; i++)
{
parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences);
failedToCreateTuple &= parameterValues[i] == null;
}
if (failedToCreateTuple)
{
return null;
}
object result = Activator.CreateInstance(type, parameterValues);
return result;
}
private static bool IsTuple(Type genericTypeDefinition)
{
return genericTypeDefinition == typeof(Tuple<>) ||
genericTypeDefinition == typeof(Tuple<,>) ||
genericTypeDefinition == typeof(Tuple<,,>) ||
genericTypeDefinition == typeof(Tuple<,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,>) ||
genericTypeDefinition == typeof(Tuple<,,,,,,,>);
}
private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences)
{
Type[] genericArgs = keyValuePairType.GetGenericArguments();
Type typeK = genericArgs[0];
Type typeV = genericArgs[1];
ObjectGenerator objectGenerator = new ObjectGenerator();
object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences);
object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences);
if (keyObject == null && valueObject == null)
{
// Failed to create key and values
return null;
}
object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject);
return result;
}
private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = arrayType.GetElementType();
Array result = Array.CreateInstance(type, size);
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
result.SetValue(element, i);
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type typeK = typeof(object);
Type typeV = typeof(object);
if (dictionaryType.IsGenericType)
{
Type[] genericArgs = dictionaryType.GetGenericArguments();
typeK = genericArgs[0];
typeV = genericArgs[1];
}
object result = Activator.CreateInstance(dictionaryType);
MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
if (newKey == null)
{
// Cannot generate a valid key
return null;
}
bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
if (!containsKey)
{
object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
addMethod.Invoke(result, new object[] { newKey, newValue });
}
}
return result;
}
private static object GenerateEnum(Type enumType)
{
Array possibleValues = Enum.GetValues(enumType);
if (possibleValues.Length > 0)
{
return possibleValues.GetValue(0);
}
return null;
}
private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences)
{
bool isGeneric = queryableType.IsGenericType;
object list;
if (isGeneric)
{
Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments());
list = GenerateCollection(listType, size, createdObjectReferences);
}
else
{
list = GenerateArray(typeof(object[]), size, createdObjectReferences);
}
if (list == null)
{
return null;
}
if (isGeneric)
{
Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments());
MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType });
return asQueryableMethod.Invoke(null, new[] { list });
}
return Queryable.AsQueryable((IEnumerable)list);
}
private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences)
{
Type type = collectionType.IsGenericType ?
collectionType.GetGenericArguments()[0] :
typeof(object);
object result = Activator.CreateInstance(collectionType);
MethodInfo addMethod = collectionType.GetMethod("Add");
bool areAllElementsNull = true;
ObjectGenerator objectGenerator = new ObjectGenerator();
for (int i = 0; i < size; i++)
{
object element = objectGenerator.GenerateObject(type, createdObjectReferences);
addMethod.Invoke(result, new object[] { element });
areAllElementsNull &= element == null;
}
if (areAllElementsNull)
{
return null;
}
return result;
}
private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences)
{
Type type = nullableType.GetGenericArguments()[0];
ObjectGenerator objectGenerator = new ObjectGenerator();
return objectGenerator.GenerateObject(type, createdObjectReferences);
}
private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences)
{
object result = null;
if (createdObjectReferences.TryGetValue(type, out result))
{
// The object has been created already, just return it. This will handle the circular reference case.
return result;
}
if (type.IsValueType)
{
result = Activator.CreateInstance(type);
}
else
{
ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes);
if (defaultCtor == null)
{
// Cannot instantiate the type because it doesn't have a default constructor
return null;
}
result = defaultCtor.Invoke(new object[0]);
}
createdObjectReferences.Add(type, result);
SetPublicProperties(type, result, createdObjectReferences);
SetPublicFields(type, result, createdObjectReferences);
return result;
}
private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (PropertyInfo property in properties)
{
if (property.CanWrite)
{
object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences);
property.SetValue(obj, propertyValue, null);
}
}
}
private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences)
{
FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance);
ObjectGenerator objectGenerator = new ObjectGenerator();
foreach (FieldInfo field in fields)
{
object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences);
field.SetValue(obj, fieldValue);
}
}
private class SimpleTypeObjectGenerator
{
private long _index = 0;
private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators();
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")]
private static Dictionary<Type, Func<long, object>> InitializeGenerators()
{
return new Dictionary<Type, Func<long, object>>
{
{ typeof(Boolean), index => true },
{ typeof(Byte), index => (Byte)64 },
{ typeof(Char), index => (Char)65 },
{ typeof(DateTime), index => DateTime.Now },
{ typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) },
{ typeof(DBNull), index => DBNull.Value },
{ typeof(Decimal), index => (Decimal)index },
{ typeof(Double), index => (Double)(index + 0.1) },
{ typeof(Guid), index => Guid.NewGuid() },
{ typeof(Int16), index => (Int16)(index % Int16.MaxValue) },
{ typeof(Int32), index => (Int32)(index % Int32.MaxValue) },
{ typeof(Int64), index => (Int64)index },
{ typeof(Object), index => new object() },
{ typeof(SByte), index => (SByte)64 },
{ typeof(Single), index => (Single)(index + 0.1) },
{
typeof(String), index =>
{
return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index);
}
},
{
typeof(TimeSpan), index =>
{
return TimeSpan.FromTicks(1234567);
}
},
{ typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) },
{ typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) },
{ typeof(UInt64), index => (UInt64)index },
{
typeof(Uri), index =>
{
return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index));
}
},
};
}
public static bool CanGenerateObject(Type type)
{
return DefaultGenerators.ContainsKey(type);
}
public object GenerateObject(Type type)
{
return DefaultGenerators[type](++_index);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
namespace System.Data.Common
{
internal sealed class DBConnectionString
{
// instances of this class are intended to be immutable, i.e readonly
// used by permission classes so it is much easier to verify correctness
// when not worried about the class being modified during execution
private static class KEY
{
internal const string Password = "password";
internal const string PersistSecurityInfo = "persist security info";
internal const string Pwd = "pwd";
};
// this class is serializable with Everett, so ugly field names can't be changed
private readonly string _encryptedUsersConnectionString;
// hash of unique keys to values
private readonly Dictionary<string, string> _parsetable;
// a linked list of key/value and their length in _encryptedUsersConnectionString
private readonly NameValuePair _keychain;
// track the existance of "password" or "pwd" in the connection string
// not used for anything anymore but must keep it set correct for V1.1 serialization
private readonly bool _hasPassword;
private readonly string[] _restrictionValues;
private readonly string _restrictions;
private readonly KeyRestrictionBehavior _behavior;
#pragma warning disable 169
// this field is no longer used, hence the warning was disabled
// however, it can not be removed or it will break serialization with V1.1
private readonly string _encryptedActualConnectionString;
#pragma warning restore 169
internal DBConnectionString(string value, string restrictions, KeyRestrictionBehavior behavior, Dictionary<string, string> synonyms, bool useOdbcRules)
: this(new DbConnectionOptions(value, synonyms, useOdbcRules), restrictions, behavior, synonyms, false)
{
// useOdbcRules is only used to parse the connection string, not to parse restrictions because values don't apply there
// the hashtable doesn't need clone since it isn't shared with anything else
}
internal DBConnectionString(DbConnectionOptions connectionOptions)
: this(connectionOptions, (string)null, KeyRestrictionBehavior.AllowOnly, null, true)
{
// used by DBDataPermission to convert from DbConnectionOptions to DBConnectionString
// since backward compatability requires Everett level classes
}
private DBConnectionString(DbConnectionOptions connectionOptions, string restrictions, KeyRestrictionBehavior behavior, Dictionary<string, string> synonyms, bool mustCloneDictionary)
{ // used by DBDataPermission
Debug.Assert(null != connectionOptions, "null connectionOptions");
switch (behavior)
{
case KeyRestrictionBehavior.PreventUsage:
case KeyRestrictionBehavior.AllowOnly:
_behavior = behavior;
break;
default:
throw ADP.InvalidKeyRestrictionBehavior(behavior);
}
// grab all the parsed details from DbConnectionOptions
_encryptedUsersConnectionString = connectionOptions.UsersConnectionString(false);
_hasPassword = connectionOptions._hasPasswordKeyword;
_parsetable = connectionOptions.Parsetable;
_keychain = connectionOptions._keyChain;
// we do not want to serialize out user password unless directed so by "persist security info=true"
// otherwise all instances of user's password will be replaced with "*"
if (_hasPassword && !connectionOptions.HasPersistablePassword)
{
if (mustCloneDictionary)
{
// clone the hashtable to replace user's password/pwd value with "*"
// we only need to clone if coming from DbConnectionOptions and password exists
_parsetable = new Dictionary<string, string>(_parsetable);
}
// different than Everett in that instead of removing password/pwd from
// the hashtable, we replace the value with '*'. This is okay since we
// serialize out with '*' so already knows what we do. Better this way
// than to treat password specially later on which causes problems.
const string star = "*";
if (_parsetable.ContainsKey(KEY.Password))
{
_parsetable[KEY.Password] = star;
}
if (_parsetable.ContainsKey(KEY.Pwd))
{
_parsetable[KEY.Pwd] = star;
}
// replace user's password/pwd value with "*" in the linked list and build a new string
_keychain = connectionOptions.ReplacePasswordPwd(out _encryptedUsersConnectionString, true);
}
if (!string.IsNullOrEmpty(restrictions))
{
_restrictionValues = ParseRestrictions(restrictions, synonyms);
_restrictions = restrictions;
}
}
private DBConnectionString(DBConnectionString connectionString, string[] restrictionValues, KeyRestrictionBehavior behavior)
{
// used by intersect for two equal connection strings with different restrictions
_encryptedUsersConnectionString = connectionString._encryptedUsersConnectionString;
_parsetable = connectionString._parsetable;
_keychain = connectionString._keychain;
_hasPassword = connectionString._hasPassword;
_restrictionValues = restrictionValues;
_restrictions = null;
_behavior = behavior;
Verify(restrictionValues);
}
internal KeyRestrictionBehavior Behavior
{
get { return _behavior; }
}
internal string ConnectionString
{
get { return _encryptedUsersConnectionString; }
}
internal bool IsEmpty
{
get { return (null == _keychain); }
}
internal NameValuePair KeyChain
{
get { return _keychain; }
}
internal string Restrictions
{
get
{
string restrictions = _restrictions;
if (null == restrictions)
{
string[] restrictionValues = _restrictionValues;
if ((null != restrictionValues) && (0 < restrictionValues.Length))
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < restrictionValues.Length; ++i)
{
if (!string.IsNullOrEmpty(restrictionValues[i]))
{
builder.Append(restrictionValues[i]);
builder.Append("=;");
}
#if DEBUG
else
{
Debug.Assert(false, "empty restriction");
}
#endif
}
restrictions = builder.ToString();
}
}
return ((null != restrictions) ? restrictions : "");
}
}
internal string this[string keyword]
{
get { return (string)_parsetable[keyword]; }
}
internal bool ContainsKey(string keyword)
{
return _parsetable.ContainsKey(keyword);
}
internal DBConnectionString Intersect(DBConnectionString entry)
{
KeyRestrictionBehavior behavior = _behavior;
string[] restrictionValues = null;
if (null == entry)
{
//Debug.WriteLine("0 entry AllowNothing");
behavior = KeyRestrictionBehavior.AllowOnly;
}
else if (_behavior != entry._behavior)
{ // subset of the AllowOnly array
behavior = KeyRestrictionBehavior.AllowOnly;
if (KeyRestrictionBehavior.AllowOnly == entry._behavior)
{ // this PreventUsage and entry AllowOnly
if (!ADP.IsEmptyArray(_restrictionValues))
{
if (!ADP.IsEmptyArray(entry._restrictionValues))
{
//Debug.WriteLine("1 this PreventUsage with restrictions and entry AllowOnly with restrictions");
restrictionValues = NewRestrictionAllowOnly(entry._restrictionValues, _restrictionValues);
}
else
{
//Debug.WriteLine("2 this PreventUsage with restrictions and entry AllowOnly with no restrictions");
}
}
else
{
//Debug.WriteLine("3/4 this PreventUsage with no restrictions and entry AllowOnly");
restrictionValues = entry._restrictionValues;
}
}
else if (!ADP.IsEmptyArray(_restrictionValues))
{ // this AllowOnly and entry PreventUsage
if (!ADP.IsEmptyArray(entry._restrictionValues))
{
//Debug.WriteLine("5 this AllowOnly with restrictions and entry PreventUsage with restrictions");
restrictionValues = NewRestrictionAllowOnly(_restrictionValues, entry._restrictionValues);
}
else
{
//Debug.WriteLine("6 this AllowOnly and entry PreventUsage with no restrictions");
restrictionValues = _restrictionValues;
}
}
else
{
//Debug.WriteLine("7/8 this AllowOnly with no restrictions and entry PreventUsage");
}
}
else if (KeyRestrictionBehavior.PreventUsage == _behavior)
{ // both PreventUsage
if (ADP.IsEmptyArray(_restrictionValues))
{
//Debug.WriteLine("9/10 both PreventUsage and this with no restrictions");
restrictionValues = entry._restrictionValues;
}
else if (ADP.IsEmptyArray(entry._restrictionValues))
{
//Debug.WriteLine("11 both PreventUsage and entry with no restrictions");
restrictionValues = _restrictionValues;
}
else
{
//Debug.WriteLine("12 both PreventUsage with restrictions");
restrictionValues = NoDuplicateUnion(_restrictionValues, entry._restrictionValues);
}
}
else if (!ADP.IsEmptyArray(_restrictionValues) && !ADP.IsEmptyArray(entry._restrictionValues))
{ // both AllowOnly with restrictions
if (_restrictionValues.Length <= entry._restrictionValues.Length)
{
//Debug.WriteLine("13a this AllowOnly with restrictions and entry AllowOnly with restrictions");
restrictionValues = NewRestrictionIntersect(_restrictionValues, entry._restrictionValues);
}
else
{
//Debug.WriteLine("13b this AllowOnly with restrictions and entry AllowOnly with restrictions");
restrictionValues = NewRestrictionIntersect(entry._restrictionValues, _restrictionValues);
}
}
else
{ // both AllowOnly
//Debug.WriteLine("14/15/16 this AllowOnly and entry AllowOnly but no restrictions");
}
// verify _hasPassword & _parsetable are in [....] between Everett/Whidbey
Debug.Assert(!_hasPassword || ContainsKey(KEY.Password) || ContainsKey(KEY.Pwd), "OnDeserialized password mismatch this");
Debug.Assert(null == entry || !entry._hasPassword || entry.ContainsKey(KEY.Password) || entry.ContainsKey(KEY.Pwd), "OnDeserialized password mismatch entry");
DBConnectionString value = new DBConnectionString(this, restrictionValues, behavior);
ValidateCombinedSet(this, value);
ValidateCombinedSet(entry, value);
return value;
}
[Conditional("DEBUG")]
private void ValidateCombinedSet(DBConnectionString componentSet, DBConnectionString combinedSet)
{
Debug.Assert(combinedSet != null, "The combined connection string should not be null");
if ((componentSet != null) && (combinedSet._restrictionValues != null) && (componentSet._restrictionValues != null))
{
if (componentSet._behavior == KeyRestrictionBehavior.AllowOnly)
{
if (combinedSet._behavior == KeyRestrictionBehavior.AllowOnly)
{
// Component==Allow, Combined==Allow
// All values in the Combined Set should also be in the Component Set
// Combined - Component == null
Debug.Assert(combinedSet._restrictionValues.Except(componentSet._restrictionValues).Count() == 0, "Combined set allows values not allowed by component set");
}
else if (combinedSet._behavior == KeyRestrictionBehavior.PreventUsage)
{
// Component==Allow, Combined==PreventUsage
// Preventions override allows, so there is nothing to check here
}
else
{
Debug.Assert(false, string.Format("Unknown behavior for combined set: {0}", combinedSet._behavior));
}
}
else if (componentSet._behavior == KeyRestrictionBehavior.PreventUsage)
{
if (combinedSet._behavior == KeyRestrictionBehavior.AllowOnly)
{
// Component==PreventUsage, Combined==Allow
// There shouldn't be any of the values from the Component Set in the Combined Set
// Intersect(Component, Combined) == null
Debug.Assert(combinedSet._restrictionValues.Intersect(componentSet._restrictionValues).Count() == 0, "Combined values allows values prevented by component set");
}
else if (combinedSet._behavior == KeyRestrictionBehavior.PreventUsage)
{
// Component==PreventUsage, Combined==PreventUsage
// All values in the Component Set should also be in the Combined Set
// Component - Combined == null
Debug.Assert(componentSet._restrictionValues.Except(combinedSet._restrictionValues).Count() == 0, "Combined values does not prevent all of the values prevented by the component set");
}
else
{
Debug.Assert(false, string.Format("Unknown behavior for combined set: {0}", combinedSet._behavior));
}
}
else
{
Debug.Assert(false, string.Format("Unknown behavior for component set: {0}", componentSet._behavior));
}
}
}
private bool IsRestrictedKeyword(string key)
{
// restricted if not found
return ((null == _restrictionValues) || (0 > Array.BinarySearch(_restrictionValues, key, StringComparer.Ordinal)));
}
internal bool IsSupersetOf(DBConnectionString entry)
{
Debug.Assert(!_hasPassword || ContainsKey(KEY.Password) || ContainsKey(KEY.Pwd), "OnDeserialized password mismatch this");
Debug.Assert(!entry._hasPassword || entry.ContainsKey(KEY.Password) || entry.ContainsKey(KEY.Pwd), "OnDeserialized password mismatch entry");
switch (_behavior)
{
case KeyRestrictionBehavior.AllowOnly:
// every key must either be in the resticted connection string or in the allowed keywords
// keychain may contain duplicates, but it is better than GetEnumerator on _parsetable.Keys
for (NameValuePair current = entry.KeyChain; null != current; current = current.Next)
{
if (!ContainsKey(current.Name) && IsRestrictedKeyword(current.Name))
{
return false;
}
}
break;
case KeyRestrictionBehavior.PreventUsage:
// every key can not be in the restricted keywords (even if in the restricted connection string)
if (null != _restrictionValues)
{
foreach (string restriction in _restrictionValues)
{
if (entry.ContainsKey(restriction))
{
return false;
}
}
}
break;
default:
Debug.Assert(false, "invalid KeyRestrictionBehavior");
throw ADP.InvalidKeyRestrictionBehavior(_behavior);
}
return true;
}
private static string[] NewRestrictionAllowOnly(string[] allowonly, string[] preventusage)
{
List<string> newlist = null;
for (int i = 0; i < allowonly.Length; ++i)
{
if (0 > Array.BinarySearch(preventusage, allowonly[i], StringComparer.Ordinal))
{
if (null == newlist)
{
newlist = new List<string>();
}
newlist.Add(allowonly[i]);
}
}
string[] restrictionValues = null;
if (null != newlist)
{
restrictionValues = newlist.ToArray();
}
Verify(restrictionValues);
return restrictionValues;
}
private static string[] NewRestrictionIntersect(string[] a, string[] b)
{
List<string> newlist = null;
for (int i = 0; i < a.Length; ++i)
{
if (0 <= Array.BinarySearch(b, a[i], StringComparer.Ordinal))
{
if (null == newlist)
{
newlist = new List<string>();
}
newlist.Add(a[i]);
}
}
string[] restrictionValues = null;
if (newlist != null)
{
restrictionValues = newlist.ToArray();
}
Verify(restrictionValues);
return restrictionValues;
}
private static string[] NoDuplicateUnion(string[] a, string[] b)
{
#if DEBUG
Debug.Assert(null != a && 0 < a.Length, "empty a");
Debug.Assert(null != b && 0 < b.Length, "empty b");
Verify(a);
Verify(b);
#endif
List<string> newlist = new List<string>(a.Length + b.Length);
for (int i = 0; i < a.Length; ++i)
{
newlist.Add(a[i]);
}
for (int i = 0; i < b.Length; ++i)
{ // find duplicates
if (0 > Array.BinarySearch(a, b[i], StringComparer.Ordinal))
{
newlist.Add(b[i]);
}
}
string[] restrictionValues = newlist.ToArray();
Array.Sort(restrictionValues, StringComparer.Ordinal);
Verify(restrictionValues);
return restrictionValues;
}
private static string[] ParseRestrictions(string restrictions, Dictionary<string, string> synonyms)
{
List<string> restrictionValues = new List<string>();
StringBuilder buffer = new StringBuilder(restrictions.Length);
int nextStartPosition = 0;
int endPosition = restrictions.Length;
while (nextStartPosition < endPosition)
{
int startPosition = nextStartPosition;
string keyname, keyvalue; // since parsing restrictions ignores values, it doesn't matter if we use ODBC rules or OLEDB rules
nextStartPosition = DbConnectionOptions.GetKeyValuePair(restrictions, startPosition, buffer, false, out keyname, out keyvalue);
if (!string.IsNullOrEmpty(keyname))
{
string realkeyname = ((null != synonyms) ? (string)synonyms[keyname] : keyname); // MDAC 85144
if (string.IsNullOrEmpty(realkeyname))
{
throw ADP.KeywordNotSupported(keyname);
}
restrictionValues.Add(realkeyname);
}
}
return RemoveDuplicates(restrictionValues.ToArray());
}
internal static string[] RemoveDuplicates(string[] restrictions)
{
int count = restrictions.Length;
if (0 < count)
{
Array.Sort(restrictions, StringComparer.Ordinal);
for (int i = 1; i < restrictions.Length; ++i)
{
string prev = restrictions[i - 1];
if ((0 == prev.Length) || (prev == restrictions[i]))
{
restrictions[i - 1] = null;
count--;
}
}
if (0 == restrictions[restrictions.Length - 1].Length)
{
restrictions[restrictions.Length - 1] = null;
count--;
}
if (count != restrictions.Length)
{
string[] tmp = new string[count];
count = 0;
for (int i = 0; i < restrictions.Length; ++i)
{
if (null != restrictions[i])
{
tmp[count++] = restrictions[i];
}
}
restrictions = tmp;
}
}
Verify(restrictions);
return restrictions;
}
[ConditionalAttribute("DEBUG")]
private static void Verify(string[] restrictionValues)
{
if (null != restrictionValues)
{
for (int i = 1; i < restrictionValues.Length; ++i)
{
Debug.Assert(!string.IsNullOrEmpty(restrictionValues[i - 1]), "empty restriction");
Debug.Assert(!string.IsNullOrEmpty(restrictionValues[i]), "empty restriction");
Debug.Assert(0 >= StringComparer.Ordinal.Compare(restrictionValues[i - 1], restrictionValues[i]));
}
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Testing;
using Newtonsoft.Json.Linq;
using Templates.Test.Helpers;
using Xunit;
using Xunit.Abstractions;
using Xunit.Sdk;
namespace Templates.Test
{
public class BlazorWasmTemplateTest : BlazorTemplateTest
{
public BlazorWasmTemplateTest(ProjectFactoryFixture projectFactory)
: base(projectFactory) { }
public override string ProjectType { get; } = "blazorwasm";
[Fact]
public async Task BlazorWasmStandaloneTemplateCanCreateBuildPublish()
{
var project = await CreateBuildPublishAsync("blazorstandalone");
// The service worker assets manifest isn't generated for non-PWA projects
var publishDir = Path.Combine(project.TemplatePublishDir, "wwwroot");
Assert.False(File.Exists(Path.Combine(publishDir, "service-worker-assets.js")), "Non-PWA templates should not produce service-worker-assets.js");
}
[Fact]
public Task BlazorWasmHostedTemplateCanCreateBuildPublish() => CreateBuildPublishAsync("blazorhosted", args: new[] { "--hosted" }, serverProject: true);
[Fact]
public Task BlazorWasmStandalonePwaTemplateCanCreateBuildPublish() => CreateBuildPublishAsync("blazorstandalonepwa", args: new[] { "--pwa" });
[Fact]
public async Task BlazorWasmHostedPwaTemplateCanCreateBuildPublish()
{
var project = await CreateBuildPublishAsync("blazorhostedpwa", args: new[] { "--hosted", "--pwa" }, serverProject: true);
var serverProject = GetSubProject(project, "Server", $"{project.ProjectName}.Server");
ValidatePublishedServiceWorker(serverProject);
}
private void ValidatePublishedServiceWorker(Project project)
{
var publishDir = Path.Combine(project.TemplatePublishDir, "wwwroot");
// When publishing the PWA template, we generate an assets manifest
// and move service-worker.published.js to overwrite service-worker.js
Assert.False(File.Exists(Path.Combine(publishDir, "service-worker.published.js")), "service-worker.published.js should not be published");
Assert.True(File.Exists(Path.Combine(publishDir, "service-worker.js")), "service-worker.js should be published");
Assert.True(File.Exists(Path.Combine(publishDir, "service-worker-assets.js")), "service-worker-assets.js should be published");
// We automatically append the SWAM version as a comment in the published service worker file
var serviceWorkerAssetsManifestContents = ReadFile(publishDir, "service-worker-assets.js");
var serviceWorkerContents = ReadFile(publishDir, "service-worker.js");
// Parse the "version": "..." value from the SWAM, and check it's in the service worker
var serviceWorkerAssetsManifestVersionMatch = new Regex(@"^\s*\""version\"":\s*(\""[^\""]+\"")", RegexOptions.Multiline)
.Match(serviceWorkerAssetsManifestContents);
Assert.True(serviceWorkerAssetsManifestVersionMatch.Success);
var serviceWorkerAssetsManifestVersionJson = serviceWorkerAssetsManifestVersionMatch.Groups[1].Captures[0].Value;
var serviceWorkerAssetsManifestVersion = JsonSerializer.Deserialize<string>(serviceWorkerAssetsManifestVersionJson);
Assert.True(serviceWorkerContents.Contains($"/* Manifest version: {serviceWorkerAssetsManifestVersion} */", StringComparison.Ordinal));
}
[ConditionalFact]
[SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/34554", Queues = "Windows.10.Arm64v8.Open")]
// LocalDB doesn't work on non Windows platforms
[OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)]
public Task BlazorWasmHostedTemplate_IndividualAuth_Works_WithLocalDB()
=> BlazorWasmHostedTemplate_IndividualAuth_Works(true);
[ConditionalFact]
[SkipOnHelix("https://github.com/dotnet/aspnetcore/issues/34554", Queues = "Windows.10.Arm64v8.Open")]
public Task BlazorWasmHostedTemplate_IndividualAuth_Works_WithOutLocalDB()
=> BlazorWasmHostedTemplate_IndividualAuth_Works(false);
private async Task<Project> CreateBuildPublishIndividualAuthProject(bool useLocalDb)
{
// Additional arguments are needed. See: https://github.com/dotnet/aspnetcore/issues/24278
Environment.SetEnvironmentVariable("EnableDefaultScopedCssItems", "true");
var project = await CreateBuildPublishAsync("blazorhostedindividual" + (useLocalDb ? "uld" : ""),
args: new[] { "--hosted", "-au", "Individual", useLocalDb ? "-uld" : "" });
var serverProject = GetSubProject(project, "Server", $"{project.ProjectName}.Server");
var serverProjectFileContents = ReadFile(serverProject.TemplateOutputDir, $"{serverProject.ProjectName}.csproj");
if (!useLocalDb)
{
Assert.Contains(".db", serverProjectFileContents);
}
var appSettings = ReadFile(serverProject.TemplateOutputDir, "appsettings.json");
var element = JsonSerializer.Deserialize<JsonElement>(appSettings);
var clientsProperty = element.GetProperty("IdentityServer").EnumerateObject().Single().Value.EnumerateObject().Single();
var replacedSection = element.GetRawText().Replace(clientsProperty.Name, serverProject.ProjectName.Replace(".Server", ".Client"));
var appSettingsPath = Path.Combine(serverProject.TemplateOutputDir, "appsettings.json");
File.WriteAllText(appSettingsPath, replacedSection);
var publishResult = await serverProject.RunDotNetPublishAsync();
Assert.True(0 == publishResult.ExitCode, ErrorMessages.GetFailedProcessMessage("publish", serverProject, publishResult));
// Run dotnet build after publish. The reason is that one uses Config = Debug and the other uses Config = Release
// The output from publish will go into bin/Release/netcoreappX.Y/publish and won't be affected by calling build
// later, while the opposite is not true.
var buildResult = await serverProject.RunDotNetBuildAsync();
Assert.True(0 == buildResult.ExitCode, ErrorMessages.GetFailedProcessMessage("build", serverProject, buildResult));
var migrationsResult = await serverProject.RunDotNetEfCreateMigrationAsync("blazorwasm");
Assert.True(0 == migrationsResult.ExitCode, ErrorMessages.GetFailedProcessMessage("run EF migrations", serverProject, migrationsResult));
serverProject.AssertEmptyMigration("blazorwasm");
return project;
}
private async Task BlazorWasmHostedTemplate_IndividualAuth_Works(bool useLocalDb)
{
var project = await CreateBuildPublishIndividualAuthProject(useLocalDb: useLocalDb);
var serverProject = GetSubProject(project, "Server", $"{project.ProjectName}.Server");
}
[Fact]
public async Task BlazorWasmStandaloneTemplate_IndividualAuth_CreateBuildPublish()
{
var project = await CreateBuildPublishAsync("blazorstandaloneindividual", args: new[] {
"-au",
"Individual",
"--authority",
"https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration",
"--client-id",
"sample-client-id"
});
}
public static TheoryData<TemplateInstance> TemplateData => new TheoryData<TemplateInstance>
{
new TemplateInstance(
"blazorwasmhostedaadb2c", "-ho",
"-au", "IndividualB2C",
"--aad-b2c-instance", "example.b2clogin.com",
"-ssp", "b2c_1_siupin",
"--client-id", "clientId",
"--domain", "my-domain",
"--default-scope", "full",
"--app-id-uri", "ApiUri",
"--api-client-id", "1234123413241324"),
new TemplateInstance(
"blazorwasmhostedaad", "-ho",
"-au", "SingleOrg",
"--domain", "my-domain",
"--tenant-id", "tenantId",
"--client-id", "clientId",
"--default-scope", "full",
"--app-id-uri", "ApiUri",
"--api-client-id", "1234123413241324"),
new TemplateInstance(
"blazorwasmhostedaadgraph", "-ho",
"-au", "SingleOrg",
"--calls-graph",
"--domain", "my-domain",
"--tenant-id", "tenantId",
"--client-id", "clientId",
"--default-scope", "full",
"--app-id-uri", "ApiUri",
"--api-client-id", "1234123413241324"),
new TemplateInstance(
"blazorwasmhostedaadapi", "-ho",
"-au", "SingleOrg",
"--called-api-url", "\"https://graph.microsoft.com\"",
"--called-api-scopes", "user.readwrite",
"--domain", "my-domain",
"--tenant-id", "tenantId",
"--client-id", "clientId",
"--default-scope", "full",
"--app-id-uri", "ApiUri",
"--api-client-id", "1234123413241324"),
new TemplateInstance(
"blazorwasmstandaloneaadb2c",
"-au", "IndividualB2C",
"--aad-b2c-instance", "example.b2clogin.com",
"-ssp", "b2c_1_siupin",
"--client-id", "clientId",
"--domain", "my-domain"),
new TemplateInstance(
"blazorwasmstandaloneaad",
"-au", "SingleOrg",
"--domain", "my-domain",
"--tenant-id", "tenantId",
"--client-id", "clientId"),
};
public class TemplateInstance
{
public TemplateInstance(string name, params string[] arguments)
{
Name = name;
Arguments = arguments;
}
public string Name { get; }
public string[] Arguments { get; }
}
[Theory]
[MemberData(nameof(TemplateData))]
public Task BlazorWasmHostedTemplate_AzureActiveDirectoryTemplate_Works(TemplateInstance instance)
=> CreateBuildPublishAsync(instance.Name, args: instance.Arguments, targetFramework: "netstandard2.1");
private string ReadFile(string basePath, string path)
{
var fullPath = Path.Combine(basePath, path);
var doesExist = File.Exists(fullPath);
Assert.True(doesExist, $"Expected file to exist, but it doesn't: {path}");
return File.ReadAllText(Path.Combine(basePath, path));
}
private void UpdatePublishedSettings(Project serverProject)
{
// Hijack here the config file to use the development key during publish.
var appSettings = JObject.Parse(File.ReadAllText(Path.Combine(serverProject.TemplateOutputDir, "appsettings.json")));
var appSettingsDevelopment = JObject.Parse(File.ReadAllText(Path.Combine(serverProject.TemplateOutputDir, "appsettings.Development.json")));
((JObject)appSettings["IdentityServer"]).Merge(appSettingsDevelopment["IdentityServer"]);
((JObject)appSettings["IdentityServer"]).Merge(new
{
IdentityServer = new
{
Key = new
{
FilePath = "./tempkey.json"
}
}
});
var testAppSettings = appSettings.ToString();
File.WriteAllText(Path.Combine(serverProject.TemplatePublishDir, "appsettings.json"), testAppSettings);
}
}
}
| |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.AccessApproval.V1.Snippets
{
using Google.Api.Gax;
using Google.Protobuf.WellKnownTypes;
using System;
using System.Linq;
using System.Threading.Tasks;
/// <summary>Generated snippets.</summary>
public sealed class GeneratedAccessApprovalServiceClientSnippets
{
/// <summary>Snippet for ListApprovalRequests</summary>
public void ListApprovalRequestsRequestObject()
{
// Snippet: ListApprovalRequests(ListApprovalRequestsMessage, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create();
// Initialize request argument(s)
ListApprovalRequestsMessage request = new ListApprovalRequestsMessage
{
Parent = "",
Filter = "",
};
// Make the request
PagedEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequests(request);
// Iterate over all response items, lazily performing RPCs as required
foreach (ApprovalRequest item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListApprovalRequestsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ApprovalRequest item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ApprovalRequest> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ApprovalRequest item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListApprovalRequestsAsync</summary>
public async Task ListApprovalRequestsRequestObjectAsync()
{
// Snippet: ListApprovalRequestsAsync(ListApprovalRequestsMessage, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync();
// Initialize request argument(s)
ListApprovalRequestsMessage request = new ListApprovalRequestsMessage
{
Parent = "",
Filter = "",
};
// Make the request
PagedAsyncEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequestsAsync(request);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ApprovalRequest item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListApprovalRequestsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ApprovalRequest item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ApprovalRequest> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ApprovalRequest item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListApprovalRequests</summary>
public void ListApprovalRequests()
{
// Snippet: ListApprovalRequests(string, string, int?, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequests(parent);
// Iterate over all response items, lazily performing RPCs as required
foreach (ApprovalRequest item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListApprovalRequestsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ApprovalRequest item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ApprovalRequest> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ApprovalRequest item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for ListApprovalRequestsAsync</summary>
public async Task ListApprovalRequestsAsync()
{
// Snippet: ListApprovalRequestsAsync(string, string, int?, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync();
// Initialize request argument(s)
string parent = "";
// Make the request
PagedAsyncEnumerable<ListApprovalRequestsResponse, ApprovalRequest> response = accessApprovalServiceClient.ListApprovalRequestsAsync(parent);
// Iterate over all response items, lazily performing RPCs as required
await response.ForEachAsync((ApprovalRequest item) =>
{
// Do something with each item
Console.WriteLine(item);
});
// Or iterate over pages (of server-defined size), performing one RPC per page
await response.AsRawResponses().ForEachAsync((ListApprovalRequestsResponse page) =>
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (ApprovalRequest item in page)
{
// Do something with each item
Console.WriteLine(item);
}
});
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<ApprovalRequest> singlePage = await response.ReadPageAsync(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (ApprovalRequest item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
// End snippet
}
/// <summary>Snippet for GetApprovalRequest</summary>
public void GetApprovalRequestRequestObject()
{
// Snippet: GetApprovalRequest(GetApprovalRequestMessage, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create();
// Initialize request argument(s)
GetApprovalRequestMessage request = new GetApprovalRequestMessage { Name = "", };
// Make the request
ApprovalRequest response = accessApprovalServiceClient.GetApprovalRequest(request);
// End snippet
}
/// <summary>Snippet for GetApprovalRequestAsync</summary>
public async Task GetApprovalRequestRequestObjectAsync()
{
// Snippet: GetApprovalRequestAsync(GetApprovalRequestMessage, CallSettings)
// Additional: GetApprovalRequestAsync(GetApprovalRequestMessage, CancellationToken)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync();
// Initialize request argument(s)
GetApprovalRequestMessage request = new GetApprovalRequestMessage { Name = "", };
// Make the request
ApprovalRequest response = await accessApprovalServiceClient.GetApprovalRequestAsync(request);
// End snippet
}
/// <summary>Snippet for GetApprovalRequest</summary>
public void GetApprovalRequest()
{
// Snippet: GetApprovalRequest(string, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
ApprovalRequest response = accessApprovalServiceClient.GetApprovalRequest(name);
// End snippet
}
/// <summary>Snippet for GetApprovalRequestAsync</summary>
public async Task GetApprovalRequestAsync()
{
// Snippet: GetApprovalRequestAsync(string, CallSettings)
// Additional: GetApprovalRequestAsync(string, CancellationToken)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
ApprovalRequest response = await accessApprovalServiceClient.GetApprovalRequestAsync(name);
// End snippet
}
/// <summary>Snippet for ApproveApprovalRequest</summary>
public void ApproveApprovalRequestRequestObject()
{
// Snippet: ApproveApprovalRequest(ApproveApprovalRequestMessage, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create();
// Initialize request argument(s)
ApproveApprovalRequestMessage request = new ApproveApprovalRequestMessage
{
Name = "",
ExpireTime = new Timestamp(),
};
// Make the request
ApprovalRequest response = accessApprovalServiceClient.ApproveApprovalRequest(request);
// End snippet
}
/// <summary>Snippet for ApproveApprovalRequestAsync</summary>
public async Task ApproveApprovalRequestRequestObjectAsync()
{
// Snippet: ApproveApprovalRequestAsync(ApproveApprovalRequestMessage, CallSettings)
// Additional: ApproveApprovalRequestAsync(ApproveApprovalRequestMessage, CancellationToken)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync();
// Initialize request argument(s)
ApproveApprovalRequestMessage request = new ApproveApprovalRequestMessage
{
Name = "",
ExpireTime = new Timestamp(),
};
// Make the request
ApprovalRequest response = await accessApprovalServiceClient.ApproveApprovalRequestAsync(request);
// End snippet
}
/// <summary>Snippet for DismissApprovalRequest</summary>
public void DismissApprovalRequestRequestObject()
{
// Snippet: DismissApprovalRequest(DismissApprovalRequestMessage, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create();
// Initialize request argument(s)
DismissApprovalRequestMessage request = new DismissApprovalRequestMessage { Name = "", };
// Make the request
ApprovalRequest response = accessApprovalServiceClient.DismissApprovalRequest(request);
// End snippet
}
/// <summary>Snippet for DismissApprovalRequestAsync</summary>
public async Task DismissApprovalRequestRequestObjectAsync()
{
// Snippet: DismissApprovalRequestAsync(DismissApprovalRequestMessage, CallSettings)
// Additional: DismissApprovalRequestAsync(DismissApprovalRequestMessage, CancellationToken)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync();
// Initialize request argument(s)
DismissApprovalRequestMessage request = new DismissApprovalRequestMessage { Name = "", };
// Make the request
ApprovalRequest response = await accessApprovalServiceClient.DismissApprovalRequestAsync(request);
// End snippet
}
/// <summary>Snippet for GetAccessApprovalSettings</summary>
public void GetAccessApprovalSettingsRequestObject()
{
// Snippet: GetAccessApprovalSettings(GetAccessApprovalSettingsMessage, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create();
// Initialize request argument(s)
GetAccessApprovalSettingsMessage request = new GetAccessApprovalSettingsMessage { Name = "", };
// Make the request
AccessApprovalSettings response = accessApprovalServiceClient.GetAccessApprovalSettings(request);
// End snippet
}
/// <summary>Snippet for GetAccessApprovalSettingsAsync</summary>
public async Task GetAccessApprovalSettingsRequestObjectAsync()
{
// Snippet: GetAccessApprovalSettingsAsync(GetAccessApprovalSettingsMessage, CallSettings)
// Additional: GetAccessApprovalSettingsAsync(GetAccessApprovalSettingsMessage, CancellationToken)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync();
// Initialize request argument(s)
GetAccessApprovalSettingsMessage request = new GetAccessApprovalSettingsMessage { Name = "", };
// Make the request
AccessApprovalSettings response = await accessApprovalServiceClient.GetAccessApprovalSettingsAsync(request);
// End snippet
}
/// <summary>Snippet for GetAccessApprovalSettings</summary>
public void GetAccessApprovalSettings()
{
// Snippet: GetAccessApprovalSettings(string, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
AccessApprovalSettings response = accessApprovalServiceClient.GetAccessApprovalSettings(name);
// End snippet
}
/// <summary>Snippet for GetAccessApprovalSettingsAsync</summary>
public async Task GetAccessApprovalSettingsAsync()
{
// Snippet: GetAccessApprovalSettingsAsync(string, CallSettings)
// Additional: GetAccessApprovalSettingsAsync(string, CancellationToken)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
AccessApprovalSettings response = await accessApprovalServiceClient.GetAccessApprovalSettingsAsync(name);
// End snippet
}
/// <summary>Snippet for UpdateAccessApprovalSettings</summary>
public void UpdateAccessApprovalSettingsRequestObject()
{
// Snippet: UpdateAccessApprovalSettings(UpdateAccessApprovalSettingsMessage, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create();
// Initialize request argument(s)
UpdateAccessApprovalSettingsMessage request = new UpdateAccessApprovalSettingsMessage
{
Settings = new AccessApprovalSettings(),
UpdateMask = new FieldMask(),
};
// Make the request
AccessApprovalSettings response = accessApprovalServiceClient.UpdateAccessApprovalSettings(request);
// End snippet
}
/// <summary>Snippet for UpdateAccessApprovalSettingsAsync</summary>
public async Task UpdateAccessApprovalSettingsRequestObjectAsync()
{
// Snippet: UpdateAccessApprovalSettingsAsync(UpdateAccessApprovalSettingsMessage, CallSettings)
// Additional: UpdateAccessApprovalSettingsAsync(UpdateAccessApprovalSettingsMessage, CancellationToken)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync();
// Initialize request argument(s)
UpdateAccessApprovalSettingsMessage request = new UpdateAccessApprovalSettingsMessage
{
Settings = new AccessApprovalSettings(),
UpdateMask = new FieldMask(),
};
// Make the request
AccessApprovalSettings response = await accessApprovalServiceClient.UpdateAccessApprovalSettingsAsync(request);
// End snippet
}
/// <summary>Snippet for UpdateAccessApprovalSettings</summary>
public void UpdateAccessApprovalSettings()
{
// Snippet: UpdateAccessApprovalSettings(AccessApprovalSettings, FieldMask, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create();
// Initialize request argument(s)
AccessApprovalSettings settings = new AccessApprovalSettings();
FieldMask updateMask = new FieldMask();
// Make the request
AccessApprovalSettings response = accessApprovalServiceClient.UpdateAccessApprovalSettings(settings, updateMask);
// End snippet
}
/// <summary>Snippet for UpdateAccessApprovalSettingsAsync</summary>
public async Task UpdateAccessApprovalSettingsAsync()
{
// Snippet: UpdateAccessApprovalSettingsAsync(AccessApprovalSettings, FieldMask, CallSettings)
// Additional: UpdateAccessApprovalSettingsAsync(AccessApprovalSettings, FieldMask, CancellationToken)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync();
// Initialize request argument(s)
AccessApprovalSettings settings = new AccessApprovalSettings();
FieldMask updateMask = new FieldMask();
// Make the request
AccessApprovalSettings response = await accessApprovalServiceClient.UpdateAccessApprovalSettingsAsync(settings, updateMask);
// End snippet
}
/// <summary>Snippet for DeleteAccessApprovalSettings</summary>
public void DeleteAccessApprovalSettingsRequestObject()
{
// Snippet: DeleteAccessApprovalSettings(DeleteAccessApprovalSettingsMessage, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create();
// Initialize request argument(s)
DeleteAccessApprovalSettingsMessage request = new DeleteAccessApprovalSettingsMessage { Name = "", };
// Make the request
accessApprovalServiceClient.DeleteAccessApprovalSettings(request);
// End snippet
}
/// <summary>Snippet for DeleteAccessApprovalSettingsAsync</summary>
public async Task DeleteAccessApprovalSettingsRequestObjectAsync()
{
// Snippet: DeleteAccessApprovalSettingsAsync(DeleteAccessApprovalSettingsMessage, CallSettings)
// Additional: DeleteAccessApprovalSettingsAsync(DeleteAccessApprovalSettingsMessage, CancellationToken)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync();
// Initialize request argument(s)
DeleteAccessApprovalSettingsMessage request = new DeleteAccessApprovalSettingsMessage { Name = "", };
// Make the request
await accessApprovalServiceClient.DeleteAccessApprovalSettingsAsync(request);
// End snippet
}
/// <summary>Snippet for DeleteAccessApprovalSettings</summary>
public void DeleteAccessApprovalSettings()
{
// Snippet: DeleteAccessApprovalSettings(string, CallSettings)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = AccessApprovalServiceClient.Create();
// Initialize request argument(s)
string name = "";
// Make the request
accessApprovalServiceClient.DeleteAccessApprovalSettings(name);
// End snippet
}
/// <summary>Snippet for DeleteAccessApprovalSettingsAsync</summary>
public async Task DeleteAccessApprovalSettingsAsync()
{
// Snippet: DeleteAccessApprovalSettingsAsync(string, CallSettings)
// Additional: DeleteAccessApprovalSettingsAsync(string, CancellationToken)
// Create client
AccessApprovalServiceClient accessApprovalServiceClient = await AccessApprovalServiceClient.CreateAsync();
// Initialize request argument(s)
string name = "";
// Make the request
await accessApprovalServiceClient.DeleteAccessApprovalSettingsAsync(name);
// End snippet
}
}
}
| |
using AutoMapper;
using AutoMapper.QueryableExtensions;
using Microsoft.AspNet.Http.Authentication;
using Microsoft.Data.Entity;
using MvcTemplate.Components.Security;
using MvcTemplate.Data.Core;
using MvcTemplate.Objects;
using MvcTemplate.Services;
using MvcTemplate.Tests.Data;
using NSubstitute;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using Xunit;
namespace MvcTemplate.Tests.Unit.Services
{
public class AccountServiceTests : IDisposable
{
private AccountService service;
private TestingContext context;
private Account account;
private IHasher hasher;
public AccountServiceTests()
{
context = new TestingContext();
hasher = Substitute.For<IHasher>();
hasher.HashPassword(Arg.Any<String>()).Returns(info => info.Arg<String>() + "Hashed");
context.DropData();
SetUpData();
Authorization.Provider = Substitute.For<IAuthorizationProvider>();
service = new AccountService(new UnitOfWork(context), hasher);
service.CurrentAccountId = account.Id;
}
public void Dispose()
{
Authorization.Provider = null;
service.Dispose();
context.Dispose();
}
#region Method: Get<TView>(String id)
[Fact]
public void Get_ReturnsViewById()
{
AccountView actual = service.Get<AccountView>(account.Id);
AccountView expected = Mapper.Map<AccountView>(account);
Assert.Equal(expected.CreationDate, actual.CreationDate);
Assert.Equal(expected.RoleTitle, actual.RoleTitle);
Assert.Equal(expected.IsLocked, actual.IsLocked);
Assert.Equal(expected.Username, actual.Username);
Assert.Equal(expected.Email, actual.Email);
Assert.Equal(expected.Id, actual.Id);
}
#endregion
#region Method: GetViews()
[Fact]
public void GetViews_ReturnsAccountViews()
{
IEnumerator<AccountView> actual = service.GetViews().GetEnumerator();
IEnumerator<AccountView> expected = context
.Set<Account>()
.Project()
.To<AccountView>()
.OrderByDescending(account => account.CreationDate)
.GetEnumerator();
while (expected.MoveNext() | actual.MoveNext())
{
Assert.Equal(expected.Current.CreationDate, actual.Current.CreationDate);
Assert.Equal(expected.Current.RoleTitle, actual.Current.RoleTitle);
Assert.Equal(expected.Current.IsLocked, actual.Current.IsLocked);
Assert.Equal(expected.Current.Username, actual.Current.Username);
Assert.Equal(expected.Current.Email, actual.Current.Email);
Assert.Equal(expected.Current.Id, actual.Current.Id);
}
}
#endregion
#region Method: IsLoggedIn(IPrincipal user)
[Theory]
[InlineData(true)]
[InlineData(false)]
public void IsLoggedIn_ReturnsIsAuthenticated(Boolean expected)
{
IPrincipal user = Substitute.For<IPrincipal>();
user.Identity.IsAuthenticated.Returns(expected);
Boolean actual = service.IsLoggedIn(user);
Assert.Equal(expected, actual);
}
#endregion
#region Method: IsActive(String id)
[Theory]
[InlineData(true)]
[InlineData(false)]
public void IsActive_ReturnsAccountState(Boolean isLocked)
{
account.IsLocked = isLocked;
context.SaveChanges();
Boolean actual = service.IsActive(account.Id);
Boolean expected = !isLocked;
Assert.Equal(expected, actual);
}
[Fact]
public void IsActive_NoAccount_ReturnsFalse()
{
Assert.False(service.IsActive("Test"));
}
#endregion
#region Method: Recover(AccountRecoveryView view)
[Fact]
public void Recover_NoEmail_ReturnsNull()
{
AccountRecoveryView view = ObjectFactory.CreateAccountRecoveryView();
view.Email = "not@existing.email";
Assert.Null(service.Recover(view));
}
[Fact]
public void Recover_Information()
{
Account account = context.Set<Account>().AsNoTracking().Single();
account.RecoveryTokenExpirationDate = DateTime.Now.AddMinutes(30);
AccountRecoveryView view = ObjectFactory.CreateAccountRecoveryView();
view.Email = view.Email.ToUpper();
String expectedToken = service.Recover(view);
Account actual = context.Set<Account>().AsNoTracking().Single();
Account expected = account;
Assert.InRange(actual.RecoveryTokenExpirationDate.Value.Ticks,
expected.RecoveryTokenExpirationDate.Value.Ticks - TimeSpan.TicksPerSecond,
expected.RecoveryTokenExpirationDate.Value.Ticks + TimeSpan.TicksPerSecond);
Assert.NotEqual(expected.RecoveryToken, actual.RecoveryToken);
Assert.Equal(expected.CreationDate, actual.CreationDate);
Assert.Equal(expectedToken, actual.RecoveryToken);
Assert.Equal(expected.IsLocked, actual.IsLocked);
Assert.Equal(expected.Passhash, actual.Passhash);
Assert.Equal(expected.Username, actual.Username);
Assert.Equal(expected.RoleId, actual.RoleId);
Assert.Equal(expected.Email, actual.Email);
Assert.Equal(expected.Id, actual.Id);
Assert.NotNull(actual.RecoveryToken);
}
#endregion
#region Method: Register(AccountRegisterView view)
[Fact]
public void Register_Account()
{
AccountRegisterView view = ObjectFactory.CreateAccountRegisterView(2);
view.Email = view.Email.ToUpper();
service.Register(view);
Account actual = context.Set<Account>().AsNoTracking().Single(account => account.Id == view.Id);
AccountRegisterView expected = view;
Assert.Equal(hasher.HashPassword(expected.Password), actual.Passhash);
Assert.Equal(expected.CreationDate, actual.CreationDate);
Assert.Equal(expected.Email.ToLower(), actual.Email);
Assert.Equal(expected.Username, actual.Username);
Assert.Null(actual.RecoveryTokenExpirationDate);
Assert.Equal(expected.Id, actual.Id);
Assert.Null(actual.RecoveryToken);
Assert.False(actual.IsLocked);
Assert.Null(actual.RoleId);
Assert.Null(actual.Role);
}
#endregion
#region Method: Reset(AccountResetView view)
[Fact]
public void Reset_Account()
{
Account account = context.Set<Account>().AsNoTracking().Single();
AccountResetView view = ObjectFactory.CreateAccountResetView();
account.Passhash = hasher.HashPassword(view.NewPassword);
account.RecoveryTokenExpirationDate = null;
account.RecoveryToken = null;
service.Reset(view);
Account actual = context.Set<Account>().AsNoTracking().Single();
Account expected = account;
Assert.Equal(expected.RecoveryTokenExpirationDate, actual.RecoveryTokenExpirationDate);
Assert.Equal(expected.RecoveryToken, actual.RecoveryToken);
Assert.Equal(expected.CreationDate, actual.CreationDate);
Assert.Equal(expected.IsLocked, actual.IsLocked);
Assert.Equal(expected.Passhash, actual.Passhash);
Assert.Equal(expected.Username, actual.Username);
Assert.Equal(expected.RoleId, actual.RoleId);
Assert.Equal(expected.Email, actual.Email);
Assert.Equal(expected.Id, actual.Id);
}
#endregion
#region Method: Create(AccountCreateView view)
[Fact]
public void Create_Account()
{
AccountCreateView view = ObjectFactory.CreateAccountCreateView(2);
view.Email = view.Email.ToUpper();
view.RoleId = account.RoleId;
service.Create(view);
Account actual = context.Set<Account>().AsNoTracking().Single(acc => acc.Id == view.Id);
AccountCreateView expected = view;
Assert.Equal(hasher.HashPassword(expected.Password), actual.Passhash);
Assert.Equal(expected.CreationDate, actual.CreationDate);
Assert.Equal(expected.Email.ToLower(), actual.Email);
Assert.Equal(expected.Username, actual.Username);
Assert.Null(actual.RecoveryTokenExpirationDate);
Assert.Equal(expected.RoleId, actual.RoleId);
Assert.Equal(expected.Id, actual.Id);
Assert.Null(actual.RecoveryToken);
Assert.False(actual.IsLocked);
}
[Fact]
public void Create_RefreshesAuthorization()
{
AccountCreateView view = ObjectFactory.CreateAccountCreateView(2);
view.RoleId = null;
service.Create(view);
Authorization.Provider.Received().Refresh();
}
#endregion
#region Method: Edit(AccountEditView view)
[Fact]
public void Edit_Account()
{
Account account = context.Set<Account>().AsNoTracking().Single();
AccountEditView view = ObjectFactory.CreateAccountEditView();
view.IsLocked = account.IsLocked = !account.IsLocked;
view.Username = account.Username + "Test";
view.RoleId = account.RoleId = null;
view.Email = account.Email + "s";
service.Edit(view);
Account actual = context.Set<Account>().AsNoTracking().Single();
Account expected = account;
Assert.Equal(expected.RecoveryTokenExpirationDate, actual.RecoveryTokenExpirationDate);
Assert.Equal(expected.RecoveryToken, actual.RecoveryToken);
Assert.Equal(expected.CreationDate, actual.CreationDate);
Assert.Equal(expected.IsLocked, actual.IsLocked);
Assert.Equal(expected.Username, actual.Username);
Assert.Equal(expected.Passhash, actual.Passhash);
Assert.Equal(expected.RoleId, actual.RoleId);
Assert.Equal(expected.Email, actual.Email);
Assert.Equal(expected.Id, actual.Id);
}
[Fact]
public void Edit_RefreshesAuthorization()
{
AccountEditView view = ObjectFactory.CreateAccountEditView();
service.Edit(view);
Authorization.Provider.Received().Refresh();
}
#endregion
#region Method: Edit(ProfileEditView view)
[Fact]
public void Edit_Profile()
{
Account account = context.Set<Account>().AsNoTracking().Single();
ProfileEditView view = ObjectFactory.CreateProfileEditView(2);
account.Passhash = hasher.HashPassword(view.NewPassword);
view.Username = account.Username += "Test";
view.Email = account.Email += "Test";
service.Edit(view);
Account actual = context.Set<Account>().AsNoTracking().Single();
Account expected = account;
Assert.Equal(expected.RecoveryTokenExpirationDate, actual.RecoveryTokenExpirationDate);
Assert.Equal(expected.RecoveryToken, actual.RecoveryToken);
Assert.Equal(expected.CreationDate, actual.CreationDate);
Assert.Equal(expected.Email.ToLower(), actual.Email);
Assert.Equal(expected.IsLocked, actual.IsLocked);
Assert.Equal(expected.Username, actual.Username);
Assert.Equal(expected.Passhash, actual.Passhash);
Assert.Equal(expected.RoleId, actual.RoleId);
Assert.Equal(expected.Id, actual.Id);
}
[Theory]
[InlineData("")]
[InlineData(null)]
[InlineData(" ")]
public void Edit_NullOrEmptyNewPassword_DoesNotEditPassword(String newPassword)
{
String passhash = context.Set<Account>().AsNoTracking().Single().Passhash;
ProfileEditView view = ObjectFactory.CreateProfileEditView();
view.NewPassword = newPassword;
service.Edit(view);
String actual = context.Set<Account>().AsNoTracking().Single().Passhash;
String expected = passhash;
Assert.Equal(expected, actual);
}
#endregion
#region Method: Delete(String id)
[Fact]
public void Delete_Account()
{
service.Delete(account.Id);
Assert.Empty(context.Set<Account>());
}
[Fact]
public void Delete_RefreshesAuthorization()
{
service.Delete(account.Id);
Authorization.Provider.Received().Refresh();
}
#endregion
#region Method: Login(AuthenticationManager authentication, String username)
[Fact]
public void Login_Account()
{
AuthenticationManager authentication = Substitute.For<AuthenticationManager>();
service.Login(authentication, account.Username.ToUpper());
authentication.Received().SignInAsync("Cookies", Arg.Is<ClaimsPrincipal>(principal =>
principal.Claims.Single().Subject.NameClaimType == "name" &&
principal.Claims.Single().Subject.RoleClaimType == "role" &&
principal.Claims.Single().Subject.Name == account.Id &&
principal.Identity.AuthenticationType == "local" &&
principal.Identity.Name == account.Id &&
principal.Identity.IsAuthenticated));
}
#endregion
#region Method: Logout(AuthenticationManager authentication)
[Fact]
public void Logout_Account()
{
AuthenticationManager authentication = Substitute.For<AuthenticationManager>();
service.Logout(authentication);
authentication.Received().SignOutAsync("Cookies");
}
#endregion
#region Test helpers
private void SetUpData()
{
account = ObjectFactory.CreateAccount();
context.Set<Role>().Add(account.Role);
context.Set<Account>().Add(account);
context.SaveChanges();
}
#endregion
}
}
| |
using FontStashSharp;
using Myra.Utility;
#if MONOGAME || FNA
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
#elif STRIDE
using Stride.Core.Mathematics;
using Stride.Graphics;
using Texture2D = Stride.Graphics.Texture;
#else
using System.Drawing;
using Myra.Platform;
using System.Numerics;
using Texture2D = System.Object;
using Matrix = System.Numerics.Matrix3x2;
#endif
namespace Myra.Graphics2D
{
public enum TextureFiltering
{
Nearest,
Linear
}
public partial class RenderContext
{
#if MONOGAME || FNA
private static RasterizerState _uiRasterizerState;
private static RasterizerState UIRasterizerState
{
get
{
if (_uiRasterizerState != null)
{
return _uiRasterizerState;
}
_uiRasterizerState = new RasterizerState
{
ScissorTestEnable = true
};
return _uiRasterizerState;
}
}
#elif STRIDE
private static readonly RasterizerStateDescription _uiRasterizerState;
static RenderContext()
{
var rs = new RasterizerStateDescription();
rs.SetDefault();
rs.ScissorTestEnable = true;
_uiRasterizerState = rs;
}
#endif
#if MONOGAME || FNA || STRIDE
private readonly SpriteBatch _renderer;
#else
private readonly IMyraRenderer _renderer;
private readonly FontStashRenderer _fontStashRenderer;
#endif
private bool _beginCalled;
private Rectangle _scissor;
private Matrix? _transform;
private TextureFiltering _textureFiltering = TextureFiltering.Nearest;
public Matrix? Transform
{
get
{
return _transform;
}
set
{
if (value == _transform)
{
return;
}
_transform = value;
if (_transform != null)
{
#if MONOGAME || FNA || STRIDE
InverseTransform = Matrix.Invert(_transform.Value);
#else
Matrix inverse = Matrix.Identity;
Matrix.Invert(_transform.Value, out inverse);
InverseTransform = inverse;
#endif
}
Flush();
}
}
internal Matrix InverseTransform { get; set; }
public Rectangle Scissor
{
get
{
return _scissor;
}
set
{
_scissor = value;
if (MyraEnvironment.DisableClipping)
{
return;
}
if (Transform != null)
{
var pos = Vector2.Transform(new Vector2(value.X, value.Y), Transform.Value);
var size = Vector2.Transform(new Vector2(value.Width, value.Height), Transform.Value);
value = new Rectangle((int)pos.X, (int)pos.Y, (int)size.X, (int)size.Y);
}
#if MONOGAME || FNA
Flush();
var device = _renderer.GraphicsDevice;
value.X += device.Viewport.X;
value.Y += device.Viewport.Y;
device.ScissorRectangle = value;
#elif STRIDE
Flush();
MyraEnvironment.Game.GraphicsContext.CommandList.SetScissorRectangle(value);
#else
_renderer.Scissor = value;
#endif
}
}
public Rectangle View { get; set; }
public float Opacity { get; set; }
public RenderContext()
{
#if MONOGAME || FNA || STRIDE
_renderer = new SpriteBatch(MyraEnvironment.Game.GraphicsDevice);
#else
_renderer = MyraEnvironment.Platform.CreateRenderer();
_fontStashRenderer = new FontStashRenderer(_renderer);
#endif
_scissor = GetDeviceScissor();
}
private Rectangle GetDeviceScissor()
{
#if MONOGAME || FNA
var device = _renderer.GraphicsDevice;
var rect = device.ScissorRectangle;
rect.X -= device.Viewport.X;
rect.Y -= device.Viewport.Y;
return rect;
#elif STRIDE
return MyraEnvironment.Game.GraphicsContext.CommandList.Scissor;
#else
return _renderer.Scissor;
#endif
}
private void SetTextureFiltering(TextureFiltering value)
{
if (_textureFiltering == value)
{
return;
}
_textureFiltering = value;
Flush();
}
public void Draw(Texture2D texture, Rectangle destinationRectangle, Rectangle? sourceRectangle, Color color)
{
SetTextureFiltering(TextureFiltering.Nearest);
color = CrossEngineStuff.MultiplyColor(color, Opacity);
#if MONOGAME || FNA
_renderer.Draw(texture, destinationRectangle, sourceRectangle, color);
#elif STRIDE
_renderer.Draw(texture, destinationRectangle, sourceRectangle, color, 0, Vector2.Zero);
#else
_renderer.Draw(texture, destinationRectangle, sourceRectangle, color);
#endif
}
#if MONOGAME || FNA || STRIDE
public void Draw(Texture2D texture, Rectangle destinationRectangle, Color color)
{
SetTextureFiltering(TextureFiltering.Nearest);
color = CrossEngineStuff.MultiplyColor(color, Opacity);
_renderer.Draw(texture, destinationRectangle, color);
}
public void Draw(Texture2D texture, Vector2 position, Color color)
{
SetTextureFiltering(TextureFiltering.Nearest);
color = CrossEngineStuff.MultiplyColor(color, Opacity);
_renderer.Draw(texture, position, color);
}
public void Draw(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color)
{
SetTextureFiltering(TextureFiltering.Nearest);
color = CrossEngineStuff.MultiplyColor(color, Opacity);
_renderer.Draw(texture, position, sourceRectangle, color);
}
public void Draw(Texture2D texture, Rectangle destinationRectangle, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, SpriteEffects effects, float layerDepth)
{
SetTextureFiltering(TextureFiltering.Nearest);
color = CrossEngineStuff.MultiplyColor(color, Opacity);
#if MONOGAME || FNA
_renderer.Draw(texture, destinationRectangle, sourceRectangle, color, rotation, origin, effects, layerDepth);
#else
_renderer.Draw(texture, destinationRectangle, sourceRectangle, color, rotation, origin, effects, ImageOrientation.AsIs, layerDepth);
#endif
}
public void Draw(Texture2D texture, Vector2 position, Rectangle? sourceRectangle, Color color, float rotation, Vector2 origin, Vector2 scale, SpriteEffects effects, float layerDepth)
{
SetTextureFiltering(TextureFiltering.Nearest);
color = CrossEngineStuff.MultiplyColor(color, Opacity);
#if MONOGAME || FNA
_renderer.Draw(texture, position, sourceRectangle, color, rotation, origin, scale, effects, layerDepth);
#else
_renderer.Draw(texture, position, sourceRectangle, color, rotation, origin, scale, effects, ImageOrientation.AsIs, layerDepth);
#endif
}
#endif
private void SetTextTextureFiltering()
{
if (!MyraEnvironment.SmoothText)
{
SetTextureFiltering(TextureFiltering.Nearest);
}
else
{
SetTextureFiltering(TextureFiltering.Linear);
}
}
/// <summary>
/// Draws a text
/// </summary>
/// <param name="text">The text which will be drawn.</param>
/// <param name="position">The drawing location on screen.</param>
/// <param name="color">A color mask.</param>
/// <param name="rotation">A rotation of this text in radians.</param>
/// <param name="origin">Center of the rotation.</param>
/// <param name="scale">A scaling of this text.</param>
/// <param name="layerDepth">A depth of the layer of this string.</param>
public void DrawString(SpriteFontBase font, string text, Vector2 position, Color color, Vector2 scale, float rotation, Vector2 origin, float layerDepth = 0.0f)
{
SetTextTextureFiltering();
color = CrossEngineStuff.MultiplyColor(color, Opacity);
#if MONOGAME || FNA || STRIDE
font.DrawText(_renderer, text, position, color, scale, rotation, origin, layerDepth);
#else
font.DrawText(_fontStashRenderer, text, position, color, scale, rotation, origin, layerDepth);
#endif
}
public void DrawString(SpriteFontBase font, string text, Vector2 position, Color color, Vector2 scale, float layerDepth = 0.0f)
{
SetTextTextureFiltering();
color = CrossEngineStuff.MultiplyColor(color, Opacity);
#if MONOGAME || FNA || STRIDE
font.DrawText(_renderer, text, position, color, scale, layerDepth);
#else
font.DrawText(_fontStashRenderer, text, position, color, scale, layerDepth);
#endif
}
/// <summary>
/// Draws a text
/// </summary>
/// <param name="text">The text which will be drawn.</param>
/// <param name="position">The drawing location on screen.</param>
/// <param name="color">A color mask.</param>
/// <param name="layerDepth">A depth of the layer of this string.</param>
public void DrawString(SpriteFontBase font, string text, Vector2 position, Color color, float layerDepth = 0.0f)
{
SetTextTextureFiltering();
color = CrossEngineStuff.MultiplyColor(color, Opacity);
#if MONOGAME || FNA || STRIDE
font.DrawText(_renderer, text, position, color, layerDepth);
#else
font.DrawText(_fontStashRenderer, text, position, color, layerDepth);
#endif
}
/// <summary>
/// Draws a text
/// </summary>
/// <param name="text">The text which will be drawn.</param>
/// <param name="position">The drawing location on screen.</param>
/// <param name="colors">Colors of glyphs.</param>
/// <param name="rotation">A rotation of this text in radians.</param>
/// <param name="origin">Center of the rotation.</param>
/// <param name="scale">A scaling of this text.</param>
/// <param name="layerDepth">A depth of the layer of this string.</param>
public void DrawString(SpriteFontBase font, string text, Vector2 position, Color[] colors, Vector2 scale, float rotation, Vector2 origin, float layerDepth = 0.0f)
{
SetTextTextureFiltering();
#if MONOGAME || FNA || STRIDE
font.DrawText(_renderer, text, position, colors, scale, rotation, origin, layerDepth);
#else
font.DrawText(_fontStashRenderer, text, position, colors, scale, rotation, origin, layerDepth);
#endif
}
public void Begin()
{
#if MONOGAME || FNA
var samplerState = _textureFiltering == TextureFiltering.Nearest ? SamplerState.PointClamp : SamplerState.LinearClamp;
_renderer.Begin(SpriteSortMode.Deferred,
BlendState.AlphaBlend,
samplerState,
null,
UIRasterizerState,
null,
Transform != null ? Transform.Value : Matrix.Identity);
#elif STRIDE
var samplerState = _textureFiltering == TextureFiltering.Nearest ?
MyraEnvironment.Game.GraphicsDevice.SamplerStates.PointClamp :
MyraEnvironment.Game.GraphicsDevice.SamplerStates.LinearClamp;
if (Transform == null)
{
_renderer.Begin(MyraEnvironment.Game.GraphicsContext,
SpriteSortMode.Deferred,
BlendStates.AlphaBlend,
samplerState,
null,
_uiRasterizerState);
} else
{
_renderer.Begin(MyraEnvironment.Game.GraphicsContext,
Transform.Value,
SpriteSortMode.Deferred,
BlendStates.AlphaBlend,
samplerState,
null,
_uiRasterizerState);
}
#else
_renderer.Begin(Transform, _textureFiltering);
#endif
_beginCalled = true;
}
public void End()
{
_renderer.End();
_beginCalled = false;
}
public void Flush()
{
if (!_beginCalled)
{
return;
}
End();
Begin();
}
}
}
| |
#region Header
/**************************************
* FILE: Machine.cs
* DATE: 13.08.2009 16:41:46
* AUTHOR: Raphael B. Estrada
* AUTHOR URL: http://www.galaktor.net
* AUTHOR E-MAIL: galaktor@gmx.de
*
* The MIT License
*
* Copyright (c) 2009 Raphael B. Estrada
* Author URL: http://www.galaktor.net
* Author E-Mail: galaktor@gmx.de
*
* 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 Header
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using NGin.Core.Logging;
using NGin.Core.Scene;
namespace NGin.Core.States.RHFSM
{
/// <summary>
/// A hierarchical finite state machine that operates recursively on an n-ary state tree.
/// <remarks>Automatically manages a root state of the type <see cref="RHFSM.MachineRoot"/>. Every other state will become a child of the root.</remarks>
/// </summary>
public class Machine : IDisposable, IMachine
{
#region Fields
#region Private Fields
private IState activeState;
// locks for thread-safety
private object activeStateLock = new object();
private bool isRunning = false;
private object isRunningLock = new object();
private object transitionLock = new object();
#endregion Private Fields
#endregion Fields
#region Constructors
#region Public Constructors
public ILogManager LogManager { get; internal set; }
/// <summary>
/// Creates a new machine. Automatically generates a root state of the type <see cref="RHFSM.MachineRoot"/>
/// </summary>
public Machine(ILogManager logManager )
{
this.RootState = new MachineRoot( this, logManager );
this.LogManager = logManager;
}
#endregion Public Constructors
#endregion Constructors
#region Events
#region Public Events
/// <summary>
/// This event is fired every time the machine starts or stops running.
/// </summary>
public event IsRunningChangedDelegate IsRunningChanged;
#endregion Public Events
#endregion Events
#region Properties
#region Public Properties
/// <summary>
/// Gets the most deepest active state within the whole tree.
/// </summary>
/// <remarks>By default this is the automatically generated <see cref="RHFSM.Machine.RootState"/>.
/// Only if the machine every segues to another state, that will be the active state.</remarks>
public IState ActiveState
{
get
{
lock ( this.activeStateLock )
{
return activeState;
}
}
private set
{
lock ( this.activeStateLock )
{
IState oldState = null;
if ( this.activeState != null )
{
// save ref to old state
oldState = this.activeState;
// unregister event handler from old state
oldState.TransitToStateRequested -= this.ActiveState_SegueToStateRequested;
}
// save new state
this.activeState = value;
// register event handler for new state
this.activeState.TransitToStateRequested += new TransitToStateDelegate( this.ActiveState_SegueToStateRequested );
}
// if there is an initial substate for the active state, then transit to it
if ( this.activeState != null && !String.IsNullOrEmpty( this.activeState.InitialSubStateName ) )
{
this.TransitToState( State.CombineStateNames( this.activeState.AbsolutePath, this.activeState.InitialSubStateName ) );
}
}
}
/// <summary>
/// Gets a value indicating if the machine is currently running or if it is deactivated.
/// </summary>
public bool IsRunning
{
get
{
lock ( this.isRunningLock )
{
return this.isRunning;
}
}
set
{
lock ( this.isRunningLock )
{
bool statusOld = this.isRunning;
this.isRunning = value;
this.FireIsRunningChangedEvent( statusOld, this.isRunning );
}
}
}
/// <summary>
/// Gets the machines root state.
/// </summary>
/// <remarks>The root state is the only state that will have no parents (null). It also is the only state with a <see cref="RHFSM.State.Depth"/>of 0.</remarks>
public IState RootState
{
get; private set;
}
#endregion Public Properties
#endregion Properties
#region Methods
#region Public Methods
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
this.Dispose( true );
GC.SuppressFinalize( this );
}
/// <summary>
/// Initializes the state machine. The given intial state id will be entered.
/// </summary>
/// <param name="initialStateName">Initial name of the state.</param>
public void Initialize(string initialStateName)
{
// set active stat to root
this.ActiveState = this.RootState;
this.IsRunning = true;
// if initial state was defined
if ( !String.IsNullOrEmpty( initialStateName ) )
{
// transit to initial state
this.TransitToState( initialStateName );
}
}
/// <summary>
/// Shutdowns the state machine. All active states will be exited and optionally disposed.
/// </summary>
/// <param name="autoDispose">If set to <c>true</c> the machine will dispose all substates as well as itself automatically.</param>
/// <remarks>Set <paramref name="autoDispose"/> to <c>false</c> if you wish to dispose your states by yourself. Remember to dispose the machine later.</remarks>
/// <seealso cref="RHFSM.Machine.Dispose()"/>
public void Shutdown( bool autoDispose )
{
// translate to root so that all active substates can exit properly
this.TransitToState( this.RootState.Name );
this.IsRunning = false;
this.RootState.ClearSubStates();
if ( autoDispose )
{
// dispose
this.Dispose();
}
}
#endregion Public Methods
#region Internal Methods
/// <summary>
/// Handles the event of the <see cref="RHFSM.Machine.ActiveState"/> requesting a transition to another state.
/// </summary>
/// <param name="sender">The state that requested a transition.</param>
/// <param name="e">The event data.</param>
internal void ActiveState_SegueToStateRequested( object sender, TransitToStateEventArgs e )
{
if ( e == null )
{
throw new ArgumentNullException( "e", "The received event arguments must not be null." );
}
this.TransitToState( e.TargetStateAbsolutePath );
}
/// <summary>
/// Calls all <see cref="RHFSM.State.Enter"/> methods on all states from the ancestor to the target state in the correct order.
/// </summary>
/// <param name="targetState">The target state down to which <see cref="RHFSM.State.Enter"/> of all states will be called. This state will be entered, too.</param>
/// <param name="startAncestor">The ancestor that will function as a starting point for the calls downwards through all states.
/// This state will not be entered, since it already should be active.</param>
/// <remarks>This algorithm is recursive. It moves from the <paramref name="targetState"/> up to the <paramref name="startAncestor"/>.
/// When the ancestor is found, it drops all the way back, calling the <see cref="RHFSM.State.Enter"/> method in the correct order.</remarks>
internal void EnterAncestors( IState targetState, IState startAncestor )
{
if ( targetState == null )
{
throw new ArgumentNullException( "targetState", "The given state must not be null." );
}
if ( startAncestor == null )
{
throw new ArgumentNullException( "startAncestor", "The given state must not be null." );
}
if ( startAncestor.Depth > targetState.Depth )
{
throw new InvalidOperationException( "The start ancestor must not be deeper than the target state." );
}
// IF current is nca, Enter() it and return.
if ( targetState == startAncestor )
{
return;
}
IState nextParent = targetState.Parent == null ? targetState : targetState.Parent;
this.EnterAncestors( nextParent, startAncestor );
targetState.Enter();
}
/// <summary>
/// Exits all states upwards, beginning with <paramref name="startState"/> and stopping right before <paramref name="targetAncestor"/>.
/// </summary>
/// <param name="startState">The starting point of the path upwards. This state will be exited, too.</param>
/// <param name="targetAncestor">The end of the path of states that will be exited. This state will not be exited.</param>
/// <remarks>This algorithm is not recursive. It moves from the <paramref name="startState"/> up to the <paramref name="targetAncestor"/>,
/// calling Enter on each state in between.</remarks>
internal void ExitAncestors( IState startState, IState targetAncestor )
{
if ( startState == null )
{
throw new ArgumentNullException( "startState", "The given state must not be null." );
}
if ( targetAncestor == null )
{
throw new ArgumentNullException( "targetAncestor", "The given state must not be null." );
}
if ( targetAncestor.Depth > startState.Depth )
{
throw new InvalidOperationException( "The target ancestor must not be deeper than the start state." );
}
while ( startState != targetAncestor )
{
startState.Exit();
startState = startState.Parent;
}
}
/// <summary>
/// Finds the nearest common ancestor of two states in the tree.
/// </summary>
/// <param name="firstState">The first of two states to perform the search for.</param>
/// <param name="secondState">The second of two states to perform the search for.</param>
/// <returns>The state that is found to be the nearest common ancestor of the two given states.</returns>
/// <remarks>This should never be used directly. It is only intended for tests. This algorithm is recursive. It compares
/// all three combinations of the given state's two ancestor generations.
/// If a parent is null, the next child is used instead, since the only state in the tree that can have null parents is
/// the root. This method always returns a result, in the worst case the root itself. Runtime complexity is O(3*d), with 'd'
/// being the depth steps between the NCA and the deeper of both given states.</remarks>
internal IState FindNearestCommonAncestorState( IState firstState, IState secondState )
{
if ( firstState == null )
{
throw new ArgumentNullException( "firstState", "The given state must not be null." );
}
if ( secondState == null )
{
throw new ArgumentNullException( "secondState", "The given state must not be null." );
}
IState deeperState = this.GetDeepestState( firstState, secondState );
IState higherState = ( firstState == deeperState ) ? secondState : firstState;
if ( deeperState.Parent == higherState )
{
return higherState;
}
else if ( higherState.Parent == deeperState )
{
return deeperState;
}
IState deeperParent = deeperState.Parent == null ? deeperState : deeperState.Parent;
IState higherParent = higherState.Parent == null ? higherState : higherState.Parent;
// if input states are identical to next input states, then a stack overflow has been detected
if ( deeperParent == firstState &&
higherParent == secondState )
{
throw new InvalidOperationException( "A potential stack overflow was detected." );
}
if ( deeperParent == higherParent )
{
// no matter which one to return, both are equal
return deeperParent;
}
else if ( deeperParent.Parent == higherParent )
{
return higherParent;
}
else if ( higherParent.Parent == deeperParent )
{
return deeperParent;
}
return FindNearestCommonAncestorState( deeperParent, higherParent );
}
/// <summary>
/// Fires an event announcing that <see cref="RHFSM.Machine.IsRunning"/> property has changed.
/// </summary>
/// <param name="statusOld">The old value of <see cref="RHFSM.Machine.IsRunning"/>.</param>
/// <param name="statusNew">The new value of <see cref="RHFSM.Machine.IsRunning"/>.</param>
internal void FireIsRunningChangedEvent( bool statusOld, bool statusNew )
{
if ( this.IsRunningChanged != null )
{
this.IsRunningChanged.Invoke( this, new IsRunningChangedEventArgs( this, statusOld, statusNew ) );
}
}
/// <summary>
/// Compares the <see cref="RHFSM.State.Depth"/> property of two states and returns the deeper of both. If both
/// are equal deep it just returns the first on.
/// </summary>
/// <param name="one">The first state.</param>
/// <param name="two">The second state.</param>
/// <returns>The deeper of both given states.</returns>
/// <remarks>This should never be used directly. It is only intended for tests.</remarks>
internal IState GetDeepestState( IState one, IState two )
{
if ( one == null )
{
throw new ArgumentNullException( "one", "The given state must not be null." );
}
if ( two == null )
{
throw new ArgumentNullException( "two", "The given state must not be null." );
}
if ( one.Depth >= two.Depth )
{
return one;
}
else
{
return two;
}
}
/// <summary>
/// Initializes the state machine. The machine will initialize at root state.
/// </summary>
/// <remarks>This should never be used directly. It is only intended for tests.</remarks>
internal void Initialize()
{
this.Initialize( null );
}
/// <summary>
/// Performs a transition to the given state identified by it's absolute path.
/// </summary>
/// <param name="targetStateAbsolutePath">The target state absolute path. An absolute path describes the state's location from the root state's point of view.
/// The path consists of the states names separated by the <see cref="RHFSM.State.SUBSTATE_SEPARATOR_CHARACTER"/>.</param>
/// <returns>The state that is active after the transition.</returns>
/// <remarks>This should never be used directly. It is only intended for tests.</remarks>
internal IState TransitToState( string targetStateAbsolutePath )
{
if ( String.IsNullOrEmpty( targetStateAbsolutePath ) )
{
throw new ArgumentNullException( "targetStateAbsolutePath", "The given target state path must not be empty or null." );
}
IState result = null;
lock ( this.transitionLock )
{
// get current and target state
IState currentState = this.ActiveState;
if ( targetStateAbsolutePath == currentState.AbsolutePath )
{
return currentState;
}
IState targetState = this.RootState[ targetStateAbsolutePath ];
IState nca = this.FindNearestCommonAncestorState( currentState, targetState );
// call all Exit() methods on the way up from current to nca
// TODO: what if a parent turns out to be null before reaching ROOT?
// this would indicate a broken tree, since only ROOT may have null as a parent
// still, this should be handled properly by throwing e.g. an InvalidOperationException
this.ExitAncestors( currentState, nca );
// call all Enter() methods on the way down from nca to target
this.EnterAncestors( targetState, nca );
// set active state to new state
this.ActiveState = targetState;
( ( State ) currentState ).IsCurrent = false;
( ( State ) this.ActiveState ).IsCurrent = true;
// save return value
result = targetState;
}
// return new state
return result;
}
#endregion Internal Methods
#region Private Methods
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
private void Dispose( bool disposing )
{
// release unmanaged resources
if ( disposing )
{
lock ( this.transitionLock )
{
// release managed resources
this.RootState.Dispose();
this.RootState = null;
}
//// do not nullify to prevent NullPointerExceptions after disposal
//this.transitionLock = null;
//this.activeStateLock = null;
//this.isRunningLock = null;
}
}
#endregion Private Methods
#endregion Methods
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Avalonia.Media;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Rendering.SceneGraph;
using Avalonia.Utilities;
using Avalonia.Visuals.Media.Imaging;
namespace Avalonia.Headless
{
internal class HeadlessPlatformRenderInterface : IPlatformRenderInterface
{
public static void Initialize()
{
AvaloniaLocator.CurrentMutable
.Bind<IPlatformRenderInterface>().ToConstant(new HeadlessPlatformRenderInterface());
}
public IEnumerable<string> InstalledFontNames { get; } = new[] { "Tahoma" };
public bool SupportsIndividualRoundRects => false;
public AlphaFormat DefaultAlphaFormat => AlphaFormat.Premul;
public PixelFormat DefaultPixelFormat => PixelFormat.Rgba8888;
public IFormattedTextImpl CreateFormattedText(string text, Typeface typeface, double fontSize, TextAlignment textAlignment, TextWrapping wrapping, Size constraint, IReadOnlyList<FormattedTextStyleSpan> spans)
{
return new HeadlessFormattedTextStub(text, constraint);
}
public IGeometryImpl CreateEllipseGeometry(Rect rect) => new HeadlessGeometryStub(rect);
public IGeometryImpl CreateLineGeometry(Point p1, Point p2)
{
var tl = new Point(Math.Min(p1.X, p2.X), Math.Min(p1.Y, p2.Y));
var br = new Point(Math.Max(p1.X, p2.X), Math.Max(p1.Y, p2.Y));
return new HeadlessGeometryStub(new Rect(tl, br));
}
public IGeometryImpl CreateRectangleGeometry(Rect rect)
{
return new HeadlessGeometryStub(rect);
}
public IStreamGeometryImpl CreateStreamGeometry() => new HeadlessStreamingGeometryStub();
public IGeometryImpl CreateGeometryGroup(FillRule fillRule, IReadOnlyList<Geometry> children) => throw new NotImplementedException();
public IGeometryImpl CreateCombinedGeometry(GeometryCombineMode combineMode, Geometry g1, Geometry g2) => throw new NotImplementedException();
public IRenderTarget CreateRenderTarget(IEnumerable<object> surfaces) => new HeadlessRenderTarget();
public IRenderTargetBitmapImpl CreateRenderTargetBitmap(PixelSize size, Vector dpi)
{
return new HeadlessBitmapStub(size, dpi);
}
public IWriteableBitmapImpl CreateWriteableBitmap(PixelSize size, Vector dpi, PixelFormat format, AlphaFormat alphaFormat)
{
return new HeadlessBitmapStub(size, dpi);
}
public IBitmapImpl LoadBitmap(string fileName)
{
return new HeadlessBitmapStub(new Size(1, 1), new Vector(96, 96));
}
public IBitmapImpl LoadBitmap(Stream stream)
{
return new HeadlessBitmapStub(new Size(1, 1), new Vector(96, 96));
}
public IWriteableBitmapImpl LoadWriteableBitmapToWidth(Stream stream, int width,
BitmapInterpolationMode interpolationMode = BitmapInterpolationMode.HighQuality)
{
return new HeadlessBitmapStub(new Size(1, 1), new Vector(96, 96));
}
public IWriteableBitmapImpl LoadWriteableBitmapToHeight(Stream stream, int height,
BitmapInterpolationMode interpolationMode = BitmapInterpolationMode.HighQuality)
{
return new HeadlessBitmapStub(new Size(1, 1), new Vector(96, 96));
}
public IWriteableBitmapImpl LoadWriteableBitmap(string fileName)
{
return new HeadlessBitmapStub(new Size(1, 1), new Vector(96, 96));
}
public IWriteableBitmapImpl LoadWriteableBitmap(Stream stream)
{
return new HeadlessBitmapStub(new Size(1, 1), new Vector(96, 96));
}
public IBitmapImpl LoadBitmap(PixelFormat format, AlphaFormat alphaFormat, IntPtr data, PixelSize size, Vector dpi, int stride)
{
return new HeadlessBitmapStub(new Size(1, 1), new Vector(96, 96));
}
public IBitmapImpl LoadBitmapToWidth(Stream stream, int width, BitmapInterpolationMode interpolationMode = BitmapInterpolationMode.HighQuality)
{
return new HeadlessBitmapStub(new Size(width, width), new Vector(96, 96));
}
public IBitmapImpl LoadBitmapToHeight(Stream stream, int height, BitmapInterpolationMode interpolationMode = BitmapInterpolationMode.HighQuality)
{
return new HeadlessBitmapStub(new Size(height, height), new Vector(96, 96));
}
public IBitmapImpl ResizeBitmap(IBitmapImpl bitmapImpl, PixelSize destinationSize, BitmapInterpolationMode interpolationMode = BitmapInterpolationMode.HighQuality)
{
return new HeadlessBitmapStub(destinationSize, new Vector(96, 96));
}
public IGlyphRunImpl CreateGlyphRun(GlyphRun glyphRun)
{
return new HeadlessGlyphRunStub();
}
class HeadlessGeometryStub : IGeometryImpl
{
public HeadlessGeometryStub(Rect bounds)
{
Bounds = bounds;
}
public Rect Bounds { get; set; }
public double ContourLength { get; } = 0;
public virtual bool FillContains(Point point) => Bounds.Contains(point);
public Rect GetRenderBounds(IPen pen)
{
if(pen is null)
{
return Bounds;
}
return Bounds.Inflate(pen.Thickness / 2);
}
public bool StrokeContains(IPen pen, Point point)
{
return false;
}
public IGeometryImpl Intersect(IGeometryImpl geometry)
=> new HeadlessGeometryStub(geometry.Bounds.Intersect(Bounds));
public ITransformedGeometryImpl WithTransform(Matrix transform) =>
new HeadlessTransformedGeometryStub(this, transform);
public bool TryGetPointAtDistance(double distance, out Point point)
{
point = new Point();
return false;
}
public bool TryGetPointAndTangentAtDistance(double distance, out Point point, out Point tangent)
{
point = new Point();
tangent = new Point();
return false;
}
public bool TryGetSegment(double startDistance, double stopDistance, bool startOnBeginFigure, out IGeometryImpl segmentGeometry)
{
segmentGeometry = null;
return false;
}
}
class HeadlessTransformedGeometryStub : HeadlessGeometryStub, ITransformedGeometryImpl
{
public HeadlessTransformedGeometryStub(IGeometryImpl b, Matrix transform) : this(Fix(b, transform))
{
}
static (IGeometryImpl, Matrix, Rect) Fix(IGeometryImpl b, Matrix transform)
{
if (b is HeadlessTransformedGeometryStub transformed)
{
b = transformed.SourceGeometry;
transform = transformed.Transform * transform;
}
return (b, transform, b.Bounds.TransformToAABB(transform));
}
private HeadlessTransformedGeometryStub((IGeometryImpl b, Matrix transform, Rect bounds) fix) : base(fix.bounds)
{
SourceGeometry = fix.b;
Transform = fix.transform;
}
public IGeometryImpl SourceGeometry { get; }
public Matrix Transform { get; }
}
class HeadlessGlyphRunStub : IGlyphRunImpl
{
public void Dispose()
{
}
}
class HeadlessStreamingGeometryStub : HeadlessGeometryStub, IStreamGeometryImpl
{
public HeadlessStreamingGeometryStub() : base(Rect.Empty)
{
}
public IStreamGeometryImpl Clone()
{
return this;
}
public IStreamGeometryContextImpl Open()
{
return new HeadlessStreamingGeometryContextStub(this);
}
class HeadlessStreamingGeometryContextStub : IStreamGeometryContextImpl
{
private readonly HeadlessStreamingGeometryStub _parent;
private double _x1, _y1, _x2, _y2;
public HeadlessStreamingGeometryContextStub(HeadlessStreamingGeometryStub parent)
{
_parent = parent;
}
void Track(Point pt)
{
if (_x1 > pt.X)
_x1 = pt.X;
if (_x2 < pt.X)
_x2 = pt.X;
if (_y1 > pt.Y)
_y1 = pt.Y;
if (_y2 < pt.Y)
_y2 = pt.Y;
}
public void Dispose()
{
_parent.Bounds = new Rect(_x1, _y1, _x2 - _x1, _y2 - _y1);
}
public void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection)
=> Track(point);
public void BeginFigure(Point startPoint, bool isFilled = true) => Track(startPoint);
public void CubicBezierTo(Point point1, Point point2, Point point3)
{
Track(point1);
Track(point2);
Track(point3);
}
public void QuadraticBezierTo(Point control, Point endPoint)
{
Track(control);
Track(endPoint);
}
public void LineTo(Point point) => Track(point);
public void EndFigure(bool isClosed)
{
Dispose();
}
public void SetFillRule(FillRule fillRule)
{
}
}
}
class HeadlessBitmapStub : IBitmapImpl, IDrawingContextLayerImpl, IWriteableBitmapImpl
{
public Size Size { get; }
public HeadlessBitmapStub(Size size, Vector dpi)
{
Size = size;
Dpi = dpi;
var pixel = Size * (Dpi / 96);
PixelSize = new PixelSize(Math.Max(1, (int)pixel.Width), Math.Max(1, (int)pixel.Height));
}
public HeadlessBitmapStub(PixelSize size, Vector dpi)
{
PixelSize = size;
Dpi = dpi;
Size = PixelSize.ToSizeWithDpi(dpi);
}
public void Dispose()
{
}
public IDrawingContextImpl CreateDrawingContext(IVisualBrushRenderer visualBrushRenderer)
{
return new HeadlessDrawingContextStub();
}
public void Blit(IDrawingContextImpl context)
{
}
public bool CanBlit => false;
public Vector Dpi { get; }
public PixelSize PixelSize { get; }
public int Version { get; set; }
public void Save(string fileName)
{
}
public void Save(Stream stream)
{
}
public ILockedFramebuffer Lock()
{
Version++;
var mem = Marshal.AllocHGlobal(PixelSize.Width * PixelSize.Height * 4);
return new LockedFramebuffer(mem, PixelSize, PixelSize.Width * 4, Dpi, PixelFormat.Rgba8888,
() => Marshal.FreeHGlobal(mem));
}
}
class HeadlessDrawingContextStub : IDrawingContextImpl
{
public void Dispose()
{
}
public Matrix Transform { get; set; }
public void Clear(Color color)
{
}
public void DrawText(IBrush foreground, Point origin, IFormattedTextImpl text)
{
}
public IDrawingContextLayerImpl CreateLayer(Size size)
{
return new HeadlessBitmapStub(size, new Vector(96, 96));
}
public void PushClip(Rect clip)
{
}
public void PopClip()
{
}
public void PushOpacity(double opacity)
{
}
public void PopOpacity()
{
}
public void PushOpacityMask(IBrush mask, Rect bounds)
{
}
public void PopOpacityMask()
{
}
public void PushGeometryClip(IGeometryImpl clip)
{
}
public void PopGeometryClip()
{
}
public void PushBitmapBlendMode(BitmapBlendingMode blendingMode)
{
}
public void PopBitmapBlendMode()
{
}
public void Custom(ICustomDrawOperation custom)
{
}
public void DrawLine(IPen pen, Point p1, Point p2)
{
throw new NotImplementedException();
}
public void DrawGeometry(IBrush brush, IPen pen, IGeometryImpl geometry)
{
}
public void DrawRectangle(IPen pen, Rect rect, float cornerRadius = 0)
{
}
public void DrawBitmap(IRef<IBitmapImpl> source, double opacity, Rect sourceRect, Rect destRect, BitmapInterpolationMode bitmapInterpolationMode = BitmapInterpolationMode.Default)
{
}
public void DrawBitmap(IRef<IBitmapImpl> source, IBrush opacityMask, Rect opacityMaskRect, Rect destRect)
{
}
public void DrawRectangle(IBrush brush, IPen pen, RoundedRect rect, BoxShadows boxShadow = default)
{
}
public void DrawEllipse(IBrush brush, IPen pen, Rect rect)
{
}
public void DrawGlyphRun(IBrush foreground, GlyphRun glyphRun)
{
}
public void PushClip(RoundedRect clip)
{
}
}
class HeadlessRenderTarget : IRenderTarget
{
public void Dispose()
{
}
public IDrawingContextImpl CreateDrawingContext(IVisualBrushRenderer visualBrushRenderer)
{
return new HeadlessDrawingContextStub();
}
}
class HeadlessFormattedTextStub : IFormattedTextImpl
{
public HeadlessFormattedTextStub(string text, Size constraint)
{
Text = text;
Constraint = constraint;
Bounds = new Rect(Constraint.Constrain(new Size(50, 50)));
}
public Size Constraint { get; }
public Rect Bounds { get; }
public string Text { get; }
public IEnumerable<FormattedTextLine> GetLines()
{
return new[] { new FormattedTextLine(Text.Length, 10) };
}
public TextHitTestResult HitTestPoint(Point point) => new TextHitTestResult();
public Rect HitTestTextPosition(int index) => new Rect();
public IEnumerable<Rect> HitTestTextRange(int index, int length) => new Rect[length];
}
}
}
| |
/*
* 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 OpenMetaverse;
using OpenSim.Region.Framework.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Timers;
using Timer = System.Timers.Timer;
namespace OpenSim.Region.Framework.Scenes
{
[Serializable]
public class KeyframeMotion
{
//private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private Vector3 m_basePosition;
private Quaternion m_baseRotation;
private Keyframe m_currentFrame;
private DataFormat m_data = DataFormat.Translation | DataFormat.Rotation;
private List<Keyframe> m_frames = new List<Keyframe>();
[NonSerialized()]
private SceneObjectGroup m_group;
[NonSerialized()]
private bool m_isCrossing;
private int m_iterations = 0;
private Keyframe[] m_keyframes;
private PlayMode m_mode = PlayMode.Forward;
// retry position for cross fail
[NonSerialized()]
private Vector3 m_nextPosition;
private bool m_running = false;
[NonSerialized()]
private Scene m_scene;
[NonSerialized()]
private bool m_selected = false;
private Vector3 m_serializedPosition;
private int m_skipLoops = 0;
// skip timer events.
//timer.stop doesn't assure there aren't event threads still being fired
[NonSerialized()]
private bool m_timerStopped;
[NonSerialized()]
private bool m_waitingCrossing;
public KeyframeMotion(SceneObjectGroup grp, PlayMode mode, DataFormat data)
{
m_mode = mode;
m_data = data;
m_group = grp;
if (grp != null)
{
m_basePosition = grp.AbsolutePosition;
m_baseRotation = grp.GroupRotation;
m_scene = grp.Scene;
}
m_timerStopped = true;
m_isCrossing = false;
m_waitingCrossing = false;
}
[Flags]
public enum DataFormat : int
{
Translation = 2,
Rotation = 1
}
public enum PlayMode : int
{
Forward = 0,
Reverse = 1,
Loop = 2,
PingPong = 3
};
public DataFormat Data
{
get { return m_data; }
}
public Scene Scene
{
get { return m_scene; }
}
public bool Selected
{
set
{
if (m_group != null)
{
if (!value)
{
// Once we're let go, recompute positions
if (m_selected)
UpdateSceneObject(m_group);
}
else
{
// Save selection position in case we get moved
if (!m_selected)
{
StopTimer();
m_serializedPosition = m_group.AbsolutePosition;
}
}
}
m_isCrossing = false;
m_waitingCrossing = false;
m_selected = value;
}
}
public static KeyframeMotion FromData(SceneObjectGroup grp, Byte[] data)
{
KeyframeMotion newMotion = null;
try
{
MemoryStream ms = new MemoryStream(data);
BinaryFormatter fmt = new BinaryFormatter();
newMotion = (KeyframeMotion)fmt.Deserialize(ms);
newMotion.m_group = grp;
if (grp != null)
{
newMotion.m_scene = grp.Scene;
if (grp.IsSelected)
newMotion.m_selected = true;
}
newMotion.m_timerStopped = false;
newMotion.m_running = true;
newMotion.m_isCrossing = false;
newMotion.m_waitingCrossing = false;
}
catch
{
newMotion = null;
}
return newMotion;
}
public KeyframeMotion Copy(SceneObjectGroup newgrp)
{
StopTimer();
KeyframeMotion newmotion = new KeyframeMotion(null, m_mode, m_data);
newmotion.m_group = newgrp;
newmotion.m_scene = newgrp.Scene;
if (m_keyframes != null)
{
newmotion.m_keyframes = new Keyframe[m_keyframes.Length];
m_keyframes.CopyTo(newmotion.m_keyframes, 0);
}
newmotion.m_frames = new List<Keyframe>(m_frames);
newmotion.m_basePosition = m_basePosition;
newmotion.m_baseRotation = m_baseRotation;
if (m_selected)
newmotion.m_serializedPosition = m_serializedPosition;
else
{
if (m_group != null)
newmotion.m_serializedPosition = m_group.AbsolutePosition;
else
newmotion.m_serializedPosition = m_serializedPosition;
}
newmotion.m_currentFrame = m_currentFrame;
newmotion.m_iterations = m_iterations;
newmotion.m_running = m_running;
if (m_running && !m_waitingCrossing)
StartTimer();
return newmotion;
}
public void CrossingFailure()
{
m_waitingCrossing = false;
if (m_group != null)
{
m_group.RootPart.Velocity = Vector3.Zero;
m_group.SendGroupRootTerseUpdate();
// m_group.RootPart.ScheduleTerseUpdate();
if (m_running)
{
StopTimer();
m_skipLoops = 1200; // 60 seconds
StartTimer();
}
}
}
public void Delete()
{
m_running = false;
StopTimer();
m_isCrossing = false;
m_waitingCrossing = false;
m_frames.Clear();
m_keyframes = null;
}
public void OnTimer(double tickDuration)
{
if (m_skipLoops > 0)
{
m_skipLoops--;
return;
}
if (m_timerStopped) // trap events still in air even after a timer.stop
return;
if (m_group == null)
return;
bool update = false;
if (m_selected)
{
if (m_group.RootPart.Velocity != Vector3.Zero)
{
m_group.RootPart.Velocity = Vector3.Zero;
m_group.SendGroupRootTerseUpdate();
}
return;
}
if (m_isCrossing)
{
// if crossing and timer running then cross failed
// wait some time then
// retry to set the position that evtually caused the outbound
// if still outside region this will call startCrossing below
m_isCrossing = false;
m_group.AbsolutePosition = m_nextPosition;
if (!m_isCrossing)
{
StopTimer();
StartTimer();
}
return;
}
if (m_frames.Count == 0)
{
GetNextList();
if (m_frames.Count == 0)
{
Stop();
Scene scene = m_group.Scene;
IScriptModule[] scriptModules = scene.RequestModuleInterfaces<IScriptModule>();
foreach (IScriptModule m in scriptModules)
{
if (m == null)
continue;
m.PostObjectEvent(m_group.RootPart.UUID, "moving_end", new object[0]);
}
return;
}
m_currentFrame = m_frames[0];
m_currentFrame.TimeMS += (int)tickDuration;
//force a update on a keyframe transition
update = true;
}
m_currentFrame.TimeMS -= (int)tickDuration;
// Do the frame processing
double remainingSteps = (double)m_currentFrame.TimeMS / tickDuration;
if (remainingSteps <= 0.0)
{
m_group.RootPart.Velocity = Vector3.Zero;
m_group.RootPart.AngularVelocity = Vector3.Zero;
m_nextPosition = (Vector3)m_currentFrame.Position;
m_group.AbsolutePosition = m_nextPosition;
// we are sending imediate updates, no doing force a extra terseUpdate
// m_group.UpdateGroupRotationR((Quaternion)m_currentFrame.Rotation);
m_group.RootPart.RotationOffset = (Quaternion)m_currentFrame.Rotation;
m_frames.RemoveAt(0);
if (m_frames.Count > 0)
m_currentFrame = m_frames[0];
update = true;
}
else
{
float completed = ((float)m_currentFrame.TimeTotal - (float)m_currentFrame.TimeMS) / (float)m_currentFrame.TimeTotal;
bool lastStep = m_currentFrame.TimeMS <= tickDuration;
Vector3 positionThisStep = m_currentFrame.StartPosition + (m_currentFrame.Position.Value - m_currentFrame.StartPosition) * completed;
Vector3 motionThisStep = positionThisStep - m_group.AbsolutePosition;
float mag = Vector3.Mag(motionThisStep);
if ((mag >= 0.02f) || lastStep)
{
m_nextPosition = m_group.AbsolutePosition + motionThisStep;
m_group.AbsolutePosition = m_nextPosition;
update = true;
}
//int totalSteps = m_currentFrame.TimeTotal / (int)tickDuration;
//m_log.DebugFormat("KeyframeMotion.OnTimer: step {0}/{1}, curPosition={2}, finalPosition={3}, motionThisStep={4} (scene {5})",
// totalSteps - remainingSteps + 1, totalSteps, m_group.AbsolutePosition, m_currentFrame.Position, motionThisStep, m_scene.RegionInfo.RegionName);
if ((Quaternion)m_currentFrame.Rotation != m_group.GroupRotation)
{
Quaternion current = m_group.GroupRotation;
Quaternion step = Quaternion.Slerp(m_currentFrame.StartRotation, (Quaternion)m_currentFrame.Rotation, completed);
step.Normalize();
/* use simpler change detection
* float angle = 0;
float aa = current.X * current.X + current.Y * current.Y + current.Z * current.Z + current.W * current.W;
float bb = step.X * step.X + step.Y * step.Y + step.Z * step.Z + step.W * step.W;
float aa_bb = aa * bb;
if (aa_bb == 0)
{
angle = 0;
}
else
{
float ab = current.X * step.X +
current.Y * step.Y +
current.Z * step.Z +
current.W * step.W;
float q = (ab * ab) / aa_bb;
if (q > 1.0f)
{
angle = 0;
}
else
{
angle = (float)Math.Acos(2 * q - 1);
}
}
if (angle > 0.01f)
*/
if (Math.Abs(step.X - current.X) > 0.001f
|| Math.Abs(step.Y - current.Y) > 0.001f
|| Math.Abs(step.Z - current.Z) > 0.001f
|| lastStep)
// assuming w is a dependente var
{
// m_group.UpdateGroupRotationR(step);
m_group.RootPart.RotationOffset = step;
//m_group.RootPart.UpdateAngularVelocity(m_currentFrame.AngularVelocity / 2);
update = true;
}
}
}
if (update)
{
m_group.SendGroupRootTerseUpdate();
}
}
public void Pause()
{
m_running = false;
StopTimer();
m_group.RootPart.Velocity = Vector3.Zero;
m_group.RootPart.AngularVelocity = Vector3.Zero;
m_group.SendGroupRootTerseUpdate();
// m_group.RootPart.ScheduleTerseUpdate();
}
public Byte[] Serialize()
{
StopTimer();
MemoryStream ms = new MemoryStream();
BinaryFormatter fmt = new BinaryFormatter();
SceneObjectGroup tmp = m_group;
m_group = null;
if (!m_selected && tmp != null)
m_serializedPosition = tmp.AbsolutePosition;
fmt.Serialize(ms, this);
m_group = tmp;
if (m_running && !m_waitingCrossing)
StartTimer();
return ms.ToArray();
}
public void SetKeyframes(Keyframe[] frames)
{
m_keyframes = frames;
}
public void Start()
{
m_isCrossing = false;
m_waitingCrossing = false;
if (m_keyframes != null && m_group != null && m_keyframes.Length > 0)
{
StartTimer();
m_running = true;
}
else
{
m_running = false;
StopTimer();
}
}
public void StartCrossingCheck()
{
// timer will be restart by crossingFailure
// or never since crossing worked and this
// should be deleted
StopTimer();
m_isCrossing = true;
m_waitingCrossing = true;
// to remove / retune to smoth crossings
if (m_group.RootPart.Velocity != Vector3.Zero)
{
m_group.RootPart.Velocity = Vector3.Zero;
m_group.SendGroupRootTerseUpdate();
// m_group.RootPart.ScheduleTerseUpdate();
}
}
public void Stop()
{
m_running = false;
m_isCrossing = false;
m_waitingCrossing = false;
StopTimer();
m_basePosition = m_group.AbsolutePosition;
m_baseRotation = m_group.GroupRotation;
m_group.RootPart.Velocity = Vector3.Zero;
m_group.RootPart.AngularVelocity = Vector3.Zero;
m_group.SendGroupRootTerseUpdate();
// m_group.RootPart.ScheduleTerseUpdate();
m_frames.Clear();
}
public void UpdateSceneObject(SceneObjectGroup grp)
{
m_isCrossing = false;
m_waitingCrossing = false;
StopTimer();
if (grp == null)
return;
m_group = grp;
m_scene = grp.Scene;
Vector3 grppos = grp.AbsolutePosition;
Vector3 offset = grppos - m_serializedPosition;
// avoid doing it more than once
// current this will happen dragging a prim to other region
m_serializedPosition = grppos;
m_basePosition += offset;
m_nextPosition += offset;
m_currentFrame.StartPosition += offset;
m_currentFrame.Position += offset;
for (int i = 0; i < m_frames.Count; i++)
{
Keyframe k = m_frames[i];
k.StartPosition += offset;
k.Position += offset;
m_frames[i] = k;
}
if (m_running)
Start();
}
private void GetNextList()
{
m_frames.Clear();
Vector3 pos = m_basePosition;
Quaternion rot = m_baseRotation;
if (m_mode == PlayMode.Loop || m_mode == PlayMode.PingPong || m_iterations == 0)
{
int direction = 1;
if (m_mode == PlayMode.Reverse || ((m_mode == PlayMode.PingPong) && ((m_iterations & 1) != 0)))
direction = -1;
int start = 0;
int end = m_keyframes.Length;
if (direction < 0)
{
start = m_keyframes.Length - 1;
end = -1;
}
for (int i = start; i != end; i += direction)
{
Keyframe k = m_keyframes[i];
k.StartPosition = pos;
if (k.Position.HasValue)
{
k.Position = (k.Position * direction);
// k.Velocity = (Vector3)k.Position / (k.TimeMS / 1000.0f);
k.Position += pos;
}
else
{
k.Position = pos;
// k.Velocity = Vector3.Zero;
}
k.StartRotation = rot;
if (k.Rotation.HasValue)
{
if (direction == -1)
k.Rotation = Quaternion.Conjugate((Quaternion)k.Rotation);
k.Rotation = rot * k.Rotation;
}
else
{
k.Rotation = rot;
}
/* ang vel not in use for now
float angle = 0;
float aa = k.StartRotation.X * k.StartRotation.X + k.StartRotation.Y * k.StartRotation.Y + k.StartRotation.Z * k.StartRotation.Z + k.StartRotation.W * k.StartRotation.W;
float bb = ((Quaternion)k.Rotation).X * ((Quaternion)k.Rotation).X + ((Quaternion)k.Rotation).Y * ((Quaternion)k.Rotation).Y + ((Quaternion)k.Rotation).Z * ((Quaternion)k.Rotation).Z + ((Quaternion)k.Rotation).W * ((Quaternion)k.Rotation).W;
float aa_bb = aa * bb;
if (aa_bb == 0)
{
angle = 0;
}
else
{
float ab = k.StartRotation.X * ((Quaternion)k.Rotation).X +
k.StartRotation.Y * ((Quaternion)k.Rotation).Y +
k.StartRotation.Z * ((Quaternion)k.Rotation).Z +
k.StartRotation.W * ((Quaternion)k.Rotation).W;
float q = (ab * ab) / aa_bb;
if (q > 1.0f)
{
angle = 0;
}
else
{
angle = (float)Math.Acos(2 * q - 1);
}
}
k.AngularVelocity = (new Vector3(0, 0, 1) * (Quaternion)k.Rotation) * (angle / (k.TimeMS / 1000));
*/
k.TimeTotal = k.TimeMS;
m_frames.Add(k);
pos = (Vector3)k.Position;
rot = (Quaternion)k.Rotation;
}
m_basePosition = pos;
m_baseRotation = rot;
m_iterations++;
}
}
private void StartTimer()
{
KeyframeTimer.Add(this);
m_timerStopped = false;
}
private void StopTimer()
{
m_timerStopped = true;
KeyframeTimer.Remove(this);
}
[Serializable]
public struct Keyframe
{
public Vector3 AngularVelocity;
public Vector3? Position;
public Quaternion? Rotation;
public Vector3 StartPosition;
public Quaternion StartRotation;
public int TimeMS;
public int TimeTotal;
};
}
public class KeyframeTimer
{
private const double m_tickDuration = 50.0;
private static Dictionary<Scene, KeyframeTimer> m_timers =
new Dictionary<Scene, KeyframeTimer>();
private object m_lockObject = new object();
private Dictionary<KeyframeMotion, object> m_motions = new Dictionary<KeyframeMotion, object>();
private Timer m_timer;
private object m_timerLock = new object();
public KeyframeTimer(Scene scene)
{
m_timer = new Timer();
m_timer.Interval = TickDuration;
m_timer.AutoReset = true;
m_timer.Elapsed += OnTimer;
}
public double TickDuration
{
get { return m_tickDuration; }
}
public static void Add(KeyframeMotion motion)
{
KeyframeTimer timer;
if (motion.Scene == null)
return;
lock (m_timers)
{
if (!m_timers.TryGetValue(motion.Scene, out timer))
{
timer = new KeyframeTimer(motion.Scene);
m_timers[motion.Scene] = timer;
if (!SceneManager.Instance.AllRegionsReady)
{
// Start the timers only once all the regions are ready. This is required
// when using megaregions, because the megaregion is correctly configured
// only after all the regions have been loaded. (If we don't do this then
// when the prim moves it might think that it crossed into a region.)
SceneManager.Instance.OnRegionsReadyStatusChange += delegate(SceneManager sm)
{
if (sm.AllRegionsReady)
timer.Start();
};
}
// Check again, in case the regions were started while we were adding the event handler
if (SceneManager.Instance.AllRegionsReady)
{
timer.Start();
}
}
}
lock (timer.m_lockObject)
{
timer.m_motions[motion] = null;
}
}
public static void Remove(KeyframeMotion motion)
{
KeyframeTimer timer;
if (motion.Scene == null)
return;
lock (m_timers)
{
if (!m_timers.TryGetValue(motion.Scene, out timer))
{
return;
}
}
lock (timer.m_lockObject)
{
timer.m_motions.Remove(motion);
}
}
public void Start()
{
lock (m_timer)
{
if (!m_timer.Enabled)
m_timer.Start();
}
}
private void OnTimer(object sender, ElapsedEventArgs ea)
{
if (!Monitor.TryEnter(m_timerLock))
return;
try
{
List<KeyframeMotion> motions;
lock (m_lockObject)
{
motions = new List<KeyframeMotion>(m_motions.Keys);
}
foreach (KeyframeMotion m in motions)
{
try
{
m.OnTimer(TickDuration);
}
catch (Exception)
{
// Don't stop processing
}
}
}
catch (Exception)
{
// Keep running no matter what
}
finally
{
Monitor.Exit(m_timerLock);
}
}
}
}
| |
// Copyright (C) 2015 Google, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#if UNITY_IOS
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using UnityEngine;
using GoogleMobileAds.Api;
using GoogleMobileAds.Common;
namespace GoogleMobileAds.iOS
{
internal class RewardBasedVideoAdClient : IRewardBasedVideoAdClient, IDisposable
{
private IntPtr rewardBasedVideoAdPtr;
private IntPtr rewardBasedVideoAdClientPtr;
#region reward based video callback types
internal delegate void GADURewardBasedVideoAdDidReceiveAdCallback(
IntPtr rewardBasedVideoAdClient);
internal delegate void GADURewardBasedVideoAdDidFailToReceiveAdWithErrorCallback(
IntPtr rewardBasedVideoClient, string error);
internal delegate void GADURewardBasedVideoAdDidOpenCallback(
IntPtr rewardBasedVideoAdClient);
internal delegate void GADURewardBasedVideoAdDidStartCallback(
IntPtr rewardBasedVideoAdClient);
internal delegate void GADURewardBasedVideoAdDidCloseCallback(
IntPtr rewardBasedVideoAdClient);
internal delegate void GADURewardBasedVideoAdDidRewardCallback(
IntPtr rewardBasedVideoAdClient, string rewardType, double rewardAmount);
internal delegate void GADURewardBasedVideoAdWillLeaveApplicationCallback(
IntPtr rewardBasedVideoAdClient);
#endregion
public event EventHandler<EventArgs> OnAdLoaded;
public event EventHandler<AdFailedToLoadEventArgs> OnAdFailedToLoad;
public event EventHandler<EventArgs> OnAdOpening;
public event EventHandler<EventArgs> OnAdStarted;
public event EventHandler<EventArgs> OnAdClosed;
public event EventHandler<Reward> OnAdRewarded;
public event EventHandler<EventArgs> OnAdLeavingApplication;
// This property should be used when setting the rewardBasedVideoPtr.
private IntPtr RewardBasedVideoAdPtr
{
get { return this.rewardBasedVideoAdPtr; }
set
{
Externs.GADURelease(this.rewardBasedVideoAdPtr);
this.rewardBasedVideoAdPtr = value;
}
}
#region IGoogleMobileAdsRewardBasedVideoClient implementation
// Creates a reward based video.
public void CreateRewardBasedVideoAd()
{
this.rewardBasedVideoAdClientPtr = (IntPtr)GCHandle.Alloc(this);
this.RewardBasedVideoAdPtr = Externs.GADUCreateRewardBasedVideoAd(
this.rewardBasedVideoAdClientPtr);
Externs.GADUSetRewardBasedVideoAdCallbacks(
this.RewardBasedVideoAdPtr,
RewardBasedVideoAdDidReceiveAdCallback,
RewardBasedVideoAdDidFailToReceiveAdWithErrorCallback,
RewardBasedVideoAdDidOpenCallback,
RewardBasedVideoAdDidStartCallback,
RewardBasedVideoAdDidCloseCallback,
RewardBasedVideoAdDidRewardUserCallback,
RewardBasedVideoAdWillLeaveApplicationCallback);
}
// Load an ad.
public void LoadAd(AdRequest request, string adUnitId)
{
IntPtr requestPtr = Utils.BuildAdRequest(request);
Externs.GADURequestRewardBasedVideoAd(
this.RewardBasedVideoAdPtr, requestPtr, adUnitId);
Externs.GADURelease(requestPtr);
}
// Show the reward based video on the screen.
public void ShowRewardBasedVideoAd()
{
Externs.GADUShowRewardBasedVideoAd(this.RewardBasedVideoAdPtr);
}
public bool IsLoaded()
{
return Externs.GADURewardBasedVideoAdReady(this.RewardBasedVideoAdPtr);
}
// Destroys the rewarded video ad.
public void DestroyRewardedVideoAd()
{
this.RewardBasedVideoAdPtr = IntPtr.Zero;
}
public void Dispose()
{
this.DestroyRewardedVideoAd();
((GCHandle)this.rewardBasedVideoAdClientPtr).Free();
}
~RewardBasedVideoAdClient()
{
this.Dispose();
}
#endregion
#region Reward based video ad callback methods
[MonoPInvokeCallback(typeof(GADURewardBasedVideoAdDidReceiveAdCallback))]
private static void RewardBasedVideoAdDidReceiveAdCallback(IntPtr rewardBasedVideoAdClient)
{
RewardBasedVideoAdClient client = IntPtrToRewardBasedVideoClient(
rewardBasedVideoAdClient);
if (client.OnAdLoaded != null)
{
client.OnAdLoaded(client, EventArgs.Empty);
}
}
[MonoPInvokeCallback(typeof(GADURewardBasedVideoAdDidFailToReceiveAdWithErrorCallback))]
private static void RewardBasedVideoAdDidFailToReceiveAdWithErrorCallback(
IntPtr rewardBasedVideoAdClient, string error)
{
RewardBasedVideoAdClient client = IntPtrToRewardBasedVideoClient(
rewardBasedVideoAdClient);
if (client.OnAdFailedToLoad != null)
{
AdFailedToLoadEventArgs args = new AdFailedToLoadEventArgs()
{
Message = error
};
client.OnAdFailedToLoad(client, args);
}
}
[MonoPInvokeCallback(typeof(GADURewardBasedVideoAdDidOpenCallback))]
private static void RewardBasedVideoAdDidOpenCallback(IntPtr rewardBasedVideoAdClient)
{
RewardBasedVideoAdClient client = IntPtrToRewardBasedVideoClient(
rewardBasedVideoAdClient);
if (client.OnAdOpening != null)
{
client.OnAdOpening(client, EventArgs.Empty);
}
}
[MonoPInvokeCallback(typeof(GADURewardBasedVideoAdDidStartCallback))]
private static void RewardBasedVideoAdDidStartCallback(IntPtr rewardBasedVideoAdClient)
{
RewardBasedVideoAdClient client = IntPtrToRewardBasedVideoClient(
rewardBasedVideoAdClient);
if (client.OnAdStarted != null)
{
client.OnAdStarted(client, EventArgs.Empty);
}
}
[MonoPInvokeCallback(typeof(GADURewardBasedVideoAdDidCloseCallback))]
private static void RewardBasedVideoAdDidCloseCallback(IntPtr rewardBasedVideoAdClient)
{
RewardBasedVideoAdClient client = IntPtrToRewardBasedVideoClient(
rewardBasedVideoAdClient);
if (client.OnAdClosed != null)
{
client.OnAdClosed(client, EventArgs.Empty);
}
}
[MonoPInvokeCallback(typeof(GADURewardBasedVideoAdDidRewardCallback))]
private static void RewardBasedVideoAdDidRewardUserCallback(
IntPtr rewardBasedVideoAdClient, string rewardType, double rewardAmount)
{
RewardBasedVideoAdClient client = IntPtrToRewardBasedVideoClient(
rewardBasedVideoAdClient);
if (client.OnAdRewarded != null)
{
Reward args = new Reward()
{
Type = rewardType,
Amount = rewardAmount
};
client.OnAdRewarded(client, args);
}
}
[MonoPInvokeCallback(typeof(GADURewardBasedVideoAdWillLeaveApplicationCallback))]
private static void RewardBasedVideoAdWillLeaveApplicationCallback(
IntPtr rewardBasedVideoAdClient)
{
RewardBasedVideoAdClient client = IntPtrToRewardBasedVideoClient(
rewardBasedVideoAdClient);
if (client.OnAdLeavingApplication != null)
{
client.OnAdLeavingApplication(client, EventArgs.Empty);
}
}
private static RewardBasedVideoAdClient IntPtrToRewardBasedVideoClient(
IntPtr rewardBasedVideoAdClient)
{
GCHandle handle = (GCHandle)rewardBasedVideoAdClient;
return handle.Target as RewardBasedVideoAdClient;
}
#endregion
}
}
#endif
| |
/*
* Copyright (c) 2014 Behrooz Amoozad
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the bd2 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 Behrooz Amoozad 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 BD2.Daemon.Buses;
namespace BD2.Daemon
{
public class ServiceManager
{
ObjectBus objectBus;
SortedDictionary<Guid, ServiceAnnounceMessage> localServices = new SortedDictionary<Guid, ServiceAnnounceMessage> ();
SortedDictionary<ServiceAnnounceMessage, Func<ServiceAgentMode , ObjectBusSession, Action, Byte[], ServiceAgent>> localServiceAgents = new SortedDictionary<ServiceAnnounceMessage, Func<ServiceAgentMode , ObjectBusSession, Action, Byte[], ServiceAgent>> ();
SortedSet<ServiceAnnounceMessage> remoteServices = new SortedSet<ServiceAnnounceMessage> ();
SortedDictionary<Guid, Tuple<ServiceRequestMessage, System.Threading.ManualResetEvent, System.Threading.ManualResetEvent>> requests = new SortedDictionary<Guid, Tuple<ServiceRequestMessage, System.Threading.ManualResetEvent, System.Threading.ManualResetEvent>> ();
SortedDictionary<Guid, ServiceResponseMessage> pendingResponses = new SortedDictionary<Guid, ServiceResponseMessage> ();
SortedDictionary<Guid, ServiceAgent> sessionAgents = new SortedDictionary<Guid, ServiceAgent> ();
public ServiceManager (ObjectBus objectBus)
{
if (objectBus == null)
throw new ArgumentNullException ("objectBus");
this.objectBus = objectBus;
objectBus.RegisterType (typeof(ServiceAnnounceMessage), ServiceAnnouncementReceived);
objectBus.RegisterType (typeof(ServiceResponseMessage), ServiceResponseReceived);
objectBus.RegisterType (typeof(ServiceRequestMessage), ServiceRequestReceived);
objectBus.RegisterType (typeof(ServiceDestroyMessage), ServiceDestroyReceived);
objectBus.RegisterType (typeof(ServiceManagerReadyMessage), ServiceManagerReadyMessageReceived);
objectBus.Start ();
}
void ServiceAnnouncementReceived (ObjectBusMessage message)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
if (message == null)
throw new ArgumentNullException ("message");
if (!(message is ServiceAnnounceMessage))
throw new ArgumentException (string.Format ("message type is not valid, must be of type {0}", typeof(ServiceAnnounceMessage).FullName));
ServiceAnnounceMessage serviceAnnouncement = (ServiceAnnounceMessage)message;
lock (remoteServices)
remoteServices.Add (serviceAnnouncement);
}
void ServiceResponseReceived (ObjectBusMessage message)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
if (message == null)
throw new ArgumentNullException ("message");
if (!(message is ServiceResponseMessage))
throw new ArgumentException (string.Format ("message type is not valid, must be of type {0}", typeof(ServiceResponseMessage).FullName));
ServiceResponseMessage serviceResponse = (ServiceResponseMessage)message;
Tuple<ServiceRequestMessage, System.Threading.ManualResetEvent, System.Threading.ManualResetEvent> requestTuple = requests [serviceResponse.RequestID];
lock (pendingResponses)
pendingResponses.Add (serviceResponse.RequestID, serviceResponse);
requestTuple.Item2.Set ();
requestTuple.Item3.WaitOne ();
}
void ServiceRequestReceived (ObjectBusMessage message)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
if (message == null)
throw new ArgumentNullException ("message");
if (!(message is ServiceRequestMessage))
throw new ArgumentException (string.Format ("message type is not valid, must be of type {0}", typeof(ServiceRequestMessage).FullName));
ServiceRequestMessage serviceRequest = (ServiceRequestMessage)message;
Func<ServiceAgentMode , ObjectBusSession, Action, Byte[], ServiceAgent> agentFunc;
lock (localServices)
lock (localServiceAgents)
agentFunc = localServiceAgents [localServices [serviceRequest.ServiceID]];
Guid responseID = Guid.NewGuid ();
ObjectBusSession session = objectBus.CreateSession (responseID, SessionDisconnected);
ServiceResponseMessage response = new ServiceResponseMessage (responseID, serviceRequest.ID, ServiceResponseStatus.Accepted);
ServiceAgent agent = agentFunc.Invoke (ServiceAgentMode.Server, session, objectBus.Flush, serviceRequest.Parameters);
lock (sessionAgents)
sessionAgents.Add (session.SessionID, agent);
objectBus.SendMessage (response);
}
void SessionDisconnected (ObjectBusSession session)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
lock (sessionAgents)
sessionAgents [session.SessionID].CallSessionDisconnected ();
}
void ServiceDestroyReceived (ObjectBusMessage message)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
if (message == null)
throw new ArgumentNullException ("message");
if (!(message is ServiceDestroyMessage)) {
throw new ArgumentException (string.Format ("message type is not valid, must be of type {0}", typeof(ServiceDestroyMessage).FullName));
}
ServiceDestroyMessage serviceDestroy = (ServiceDestroyMessage)message;
lock (sessionAgents)
sessionAgents [serviceDestroy.SessionID].CallDestroyRequestReceived ();
objectBus.DestroySession (serviceDestroy);
}
public SortedSet<ServiceAnnounceMessage> EnumerateRemoteServices ()
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
lock (remoteServices)
return new SortedSet<ServiceAnnounceMessage> (remoteServices);
}
public void AnnounceService (ServiceAnnounceMessage serviceAnnouncement, Func<ServiceAgentMode , ObjectBusSession, Action, byte[], ServiceAgent> func)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
if (serviceAnnouncement == null)
throw new ArgumentNullException ("serviceAnnouncement");
if (func == null)
throw new ArgumentNullException ("func");
lock (localServices)
lock (localServiceAgents) {
localServices.Add (serviceAnnouncement.ID, serviceAnnouncement);
localServiceAgents.Add (serviceAnnouncement, func);
}
objectBus.SendMessage (serviceAnnouncement);
}
public void AnounceReady ()
{
objectBus.SendMessage (new ServiceManagerReadyMessage ());
}
System.Threading.ManualResetEvent MREReady = new System.Threading.ManualResetEvent (false);
bool remoteReady;
public bool RemoteReady {
get {
return remoteReady;
}
private set {
remoteReady = value;
if (value)
MREReady.Set ();
else
MREReady.Reset ();
}
}
void ServiceManagerReadyMessageReceived (ObjectBusMessage message)
{
System.Threading.Thread.Sleep (100);
RemoteReady = true;
}
public void WaitForRemoteReady ()
{
MREReady.WaitOne ();
}
void WaitForRemoteReady (int millisecondsTimeout)
{
MREReady.WaitOne (millisecondsTimeout);
}
public ServiceAgent RequestService (ServiceAnnounceMessage remoteServiceAnnouncement, byte[] parameters, Func<ServiceAgentMode , ObjectBusSession, Action, Byte[], ServiceAgent> func, Byte[] localAgentParameters)
{
#if TRACE
Console.WriteLine (new System.Diagnostics.StackTrace (true).GetFrame (0));
#endif
lock (remoteServices)
if (!remoteServices.Contains (remoteServiceAnnouncement))
throw new InvalidOperationException ("The provided remoteServiceAnnouncement is not valid.");
ServiceRequestMessage request = new ServiceRequestMessage (Guid.NewGuid (), remoteServiceAnnouncement.ID, parameters);
System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent (false);
System.Threading.ManualResetEvent mre_done = new System.Threading.ManualResetEvent (false);
lock (requests)
requests.Add (request.ID, new Tuple<ServiceRequestMessage, System.Threading.ManualResetEvent, System.Threading.ManualResetEvent> (request, mre, mre_done));
objectBus.SendMessage (request);
mre.WaitOne ();
//todo: add exception handling here
ServiceResponseMessage response = pendingResponses [request.ID];
lock (pendingResponses)
pendingResponses.Remove (response.RequestID);
Console.WriteLine ("Service request accepted, remote created a session with ID {0}", response.ID);
ServiceAgent agent = func (ServiceAgentMode.Client, objectBus.CreateSession (response.ID, SessionDisconnected), objectBus.Flush, localAgentParameters);
sessionAgents.Add (response.ID, agent);
mre_done.Set ();
return agent;
}
}
}
| |
/*
Copyright 2015 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language governing permissions
and limitations under the License
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Windows.Phone.PersonalInformation;
using Microsoft.Phone.Tasks;
using Microsoft.Phone.UserData;
using System.Windows;
using WPCordovaClassLib.Cordova;
using WPCordovaClassLib.Cordova.Commands;
using WPCordovaClassLib.CordovaLib;
namespace Cordova.Extension.Commands
{
public class IntelXDKContacts: BaseCommand
{
private ContactStore store;
AddressChooserTask addressChooserTask;
private bool busy;
private const string ContactStoreLocalInstanceIdKey = "LocalInstanceId";
private bool isGetContacts = false;
/// <summary>
/// Constructor
/// </summary>
public IntelXDKContacts()
{
}
#region Public Methods
public void getContactInfo(string parameters)
{
}
/// <summary>
/// Address Chooser
/// </summary>
/// <param name="parameters"></param>
public void chooseContact(string parameters)
{
// WP8 does not allow the editing of the contact. Just return NOT AVAILABLE IN WINDOES PHONE 8 message
string js = "javascript: var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.choose',true,true);e.success=false;" +
"e.error='NOT AVAILABLE IN WINDOES PHONE 8';document.dispatchEvent(e);";
//InjectJS("javascript:" + js);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
return;
try
{
if (busy == true)
{
js = "javascript: var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.busy',true,true);e.success=false;" +
"e.message='busy';document.dispatchEvent(e);";
//InjectJS("javascript:" + js);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
return;
}
busy = true;
addressChooserTask = new AddressChooserTask();
addressChooserTask.Completed += new EventHandler<AddressResult>(addressChooserTask_Completed);
addressChooserTask.Show();
}
catch (Exception e)
{
js = string.Format(" var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.choose',true,true);" +
"e.success=false;e.error='{0}';document.dispatchEvent(e);", "There was a problem choosing a contact.");
//InjectJS("javascript:" + js);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
}
}
/// <summary>
/// Add Contact (Launcher)
/// </summary>
/// <param name="parameters"></param>
public void addContact(string parameters)
{
string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(parameters);
string givenName = (args.Length>1) ? HttpUtility.UrlDecode(args[0]) : "";
string familyName = (args.Length>1) ? HttpUtility.UrlDecode(args[1]) : "";
string street = (args.Length>1) ? HttpUtility.UrlDecode(args[2]) : "";
string city = (args.Length>1) ? HttpUtility.UrlDecode(args[3]) : "";
string state = (args.Length>1) ? HttpUtility.UrlDecode(args[4]) : "";
string zip = (args.Length>1) ? HttpUtility.UrlDecode(args[5]) : "";
string country = (args.Length>1) ? HttpUtility.UrlDecode(args[6]) : "";
string phone = (args.Length>1) ? HttpUtility.UrlDecode(args[7]) : "";
string email = (args.Length>1) ? HttpUtility.UrlDecode(args[8]) : "";
SaveContactTask addContactTask = new SaveContactTask();
addContactTask.Completed += new EventHandler<SaveContactResult>(addContactTask_Completed);
addContactTask.FirstName = givenName;
addContactTask.LastName = familyName;
addContactTask.HomePhone = phone;
addContactTask.PersonalEmail = email;
addContactTask.HomeAddressCity = city;
addContactTask.HomeAddressCountry = country;
addContactTask.HomeAddressState = state;
addContactTask.HomeAddressZipCode = zip;
addContactTask.HomeAddressStreet = street;
addContactTask.Show();
}
/// <summary>
/// Retrieve All Contacts
/// </summary>
/// <param name="parameters"></param>
public void getContacts(string parameters)
{
isGetContacts = true;
getAllContacts();
}
/// <summary>
/// Edit Contact
/// </summary>
/// <param name="parameters"></param>
public void editContact(string parameters)
{
EditContact(parameters);
}
/// <summary>
/// Remove Contact
/// </summary>
/// <param name="parameters"></param>
async public void removeContact(string parameters)
{
// WP8 does not allow the editing of the contact. Just return NOT AVAILABLE IN WINDOES PHONE 8 message
string js = "javascript: var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.remove',true,true);e.success=false;" +
"e.error='NOT AVAILABLE IN WINDOES PHONE 8';document.dispatchEvent(e);";
//InjectJS("javascript:" + js);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
return;
string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(parameters);
string contactId = HttpUtility.UrlDecode(args[0]);
if( busy == true ) {
js = "javascript: var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.busy',true,true);e.success=false;" +
"e.message='busy';document.dispatchEvent(e);";
//InjectJS(js);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
return;
}
try{
ContactStore store = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly);
StoredContact contact = await store.FindContactByIdAsync(contactId);
await store.DeleteContactAsync(contactId);
getAllContacts();
js = string.Format("var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.remove',true,true);e.success=true;" +
"e.contactid='{0}';document.dispatchEvent(e);", contactId);
//InjectJS("javascript: "+js);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
busy = false;
}
catch(Exception e)
{
js = string.Format("var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.remove',true,true);e.success=false;" +
"e.error='contact not found';e.contactid='{0}';document.dispatchEvent(e);", contactId);
//InjectJS("javascript: "+errjs);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
busy = false;
return;
}
}
#endregion
#region Chooser/Launcher Handlers
/// <summary>
/// Choose Address Launcher Handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void addressChooserTask_Completed(object sender, AddressResult e)
{
string js = "";
getAllContacts();
switch (e.TaskResult)
{
case TaskResult.OK:
AddressResult address = (AddressResult)e;
js = string.Format("javascript: var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.choose',true,true);" +
"e.success=true;e.contactid='{0}';document.dispatchEvent(e);", "");
busy = false;
break;
case TaskResult.Cancel:
//js = new CommandResponse(new JsEvent { CommandType = CommandTypeEnum.APPMOBI_CONTACTS_CHOOSE, Cancelled = true, ErrorMessage = "Choose contact cancelled." }).ToString();
js = string.Format("javascript: var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.choose',true,true);e.cancelled=true;" +
"e.success=false;e.error='{0}';document.dispatchEvent(e);", "There was a problem choosing a contact.");
busy = false;
break;
case TaskResult.None:
//js = new CommandResponse(new JsEvent { CommandType = CommandTypeEnum.APPMOBI_CONTACTS_CHOOSE, ErrorMessage = "There was a problem choosing the contact." }).ToString();
js = string.Format(" var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.choose',true,true);e.cancelled=false;" +
"e.success=false;e.error='{0}';document.dispatchEvent(e);", "There was a problem choosing the contact.");
break;
}
//InjectJS("javascript:" + js);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
}
/// <summary>
/// Add Contact Chooser Handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void addContactTask_Completed(object sender, SaveContactResult e)
{
string js = "";
getAllContacts();
switch (e.TaskResult)
{
case TaskResult.OK:
js = string.Format("var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.add',true,true);e.success=true;" +
"e.contactid='{0}';document.dispatchEvent(e);", ((Microsoft.Phone.Tasks.SaveContactTask)(sender)).FirstName + " " +((Microsoft.Phone.Tasks.SaveContactTask)(sender)).LastName) ; //contactId);
break;
case TaskResult.Cancel:
//js = new CommandResponse(new JsEvent { CommandType = CommandTypeEnum.APPMOBI_CONTACTS_ADD, Cancelled = true, ErrorMessage = "Add contact cancelled." }).ToString();
js = string.Format(" var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.add',true,true);e.cancelled=true;" +
"e.success=false;e.error='{0}';document.dispatchEvent(e);", "Add contact cancelled.");
break;
case TaskResult.None:
//js = new CommandResponse(new JsEvent { CommandType = CommandTypeEnum.APPMOBI_CONTACTS_ADD, ErrorMessage = "There was a problem adding the contact." }).ToString();
js = string.Format(" var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.add',true,true);e.cancelled=false;" +
"e.success=false;e.error='{0}';document.dispatchEvent(e);", "There was a problem adding the contact.");
break;
}
//InjectJS("javascript:" + js);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
busy = false;
}
/// <summary>
/// Search Contact Handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Contacts_SearchCompleted(object sender, ContactsSearchEventArgs e)
{
string jsContacts = "[";
bool first = true;
foreach (Contact con in e.Results)
{
if (!first) jsContacts += ",";
//GRAB CURRENT LOOKUP_KEY;
string jsPerson = JSONValueForPerson(con);
jsContacts += jsPerson;
first = false;
}
jsContacts += "];";
string js = "javascript: var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.internal.get',true,true);e.success=true;" +
"e.contacts=" + jsContacts + ";" +
"document.dispatchEvent(e);";
if (isGetContacts)
{
isGetContacts = false;
js += "e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.get',true,true);e.success=true;document.dispatchEvent(e);";
}
//InjectJS("javascript:" + jsContacts + js);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
}
#endregion
//async public void AddContactFromStore(string parameters)
//{
// string[] tempParams = HttpUtility.UrlDecode(parameters).Split('~');
// string remoteId = tempParams[0];
// string givenName = tempParams[1];
// string familyName = tempParams[2];
// string street = tempParams[3];
// string city = tempParams[4];
// string state = tempParams[5];
// string zip = tempParams[6];
// string country = tempParams[7];
// string phone = tempParams[8];
// string email = tempParams[9];
// store = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly);
// StoredContact contact = new StoredContact(store);
// RemoteIdHelper remoteIDHelper = new RemoteIdHelper();
// await remoteIDHelper.SetRemoteIdGuid(store);
// contact.RemoteId = await remoteIDHelper.GetTaggedRemoteId(store, remoteId);
// contact.GivenName = givenName;
// contact.FamilyName = familyName;
// string address = street + Environment.NewLine + city + ", " + state + " " + zip + Environment.NewLine + country;
// IDictionary<string, object> props = await contact.GetPropertiesAsync();
// props.Add(KnownContactProperties.Email, email);
// //props.Add(KnownContactProperties.Address, address);
// props.Add(KnownContactProperties.Telephone, phone);
// //IDictionary<string, object> extprops = await contact.GetExtendedPropertiesAsync();
// //extprops.Add("Codename", codeName);
// await contact.SaveAsync();
//}
#region Private methods
async private void EditContact(string parameters)
{
string js = "";
// WP8 does not allow the editing of the contact. Just return NOT AVAILABLE IN WINDOES PHONE 8 message
js = "javascript: var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.edit',true,true);e.success=false;" +
"e.error='NOT AVAILABLE IN WINDOES PHONE 8';document.dispatchEvent(e);";
//InjectJS("javascript:" + js);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
return;
string[] args = WPCordovaClassLib.Cordova.JSON.JsonHelper.Deserialize<string[]>(parameters);
getAllContacts();
string contactId = HttpUtility.UrlDecode(args[0]);
if (busy == true)
{
js = "javascript: var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.busy',true,true);e.success=false;" +
"e.message='busy';document.dispatchEvent(e);";
//InjectJS("javascript:" + js);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
return;
}
try
{
ContactStore store = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly);
StoredContact contact = await store.FindContactByRemoteIdAsync(contactId);
if (contact != null)
{
}
else
{
js = string.Format("javascript: var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.edit',true,true);e.success=false;" +
"e.error='contact not found';e.contactid='{0}';document.dispatchEvent(e);", contactId);
//InjectJS("javascript:" + js);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
return;
}
}
catch (Exception e)
{
js = string.Format("javascript: var e = document.createEvent('Events');" +
"e.initEvent('intel.xdk.contacts.edit',true,true);e.success=false;" +
"e.error='{0}';e.contactid='{1}';document.dispatchEvent(e);", e.Message, contactId);
//InjectJS("javascript:" + js);
InvokeCustomScript(new ScriptCallback("eval", new string[] { js }), true);
return;
}
}
/// <summary>
/// Update Contact Information
/// </summary>
/// <param name="remoteId"></param>
/// <param name="givenName"></param>
/// <param name="familyName"></param>
/// <param name="email"></param>
/// <param name="codeName"></param>
async private void UpdateContact(string remoteId, string givenName, string familyName, string email, string codeName)
{
store = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly);
string taggedRemoteId = await GetTaggedRemoteId(store, remoteId);
StoredContact contact = await store.FindContactByRemoteIdAsync(taggedRemoteId);
if (contact != null)
{
contact.GivenName = givenName;
contact.FamilyName = familyName;
IDictionary<string, object> props = await contact.GetPropertiesAsync();
props[KnownContactProperties.Email] = email;
IDictionary<string, object> extprops = await contact.GetExtendedPropertiesAsync();
extprops["Codename"] = codeName;
await contact.SaveAsync();
}
}
/// <summary>
/// Delete Contact
/// </summary>
/// <param name="id"></param>
async private void DeleteContact(string id)
{
store = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly);
StoredContact contact = await store.FindContactByIdAsync(id);
await store.DeleteContactAsync(id);
}
/// <summary>
/// Retrieve list of contacts from the store
/// </summary>
/// <param name="parameters"></param>
async public void GetContactsFromStore(string parameters)
{
store = await ContactStore.CreateOrOpenAsync(ContactStoreSystemAccessMode.ReadWrite, ContactStoreApplicationAccessMode.ReadOnly);
ContactQueryOptions options = new ContactQueryOptions();
options.DesiredFields.Add(KnownContactProperties.Email);
options.DesiredFields.Add(KnownContactProperties.Address);
options.DesiredFields.Add(KnownContactProperties.Telephone);
ContactQueryResult result = store.CreateContactQuery(options);
IReadOnlyList<StoredContact> contacts = await result.GetContactsAsync();
string jsContacts = "AppMobi.people = [";
foreach (StoredContact con in contacts)
{
IDictionary<string, object> temps = await con.GetPropertiesAsync();
string displayName = "";
Windows.Phone.PersonalInformation.ContactAddress address;
string familyName = "";
string givenName = "";
string email = "";
string telephone = "";
if (temps.ContainsKey("DisplayName"))
displayName = (string)temps["DisplayName"];
if (temps.ContainsKey("Address"))
address = (Windows.Phone.PersonalInformation.ContactAddress)temps["Address"];
if (temps.ContainsKey("FamilyName"))
familyName = (string)temps["FamilyName"];
if (temps.ContainsKey("GivenName"))
givenName = (string)temps["GivenName"];
if (temps.ContainsKey("Email"))
email = (string)temps["Email"];
if (temps.ContainsKey("Telephone"))
telephone = (string)temps["Telephone"];
}
jsContacts += "];";
}
/// <summary>
/// Get a list of all Contacts in the store
/// </summary>
private void getAllContacts()
{
Contacts cons = new Contacts();
cons.SearchCompleted += new EventHandler<ContactsSearchEventArgs>(Contacts_SearchCompleted);
cons.SearchAsync(String.Empty, FilterKind.None, "Get All Contacts");
}
/// <summary>
/// Convert the Contact class to a JSON representation
/// </summary>
/// <param name="contact"></param>
/// <returns></returns>
private string JSONValueForPerson(Contact contact)
{
//PROCESS NAME ELEMENTS FOR CURRENT CONTACT ID
String firstName = "",lastName = "", compositeName = "", id="";
if (contact != null)
{
id = "Temp";
if (contact.CompleteName != null)
{
firstName = contact.CompleteName.FirstName;
lastName = contact.CompleteName.LastName;
}
compositeName = firstName + " " + lastName;
firstName = (firstName == null)?"":EscapeStuff(firstName);
lastName = (lastName == null)?"":EscapeStuff(lastName);
compositeName = (compositeName == null)?"":EscapeStuff(compositeName);
}
//PROCESS EMAIL ADDRESES FOR CURRENT CONTACT ID
String emailAddresses = "[]";
if (contact.EmailAddresses.Count() > 0)
{
bool first = true;
emailAddresses = "[";
foreach (var emailAdddress in contact.EmailAddresses)
{
if (!first) emailAddresses += ",";
String email = emailAdddress.EmailAddress;
email = EscapeStuff(email);
//String emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
emailAddresses += "\"" + email + "\"";
first = false;
}
emailAddresses += "]";
}
//PROCESS PHONE NUMBERS FOR CURRENT CONTACT ID
String phoneNumbers = "[]";
if (contact.PhoneNumbers.Count() > 0)
{
bool first = true;
phoneNumbers = "[";
foreach (var phoneNumber in contact.PhoneNumbers)
{
if (!first) phoneNumbers += ",";
String phoneNum = phoneNumber.PhoneNumber;
phoneNum = EscapeStuff(phoneNum);
phoneNumbers += "\"" + phoneNum + "\"";
first = false;
}
phoneNumbers += "]";
}
//PROCESS STREET ADDRESSES FOR CURRENT CONTACT ID
String streetAddresses = "[]";
if (contact.Addresses.Count() > 0)
{
bool first = true;
streetAddresses = "[";
foreach (var address in contact.Addresses)
{
if (!first) streetAddresses += ",";
String street = address.PhysicalAddress.AddressLine1.Replace("\n", " ").Replace("\r", "");
String city = address.PhysicalAddress.City;
String state = address.PhysicalAddress.StateProvince;
String zip = address.PhysicalAddress.PostalCode;
String country = address.PhysicalAddress.CountryRegion;
street = EscapeStuff(street);
city = EscapeStuff(city);
state = EscapeStuff(state);
zip = EscapeStuff(zip);
country = EscapeStuff(country);
String addressstr = string.Format("{{ \"street\":\"{0}\", \"city\":\"{1}\", \"state\":\"{2}\", \"zip\":\"{3}\", \"country\":\"{4}\" }}",
street, city, state, zip, country);
streetAddresses += addressstr;
first = false;
}
streetAddresses += "]";
}
string jsPerson = string.Format("{{ \"id\":\"{0}\", \"name\":\"{1}\", \"first\":\"{2}\", \"last\":\"{3}\", \"phones\":{4}, \"emails\":{5}, \"addresses\":{6} }}",
contact.GetHashCode(), compositeName, firstName, lastName, phoneNumbers, emailAddresses, streetAddresses);
return jsPerson.Replace("\r\n|\\r\\n|\\r|\\n", "\\\\n");
}
/// <summary>
/// Escape the string
/// </summary>
/// <param name="myString"></param>
/// <returns></returns>
private string EscapeStuff(string myString)
{
if(myString == null)
return "";
myString = myString.Replace("\\\\", "\\\\\\\\");
myString = myString.Replace("'", "\\\\'");
return myString;
}
public async Task<string> GetTaggedRemoteId(ContactStore store, string remoteId)
{
string taggedRemoteId = string.Empty;
System.Collections.Generic.IDictionary<string, object> properties;
properties = await store.LoadExtendedPropertiesAsync().AsTask<System.Collections.Generic.IDictionary<string, object>>();
if (properties.ContainsKey(ContactStoreLocalInstanceIdKey))
{
taggedRemoteId = string.Format("{0}_{1}", properties[ContactStoreLocalInstanceIdKey], remoteId);
}
else
{
// handle error condition
}
return taggedRemoteId;
}
#endregion
}
}
| |
using System;
using System.Data;
using Csla;
using Csla.Data;
using SelfLoadSoftDelete.DataAccess;
using SelfLoadSoftDelete.DataAccess.ERLevel;
namespace SelfLoadSoftDelete.Business.ERLevel
{
/// <summary>
/// G05_SubContinent_ReChild (editable child object).<br/>
/// This is a generated base class of <see cref="G05_SubContinent_ReChild"/> business object.
/// </summary>
/// <remarks>
/// This class is an item of <see cref="G04_SubContinent"/> collection.
/// </remarks>
[Serializable]
public partial class G05_SubContinent_ReChild : BusinessBase<G05_SubContinent_ReChild>
{
#region State Fields
[NotUndoable]
private byte[] _rowVersion = new byte[] {};
#endregion
#region Business Properties
/// <summary>
/// Maintains metadata about <see cref="SubContinent_Child_Name"/> property.
/// </summary>
public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Countries Child Name");
/// <summary>
/// Gets or sets the Countries Child Name.
/// </summary>
/// <value>The Countries Child Name.</value>
public string SubContinent_Child_Name
{
get { return GetProperty(SubContinent_Child_NameProperty); }
set { SetProperty(SubContinent_Child_NameProperty, value); }
}
#endregion
#region Factory Methods
/// <summary>
/// Factory method. Creates a new <see cref="G05_SubContinent_ReChild"/> object.
/// </summary>
/// <returns>A reference to the created <see cref="G05_SubContinent_ReChild"/> object.</returns>
internal static G05_SubContinent_ReChild NewG05_SubContinent_ReChild()
{
return DataPortal.CreateChild<G05_SubContinent_ReChild>();
}
/// <summary>
/// Factory method. Loads a <see cref="G05_SubContinent_ReChild"/> object, based on given parameters.
/// </summary>
/// <param name="subContinent_ID2">The SubContinent_ID2 parameter of the G05_SubContinent_ReChild to fetch.</param>
/// <returns>A reference to the fetched <see cref="G05_SubContinent_ReChild"/> object.</returns>
internal static G05_SubContinent_ReChild GetG05_SubContinent_ReChild(int subContinent_ID2)
{
return DataPortal.FetchChild<G05_SubContinent_ReChild>(subContinent_ID2);
}
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="G05_SubContinent_ReChild"/> class.
/// </summary>
/// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public G05_SubContinent_ReChild()
{
// Use factory methods and do not use direct creation.
// show the framework that this is a child object
MarkAsChild();
}
#endregion
#region Data Access
/// <summary>
/// Loads default values for the <see cref="G05_SubContinent_ReChild"/> object properties.
/// </summary>
[Csla.RunLocal]
protected override void Child_Create()
{
var args = new DataPortalHookArgs();
OnCreate(args);
base.Child_Create();
}
/// <summary>
/// Loads a <see cref="G05_SubContinent_ReChild"/> object from the database, based on given criteria.
/// </summary>
/// <param name="subContinent_ID2">The Sub Continent ID2.</param>
protected void Child_Fetch(int subContinent_ID2)
{
var args = new DataPortalHookArgs(subContinent_ID2);
OnFetchPre(args);
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var dal = dalManager.GetProvider<IG05_SubContinent_ReChildDal>();
var data = dal.Fetch(subContinent_ID2);
Fetch(data);
}
OnFetchPost(args);
// check all object rules and property rules
BusinessRules.CheckRules();
}
private void Fetch(IDataReader data)
{
using (var dr = new SafeDataReader(data))
{
if (dr.Read())
{
Fetch(dr);
}
}
}
/// <summary>
/// Loads a <see cref="G05_SubContinent_ReChild"/> object from the given SafeDataReader.
/// </summary>
/// <param name="dr">The SafeDataReader to use.</param>
private void Fetch(SafeDataReader dr)
{
// Value properties
LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name"));
_rowVersion = dr.GetValue("RowVersion") as byte[];
var args = new DataPortalHookArgs(dr);
OnFetchRead(args);
}
/// <summary>
/// Inserts a new <see cref="G05_SubContinent_ReChild"/> object in the database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Insert(G04_SubContinent parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnInsertPre(args);
var dal = dalManager.GetProvider<IG05_SubContinent_ReChildDal>();
using (BypassPropertyChecks)
{
_rowVersion = dal.Insert(
parent.SubContinent_ID,
SubContinent_Child_Name
);
}
OnInsertPost(args);
}
}
/// <summary>
/// Updates in the database all changes made to the <see cref="G05_SubContinent_ReChild"/> object.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_Update(G04_SubContinent parent)
{
if (!IsDirty)
return;
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnUpdatePre(args);
var dal = dalManager.GetProvider<IG05_SubContinent_ReChildDal>();
using (BypassPropertyChecks)
{
_rowVersion = dal.Update(
parent.SubContinent_ID,
SubContinent_Child_Name,
_rowVersion
);
}
OnUpdatePost(args);
}
}
/// <summary>
/// Self deletes the <see cref="G05_SubContinent_ReChild"/> object from database.
/// </summary>
/// <param name="parent">The parent object.</param>
[Transactional(TransactionalTypes.TransactionScope)]
private void Child_DeleteSelf(G04_SubContinent parent)
{
using (var dalManager = DalFactorySelfLoadSoftDelete.GetManager())
{
var args = new DataPortalHookArgs();
OnDeletePre(args);
var dal = dalManager.GetProvider<IG05_SubContinent_ReChildDal>();
using (BypassPropertyChecks)
{
dal.Delete(parent.SubContinent_ID);
}
OnDeletePost(args);
}
}
#endregion
#region DataPortal Hooks
/// <summary>
/// Occurs after setting all defaults for object creation.
/// </summary>
partial void OnCreate(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation.
/// </summary>
partial void OnDeletePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Delete, after the delete operation, before Commit().
/// </summary>
partial void OnDeletePost(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the fetch operation.
/// </summary>
partial void OnFetchPre(DataPortalHookArgs args);
/// <summary>
/// Occurs after the fetch operation (object or collection is fully loaded and set up).
/// </summary>
partial void OnFetchPost(DataPortalHookArgs args);
/// <summary>
/// Occurs after the low level fetch operation, before the data reader is destroyed.
/// </summary>
partial void OnFetchRead(DataPortalHookArgs args);
/// <summary>
/// Occurs after setting query parameters and before the update operation.
/// </summary>
partial void OnUpdatePre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit().
/// </summary>
partial void OnUpdatePost(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation.
/// </summary>
partial void OnInsertPre(DataPortalHookArgs args);
/// <summary>
/// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit().
/// </summary>
partial void OnInsertPost(DataPortalHookArgs args);
#endregion
}
}
| |
// 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.
// File System.Windows.Controls.Calendar.cs
// Automatically generated contract file.
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;
// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108
namespace System.Windows.Controls
{
public partial class Calendar : Control
{
#region Methods and constructors
public Calendar()
{
}
public override void OnApplyTemplate()
{
}
protected override System.Windows.Automation.Peers.AutomationPeer OnCreateAutomationPeer()
{
return default(System.Windows.Automation.Peers.AutomationPeer);
}
protected virtual new void OnDisplayDateChanged(CalendarDateChangedEventArgs e)
{
}
protected virtual new void OnDisplayModeChanged(CalendarModeChangedEventArgs e)
{
}
protected override void OnKeyDown(System.Windows.Input.KeyEventArgs e)
{
}
protected override void OnKeyUp(System.Windows.Input.KeyEventArgs e)
{
}
protected virtual new void OnSelectedDatesChanged(SelectionChangedEventArgs e)
{
}
protected virtual new void OnSelectionModeChanged(EventArgs e)
{
}
#endregion
#region Properties and indexers
public CalendarBlackoutDatesCollection BlackoutDates
{
get
{
return default(CalendarBlackoutDatesCollection);
}
}
public System.Windows.Style CalendarButtonStyle
{
get
{
return default(System.Windows.Style);
}
set
{
}
}
public System.Windows.Style CalendarDayButtonStyle
{
get
{
return default(System.Windows.Style);
}
set
{
}
}
public System.Windows.Style CalendarItemStyle
{
get
{
return default(System.Windows.Style);
}
set
{
}
}
public DateTime DisplayDate
{
get
{
return default(DateTime);
}
set
{
}
}
public Nullable<DateTime> DisplayDateEnd
{
get
{
return default(Nullable<DateTime>);
}
set
{
}
}
public Nullable<DateTime> DisplayDateStart
{
get
{
return default(Nullable<DateTime>);
}
set
{
}
}
public CalendarMode DisplayMode
{
get
{
return default(CalendarMode);
}
set
{
}
}
public DayOfWeek FirstDayOfWeek
{
get
{
return default(DayOfWeek);
}
set
{
}
}
public bool IsTodayHighlighted
{
get
{
return default(bool);
}
set
{
}
}
public Nullable<DateTime> SelectedDate
{
get
{
return default(Nullable<DateTime>);
}
set
{
}
}
public SelectedDatesCollection SelectedDates
{
get
{
return default(SelectedDatesCollection);
}
}
public CalendarSelectionMode SelectionMode
{
get
{
return default(CalendarSelectionMode);
}
set
{
}
}
#endregion
#region Events
public event EventHandler<CalendarDateChangedEventArgs> DisplayDateChanged
{
add
{
}
remove
{
}
}
public event EventHandler<CalendarModeChangedEventArgs> DisplayModeChanged
{
add
{
}
remove
{
}
}
public event EventHandler<SelectionChangedEventArgs> SelectedDatesChanged
{
add
{
}
remove
{
}
}
public event EventHandler<EventArgs> SelectionModeChanged
{
add
{
}
remove
{
}
}
#endregion
#region Fields
public readonly static System.Windows.DependencyProperty CalendarButtonStyleProperty;
public readonly static System.Windows.DependencyProperty CalendarDayButtonStyleProperty;
public readonly static System.Windows.DependencyProperty CalendarItemStyleProperty;
public readonly static System.Windows.DependencyProperty DisplayDateEndProperty;
public readonly static System.Windows.DependencyProperty DisplayDateProperty;
public readonly static System.Windows.DependencyProperty DisplayDateStartProperty;
public readonly static System.Windows.DependencyProperty DisplayModeProperty;
public readonly static System.Windows.DependencyProperty FirstDayOfWeekProperty;
public readonly static System.Windows.DependencyProperty IsTodayHighlightedProperty;
public readonly static System.Windows.DependencyProperty SelectedDateProperty;
public readonly static System.Windows.RoutedEvent SelectedDatesChangedEvent;
public readonly static System.Windows.DependencyProperty SelectionModeProperty;
#endregion
}
}
| |
using Lucene.Net.Attributes;
using Lucene.Net.Documents;
using Lucene.Net.Support.Threading;
using NUnit.Framework;
using System;
using System.Threading;
using Console = Lucene.Net.Support.SystemConsole;
namespace Lucene.Net.Search
{
using Automaton = Lucene.Net.Util.Automaton.Automaton;
using AutomatonTestUtil = Lucene.Net.Util.Automaton.AutomatonTestUtil;
using BasicAutomata = Lucene.Net.Util.Automaton.BasicAutomata;
using BasicOperations = Lucene.Net.Util.Automaton.BasicOperations;
using Directory = Lucene.Net.Store.Directory;
/*
* 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 Document = Documents.Document;
using Field = Field;
using IndexReader = Lucene.Net.Index.IndexReader;
using LuceneTestCase = Lucene.Net.Util.LuceneTestCase;
using MultiFields = Lucene.Net.Index.MultiFields;
using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter;
using SingleTermsEnum = Lucene.Net.Index.SingleTermsEnum;
using Term = Lucene.Net.Index.Term;
using Terms = Lucene.Net.Index.Terms;
using TermsEnum = Lucene.Net.Index.TermsEnum;
using TestUtil = Lucene.Net.Util.TestUtil;
[TestFixture]
public class TestAutomatonQuery : LuceneTestCase
{
private Directory Directory;
private IndexReader Reader;
private IndexSearcher Searcher;
private readonly string FN = "field";
[SetUp]
public override void SetUp()
{
base.SetUp();
Directory = NewDirectory();
RandomIndexWriter writer = new RandomIndexWriter(Random(), Directory, Similarity, TimeZone);
Document doc = new Document();
Field titleField = NewTextField("title", "some title", Field.Store.NO);
Field field = NewTextField(FN, "this is document one 2345", Field.Store.NO);
Field footerField = NewTextField("footer", "a footer", Field.Store.NO);
doc.Add(titleField);
doc.Add(field);
doc.Add(footerField);
writer.AddDocument(doc);
field.SetStringValue("some text from doc two a short piece 5678.91");
writer.AddDocument(doc);
field.SetStringValue("doc three has some different stuff" + " with numbers 1234 5678.9 and letter b");
writer.AddDocument(doc);
Reader = writer.Reader;
Searcher = NewSearcher(Reader);
writer.Dispose();
}
[TearDown]
public override void TearDown()
{
Reader.Dispose();
Directory.Dispose();
base.TearDown();
}
private Term NewTerm(string value)
{
return new Term(FN, value);
}
private int AutomatonQueryNrHits(AutomatonQuery query)
{
if (VERBOSE)
{
Console.WriteLine("TEST: run aq=" + query);
}
return Searcher.Search(query, 5).TotalHits;
}
private void AssertAutomatonHits(int expected, Automaton automaton)
{
AutomatonQuery query = new AutomatonQuery(NewTerm("bogus"), automaton);
query.MultiTermRewriteMethod = MultiTermQuery.SCORING_BOOLEAN_QUERY_REWRITE;
Assert.AreEqual(expected, AutomatonQueryNrHits(query));
query.MultiTermRewriteMethod = MultiTermQuery.CONSTANT_SCORE_FILTER_REWRITE;
Assert.AreEqual(expected, AutomatonQueryNrHits(query));
query.MultiTermRewriteMethod = MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE;
Assert.AreEqual(expected, AutomatonQueryNrHits(query));
query.MultiTermRewriteMethod = MultiTermQuery.CONSTANT_SCORE_AUTO_REWRITE_DEFAULT;
Assert.AreEqual(expected, AutomatonQueryNrHits(query));
}
/// <summary>
/// Test some very simple automata.
/// </summary>
[Test]
public virtual void TestBasicAutomata()
{
AssertAutomatonHits(0, BasicAutomata.MakeEmpty());
AssertAutomatonHits(0, BasicAutomata.MakeEmptyString());
AssertAutomatonHits(2, BasicAutomata.MakeAnyChar());
AssertAutomatonHits(3, BasicAutomata.MakeAnyString());
AssertAutomatonHits(2, BasicAutomata.MakeString("doc"));
AssertAutomatonHits(1, BasicAutomata.MakeChar('a'));
AssertAutomatonHits(2, BasicAutomata.MakeCharRange('a', 'b'));
AssertAutomatonHits(2, BasicAutomata.MakeInterval(1233, 2346, 0));
AssertAutomatonHits(1, BasicAutomata.MakeInterval(0, 2000, 0));
AssertAutomatonHits(2, BasicOperations.Union(BasicAutomata.MakeChar('a'), BasicAutomata.MakeChar('b')));
AssertAutomatonHits(0, BasicOperations.Intersection(BasicAutomata.MakeChar('a'), BasicAutomata.MakeChar('b')));
AssertAutomatonHits(1, BasicOperations.Minus(BasicAutomata.MakeCharRange('a', 'b'), BasicAutomata.MakeChar('a')));
}
/// <summary>
/// Test that a nondeterministic automaton works correctly. (It should will be
/// determinized)
/// </summary>
[Test]
public virtual void TestNFA()
{
// accept this or three, the union is an NFA (two transitions for 't' from
// initial state)
Automaton nfa = BasicOperations.Union(BasicAutomata.MakeString("this"), BasicAutomata.MakeString("three"));
AssertAutomatonHits(2, nfa);
}
[Test]
public virtual void TestEquals()
{
AutomatonQuery a1 = new AutomatonQuery(NewTerm("foobar"), BasicAutomata.MakeString("foobar"));
// reference to a1
AutomatonQuery a2 = a1;
// same as a1 (accepts the same language, same term)
AutomatonQuery a3 = new AutomatonQuery(NewTerm("foobar"), BasicOperations.Concatenate(BasicAutomata.MakeString("foo"), BasicAutomata.MakeString("bar")));
// different than a1 (same term, but different language)
AutomatonQuery a4 = new AutomatonQuery(NewTerm("foobar"), BasicAutomata.MakeString("different"));
// different than a1 (different term, same language)
AutomatonQuery a5 = new AutomatonQuery(NewTerm("blah"), BasicAutomata.MakeString("foobar"));
Assert.AreEqual(a1.GetHashCode(), a2.GetHashCode());
Assert.AreEqual(a1, a2);
Assert.AreEqual(a1.GetHashCode(), a3.GetHashCode());
Assert.AreEqual(a1, a3);
// different class
AutomatonQuery w1 = new WildcardQuery(NewTerm("foobar"));
// different class
AutomatonQuery w2 = new RegexpQuery(NewTerm("foobar"));
Assert.IsFalse(a1.Equals(w1));
Assert.IsFalse(a1.Equals(w2));
Assert.IsFalse(w1.Equals(w2));
Assert.IsFalse(a1.Equals(a4));
Assert.IsFalse(a1.Equals(a5));
Assert.IsFalse(a1.Equals(null));
}
/// <summary>
/// Test that rewriting to a single term works as expected, preserves
/// MultiTermQuery semantics.
/// </summary>
[Test]
public virtual void TestRewriteSingleTerm()
{
AutomatonQuery aq = new AutomatonQuery(NewTerm("bogus"), BasicAutomata.MakeString("piece"));
Terms terms = MultiFields.GetTerms(Searcher.IndexReader, FN);
Assert.IsTrue(aq.GetTermsEnum(terms) is SingleTermsEnum);
Assert.AreEqual(1, AutomatonQueryNrHits(aq));
}
/// <summary>
/// Test that rewriting to a prefix query works as expected, preserves
/// MultiTermQuery semantics.
/// </summary>
[Test]
public virtual void TestRewritePrefix()
{
Automaton pfx = BasicAutomata.MakeString("do");
pfx.ExpandSingleton(); // expand singleton representation for testing
Automaton prefixAutomaton = BasicOperations.Concatenate(pfx, BasicAutomata.MakeAnyString());
AutomatonQuery aq = new AutomatonQuery(NewTerm("bogus"), prefixAutomaton);
Terms terms = MultiFields.GetTerms(Searcher.IndexReader, FN);
var en = aq.GetTermsEnum(terms);
Assert.IsTrue(en is PrefixTermsEnum, "Expected type PrefixTermEnum but was {0}", en.GetType().Name);
Assert.AreEqual(3, AutomatonQueryNrHits(aq));
}
/// <summary>
/// Test handling of the empty language
/// </summary>
[Test]
public virtual void TestEmptyOptimization()
{
AutomatonQuery aq = new AutomatonQuery(NewTerm("bogus"), BasicAutomata.MakeEmpty());
// not yet available: Assert.IsTrue(aq.getEnum(searcher.getIndexReader())
// instanceof EmptyTermEnum);
Terms terms = MultiFields.GetTerms(Searcher.IndexReader, FN);
Assert.AreSame(TermsEnum.EMPTY, aq.GetTermsEnum(terms));
Assert.AreEqual(0, AutomatonQueryNrHits(aq));
}
[Test, LongRunningTest]
public virtual void TestHashCodeWithThreads()
{
AutomatonQuery[] queries = new AutomatonQuery[1000];
for (int i = 0; i < queries.Length; i++)
{
queries[i] = new AutomatonQuery(new Term("bogus", "bogus"), AutomatonTestUtil.RandomAutomaton(Random()));
}
CountdownEvent startingGun = new CountdownEvent(1);
int numThreads = TestUtil.NextInt(Random(), 2, 5);
ThreadClass[] threads = new ThreadClass[numThreads];
for (int threadID = 0; threadID < numThreads; threadID++)
{
ThreadClass thread = new ThreadAnonymousInnerClassHelper(this, queries, startingGun);
threads[threadID] = thread;
thread.Start();
}
startingGun.Signal();
foreach (ThreadClass thread in threads)
{
thread.Join();
}
}
private class ThreadAnonymousInnerClassHelper : ThreadClass
{
private readonly TestAutomatonQuery OuterInstance;
private AutomatonQuery[] Queries;
private CountdownEvent StartingGun;
public ThreadAnonymousInnerClassHelper(TestAutomatonQuery outerInstance, AutomatonQuery[] queries, CountdownEvent startingGun)
{
this.OuterInstance = outerInstance;
this.Queries = queries;
this.StartingGun = startingGun;
}
public override void Run()
{
StartingGun.Wait();
for (int i = 0; i < Queries.Length; i++)
{
Queries[i].GetHashCode();
}
}
}
}
}
| |
using System;
using log4net;
using Umbraco.Core.Logging;
using System.IO;
using System.Linq;
using Umbraco.Core.IO;
using Umbraco.Core.Persistence;
using Umbraco.Core.Persistence.UnitOfWork;
using Umbraco.Core.Publishing;
using umbraco.interfaces;
namespace Umbraco.Core.Services
{
/// <summary>
/// The Umbraco ServiceContext, which provides access to the following services:
/// <see cref="IContentService"/>, <see cref="IContentTypeService"/>, <see cref="IDataTypeService"/>,
/// <see cref="IFileService"/>, <see cref="ILocalizationService"/> and <see cref="IMediaService"/>.
/// </summary>
public class ServiceContext
{
private Lazy<IPublicAccessService> _publicAccessService;
private Lazy<ITaskService> _taskService;
private Lazy<IDomainService> _domainService;
private Lazy<IAuditService> _auditService;
private Lazy<ILocalizedTextService> _localizedTextService;
private Lazy<ITagService> _tagService;
private Lazy<IContentService> _contentService;
private Lazy<IUserService> _userService;
private Lazy<IMemberService> _memberService;
private Lazy<IMediaService> _mediaService;
private Lazy<IContentTypeService> _contentTypeService;
private Lazy<IDataTypeService> _dataTypeService;
private Lazy<IFileService> _fileService;
private Lazy<ILocalizationService> _localizationService;
private Lazy<IPackagingService> _packagingService;
private Lazy<ServerRegistrationService> _serverRegistrationService;
private Lazy<IEntityService> _entityService;
private Lazy<IRelationService> _relationService;
private Lazy<IApplicationTreeService> _treeService;
private Lazy<ISectionService> _sectionService;
private Lazy<IMacroService> _macroService;
private Lazy<IMemberTypeService> _memberTypeService;
private Lazy<IMemberGroupService> _memberGroupService;
private Lazy<INotificationService> _notificationService;
private Lazy<IExternalLoginService> _externalLoginService;
/// <summary>
/// public ctor - will generally just be used for unit testing all items are optional and if not specified, the defaults will be used
/// </summary>
/// <param name="contentService"></param>
/// <param name="mediaService"></param>
/// <param name="contentTypeService"></param>
/// <param name="dataTypeService"></param>
/// <param name="fileService"></param>
/// <param name="localizationService"></param>
/// <param name="packagingService"></param>
/// <param name="entityService"></param>
/// <param name="relationService"></param>
/// <param name="memberGroupService"></param>
/// <param name="memberTypeService"></param>
/// <param name="memberService"></param>
/// <param name="userService"></param>
/// <param name="sectionService"></param>
/// <param name="treeService"></param>
/// <param name="tagService"></param>
/// <param name="notificationService"></param>
/// <param name="localizedTextService"></param>
/// <param name="auditService"></param>
/// <param name="domainService"></param>
/// <param name="taskService"></param>
/// <param name="macroService"></param>
/// <param name="publicAccessService"></param>
public ServiceContext(
IContentService contentService = null,
IMediaService mediaService = null,
IContentTypeService contentTypeService = null,
IDataTypeService dataTypeService = null,
IFileService fileService = null,
ILocalizationService localizationService = null,
IPackagingService packagingService = null,
IEntityService entityService = null,
IRelationService relationService = null,
IMemberGroupService memberGroupService = null,
IMemberTypeService memberTypeService = null,
IMemberService memberService = null,
IUserService userService = null,
ISectionService sectionService = null,
IApplicationTreeService treeService = null,
ITagService tagService = null,
INotificationService notificationService = null,
ILocalizedTextService localizedTextService = null,
IAuditService auditService = null,
IDomainService domainService = null,
ITaskService taskService = null,
IMacroService macroService = null,
IPublicAccessService publicAccessService = null,
IExternalLoginService externalLoginService = null)
{
if (externalLoginService != null) _externalLoginService = new Lazy<IExternalLoginService>(() => externalLoginService);
if (auditService != null) _auditService = new Lazy<IAuditService>(() => auditService);
if (localizedTextService != null) _localizedTextService = new Lazy<ILocalizedTextService>(() => localizedTextService);
if (tagService != null) _tagService = new Lazy<ITagService>(() => tagService);
if (contentService != null) _contentService = new Lazy<IContentService>(() => contentService);
if (mediaService != null) _mediaService = new Lazy<IMediaService>(() => mediaService);
if (contentTypeService != null) _contentTypeService = new Lazy<IContentTypeService>(() => contentTypeService);
if (dataTypeService != null) _dataTypeService = new Lazy<IDataTypeService>(() => dataTypeService);
if (fileService != null) _fileService = new Lazy<IFileService>(() => fileService);
if (localizationService != null) _localizationService = new Lazy<ILocalizationService>(() => localizationService);
if (packagingService != null) _packagingService = new Lazy<IPackagingService>(() => packagingService);
if (entityService != null) _entityService = new Lazy<IEntityService>(() => entityService);
if (relationService != null) _relationService = new Lazy<IRelationService>(() => relationService);
if (sectionService != null) _sectionService = new Lazy<ISectionService>(() => sectionService);
if (memberGroupService != null) _memberGroupService = new Lazy<IMemberGroupService>(() => memberGroupService);
if (memberTypeService != null) _memberTypeService = new Lazy<IMemberTypeService>(() => memberTypeService);
if (treeService != null) _treeService = new Lazy<IApplicationTreeService>(() => treeService);
if (memberService != null) _memberService = new Lazy<IMemberService>(() => memberService);
if (userService != null) _userService = new Lazy<IUserService>(() => userService);
if (notificationService != null) _notificationService = new Lazy<INotificationService>(() => notificationService);
if (domainService != null) _domainService = new Lazy<IDomainService>(() => domainService);
if (taskService != null) _taskService = new Lazy<ITaskService>(() => taskService);
if (macroService != null) _macroService = new Lazy<IMacroService>(() => macroService);
if (publicAccessService != null) _publicAccessService = new Lazy<IPublicAccessService>(() => publicAccessService);
}
internal ServiceContext(
RepositoryFactory repositoryFactory,
IDatabaseUnitOfWorkProvider dbUnitOfWorkProvider,
IUnitOfWorkProvider fileUnitOfWorkProvider,
BasePublishingStrategy publishingStrategy,
CacheHelper cache,
ILogger logger)
{
BuildServiceCache(dbUnitOfWorkProvider, fileUnitOfWorkProvider, publishingStrategy, cache,
repositoryFactory,
logger);
}
/// <summary>
/// Builds the various services
/// </summary>
private void BuildServiceCache(
IDatabaseUnitOfWorkProvider dbUnitOfWorkProvider,
IUnitOfWorkProvider fileUnitOfWorkProvider,
BasePublishingStrategy publishingStrategy,
CacheHelper cache,
RepositoryFactory repositoryFactory,
ILogger logger)
{
var provider = dbUnitOfWorkProvider;
var fileProvider = fileUnitOfWorkProvider;
if (_externalLoginService == null)
_externalLoginService = new Lazy<IExternalLoginService>(() => new ExternalLoginService(provider, repositoryFactory, logger));
if (_publicAccessService == null)
_publicAccessService = new Lazy<IPublicAccessService>(() => new PublicAccessService(provider, repositoryFactory, logger));
if (_taskService == null)
_taskService = new Lazy<ITaskService>(() => new TaskService(provider, repositoryFactory, logger));
if (_domainService == null)
_domainService = new Lazy<IDomainService>(() => new DomainService(provider, repositoryFactory, logger));
if (_auditService == null)
_auditService = new Lazy<IAuditService>(() => new AuditService(provider, repositoryFactory, logger));
if (_localizedTextService == null)
{
_localizedTextService = new Lazy<ILocalizedTextService>(() => new LocalizedTextService(
new Lazy<LocalizedTextServiceFileSources>(() =>
{
var mainLangFolder = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Umbraco + "/config/lang/"));
var appPlugins = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.AppPlugins));
var configLangFolder = new DirectoryInfo(IOHelper.MapPath(SystemDirectories.Config + "/lang/"));
var pluginLangFolders = appPlugins.Exists == false
? Enumerable.Empty<LocalizedTextServiceSupplementaryFileSource>()
: appPlugins.GetDirectories()
.SelectMany(x => x.GetDirectories("Lang"))
.SelectMany(x => x.GetFiles("*.xml", SearchOption.TopDirectoryOnly))
.Where(x => Path.GetFileNameWithoutExtension(x.FullName).Length == 5)
.Select(x => new LocalizedTextServiceSupplementaryFileSource(x, false));
//user defined langs that overwrite the default, these should not be used by plugin creators
var userLangFolders = configLangFolder.Exists == false
? Enumerable.Empty<LocalizedTextServiceSupplementaryFileSource>()
: configLangFolder
.GetFiles("*.user.xml", SearchOption.TopDirectoryOnly)
.Where(x => Path.GetFileNameWithoutExtension(x.FullName).Length == 10)
.Select(x => new LocalizedTextServiceSupplementaryFileSource(x, true));
return new LocalizedTextServiceFileSources(
logger,
cache.RuntimeCache,
mainLangFolder,
pluginLangFolders.Concat(userLangFolders));
}),
logger));
}
if (_notificationService == null)
_notificationService = new Lazy<INotificationService>(() => new NotificationService(provider, _userService.Value, _contentService.Value, logger));
if (_serverRegistrationService == null)
_serverRegistrationService = new Lazy<ServerRegistrationService>(() => new ServerRegistrationService(provider, repositoryFactory, logger));
if (_userService == null)
_userService = new Lazy<IUserService>(() => new UserService(provider, repositoryFactory, logger));
if (_memberService == null)
_memberService = new Lazy<IMemberService>(() => new MemberService(provider, repositoryFactory, logger, _memberGroupService.Value, _dataTypeService.Value));
if (_contentService == null)
_contentService = new Lazy<IContentService>(() => new ContentService(provider, repositoryFactory, logger, publishingStrategy, _dataTypeService.Value, _userService.Value));
if (_mediaService == null)
_mediaService = new Lazy<IMediaService>(() => new MediaService(provider, repositoryFactory, logger, _dataTypeService.Value, _userService.Value));
if (_contentTypeService == null)
_contentTypeService = new Lazy<IContentTypeService>(() => new ContentTypeService(provider, repositoryFactory, logger, _contentService.Value, _mediaService.Value));
if (_dataTypeService == null)
_dataTypeService = new Lazy<IDataTypeService>(() => new DataTypeService(provider, repositoryFactory, logger));
if (_fileService == null)
_fileService = new Lazy<IFileService>(() => new FileService(fileProvider, provider, repositoryFactory));
if (_localizationService == null)
_localizationService = new Lazy<ILocalizationService>(() => new LocalizationService(provider, repositoryFactory, logger));
if (_packagingService == null)
_packagingService = new Lazy<IPackagingService>(() => new PackagingService(logger, _contentService.Value, _contentTypeService.Value, _mediaService.Value, _macroService.Value, _dataTypeService.Value, _fileService.Value, _localizationService.Value, _userService.Value, repositoryFactory, provider));
if (_entityService == null)
_entityService = new Lazy<IEntityService>(() => new EntityService(
provider, repositoryFactory, logger,
_contentService.Value, _contentTypeService.Value, _mediaService.Value, _dataTypeService.Value, _memberService.Value, _memberTypeService.Value,
cache.RuntimeCache));
if (_relationService == null)
_relationService = new Lazy<IRelationService>(() => new RelationService(provider, repositoryFactory, logger, _entityService.Value));
if (_treeService == null)
_treeService = new Lazy<IApplicationTreeService>(() => new ApplicationTreeService(logger, cache));
if (_sectionService == null)
_sectionService = new Lazy<ISectionService>(() => new SectionService(_userService.Value, _treeService.Value, provider, cache));
if (_macroService == null)
_macroService = new Lazy<IMacroService>(() => new MacroService(provider, repositoryFactory, logger));
if (_memberTypeService == null)
_memberTypeService = new Lazy<IMemberTypeService>(() => new MemberTypeService(provider, repositoryFactory, logger, _memberService.Value));
if (_tagService == null)
_tagService = new Lazy<ITagService>(() => new TagService(provider, repositoryFactory, logger));
if (_memberGroupService == null)
_memberGroupService = new Lazy<IMemberGroupService>(() => new MemberGroupService(provider, repositoryFactory, logger));
}
/// <summary>
/// Gets the <see cref="IPublicAccessService"/>
/// </summary>
public IPublicAccessService PublicAccessService
{
get { return _publicAccessService.Value; }
}
/// <summary>
/// Gets the <see cref="ITaskService"/>
/// </summary>
public ITaskService TaskService
{
get { return _taskService.Value; }
}
/// <summary>
/// Gets the <see cref="IDomainService"/>
/// </summary>
public IDomainService DomainService
{
get { return _domainService.Value; }
}
/// <summary>
/// Gets the <see cref="IAuditService"/>
/// </summary>
public IAuditService AuditService
{
get { return _auditService.Value; }
}
/// <summary>
/// Gets the <see cref="ILocalizedTextService"/>
/// </summary>
public ILocalizedTextService TextService
{
get { return _localizedTextService.Value; }
}
/// <summary>
/// Gets the <see cref="INotificationService"/>
/// </summary>
public INotificationService NotificationService
{
get { return _notificationService.Value; }
}
/// <summary>
/// Gets the <see cref="ServerRegistrationService"/>
/// </summary>
public ServerRegistrationService ServerRegistrationService
{
get { return _serverRegistrationService.Value; }
}
/// <summary>
/// Gets the <see cref="ITagService"/>
/// </summary>
public ITagService TagService
{
get { return _tagService.Value; }
}
/// <summary>
/// Gets the <see cref="IMacroService"/>
/// </summary>
public IMacroService MacroService
{
get { return _macroService.Value; }
}
/// <summary>
/// Gets the <see cref="IEntityService"/>
/// </summary>
public IEntityService EntityService
{
get { return _entityService.Value; }
}
/// <summary>
/// Gets the <see cref="IRelationService"/>
/// </summary>
public IRelationService RelationService
{
get { return _relationService.Value; }
}
/// <summary>
/// Gets the <see cref="IContentService"/>
/// </summary>
public IContentService ContentService
{
get { return _contentService.Value; }
}
/// <summary>
/// Gets the <see cref="IContentTypeService"/>
/// </summary>
public IContentTypeService ContentTypeService
{
get { return _contentTypeService.Value; }
}
/// <summary>
/// Gets the <see cref="IDataTypeService"/>
/// </summary>
public IDataTypeService DataTypeService
{
get { return _dataTypeService.Value; }
}
/// <summary>
/// Gets the <see cref="IFileService"/>
/// </summary>
public IFileService FileService
{
get { return _fileService.Value; }
}
/// <summary>
/// Gets the <see cref="ILocalizationService"/>
/// </summary>
public ILocalizationService LocalizationService
{
get { return _localizationService.Value; }
}
/// <summary>
/// Gets the <see cref="IMediaService"/>
/// </summary>
public IMediaService MediaService
{
get { return _mediaService.Value; }
}
/// <summary>
/// Gets the <see cref="PackagingService"/>
/// </summary>
public IPackagingService PackagingService
{
get { return _packagingService.Value; }
}
/// <summary>
/// Gets the <see cref="UserService"/>
/// </summary>
public IUserService UserService
{
get { return _userService.Value; }
}
/// <summary>
/// Gets the <see cref="MemberService"/>
/// </summary>
public IMemberService MemberService
{
get { return _memberService.Value; }
}
/// <summary>
/// Gets the <see cref="SectionService"/>
/// </summary>
public ISectionService SectionService
{
get { return _sectionService.Value; }
}
/// <summary>
/// Gets the <see cref="ApplicationTreeService"/>
/// </summary>
public IApplicationTreeService ApplicationTreeService
{
get { return _treeService.Value; }
}
/// <summary>
/// Gets the MemberTypeService
/// </summary>
public IMemberTypeService MemberTypeService
{
get { return _memberTypeService.Value; }
}
/// <summary>
/// Gets the MemberGroupService
/// </summary>
public IMemberGroupService MemberGroupService
{
get { return _memberGroupService.Value; }
}
public IExternalLoginService ExternalLoginService
{
get { return _externalLoginService.Value; }
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
namespace LumiSoft.Net.SIP.Message
{
/// <summary>
/// Implements SIP "Authentication-Info" value. Defined in RFC 3261.
/// According RFC 3261 authentication info can contain Digest authentication info only.
/// </summary>
public class SIP_t_AuthenticationInfo : SIP_t_Value
{
private string m_NextNonce = null;
private string m_Qop = null;
private string m_ResponseAuth = null;
private string m_CNonce = null;
private int m_NonceCount = -1;
/// <summary>
/// Default constructor.
/// </summary>
/// <param name="value">Authentication-Info valu value.</param>
public SIP_t_AuthenticationInfo(string value)
{
Parse(new StringReader(value));
}
#region method Parse
/// <summary>
/// Parses "Authentication-Info" from specified value.
/// </summary>
/// <param name="value">SIP "Authentication-Info" value.</param>
/// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception>
/// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception>
public void Parse(string value)
{
if(value == null){
throw new ArgumentNullException("value");
}
Parse(new StringReader(value));
}
/// <summary>
/// Parses "Authentication-Info" from specified reader.
/// </summary>
/// <param name="reader">Reader what contains Authentication-Info value.</param>
/// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception>
/// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception>
public override void Parse(StringReader reader)
{
/*
Authentication-Info = "Authentication-Info" HCOLON ainfo *(COMMA ainfo)
ainfo = nextnonce / message-qop / response-auth / cnonce / nonce-count
nextnonce = "nextnonce" EQUAL nonce-value
response-auth = "rspauth" EQUAL response-digest
response-digest = LDQUOT *LHEX RDQUOT
nc-value = 8LHEX
*/
if(reader == null){
throw new ArgumentNullException("reader");
}
while(reader.Available > 0){
string word = reader.QuotedReadToDelimiter(',');
if(word != null && word.Length > 0){
string[] name_value = word.Split(new char[]{'='},2);
if(name_value[0].ToLower() == "nextnonce"){
this.NextNonce = name_value[1];
}
else if(name_value[0].ToLower() == "qop"){
this.Qop = name_value[1];
}
else if(name_value[0].ToLower() == "rspauth"){
this.ResponseAuth = name_value[1];
}
else if(name_value[0].ToLower() == "cnonce"){
this.CNonce = name_value[1];
}
else if(name_value[0].ToLower() == "nc"){
this.NonceCount = Convert.ToInt32(name_value[1]);
}
else{
throw new SIP_ParseException("Invalid Authentication-Info value !");
}
}
}
}
#endregion
#region method ToStringValue
/// <summary>
/// Converts SIP_t_AuthenticationInfo to valid Authentication-Info value.
/// </summary>
/// <returns></returns>
public override string ToStringValue()
{
/*
Authentication-Info = "Authentication-Info" HCOLON ainfo *(COMMA ainfo)
ainfo = nextnonce / message-qop / response-auth / cnonce / nonce-count
nextnonce = "nextnonce" EQUAL nonce-value
response-auth = "rspauth" EQUAL response-digest
response-digest = LDQUOT *LHEX RDQUOT
nc-value = 8LHEX
*/
StringBuilder retVal = new StringBuilder();
if(m_NextNonce != null){
retVal.Append("nextnonce=" + m_NextNonce);
}
if(m_Qop != null){
if(retVal.Length > 0){
retVal.Append(',');
}
retVal.Append("qop=" + m_Qop);
}
if(m_ResponseAuth != null){
if(retVal.Length > 0){
retVal.Append(',');
}
retVal.Append("rspauth=" + TextUtils.QuoteString(m_ResponseAuth));
}
if(m_CNonce != null){
if(retVal.Length > 0){
retVal.Append(',');
}
retVal.Append("cnonce=" + m_CNonce);
}
if(m_NonceCount != -1){
if(retVal.Length > 0){
retVal.Append(',');
}
retVal.Append("nc=" + m_NonceCount.ToString("X8"));
}
return retVal.ToString();
}
#endregion
#region Properties Implementation
/// <summary>
/// Gets or sets server next predicted nonce value. Value null means that value not specified.
/// </summary>
public string NextNonce
{
get{ return m_NextNonce; }
set{ m_NextNonce = value; }
}
/// <summary>
/// Gets or sets QOP value. Value null means that value not specified.
/// </summary>
public string Qop
{
get{ return m_Qop; }
set{ m_Qop = value; }
}
/// <summary>
/// Gets or sets rspauth value. Value null means that value not specified.
/// This can be only HEX value.
/// </summary>
public string ResponseAuth
{
get{ return m_ResponseAuth; }
set{
// TODO: Check that value is hex value
m_ResponseAuth = value;
}
}
/// <summary>
/// Gets or sets cnonce value. Value null means that value not specified.
/// </summary>
public string CNonce
{
get{ return m_CNonce; }
set{ m_CNonce = value; }
}
/// <summary>
/// Gets or sets nonce count. Value -1 means that value not specified.
/// </summary>
public int NonceCount
{
get{ return m_NonceCount; }
set{
if(value < 0){
m_NonceCount = -1;
}
else{
m_NonceCount = value;
}
}
}
#endregion
}
}
| |
//
// PlayQueueSource.cs
//
// Authors:
// Aaron Bockover <abockover@novell.com>
// Alexander Kojevnikov <alexander@kojevnikov.com>
//
// Copyright (C) 2008 Novell, Inc.
// Copyright (C) 2009 Alexander Kojevnikov
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using System.Collections.Generic;
using System.Linq;
using Mono.Unix;
using Hyena;
using Hyena.Collections;
using Hyena.Data.Sqlite;
using Banshee.Collection;
using Banshee.Collection.Database;
using Banshee.Configuration;
using Banshee.Database;
using Banshee.Gui;
using Banshee.Library;
using Banshee.MediaEngine;
using Banshee.PlaybackController;
using Banshee.Playlist;
using Banshee.Preferences;
using Banshee.ServiceStack;
using Banshee.Sources;
namespace Banshee.PlayQueue
{
public class PlayQueueSource : PlaylistSource, IBasicPlaybackController, IPlayQueue, IDBusExportable, IDisposable
{
private static string special_playlist_name = Catalog.GetString ("Play Queue");
private ITrackModelSource prior_playback_source;
private DatabaseTrackInfo current_track;
private Shuffler shuffler;
private long offset = -1;
private TrackInfo prior_playback_track;
private PlayQueueActions actions;
private bool was_playing = false;
protected DateTime source_set_at = DateTime.MinValue;
private HeaderWidget header_widget;
private SourcePage pref_page;
private Section pref_section;
private string populate_shuffle_mode = PopulateModeSchema.Get ();
private string populate_from_name = PopulateFromSchema.Get ();
private DatabaseSource populate_from = null;
private int played_songs_number = PlayedSongsNumberSchema.Get ();
private int upcoming_songs_number = UpcomingSongsNumberSchema.Get ();
public PlayQueueSource () : base (Catalog.GetString ("Play Queue"), null)
{
BindToDatabase ();
TypeUniqueId = DbId.ToString ();
Initialize ();
AfterInitialized ();
Order = 20;
Properties.SetString ("Icon.Name", "source-playlist");
Properties.SetString ("RemoveTracksActionLabel", Catalog.GetString ("Remove From Play Queue"));
DatabaseTrackModel.ForcedSortQuery = "CorePlaylistEntries.ViewOrder ASC, CorePlaylistEntries.EntryID ASC";
DatabaseTrackModel.CanReorder = true;
ServiceManager.PlayerEngine.ConnectEvent (OnPlayerEvent);
ServiceManager.PlaybackController.TrackStarted += OnTrackStarted;
// TODO change this Gtk.Action code so that the actions can be removed. And so this
// class doesn't depend on Gtk/ThickClient.
actions = new PlayQueueActions (this);
Properties.SetString ("ActiveSourceUIResource", "ActiveSourceUI.xml");
Properties.SetString ("GtkActionPath", "/PlayQueueContextMenu");
// TODO listen to all primary sources, and handle transient primary sources
ServiceManager.SourceManager.MusicLibrary.TracksChanged += HandleTracksChanged;
ServiceManager.SourceManager.MusicLibrary.TracksDeleted += HandleTracksDeleted;
ServiceManager.SourceManager.VideoLibrary.TracksChanged += HandleTracksChanged;
ServiceManager.SourceManager.VideoLibrary.TracksDeleted += HandleTracksDeleted;
populate_from = ServiceManager.SourceManager.Sources.FirstOrDefault (
source => source.Name == populate_from_name) as DatabaseSource;
if (populate_from != null) {
populate_from.Reload ();
}
TrackModel.Reloaded += HandleReloaded;
int saved_offset = DatabaseConfigurationClient.Client.Get (CurrentOffsetSchema, CurrentOffsetSchema.Get ());
Offset = Math.Min (
saved_offset,
ServiceManager.DbConnection.Query<long> (@"
SELECT MAX(ViewOrder) + 1
FROM CorePlaylistEntries
WHERE PlaylistID = ?", DbId));
ServiceManager.SourceManager.AddSource (this);
}
protected override void Initialize ()
{
base.Initialize ();
shuffler = new Shuffler (UniqueId);
InstallPreferences ();
header_widget = CreateHeaderWidget ();
header_widget.ShowAll ();
Properties.Set<Gtk.Widget> ("Nereid.SourceContents.HeaderWidget", header_widget);
}
public HeaderWidget CreateHeaderWidget ()
{
var header_widget = new HeaderWidget (shuffler, populate_shuffle_mode, populate_from_name);
header_widget.ModeChanged += delegate (object sender, EventArgs<RandomBy> e) {
populate_shuffle_mode = e.Value.Id;
PopulateModeSchema.Set (populate_shuffle_mode);
UpdatePlayQueue ();
OnUpdated ();
};
populate_shuffle_mode = header_widget.ShuffleModeId;
header_widget.SourceChanged += delegate (object sender, EventArgs<DatabaseSource> e) {
populate_from = e.Value;
if (populate_from == null) {
populate_from_name = String.Empty;
PopulateFromSchema.Set (String.Empty);
return;
}
populate_from_name = e.Value.Name;
PopulateFromSchema.Set (e.Value.Name);
source_set_at = DateTime.Now;
populate_from.Reload ();
Refresh ();
};
return header_widget;
}
// Randomizes the ViewOrder of all the enabled, unplayed/playing songs
public void Shuffle ()
{
if (!Populate) {
if (current_track == null)
return;
int enabled_count = EnabledCount;
int first_view_order = (int)CurrentTrackViewOrder;
int last_view_order = first_view_order + enabled_count;
// If the current track is playing, don't shuffle it
if (ServiceManager.PlayerEngine.IsPlaying (current_track))
first_view_order++;
// Nothing to do if less than 2 tracks
if (last_view_order - first_view_order < 2)
return;
// Save the current_track index, so we can update the current track
// to be whatever one is at that position after we shuffle them -- assuming
// the current_track isn't already playing.
int current_index = TrackModel.IndexOf (current_track);
// Setup a function that will return a random ViewOrder in the range we want
var rand = new Random ();
var func_id = "play-queue-shuffle-order-" + rand.NextDouble ().ToString ();
var view_orders = Enumerable.Range (first_view_order, last_view_order)
.OrderBy (a => rand.NextDouble ())
.ToList ();
int i = 0;
BinaryFunction.Add (func_id, (f, b) => view_orders[i++]);
ServiceManager.DbConnection.Execute (
"UPDATE CorePlaylistEntries SET ViewOrder = HYENA_BINARY_FUNCTION (?, NULL, NULL) WHERE PlaylistID = ? AND ViewOrder >= ?",
func_id, DbId, first_view_order
);
BinaryFunction.Remove (func_id);
Reload ();
// Update the current track unless it was playing (and therefore wasn't moved)
if (!ServiceManager.PlayerEngine.IsPlaying (current_track)) {
SetCurrentTrack (TrackModel[current_index] as DatabaseTrackInfo);
}
}
}
#region IPlayQueue, IDBusExportable
public void EnqueueUri (string uri)
{
EnqueueUri (uri, false);
}
public void EnqueueUri (string uri, bool prepend)
{
EnqueueId (DatabaseTrackInfo.GetTrackIdForUri (uri), prepend, false);
}
public void EnqueueTrack (TrackInfo track, bool prepend)
{
DatabaseTrackInfo db_track = track as DatabaseTrackInfo;
if (db_track != null) {
EnqueueId (db_track.TrackId, prepend, false);
} else {
EnqueueUri (track.Uri.AbsoluteUri, prepend);
}
}
private void EnqueueId (int trackId, bool prepend, bool generated)
{
if (trackId <= 0) {
return;
}
long view_order;
if (prepend && current_track != null) {
// We are going to prepend the track to the play queue, which means
// adding it after the current_track. Now find the corresponding view_order.
view_order = ServiceManager.DbConnection.Query<long> (@"
SELECT ViewOrder + 1
FROM CorePlaylistEntries
WHERE PlaylistID = ? AND EntryID = ?",
DbId, Convert.ToInt64 (current_track.CacheEntryId)
);
} else {
if (generated) {
// view_order will point after the last track in the queue.
view_order = MaxViewOrder;
}
else {
// view_order will point after the last non-generated track in the queue.
view_order = ServiceManager.DbConnection.Query<long> (@"
SELECT MAX(ViewOrder) + 1
FROM CorePlaylistEntries
WHERE PlaylistID = ? AND Generated = 0",
DbId
);
}
}
// Increment the order of all tracks after view_order
ServiceManager.DbConnection.Execute (@"
UPDATE CorePlaylistEntries
SET ViewOrder = ViewOrder + 1
WHERE PlaylistID = ? AND ViewOrder >= ?",
DbId, view_order
);
// Add the track to the queue using the view order calculated above.
ServiceManager.DbConnection.Execute (@"
INSERT INTO CorePlaylistEntries
(PlaylistID, TrackID, ViewOrder, Generated)
VALUES (?, ?, ?, ?)",
DbId, trackId, view_order, generated ? 1 : 0
);
if (!generated) {
shuffler.RecordShuffleModification (trackId, ShuffleModificationType.Insertion);
}
OnTracksAdded ();
NotifyUser ();
}
IDBusExportable IDBusExportable.Parent {
get { return ServiceManager.SourceManager; }
}
string IService.ServiceName {
get { return "PlayQueue"; }
}
private long CurrentTrackViewOrder {
get {
// Get the ViewOrder of the current_track
return current_track == null
? ServiceManager.DbConnection.Query<long> (@"
SELECT MAX(ViewOrder) + 1
FROM CorePlaylistEntries
WHERE PlaylistID = ?",
DbId)
: ServiceManager.DbConnection.Query<long> (@"
SELECT ViewOrder
FROM CorePlaylistEntries
WHERE PlaylistID = ? AND EntryID = ?",
DbId, Convert.ToInt64 (current_track.CacheEntryId));
}
}
#endregion
public override bool AddSelectedTracks (Source source)
{
if ((Parent == null || source == Parent || source.Parent == Parent) && AcceptsInputFromSource (source)) {
DatabaseTrackListModel model = (source as ITrackModelSource).TrackModel as DatabaseTrackListModel;
if (model == null) {
return false;
}
long current_view_order = CurrentTrackViewOrder;
// If the current_track is not playing, insert before it.
int index = -1;
if (current_track != null && !ServiceManager.PlayerEngine.IsPlaying (current_track)) {
current_view_order--;
index = TrackModel.IndexOf (current_track);
}
// view_order will point to the last pending non-generated track in the queue
// or to the current_track if all tracks are generated. We want to insert tracks after it.
long view_order = Math.Max(current_view_order, ServiceManager.DbConnection.Query<long> (@"
SELECT MAX(ViewOrder)
FROM CorePlaylistEntries
WHERE PlaylistID = ? AND ViewOrder > ? AND Generated = 0",
DbId, current_view_order
));
WithTrackSelection (model, shuffler.RecordInsertions);
// Add the tracks to the end of the queue.
WithTrackSelection (model, AddTrackRange);
// Shift generated tracks to the end of the queue.
ServiceManager.DbConnection.Execute (@"
UPDATE CorePlaylistEntries
SET ViewOrder = ViewOrder - ? + ?
WHERE PlaylistID = ? AND ViewOrder > ? AND Generated = 1",
view_order, MaxViewOrder, DbId, view_order
);
OnTracksAdded ();
OnUserNotifyUpdated ();
// If the current_track was not playing, and there were no non-generated tracks,
// mark the first added track as current.
if (index != -1 && view_order == current_view_order) {
SetCurrentTrack (TrackModel[index] as DatabaseTrackInfo);
SetAsPlaybackSourceUnlessPlaying ();
}
return true;
}
return false;
}
private void SetAsPlaybackSourceUnlessPlaying ()
{
if (current_track != null && ServiceManager.PlaybackController.Source != this) {
bool set_source = !ServiceManager.PlayerEngine.IsPlaying ();
if (!set_source) {
long view_order = ServiceManager.DbConnection.Query<long> (@"
SELECT ViewOrder
FROM CorePlaylistEntries
WHERE PlaylistID = ? AND EntryID = ?",
DbId, Convert.ToInt64 (current_track.CacheEntryId));
long nongenerated = ServiceManager.DbConnection.Query<long> (@"
SELECT COUNT(*)
FROM CorePlaylistEntries
WHERE PlaylistID = ? AND ViewOrder >= ? AND Generated = 0",
DbId, view_order);
set_source = nongenerated > 0;
}
if (set_source) {
PriorSource = ServiceManager.PlaybackController.Source;
ServiceManager.PlaybackController.NextSource = this;
}
}
}
public void Clear ()
{
Clear (false);
}
private void Clear (bool disposing)
{
ServiceManager.DbConnection.Execute (@"
DELETE FROM CorePlaylistEntries
WHERE PlaylistID = ?", DbId
);
offset = 0;
SetCurrentTrack (null);
if (disposing) {
return;
}
if (this == ServiceManager.PlaybackController.Source && ServiceManager.PlayerEngine.IsPlaying ()) {
ServiceManager.PlayerEngine.Close();
}
Reload ();
}
public void Dispose ()
{
int track_index = current_track == null ? Count : Math.Max (0, TrackModel.IndexOf (current_track));
DatabaseConfigurationClient.Client.Set (CurrentTrackSchema, track_index);
ServiceManager.PlayerEngine.DisconnectEvent (OnPlayerEvent);
ServiceManager.PlaybackController.TrackStarted -= OnTrackStarted;
if (actions != null) {
actions.Dispose ();
}
UninstallPreferences ();
Properties.Remove ("Nereid.SourceContents.HeaderWidget");
if (header_widget != null) {
header_widget.Destroy ();
header_widget = null;
}
if (!Populate && ClearOnQuitSchema.Get ()) {
Clear (true);
}
}
private void BindToDatabase ()
{
int result = ServiceManager.DbConnection.Query<int> (
"SELECT PlaylistID FROM CorePlaylists WHERE Special = 1 AND Name = ? LIMIT 1",
special_playlist_name
);
if (result != 0) {
DbId = result;
} else {
DbId = ServiceManager.DbConnection.Execute (new HyenaSqliteCommand (@"
INSERT INTO CorePlaylists (PlaylistID, Name, SortColumn, SortType, Special) VALUES (NULL, ?, -1, 0, 1)
", special_playlist_name));
}
}
protected override void OnTracksAdded ()
{
int old_count = Count;
base.OnTracksAdded ();
if (current_track == null && old_count < Count) {
SetCurrentTrack (TrackModel[old_count] as DatabaseTrackInfo);
}
SetAsPlaybackSourceUnlessPlaying ();
}
protected override void OnTracksRemoved ()
{
base.OnTracksRemoved ();
if (this == ServiceManager.PlaybackController.Source &&
ServiceManager.PlayerEngine.IsPlaying () &&
TrackModel.IndexOf (ServiceManager.PlayerEngine.CurrentTrack) == -1) {
if (ServiceManager.PlayerEngine.CurrentState == PlayerState.Paused || current_track == null) {
ServiceManager.PlayerEngine.Close();
} else {
ServiceManager.PlayerEngine.OpenPlay (current_track);
}
}
UpdatePlayQueue ();
}
protected override void RemoveTrackRange (DatabaseTrackListModel model, RangeCollection.Range range)
{
shuffler.RecordShuffleModifications (model, range, ShuffleModificationType.Discard);
base.RemoveTrackRange (model, range);
model.Selection.UnselectRange (range.Start, range.End);
int index = TrackModel.IndexOf (current_track);
if (range.Start <= index && index <= range.End) {
SetCurrentTrack (range.End + 1 < Count ? TrackModel[range.End + 1] as DatabaseTrackInfo : null);
}
}
private void HandleReloaded(object sender, EventArgs e)
{
int track_index = DatabaseConfigurationClient.Client.Get (CurrentTrackSchema, CurrentTrackSchema.Get ());
if (track_index < Count) {
SetCurrentTrack (TrackModel[track_index] as DatabaseTrackInfo);
}
SetAsPlaybackSourceUnlessPlaying ();
TrackModel.Reloaded -= HandleReloaded;
}
public override void ReorderSelectedTracks (int drop_row)
{
// If the current_track is not playing, dropping tracks may change it.
// If the selection is dropped above the current_track, the first pending
// of the dropped tracks (if any) will become the new current_track.
// If the tracks are dropped below the curren_track,
// the first pending track not in the selection will become current.
if (current_track != null && !ServiceManager.PlayerEngine.IsPlaying (current_track)) {
int current_index = TrackModel.IndexOf (current_track);
bool above = drop_row <= current_index;
int new_index = -1;
for (int index = current_index; index < TrackModel.Count; index++) {
if (above == TrackModel.Selection.Contains (index)) {
new_index = index;
break;
}
}
if (new_index != current_index && new_index >= 0) {
SetCurrentTrack (TrackModel[new_index] as DatabaseTrackInfo);
}
}
base.ReorderSelectedTracks (drop_row);
}
private void OnPlayerEvent (PlayerEventArgs args)
{
if (args.Event == PlayerEvent.EndOfStream) {
if (this == ServiceManager.PlaybackController.Source &&
TrackModel.IndexOf (current_track) == Count - 1) {
SetCurrentTrack (null);
UpdatePlayQueue ();
if (was_playing) {
ServiceManager.PlaybackController.PriorTrack = prior_playback_track;
} else {
ServiceManager.PlaybackController.StopWhenFinished = true;
}
}
if (ServiceManager.PlaybackController.StopWhenFinished) {
if (current_track != null && ServiceManager.PlayerEngine.CurrentTrack == current_track) {
int index = TrackModel.IndexOf (current_track) + 1;
SetCurrentTrack (index < Count ? TrackModel[index] as DatabaseTrackInfo : null);
}
}
} else if (args.Event == PlayerEvent.StartOfStream) {
if (TrackModel.IndexOf (ServiceManager.PlayerEngine.CurrentTrack) != -1) {
SetCurrentTrack (ServiceManager.PlayerEngine.CurrentTrack as DatabaseTrackInfo);
SetAsPlaybackSourceUnlessPlaying ();
UpdatePlayQueue ();
} else {
prior_playback_track = ServiceManager.PlayerEngine.CurrentTrack;
}
}
}
public override void Reload ()
{
enabled_cache.Clear ();
base.Reload ();
if (current_track == null) {
if (this == ServiceManager.PlaybackController.Source ||
this == ServiceManager.PlaybackController.NextSource) {
ServiceManager.PlaybackController.NextSource = PriorSource;
}
}
}
protected override DatabaseTrackListModel CreateTrackModelFor (DatabaseSource src)
{
return new PlayQueueTrackListModel (ServiceManager.DbConnection, DatabaseTrackInfo.Provider, (PlayQueueSource) src);
}
bool IBasicPlaybackController.First ()
{
return ((IBasicPlaybackController)this).Next (false, true);
}
bool IBasicPlaybackController.Next (bool restart, bool changeImmediately)
{
if (current_track != null && ServiceManager.PlayerEngine.CurrentTrack == current_track) {
int index = TrackModel.IndexOf (current_track) + 1;
SetCurrentTrack (index < Count ? TrackModel[index] as DatabaseTrackInfo : null);
}
if (current_track == null) {
UpdatePlayQueue ();
ServiceManager.PlaybackController.Source = PriorSource;
if (was_playing) {
ServiceManager.PlaybackController.PriorTrack = prior_playback_track;
ServiceManager.PlaybackController.Next (restart, changeImmediately);
} else {
if (!changeImmediately) {
ServiceManager.PlayerEngine.SetNextTrack ((TrackInfo)null);
}
ServiceManager.PlayerEngine.Close ();
}
return true;
}
if (changeImmediately) {
ServiceManager.PlayerEngine.OpenPlay (current_track);
} else {
ServiceManager.PlayerEngine.SetNextTrack (current_track);
}
return true;
}
bool IBasicPlaybackController.Previous (bool restart)
{
if (current_track != null && ServiceManager.PlayerEngine.CurrentTrack == current_track) {
int index = TrackModel.IndexOf (current_track);
if (index > 0) {
SetCurrentTrack (TrackModel[index - 1] as DatabaseTrackInfo);
}
ServiceManager.PlayerEngine.OpenPlay (current_track);
}
return true;
}
private void UpdatePlayQueue ()
{
// Find the ViewOrder of the current_track.
long view_order;
if (current_track == null) {
view_order = ServiceManager.DbConnection.Query<long> (@"
SELECT MAX(ViewOrder) + 1
FROM CorePlaylistEntries
WHERE PlaylistID = ?", DbId
);
}
else {
view_order = ServiceManager.DbConnection.Query<long> (@"
SELECT ViewOrder
FROM CorePlaylistEntries
WHERE PlaylistID = ? AND EntryID = ?",
DbId, Convert.ToInt64 (current_track.CacheEntryId)
);
}
// Offset the model so that no more than played_songs_number tracks are shown before the current_track.
Offset = played_songs_number == 0 ? view_order : ServiceManager.DbConnection.Query<long> (@"
SELECT MIN(ViewOrder)
FROM (
SELECT ViewOrder
FROM CorePlaylistEntries
WHERE PlaylistID = ? AND ViewOrder < ?
ORDER BY ViewOrder DESC
LIMIT ?
)", DbId, view_order, played_songs_number
);
// Check if we need to add more tracks.
int tracks_to_add = upcoming_songs_number -
(current_track == null ? 0 : Count - TrackModel.IndexOf (current_track) - 1);
// If the current track is not playing count it as well.
if (current_track != null && !ServiceManager.PlayerEngine.IsPlaying (current_track)) {
tracks_to_add--;
}
if (tracks_to_add > 0 && Populate && populate_from != null) {
// Add songs from the selected source, skip if all tracks need to be populated.
bool skip = tracks_to_add == upcoming_songs_number;
for (int i = 0; i < tracks_to_add; i++) {
var track = populate_from.DatabaseTrackModel.GetRandom (
source_set_at, populate_shuffle_mode, false, skip && i == 0, shuffler) as DatabaseTrackInfo;
if (track != null) {
EnqueueId (track.TrackId, false, true);
}
}
OnTracksAdded ();
if (current_track == null && Count > 0) {
// If the queue was empty, make the first added track the current one.
SetCurrentTrack (TrackModel[0] as DatabaseTrackInfo);
ServiceManager.PlayerEngine.OpenPlay (current_track);
}
}
}
private readonly Dictionary<int, bool> enabled_cache = new Dictionary<int, bool> ();
public bool IsTrackEnabled (int index)
{
if (!enabled_cache.ContainsKey (index)) {
int current_index = current_track == null ? Count : TrackModel.IndexOf (current_track);
enabled_cache.Add (index, index >= current_index);
}
return enabled_cache[index];
}
private void SetCurrentTrack (DatabaseTrackInfo track)
{
enabled_cache.Clear ();
current_track = track;
}
public void Refresh ()
{
int index = current_track == null ? Count : TrackModel.IndexOf (current_track);
// If the current track is not playing refresh it too.
if (current_track != null && !ServiceManager.PlayerEngine.IsPlaying (current_track)) {
index--;
}
if (index + 1 < Count) {
// Get the ViewOrder of the current_track
long current_view_order = CurrentTrackViewOrder;
// Get the list of generated tracks.
var generated = new HashSet<long> ();
foreach (long trackID in ServiceManager.DbConnection.QueryEnumerable<long> ( @"
SELECT TrackID
FROM CorePlaylistEntries
WHERE PlaylistID = ? AND Generated = 1 AND ViewOrder >= ?",
DbId, current_view_order)) {
generated.Add (trackID);
}
// Collect the indices of all generated tracks.
var ranges = new RangeCollection ();
for (int i = index + 1; i < Count; i++) {
if (generated.Contains (((DatabaseTrackInfo)TrackModel[i]).TrackId)) {
ranges.Add (i);
}
}
bool removed = false;
foreach (var range in ranges.Ranges) {
RemoveTrackRange (DatabaseTrackModel, range);
removed = true;
}
if (removed) {
OnTracksRemoved ();
}
} else if (Count == 0 || current_track == null) {
UpdatePlayQueue ();
}
}
public void AddMoreRandomTracks ()
{
int current_fill = current_track == null ? 0 : Count - TrackModel.IndexOf (current_track) - 1;
upcoming_songs_number += current_fill;
UpdatePlayQueue ();
upcoming_songs_number -= current_fill;
}
private void OnTrackStarted(object sender, EventArgs e)
{
SetAsPlaybackSourceUnlessPlaying ();
}
private bool enable_population = true;
public bool Populate {
get { return enable_population && populate_shuffle_mode != "off"; }
set { enable_population = value; }
}
private ITrackModelSource PriorSource {
get {
if (prior_playback_source == null || prior_playback_source == this) {
return (ITrackModelSource)ServiceManager.SourceManager.DefaultSource;
}
return prior_playback_source;
}
set {
if (value == null || value == this) {
return;
}
prior_playback_source = value;
was_playing = ServiceManager.PlayerEngine.IsPlaying ();
}
}
public long Offset {
get { return offset; }
protected set {
if (value != offset) {
offset = value;
DatabaseConfigurationClient.Client.Set (CurrentOffsetSchema, (int)offset);
Reload ();
}
}
}
public override int EnabledCount {
get {
return current_track == null ? 0 : Count - TrackModel.IndexOf (current_track);
}
}
public override int FilteredCount {
get { return EnabledCount; }
}
public override bool CanRename {
get { return false; }
}
public override bool CanSearch {
get { return false; }
}
public override bool ShowBrowser {
get { return false; }
}
protected override bool HasArtistAlbum {
get { return false; }
}
public override bool ConfirmRemoveTracks {
get { return false; }
}
public override bool CanRepeat {
get { return false; }
}
public override bool CanShuffle {
get { return false; }
}
public override bool CanUnmap {
get { return false; }
}
public override string PreferencesPageId {
get { return "play-queue"; }
}
private void InstallPreferences ()
{
pref_page = new Banshee.Preferences.SourcePage (PreferencesPageId, Name, "source-playlist", 500);
pref_section = pref_page.Add (new Section ());
pref_section.ShowLabel = false;
pref_section.Add (new SchemaPreference<int> (PlayedSongsNumberSchema,
Catalog.GetString ("Number of _played songs to show"), null, delegate {
played_songs_number = PlayedSongsNumberSchema.Get ();
UpdatePlayQueue ();
}
));
pref_section.Add (new SchemaPreference<int> (UpcomingSongsNumberSchema,
Catalog.GetString ("Number of _upcoming songs to show"), null, delegate {
upcoming_songs_number = UpcomingSongsNumberSchema.Get ();
UpdatePlayQueue ();
}
));
}
private void UninstallPreferences ()
{
pref_page.Dispose ();
pref_page = null;
pref_section = null;
}
public static readonly SchemaEntry<bool> ClearOnQuitSchema = new SchemaEntry<bool> (
"plugins.play_queue", "clear_on_quit",
false,
"Clear on Quit",
"Clear the play queue when quitting"
);
// TODO: By 1.8 next two schemas can be removed. They are kept only to ease
// the migration from GConfConfigurationClient to DatabaseConfigurationClient.
private static readonly SchemaEntry<int> CurrentTrackSchema = new SchemaEntry<int> (
"plugins.play_queue", "current_track",
0,
"Current Track",
"Current track in the Play Queue"
);
private static readonly SchemaEntry<int> CurrentOffsetSchema = new SchemaEntry<int> (
"plugins.play_queue", "current_offset",
0,
"Current Offset",
"Current offset of the Play Queue"
);
public static readonly SchemaEntry<string> PopulateModeSchema = new SchemaEntry<string> (
"plugins.play_queue", "populate_shuffle_mode",
"off",
"Play Queue population mode",
"How (and if) the Play Queue should be randomly populated"
);
public static readonly SchemaEntry<string> PopulateFromSchema = new SchemaEntry<string> (
"plugins.play_queue", "populate_from",
ServiceManager.SourceManager.MusicLibrary.Name,
"Source to poplulate from",
"Name of the source to populate the the Play Queue from"
);
public static readonly SchemaEntry<int> PlayedSongsNumberSchema = new SchemaEntry<int> (
"plugins.play_queue", "played_songs_number",
10, 0, 100,
"Played Songs Number",
"Number of played songs to show in the Play Queue"
);
public static readonly SchemaEntry<int> UpcomingSongsNumberSchema = new SchemaEntry<int> (
"plugins.play_queue", "upcoming_songs_number",
10, 1, 100,
"Upcoming Songs Number",
"Number of upcoming songs to show in the Play Queue"
);
}
}
| |
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Avalonia.Media;
using Avalonia.Platform;
using SkiaSharp;
namespace Avalonia.Skia
{
unsafe class FormattedTextImpl : IFormattedTextImpl
{
public SKPaint Paint { get; private set; }
public FormattedTextImpl(string text)
{
_text = text;
Paint = new SKPaint();
Paint.TextEncoding = SKTextEncoding.Utf16;
Paint.IsStroke = false;
Paint.IsAntialias = true;
LineOffset = 0;
// Replace 0 characters with zero-width spaces (200B)
_text = _text.Replace((char)0, (char)0x200B);
}
public static FormattedTextImpl Create(string text, string fontFamilyName, double fontSize, FontStyle fontStyle,
TextAlignment textAlignment, FontWeight fontWeight)
{
var typeface = TypefaceCache.GetTypeface(fontFamilyName, fontStyle, fontWeight);
FormattedTextImpl instance = new FormattedTextImpl(text);
instance.Paint.Typeface = typeface;
instance.Paint.TextSize = (float)fontSize;
instance.Paint.TextAlign = textAlignment.ToSKTextAlign();
instance.Rebuild();
return instance;
}
private readonly string _text;
readonly List<FormattedTextLine> _lines = new List<FormattedTextLine>();
readonly List<Rect> _rects = new List<Rect>();
List<AvaloniaFormattedTextLine> _skiaLines;
SKRect[] _skiaRects;
Size _size;
const float MAX_LINE_WIDTH = 10000;
float LineOffset;
float WidthConstraint = -1;
struct AvaloniaFormattedTextLine
{
public float Top;
public int Start;
public int Length;
public float Height;
public float Width;
};
public IEnumerable<FormattedTextLine> GetLines()
{
return _lines;
}
public TextHitTestResult HitTestPoint(Point point)
{
for (int c = 0; c < _rects.Count; c++)
{
//TODO: Detect line first
var rc = _rects[c];
if (rc.Contains(point))
{
return new TextHitTestResult
{
IsInside = true,
TextPosition = c,
IsTrailing = (point.X - rc.X) > rc.Width / 2
};
}
}
bool end = point.X > _size.Width || point.Y > _size.Height;
return new TextHitTestResult() { IsTrailing = end, TextPosition = end ? _text.Length - 1 : 0 };
}
public Rect HitTestTextPosition(int index)
{
if (index < 0 || index >= _rects.Count)
return new Rect();
return _rects[index];
}
public IEnumerable<Rect> HitTestTextRange(int index, int length)
{
for (var c = 0; c < length; c++)
yield return _rects[c + index];
}
public Size Measure()
{
return _size;
}
public void SetForegroundBrush(IBrush brush, int startIndex, int length)
{
// TODO: we need an implementation here to properly support FormattedText
}
void Rebuild()
{
var length = _text.Length;
_lines.Clear();
_skiaRects = new SKRect[length];
_skiaLines = new List<AvaloniaFormattedTextLine>();
int curOff = 0;
float curY = 0;
var metrics = Paint.FontMetrics;
var mTop = metrics.Top; // The greatest distance above the baseline for any glyph (will be <= 0).
var mBottom = metrics.Bottom; // The greatest distance below the baseline for any glyph (will be >= 0).
var mLeading = metrics.Leading; // The recommended distance to add between lines of text (will be >= 0).
// This seems like the best measure of full vertical extent
float lineHeight = mBottom - mTop;
// Rendering is relative to baseline
LineOffset = -metrics.Top;
string subString;
byte[] bytes;
GCHandle pinnedArray;
IntPtr pointer;
for (int c = 0; curOff < length; c++)
{
float lineWidth = -1;
int measured;
int extraSkip = 0;
if (WidthConstraint <= 0)
{
measured = length;
}
else
{
float constraint = WidthConstraint;
if (constraint > MAX_LINE_WIDTH)
constraint = MAX_LINE_WIDTH;
subString = _text.Substring(curOff);
// TODO: This method is not linking into SkiaSharp so we must use the RAW buffer version for now
//measured = (int)Paint.BreakText(subString, constraint, out lineWidth) / 2;
bytes = Encoding.UTF8.GetBytes(subString);
pinnedArray = GCHandle.Alloc(bytes, GCHandleType.Pinned);
pointer = pinnedArray.AddrOfPinnedObject();
// for some reason I have to pass nBytes * 2. I assume under the hood it expects Unicode/WChar??
measured = (int)Paint.BreakText(pointer, (IntPtr)(bytes.Length * 2), constraint, out lineWidth) / 2;
pinnedArray.Free();
if (measured == 0)
{
measured = 1;
lineWidth = -1;
}
char nextChar = ' ';
if (curOff + measured < length)
nextChar = _text[curOff + measured];
if (nextChar != ' ')
{
// Perform scan for the last space and end the line there
for (int si = curOff + measured - 1; si > curOff; si--)
{
if (_text[si] == ' ')
{
measured = si - curOff;
extraSkip = 1;
break;
}
}
}
}
AvaloniaFormattedTextLine line = new AvaloniaFormattedTextLine();
line.Start = curOff;
line.Length = measured;
line.Width = lineWidth;
line.Height = lineHeight;
line.Top = curY;
if (line.Width < 0)
line.Width = _skiaRects[line.Start + line.Length - 1].Right;
// Build character rects
for (int i = line.Start; i < line.Start + line.Length; i++)
{
float prevRight = 0;
if (i != line.Start)
prevRight = _skiaRects[i - 1].Right;
subString = _text.Substring(line.Start, i - line.Start + 1);
float w = Paint.MeasureText(subString);
SKRect rc;
rc.Left = prevRight;
rc.Right = w;
rc.Top = line.Top;
rc.Bottom = line.Top + line.Height;
_skiaRects[i] = rc;
}
subString = _text.Substring(line.Start, line.Length);
line.Width = Paint.MeasureText(subString);
_skiaLines.Add(line);
curY += lineHeight;
// TODO: We may want to consider adding Leading to the vertical line spacing but for now
// it appears to make no difference. Revisit as part of FormattedText improvements.
//
//curY += mLeading;
curOff += measured + extraSkip;
}
// Now convert to Avalonia data formats
_lines.Clear();
_rects.Clear();
float maxX = 0;
for (var c = 0; c < _skiaLines.Count; c++)
{
var w = _skiaLines[c].Width;
if (maxX < w)
maxX = w;
_lines.Add(new FormattedTextLine(_skiaLines[c].Length, _skiaLines[c].Height));
}
for (var c = 0; c < _text.Length; c++)
{
_rects.Add(_skiaRects[c].ToAvaloniaRect());
}
if (_skiaLines.Count == 0)
{
_size = new Size();
}
else
{
var lastLine = _skiaLines[_skiaLines.Count - 1];
_size = new Size(maxX, lastLine.Top + lastLine.Height);
}
}
internal void Draw(SKCanvas canvas, SKPoint origin)
{
SKPaint paint = Paint;
/* TODO: This originated from Native code, it might be useful for debugging character positions as
* we improve the FormattedText support. Will need to port this to C# obviously. Rmove when
* not needed anymore.
SkPaint dpaint;
ctx->Canvas->save();
ctx->Canvas->translate(origin.fX, origin.fY);
for (int c = 0; c < Lines.size(); c++)
{
dpaint.setARGB(255, 0, 0, 0);
SkRect rc;
rc.fLeft = 0;
rc.fTop = Lines[c].Top;
rc.fRight = Lines[c].Width;
rc.fBottom = rc.fTop + LineOffset;
ctx->Canvas->drawRect(rc, dpaint);
}
for (int c = 0; c < Length; c++)
{
dpaint.setARGB(255, c % 10 * 125 / 10 + 125, (c * 7) % 10 * 250 / 10, (c * 13) % 10 * 250 / 10);
dpaint.setStyle(SkPaint::kFill_Style);
ctx->Canvas->drawRect(Rects[c], dpaint);
}
ctx->Canvas->restore();
*/
for (int c = 0; c < _skiaLines.Count; c++)
{
AvaloniaFormattedTextLine line = _skiaLines[c];
var subString = _text.Substring(line.Start, line.Length);
canvas.DrawText(subString, origin.X, origin.Y + line.Top + LineOffset, paint);
}
}
Size _constraint = new Size(double.PositiveInfinity, double.PositiveInfinity);
public Size Constraint
{
get { return _constraint; }
set
{
if (_constraint == value)
return;
_constraint = value;
WidthConstraint = (_constraint.Width != double.PositiveInfinity)
? (float)_constraint.Width
: -1;
Rebuild();
}
}
public override string ToString()
{
return _text;
}
public void Dispose()
{
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Threading;
using System.Transactions.Distributed;
namespace System.Transactions
{
public class TransactionEventArgs : EventArgs
{
internal Transaction _transaction;
public Transaction Transaction => _transaction;
}
public delegate void TransactionCompletedEventHandler(object sender, TransactionEventArgs e);
public enum IsolationLevel
{
Serializable = 0,
RepeatableRead = 1,
ReadCommitted = 2,
ReadUncommitted = 3,
Snapshot = 4,
Chaos = 5,
Unspecified = 6,
}
public enum TransactionStatus
{
Active = 0,
Committed = 1,
Aborted = 2,
InDoubt = 3
}
public enum DependentCloneOption
{
BlockCommitUntilComplete = 0,
RollbackIfNotComplete = 1,
}
[Flags]
public enum EnlistmentOptions
{
None = 0x0,
EnlistDuringPrepareRequired = 0x1,
}
// When we serialize a Transaction, we specify the type DistributedTransaction, so a Transaction never
// actually gets deserialized.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2229", Justification = "Serialization not yet supported and will be done using DistributedTransaction")]
public class Transaction : IDisposable, ISerializable
{
// UseServiceDomain
//
// Property tells parts of system.transactions if it should use a
// service domain for current.
[System.Runtime.CompilerServices.MethodImplAttribute(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
internal static bool UseServiceDomainForCurrent() => false;
// InteropMode
//
// This property figures out the current interop mode based on the
// top of the transaction scope stack as well as the default mode
// from config.
internal static EnterpriseServicesInteropOption InteropMode(TransactionScope currentScope)
{
if (currentScope != null)
{
return currentScope.InteropMode;
}
return EnterpriseServicesInteropOption.None;
}
internal static Transaction FastGetTransaction(TransactionScope currentScope, ContextData contextData, out Transaction contextTransaction)
{
Transaction current = null;
contextTransaction = null;
contextTransaction = contextData.CurrentTransaction;
switch (InteropMode(currentScope))
{
case EnterpriseServicesInteropOption.None:
current = contextTransaction;
// If there is a transaction in the execution context or if there is a current transaction scope
// then honer the transaction context.
if (current == null && currentScope == null)
{
// Otherwise check for an external current.
if (TransactionManager.s_currentDelegateSet)
{
current = TransactionManager.s_currentDelegate();
}
else
{
current = EnterpriseServices.GetContextTransaction(contextData);
}
}
break;
case EnterpriseServicesInteropOption.Full:
current = EnterpriseServices.GetContextTransaction(contextData);
break;
case EnterpriseServicesInteropOption.Automatic:
if (EnterpriseServices.UseServiceDomainForCurrent())
{
current = EnterpriseServices.GetContextTransaction(contextData);
}
else
{
current = contextData.CurrentTransaction;
}
break;
}
return current;
}
// GetCurrentTransactionAndScope
//
// Returns both the current transaction and scope. This is implemented for optimizations
// in TransactionScope because it is required to get both of them in several cases.
internal static void GetCurrentTransactionAndScope(
TxLookup defaultLookup,
out Transaction current,
out TransactionScope currentScope,
out Transaction contextTransaction)
{
current = null;
currentScope = null;
contextTransaction = null;
ContextData contextData = ContextData.LookupContextData(defaultLookup);
if (contextData != null)
{
currentScope = contextData.CurrentScope;
current = FastGetTransaction(currentScope, contextData, out contextTransaction);
}
}
public static Transaction Current
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "Transaction.get_Current");
}
Transaction current = null;
TransactionScope currentScope = null;
Transaction contextValue = null;
GetCurrentTransactionAndScope(TxLookup.Default, out current, out currentScope, out contextValue);
if (currentScope != null)
{
if (currentScope.ScopeComplete)
{
throw new InvalidOperationException(SR.TransactionScopeComplete);
}
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "Transaction.get_Current");
}
return current;
}
set
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceBase, "Transaction.set_Current");
}
// Bring your own Transaction(BYOT) is supported only for legacy scenarios.
// This transaction won't be flown across thread continuations.
if (InteropMode(ContextData.TLSCurrentData.CurrentScope) != EnterpriseServicesInteropOption.None)
{
if (etwLog.IsEnabled())
{
etwLog.InvalidOperation("Transaction", "Transaction.set_Current");
}
throw new InvalidOperationException(SR.CannotSetCurrent);
}
// Support only legacy scenarios using TLS.
ContextData.TLSCurrentData.CurrentTransaction = value;
// Clear CallContext data.
CallContextCurrentData.ClearCurrentData(null, false);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceBase, "Transaction.set_Current");
}
}
}
// Storage for the transaction isolation level
internal IsolationLevel _isoLevel;
// Storage for the consistent flag
internal bool _complete = false;
// Record an identifier for this clone
internal int _cloneId;
// Storage for a disposed flag
internal const int _disposedTrueValue = 1;
internal int _disposed = 0;
internal bool Disposed { get { return _disposed == Transaction._disposedTrueValue; } }
internal Guid DistributedTxId
{
get
{
Guid returnValue = Guid.Empty;
if (_internalTransaction != null)
{
returnValue = _internalTransaction.DistributedTxId;
}
return returnValue;
}
}
// Internal synchronization object for transactions. It is not safe to lock on the
// transaction object because it is public and users of the object may lock it for
// other purposes.
internal InternalTransaction _internalTransaction;
// The TransactionTraceIdentifier for the transaction instance.
internal TransactionTraceIdentifier _traceIdentifier;
// Not used by anyone
private Transaction() { }
// Create a transaction with the given settings
//
internal Transaction(IsolationLevel isoLevel, InternalTransaction internalTransaction)
{
TransactionManager.ValidateIsolationLevel(isoLevel);
_isoLevel = isoLevel;
// Never create a transaction with an IsolationLevel of Unspecified.
if (IsolationLevel.Unspecified == _isoLevel)
{
_isoLevel = TransactionManager.DefaultIsolationLevel;
}
if (internalTransaction != null)
{
_internalTransaction = internalTransaction;
_cloneId = Interlocked.Increment(ref _internalTransaction._cloneCount);
}
else
{
// Null is passed from the constructor of a CommittableTransaction. That
// constructor will fill in the traceIdentifier because it has allocated the
// internal transaction.
}
}
internal Transaction(DistributedTransaction distributedTransaction)
{
_isoLevel = distributedTransaction.IsolationLevel;
_internalTransaction = new InternalTransaction(this, distributedTransaction);
_cloneId = Interlocked.Increment(ref _internalTransaction._cloneCount);
}
internal Transaction(IsolationLevel isoLevel, ISimpleTransactionSuperior superior)
{
TransactionManager.ValidateIsolationLevel(isoLevel);
if (superior == null)
{
throw new ArgumentNullException(nameof(superior));
}
_isoLevel = isoLevel;
// Never create a transaction with an IsolationLevel of Unspecified.
if (IsolationLevel.Unspecified == _isoLevel)
{
_isoLevel = TransactionManager.DefaultIsolationLevel;
}
_internalTransaction = new InternalTransaction(this, superior);
// ISimpleTransactionSuperior is defined to also promote to MSDTC.
_internalTransaction.SetPromoterTypeToMSDTC();
_cloneId = 1;
}
#region System.Object Overrides
// Don't use the identifier for the hash code.
//
public override int GetHashCode()
{
return _internalTransaction.TransactionHash;
}
// Don't allow equals to get the identifier
//
public override bool Equals(object obj)
{
Transaction transaction = obj as Transaction;
// If we can't cast the object as a Transaction, it must not be equal
// to this, which is a Transaction.
if (null == transaction)
{
return false;
}
// Check the internal transaction object for equality.
return _internalTransaction.TransactionHash == transaction._internalTransaction.TransactionHash;
}
public static bool operator ==(Transaction x, Transaction y)
{
if (((object)x) != null)
{
return x.Equals(y);
}
return ((object)y) == null;
}
public static bool operator !=(Transaction x, Transaction y)
{
if (((object)x) != null)
{
return !x.Equals(y);
}
return ((object)y) != null;
}
#endregion
public TransactionInformation TransactionInformation
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
TransactionInformation txInfo = _internalTransaction._transactionInformation;
if (txInfo == null)
{
// A race would only result in an extra allocation
txInfo = new TransactionInformation(_internalTransaction);
_internalTransaction._transactionInformation = txInfo;
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return txInfo;
}
}
// Return the Isolation Level for the given transaction
//
public IsolationLevel IsolationLevel
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return _isoLevel;
}
}
/// <summary>
/// Gets the PromoterType value for the transaction.
/// </summary>
/// <value>
/// If the transaction has not yet been promoted and does not yet have a promotable single phase enlistment,
/// this property value will be Guid.Empty.
///
/// If the transaction has been promoted or has a promotable single phase enlistment, this will return the
/// promoter type specified by the transaction promoter.
///
/// If the transaction is, or will be, promoted to MSDTC, the value will be TransactionInterop.PromoterTypeDtc.
/// </value>
public Guid PromoterType
{
get
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
lock (_internalTransaction)
{
return _internalTransaction._promoterType;
}
}
}
/// <summary>
/// Gets the PromotedToken for the transaction.
///
/// If the transaction has not already been promoted, retrieving this value will cause promotion. Before retrieving the
/// PromotedToken, the Transaction.PromoterType value should be checked to see if it is a promoter type (Guid) that the
/// caller understands. If the caller does not recognize the PromoterType value, retrieving the PromotedToken doesn't
/// have much value because the caller doesn't know how to utilize it. But if the PromoterType is recognized, the
/// caller should know how to utilize the PromotedToken to communicate with the promoting distributed transaction
/// coordinator to enlist on the distributed transaction.
///
/// If the value of a transaction's PromoterType is TransactionInterop.PromoterTypeDtc, then that transaction's
/// PromotedToken will be an MSDTC-based TransmitterPropagationToken.
/// </summary>
/// <returns>
/// The byte[] that can be used to enlist with the distributed transaction coordinator used to promote the transaction.
/// The format of the byte[] depends upon the value of Transaction.PromoterType.
/// </returns>
public byte[] GetPromotedToken()
{
// We need to ask the current transaction state for the PromotedToken because depending on the state
// we may need to induce a promotion.
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
// We always make a copy of the promotedToken stored in the internal transaction.
byte[] internalPromotedToken;
lock (_internalTransaction)
{
internalPromotedToken = _internalTransaction.State.PromotedToken(_internalTransaction);
}
byte[] toReturn = new byte[internalPromotedToken.Length];
Array.Copy(internalPromotedToken, toReturn, toReturn.Length);
return toReturn;
}
public Enlistment EnlistDurable(
Guid resourceManagerIdentifier,
IEnlistmentNotification enlistmentNotification,
EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (resourceManagerIdentifier == Guid.Empty)
{
throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
}
if (enlistmentNotification == null)
{
throw new ArgumentNullException(nameof(enlistmentNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.EnlistDurable(_internalTransaction,
resourceManagerIdentifier, enlistmentNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return enlistment;
}
}
// Forward request to the state machine to take the appropriate action.
//
public Enlistment EnlistDurable(
Guid resourceManagerIdentifier,
ISinglePhaseNotification singlePhaseNotification,
EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (resourceManagerIdentifier == Guid.Empty)
{
throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
}
if (singlePhaseNotification == null)
{
throw new ArgumentNullException(nameof(singlePhaseNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.EnlistDurable(_internalTransaction,
resourceManagerIdentifier, singlePhaseNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return enlistment;
}
}
public void Rollback()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
etwLog.TransactionRollback(this, "Transaction");
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
lock (_internalTransaction)
{
Debug.Assert(_internalTransaction.State != null);
_internalTransaction.State.Rollback(_internalTransaction, null);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
public void Rollback(Exception e)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
etwLog.TransactionRollback(this, "Transaction");
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
lock (_internalTransaction)
{
Debug.Assert(_internalTransaction.State != null);
_internalTransaction.State.Rollback(_internalTransaction, e);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
// Forward request to the state machine to take the appropriate action.
//
public Enlistment EnlistVolatile(IEnlistmentNotification enlistmentNotification, EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (enlistmentNotification == null)
{
throw new ArgumentNullException(nameof(enlistmentNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.EnlistVolatile(_internalTransaction,
enlistmentNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return enlistment;
}
}
// Forward request to the state machine to take the appropriate action.
//
public Enlistment EnlistVolatile(ISinglePhaseNotification singlePhaseNotification, EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (singlePhaseNotification == null)
{
throw new ArgumentNullException(nameof(singlePhaseNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.EnlistVolatile(_internalTransaction,
singlePhaseNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return enlistment;
}
}
// Create a clone of the transaction that forwards requests to this object.
//
public Transaction Clone()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
Transaction clone = InternalClone();
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return clone;
}
internal Transaction InternalClone()
{
Transaction clone = new Transaction(_isoLevel, _internalTransaction);
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.TransactionCloneCreate(clone, "Transaction");
}
return clone;
}
// Create a dependent clone of the transaction that forwards requests to this object.
//
public DependentTransaction DependentClone(
DependentCloneOption cloneOption
)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (cloneOption != DependentCloneOption.BlockCommitUntilComplete
&& cloneOption != DependentCloneOption.RollbackIfNotComplete)
{
throw new ArgumentOutOfRangeException(nameof(cloneOption));
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
DependentTransaction clone = new DependentTransaction(
_isoLevel, _internalTransaction, cloneOption == DependentCloneOption.BlockCommitUntilComplete);
if (etwLog.IsEnabled())
{
etwLog.TransactionCloneCreate(clone, "DependentTransaction");
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return clone;
}
internal TransactionTraceIdentifier TransactionTraceId
{
get
{
if (_traceIdentifier == TransactionTraceIdentifier.Empty)
{
lock (_internalTransaction)
{
if (_traceIdentifier == TransactionTraceIdentifier.Empty)
{
TransactionTraceIdentifier temp = new TransactionTraceIdentifier(
_internalTransaction.TransactionTraceId.TransactionIdentifier,
_cloneId);
Interlocked.MemoryBarrier();
_traceIdentifier = temp;
}
}
}
return _traceIdentifier;
}
}
// Forward request to the state machine to take the appropriate action.
//
public event TransactionCompletedEventHandler TransactionCompleted
{
add
{
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
lock (_internalTransaction)
{
// Register for completion with the inner transaction
_internalTransaction.State.AddOutcomeRegistrant(_internalTransaction, value);
}
}
remove
{
lock (_internalTransaction)
{
_internalTransaction._transactionCompletedDelegate = (TransactionCompletedEventHandler)
System.Delegate.Remove(_internalTransaction._transactionCompletedDelegate, value);
}
}
}
public void Dispose()
{
InternalDispose();
}
// Handle Transaction Disposal.
//
internal virtual void InternalDispose()
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Interlocked.Exchange(ref _disposed, Transaction._disposedTrueValue) == Transaction._disposedTrueValue)
{
return;
}
// Attempt to clean up the internal transaction
long remainingITx = Interlocked.Decrement(ref _internalTransaction._cloneCount);
if (remainingITx == 0)
{
_internalTransaction.Dispose();
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
}
// Ask the state machine for serialization info.
//
void ISerializable.GetObjectData(
SerializationInfo serializationInfo,
StreamingContext context)
{
//TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
//if (etwLog.IsEnabled())
//{
// etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
//}
//if (Disposed)
//{
// throw new ObjectDisposedException(nameof(Transaction));
//}
//if (serializationInfo == null)
//{
// throw new ArgumentNullException(nameof(serializationInfo));
//}
//if (_complete)
//{
// throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
//}
//lock (_internalTransaction)
//{
// _internalTransaction.State.GetObjectData(_internalTransaction, serializationInfo, context);
//}
//if (etwLog.IsEnabled())
//{
// etwLog.TransactionSerialized(this, "Transaction");
// etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
//}
throw new PlatformNotSupportedException();
}
/// <summary>
/// Create a promotable single phase enlistment that promotes to MSDTC.
/// </summary>
/// <param name="promotableSinglePhaseNotification">The object that implements the IPromotableSinglePhaseNotification interface.</param>
/// <returns>
/// True if the enlistment is successful.
///
/// False if the transaction already has a durable enlistment or promotable single phase enlistment or
/// if the transaction has already promoted. In this case, the caller will need to enlist in the transaction through other
/// means, such as Transaction.EnlistDurable or retrieve the MSDTC export cookie or propagation token to enlist with MSDTC.
/// </returns>
// We apparently didn't spell Promotable like FXCop thinks it should be spelled.
public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification)
{
return EnlistPromotableSinglePhase(promotableSinglePhaseNotification, TransactionInterop.PromoterTypeDtc);
}
/// <summary>
/// Create a promotable single phase enlistment that promotes to a distributed transaction manager other than MSDTC.
/// </summary>
/// <param name="promotableSinglePhaseNotification">The object that implements the IPromotableSinglePhaseNotification interface.</param>
/// <param name="promoterType">
/// The promoter type Guid that identifies the format of the byte[] that is returned by the ITransactionPromoter.Promote
/// call that is implemented by the IPromotableSinglePhaseNotificationObject, and thus the promoter of the transaction.
/// </param>
/// <returns>
/// True if the enlistment is successful.
///
/// False if the transaction already has a durable enlistment or promotable single phase enlistment or
/// if the transaction has already promoted. In this case, the caller will need to enlist in the transaction through other
/// means.
///
/// If the Transaction.PromoterType matches the promoter type supported by the caller, then the
/// Transaction.PromotedToken can be retrieved and used to enlist directly with the identified distributed transaction manager.
///
/// How the enlistment is created with the distributed transaction manager identified by the Transaction.PromoterType
/// is defined by that distributed transaction manager.
/// </returns>
public bool EnlistPromotableSinglePhase(IPromotableSinglePhaseNotification promotableSinglePhaseNotification, Guid promoterType)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (promotableSinglePhaseNotification == null)
{
throw new ArgumentNullException(nameof(promotableSinglePhaseNotification));
}
if (promoterType == Guid.Empty)
{
throw new ArgumentException(SR.PromoterTypeInvalid, nameof(promoterType));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
bool succeeded = false;
lock (_internalTransaction)
{
succeeded = _internalTransaction.State.EnlistPromotableSinglePhase(_internalTransaction, promotableSinglePhaseNotification, this, promoterType);
}
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return succeeded;
}
public Enlistment PromoteAndEnlistDurable(Guid resourceManagerIdentifier,
IPromotableSinglePhaseNotification promotableNotification,
ISinglePhaseNotification enlistmentNotification,
EnlistmentOptions enlistmentOptions)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceDistributed, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (resourceManagerIdentifier == Guid.Empty)
{
throw new ArgumentException(SR.BadResourceManagerId, nameof(resourceManagerIdentifier));
}
if (promotableNotification == null)
{
throw new ArgumentNullException(nameof(promotableNotification));
}
if (enlistmentNotification == null)
{
throw new ArgumentNullException(nameof(enlistmentNotification));
}
if (enlistmentOptions != EnlistmentOptions.None && enlistmentOptions != EnlistmentOptions.EnlistDuringPrepareRequired)
{
throw new ArgumentOutOfRangeException(nameof(enlistmentOptions));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
Enlistment enlistment = _internalTransaction.State.PromoteAndEnlistDurable(_internalTransaction,
resourceManagerIdentifier, promotableNotification, enlistmentNotification, enlistmentOptions, this);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceDistributed, this);
}
return enlistment;
}
}
public void SetDistributedTransactionIdentifier(IPromotableSinglePhaseNotification promotableNotification,
Guid distributedTransactionIdentifier)
{
TransactionsEtwProvider etwLog = TransactionsEtwProvider.Log;
if (etwLog.IsEnabled())
{
etwLog.MethodEnter(TraceSourceType.TraceSourceLtm, this);
}
if (Disposed)
{
throw new ObjectDisposedException(nameof(Transaction));
}
if (promotableNotification == null)
{
throw new ArgumentNullException(nameof(promotableNotification));
}
if (distributedTransactionIdentifier == Guid.Empty)
{
throw new ArgumentException(null, nameof(distributedTransactionIdentifier));
}
if (_complete)
{
throw TransactionException.CreateTransactionCompletedException(DistributedTxId);
}
lock (_internalTransaction)
{
_internalTransaction.State.SetDistributedTransactionId(_internalTransaction,
promotableNotification,
distributedTransactionIdentifier);
if (etwLog.IsEnabled())
{
etwLog.MethodExit(TraceSourceType.TraceSourceLtm, this);
}
return;
}
}
internal DistributedTransaction Promote()
{
lock (_internalTransaction)
{
// This method is only called when we expect to be promoting to MSDTC.
_internalTransaction.ThrowIfPromoterTypeIsNotMSDTC();
_internalTransaction.State.Promote(_internalTransaction);
return _internalTransaction.PromotedTransaction;
}
}
}
//
// The following code & data is related to management of Transaction.Current
//
internal enum DefaultComContextState
{
Unknown = 0,
Unavailable = -1,
Available = 1
}
//
// The TxLookup enum is used internally to detect where the ambient context needs to be stored or looked up.
// Default - Used internally when looking up Transaction.Current.
// DefaultCallContext - Used when TransactionScope with async flow option is enabled. Internally we will use CallContext to store the ambient transaction.
// Default TLS - Used for legacy/syncronous TransactionScope. Internally we will use TLS to store the ambient transaction.
//
internal enum TxLookup
{
Default,
DefaultCallContext,
DefaultTLS,
}
//
// CallContextCurrentData holds the ambient transaction and uses CallContext and ConditionalWeakTable to track the ambient transaction.
// For async flow scenarios, we should not allow flowing of transaction across app domains. To prevent transaction from flowing across
// AppDomain/Remoting boundaries, we are using ConditionalWeakTable to hold the actual ambient transaction and store only a object reference
// in CallContext. When TransactionScope is used to invoke a call across AppDomain/Remoting boundaries, only the object reference will be sent
// across and not the actual ambient transaction which is stashed away in the ConditionalWeakTable.
//
internal static class CallContextCurrentData
{
private static AsyncLocal<ContextKey> s_currentTransaction = new AsyncLocal<ContextKey>();
// ConditionalWeakTable is used to automatically remove the entries that are no longer referenced. This will help prevent leaks in async nested TransactionScope
// usage and when child nested scopes are not syncronized properly.
private static readonly ConditionalWeakTable<ContextKey, ContextData> s_contextDataTable = new ConditionalWeakTable<ContextKey, ContextData>();
//
// Set CallContext data with the given contextKey.
// return the ContextData if already present in contextDataTable, otherwise return the default value.
//
public static ContextData CreateOrGetCurrentData(ContextKey contextKey)
{
s_currentTransaction.Value = contextKey;
return s_contextDataTable.GetValue(contextKey, (env) => new ContextData(true));
}
public static void ClearCurrentData(ContextKey contextKey, bool removeContextData)
{
// Get the current ambient CallContext.
ContextKey key = s_currentTransaction.Value;
if (contextKey != null || key != null)
{
// removeContextData flag is used for perf optimization to avoid removing from the table in certain nested TransactionScope usage.
if (removeContextData)
{
// if context key is passed in remove that from the contextDataTable, otherwise remove the default context key.
s_contextDataTable.Remove(contextKey ?? key);
}
if (key != null)
{
s_currentTransaction.Value = null;
}
}
}
public static bool TryGetCurrentData(out ContextData currentData)
{
currentData = null;
ContextKey contextKey = s_currentTransaction.Value;
if (contextKey == null)
{
return false;
}
else
{
return s_contextDataTable.TryGetValue(contextKey, out currentData);
}
}
}
//
// MarshalByRefObject is needed for cross AppDomain scenarios where just using object will end up with a different reference when call is made across serialization boundary.
//
internal class ContextKey // : MarshalByRefObject
{
}
internal class ContextData
{
internal TransactionScope CurrentScope;
internal Transaction CurrentTransaction;
internal DefaultComContextState DefaultComContextState;
internal WeakReference WeakDefaultComContext;
internal bool _asyncFlow;
[ThreadStatic]
private static ContextData t_staticData;
internal ContextData(bool asyncFlow)
{
_asyncFlow = asyncFlow;
}
internal static ContextData TLSCurrentData
{
get
{
ContextData data = t_staticData;
if (data == null)
{
data = new ContextData(false);
t_staticData = data;
}
return data;
}
set
{
if (value == null && t_staticData != null)
{
// set each property to null to retain one TLS ContextData copy.
t_staticData.CurrentScope = null;
t_staticData.CurrentTransaction = null;
t_staticData.DefaultComContextState = DefaultComContextState.Unknown;
t_staticData.WeakDefaultComContext = null;
}
else
{
t_staticData = value;
}
}
}
internal static ContextData LookupContextData(TxLookup defaultLookup)
{
ContextData currentData = null;
if (CallContextCurrentData.TryGetCurrentData(out currentData))
{
if (currentData.CurrentScope == null && currentData.CurrentTransaction == null && defaultLookup != TxLookup.DefaultCallContext)
{
// Clear Call Context Data
CallContextCurrentData.ClearCurrentData(null, true);
return TLSCurrentData;
}
return currentData;
}
else
{
return TLSCurrentData;
}
}
}
}
| |
#region Copyright (c) 2003, newtelligence AG. All rights reserved.
/*
// Copyright (c) 2003, newtelligence AG. (http://www.newtelligence.com)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are permitted
// provided that the following conditions are met:
//
// (1) Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// (2) Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// (3) Neither the name of the newtelligence AG nor the names of its contributors may be used
// to endorse or promote products derived from this software without specific prior
// written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
// IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
// OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -------------------------------------------------------------------------
//
//
*/
#endregion
using System;
using System.Web;
using System.Web.UI;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Web.UI.WebControls;
using System.IO;
namespace newtelligence.DasBlog.Web.Core.WebControls
{
public enum ShadowImageType
{
TopLeft, Top, TopRight,
Right,BottomRight,Bottom,
BottomLeft, Left, Blank
}
public class ShadowBoxDesigner : System.Web.UI.Design.ContainerControlDesigner
{
}
public class DrawingHelpers
{
private static Blend shadowBlendScaleLinear;
private static Blend shadowBlendScaleRadial;
static DrawingHelpers()
{
shadowBlendScaleLinear = new Blend(3);
shadowBlendScaleLinear.Positions[0]=0.0f;
shadowBlendScaleLinear.Factors[0]=0.0f;
shadowBlendScaleLinear.Positions[1]=0.50f;
shadowBlendScaleLinear.Factors[1]=0.80f;
shadowBlendScaleLinear.Positions[2]=1f;
shadowBlendScaleLinear.Factors[2]=1f;
shadowBlendScaleRadial = new Blend(3);
shadowBlendScaleRadial.Positions[0]=0.0f;
shadowBlendScaleRadial.Factors[0]=0.0f;
shadowBlendScaleRadial.Positions[1]=0.50f;
shadowBlendScaleRadial.Factors[1]=0.20f;
shadowBlendScaleRadial.Positions[2]=1f;
shadowBlendScaleRadial.Factors[2]=1f;
}
public static byte[] CreateShadowImage(
ShadowImageType imageType,
int Width,
int Height,
Color ShadowColor,
Color BackColor,
ImageFormat Format)
{
MemoryStream memStream = new MemoryStream();
Bitmap bmpPaint = new Bitmap(Width,Height);
Graphics grph = Graphics.FromImage(bmpPaint);
if ( imageType == ShadowImageType.Blank )
{
SolidBrush brush;
brush = new SolidBrush(BackColor);
grph.FillRectangle(brush,0,0,Width,Height);
}
else if ( imageType == ShadowImageType.Top || imageType == ShadowImageType.Bottom ||
imageType == ShadowImageType.Left || imageType == ShadowImageType.Right )
{
int angle=0;
switch( imageType )
{
case ShadowImageType.Top:
angle = 270; break;
case ShadowImageType.Right:
angle = 0; break;
case ShadowImageType.Bottom:
angle = 90; break;
case ShadowImageType.Left:
angle = 180; break;
}
LinearGradientBrush brush;
brush = new LinearGradientBrush(
new Rectangle(0,0,Width,Height),
ShadowColor,
BackColor,
angle,true);
brush.Blend = shadowBlendScaleLinear;
grph.FillRectangle(brush,0,0,Width,Height);
}
else
{
GraphicsPath path = new GraphicsPath();
path.AddEllipse(0, 0, Width*2,Height*2);
PathGradientBrush brush = new PathGradientBrush(path);
brush.CenterColor = ShadowColor;
Color[] colors = {BackColor};
brush.SurroundColors = colors;
if ( imageType == ShadowImageType.BottomRight )
{
brush.TranslateTransform(-Width,-Height);
}
else if ( imageType == ShadowImageType.TopRight )
{
brush.TranslateTransform(-Width,0);
}
else if ( imageType == ShadowImageType.BottomLeft )
{
brush.TranslateTransform(0,-Height);
}
brush.CenterPoint=new PointF(Width,Height);
brush.Blend = shadowBlendScaleRadial;
grph.FillRectangle(new SolidBrush(BackColor),0, 0, Width, Height);
grph.FillRectangle(brush, 0, 0, Width, Height);
}
bmpPaint.Save(memStream,Format);
return memStream.GetBuffer();
}
}
/// <summary>
/// The ShadowBox is an ASP.NET WebControl that dynamically draws a drop
/// shadow.
/// </summary>
[ToolboxBitmap(typeof(ShadowBox),"ShadowBoxToolbarItem.bmp")]
[Designer(typeof(ShadowBoxDesigner))]
[ToolboxData("<{0}:ShadowBox runat=server>Shadow Box</{0}:ShadowBox>")]
[ParseChildren(false)]
[PersistChildren(true)]
public class ShadowBox : System.Web.UI.WebControls.WebControl,
IRenderControlImage
{
private const string imgTopLeft="tl";
private const string imgTop="tp";
private const string imgTopRight="tr";
private const string imgRight="rg";
private const string imgBottomRight="br";
private const string imgBottom="bt";
private const string imgBottomLeft="bl";
private const string imgLeft="lf";
private const string imgBlank="bk";
private int shadowDepth;
private Color shadowColor;
public ShadowBox()
{
shadowDepth = 6;
shadowColor = Color.Gray;
}
private void RenderImage( HttpResponse Response, string ImageVariant, int Width, int Height, Color ShadowColor, Color BackgroundColor )
{
ShadowImageType imageType;
switch ( ImageVariant )
{
case imgTopLeft:
imageType=ShadowImageType.TopLeft;break;
case imgTop:
imageType=ShadowImageType.Top;break;
case imgTopRight:
imageType=ShadowImageType.TopRight;break;
case imgRight:
imageType=ShadowImageType.Right;break;
case imgBottomRight:
imageType=ShadowImageType.BottomRight;break;
case imgBottom:
imageType=ShadowImageType.Bottom;break;
case imgBottomLeft:
imageType=ShadowImageType.BottomLeft;break;
case imgLeft:
imageType=ShadowImageType.Left;break;
case imgBlank:
default:
imageType=ShadowImageType.Blank;break;
}
byte[] image = DrawingHelpers.CreateShadowImage(
imageType,
Width,
Height,
ShadowColor,
BackgroundColor,
ImageFormat.Png );
Response.ContentType="image/png";
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.OutputStream.Write(image,0,image.Length);
}
void IRenderControlImage.Render( HttpContext Context, string[] Args )
{
if ( Args.Length >= 5 )
{
string imageVariant = Args[0];
int width=Convert.ToInt32(Args[1],10);
int height=Convert.ToInt32(Args[2],10);
Color shadowColor = Color.FromArgb(Convert.ToInt32(Args[3],16));
Color backColor = Color.FromArgb(Convert.ToInt32(Args[4],16));
RenderImage( Context.Response, imageVariant, width, height, shadowColor, backColor );
}
}
[Browsable(true),Bindable(true)]
public int ShadowDepth
{
get
{
return shadowDepth;
}
set
{
shadowDepth = value;
}
}
[Browsable(true),Bindable(true),
Editor("System.Drawing.Design.ColorEditor",
"System.Drawing.Design.UITypeEditor")]
public Color ShadowColor
{
get
{
return shadowColor;
}
set
{
shadowColor = value;
}
}
public string GetImageUrl( string imageName )
{
Color effectiveBackColor = BackColor;
if ( effectiveBackColor.A == 0 )
{
Control ctrl = this.Parent;
while ( ctrl != null )
{
if ( ctrl is WebControl )
{
Color clr = ((WebControl)ctrl).BackColor;
if ( clr.A != 0 )
{
effectiveBackColor = clr;
break;
}
}
ctrl = ctrl.Parent;
}
if ( effectiveBackColor.A == 0)
{
effectiveBackColor = Color.White;
}
}
else
{
effectiveBackColor = this.BackColor;
}
return ControlImageModule.GetImageHRef(
Context,GetType(),
new String[]{
imageName,
shadowDepth.ToString(),
shadowDepth.ToString(),
shadowColor.ToArgb().ToString("x"),
effectiveBackColor.ToArgb().ToString("x"),
}
);
}
/// <summary>
/// Render this control to the output parameter specified.
/// </summary>
/// <param name="output"> The HTML writer to write out to </param>
protected override void Render(HtmlTextWriter output)
{
StringWriter baseStream;
HtmlTextWriter htmlStream;
Table tbl;
TableRow tr;
TableCell td;
System.Web.UI.WebControls.Image img;
tbl = new Table();
tbl.ID=this.ID;
tbl.BackColor=this.BackColor;
tbl.Width = this.Width;
tbl.Height=this.Height;
tbl.CssClass=this.CssClass;
tbl.BorderWidth=Unit.Pixel(0);
tbl.CellPadding=0;
tbl.CellSpacing=0;
foreach( string key in this.Style.Keys )
{
tbl.Style.Add( key, this.Style[key]);
}
tbl.Rows.Add(tr = new TableRow());
tr.Cells.Add(td = new TableCell());
td.BorderWidth=this.BorderWidth;
td.BorderStyle=this.BorderStyle;
td.BorderColor=this.BorderColor;
baseStream = new StringWriter();
htmlStream = new HtmlTextWriter(baseStream);
RenderChildren(htmlStream);
td.Controls.Add(new LiteralControl(baseStream.ToString()));
tr.Cells.Add(td = new TableCell());
td.VerticalAlign=VerticalAlign.Top;
td.Width=Unit.Pixel(shadowDepth);
td.Style.Add("background","url('"+GetImageUrl(imgRight)+"')");
td.Controls.Add(img = new System.Web.UI.WebControls.Image() );
img.Width=Unit.Pixel(shadowDepth);
img.Height=Unit.Pixel(shadowDepth);
img.ImageUrl=GetImageUrl(imgBlank);
img.AlternateText = "[ShadowBox]";
td.Controls.Add(new LiteralControl("<br />"));
td.Controls.Add(img = new System.Web.UI.WebControls.Image() );
img.Width=Unit.Pixel(shadowDepth);
img.Height=Unit.Pixel(shadowDepth);
img.ImageUrl = GetImageUrl(imgTopRight);
img.AlternateText = "[ShadowBox]";
tbl.Rows.Add(tr = new TableRow());
tr.Cells.Add(td = new TableCell());
td.HorizontalAlign=HorizontalAlign.Left;
td.Height=Unit.Pixel(shadowDepth);
td.Style.Add("background","url('"+GetImageUrl(imgBottom)+"')");
td.Controls.Add(img = new System.Web.UI.WebControls.Image() );
img.Width=Unit.Pixel(shadowDepth);
img.Height=Unit.Pixel(shadowDepth);
img.ImageUrl = GetImageUrl(imgBlank);
img.AlternateText = "[ShadowBox]";
td.Controls.Add(img = new System.Web.UI.WebControls.Image() );
img.Width=Unit.Pixel(shadowDepth);
img.Height=Unit.Pixel(shadowDepth);
img.ImageUrl = GetImageUrl(imgBottomLeft);
img.AlternateText = "[ShadowBox]";
tr.Cells.Add(td = new TableCell());
td.Width = Unit.Pixel(shadowDepth);
td.Height = Unit.Pixel(shadowDepth);
td.Controls.Add(img = new System.Web.UI.WebControls.Image() );
img.Width=Unit.Pixel(shadowDepth);
img.Height=Unit.Pixel(shadowDepth);
img.ImageUrl = GetImageUrl(imgBottomRight);
img.AlternateText = "[ShadowBox]";
tbl.RenderControl(output);
}
}
}
| |
/*
* Console.cs - Implementation of the "System.Console" class.
*
* Copyright (C) 2001, 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System
{
using System.IO;
using System.Text;
using System.Private;
using Platform;
public sealed class Console
{
#if !CONFIG_SMALL_CONSOLE
// Cached copies of the stdin, stdout, and stderr streams.
private static TextReader stdin = null;
private static TextWriter stdout = null;
private static TextWriter stderr = null;
// This class cannot be instantiated.
private Console() {}
// Open the standard input stream.
public static Stream OpenStandardInput()
{
return new StdStream(0);
}
public static Stream OpenStandardInput(int bufferSize)
{
return new StdStream(0);
}
// Open the standard output stream.
public static Stream OpenStandardOutput()
{
return new StdStream(1);
}
public static Stream OpenStandardOutput(int bufferSize)
{
return new StdStream(1);
}
// Open the standard error stream.
public static Stream OpenStandardError()
{
return new StdStream(2);
}
public static Stream OpenStandardError(int bufferSize)
{
return new StdStream(2);
}
// Get the standard input stream.
public static TextReader In
{
get
{
lock(typeof(Console))
{
if(stdin != null)
{
return stdin;
}
else
{
stdin = new StdReader(0);
return stdin;
}
}
}
}
// Get the standard output stream.
public static TextWriter Out
{
get
{
lock(typeof(Console))
{
if(stdout != null)
{
return stdout;
}
else
{
Encoding encoding = Encoding.Default;
if(encoding is UTF8Encoding)
{
// Disable the preamble if UTF-8.
encoding = new UTF8Encoding();
}
StreamWriter writer = new StreamWriter
(new StdStream(1), encoding);
writer.AutoFlush = true;
SetOut(writer);
return stdout;
}
}
}
}
// Get the standard error stream.
public static TextWriter Error
{
get
{
lock(typeof(Console))
{
if(stderr != null)
{
return stderr;
}
else
{
Encoding encoding = Encoding.Default;
if(encoding is UTF8Encoding)
{
// Disable the preamble if UTF-8.
encoding = new UTF8Encoding();
}
StreamWriter writer = new StreamWriter
(new StdStream(2), encoding);
writer.AutoFlush = true;
SetError(writer);
return stderr;
}
}
}
}
#if CONFIG_FRAMEWORK_2_0
// Get or set the input stream's encoding.
[TODO]
public static Encoding InputEncoding
{
get
{
// TODO
return Encoding.Default;
}
set
{
// TODO
}
}
// Get or set the output stream's encoding.
[TODO]
public static Encoding OutputEncoding
{
get
{
// TODO
return Encoding.Default;
}
set
{
// TODO
}
}
#endif
// Set the standard input stream.
public static void SetIn(TextReader newIn)
{
if(newIn == null)
{
throw new ArgumentNullException("newIn");
}
stdin = TextReader.Synchronized(newIn);
}
// Set the standard output stream.
public static void SetOut(TextWriter newOut)
{
if(newOut == null)
{
throw new ArgumentNullException("newOut");
}
stdout = TextWriter.Synchronized(newOut);
}
// Set the standard error stream.
public static void SetError(TextWriter newError)
{
if(newError == null)
{
throw new ArgumentNullException("newError");
}
stderr = TextWriter.Synchronized(newError);
}
// Read a character from the standard input stream.
public static int Read()
{
NormalMode();
return In.Read();
}
// Read a line from the standard input stream.
public static String ReadLine()
{
NormalMode();
return In.ReadLine();
}
// Write a formatted string to standard output.
public static void Write(String format, Object arg0)
{
Out.Write(format, arg0);
}
public static void Write(String format, Object arg0, Object arg1)
{
Out.Write(format, arg0, arg1);
}
public static void Write(String format, Object arg0, Object arg1,
Object arg2)
{
Out.Write(format, arg0, arg1, arg2);
}
public static void Write(String format, params Object[] args)
{
Out.Write(format, args);
}
#if !ECMA_COMPAT
[CLSCompliant(false)]
public static void Write(String format, Object arg0, Object arg1,
Object arg2, Object arg3, __arglist)
{
ArgIterator iter = new ArgIterator(__arglist);
Object[] list = new Object [4 + iter.GetRemainingCount()];
list[0] = arg0;
list[1] = arg1;
list[2] = arg2;
list[3] = arg3;
int posn = 4;
while(posn < list.Length)
{
list[posn] = TypedReference.ToObject(iter.GetNextArg());
++posn;
}
Out.Write(format, list);
}
#endif // !ECMA_COMPAT
// Write primitive values to standard output.
public static void Write(bool value)
{
Out.Write(value);
}
public static void Write(char value)
{
Out.Write(value);
}
public static void Write(char[] value)
{
Out.Write(value);
}
public static void Write(char[] value, int index, int count)
{
Out.Write(value, index, count);
}
#if CONFIG_EXTENDED_NUMERICS
public static void Write(double value)
{
Out.Write(value);
}
public static void Write(Decimal value)
{
Out.Write(value);
}
public static void Write(float value)
{
Out.Write(value);
}
#endif
public static void Write(int value)
{
Out.Write(value);
}
[CLSCompliant(false)]
public static void Write(uint value)
{
Out.Write(value);
}
public static void Write(long value)
{
Out.Write(value);
}
[CLSCompliant(false)]
public static void Write(ulong value)
{
Out.Write(value);
}
public static void Write(Object value)
{
Out.Write(value);
}
public static void Write(String value)
{
Out.Write(value);
}
// Write a newline to standard output.
public static void WriteLine()
{
Out.WriteLine();
}
// Write a formatted string to standard output followed by a newline.
public static void WriteLine(String format, Object arg0)
{
Out.WriteLine(format, arg0);
}
public static void WriteLine(String format, Object arg0, Object arg1)
{
Out.WriteLine(format, arg0, arg1);
}
public static void WriteLine(String format, Object arg0, Object arg1,
Object arg2)
{
Out.WriteLine(format, arg0, arg1, arg2);
}
public static void WriteLine(String format, params Object[] args)
{
Out.WriteLine(format, args);
}
#if !ECMA_COMPAT
[CLSCompliant(false)]
public static void WriteLine(String format, Object arg0, Object arg1,
Object arg2, Object arg3, __arglist)
{
ArgIterator iter = new ArgIterator(__arglist);
Object[] list = new Object [4 + iter.GetRemainingCount()];
list[0] = arg0;
list[1] = arg1;
list[2] = arg2;
list[3] = arg3;
int posn = 4;
while(posn < list.Length)
{
list[posn] = TypedReference.ToObject(iter.GetNextArg());
++posn;
}
Out.WriteLine(format, list);
}
#endif // !ECMA_COMPAT
// Write primitive values to standard output followed by a newline.
public static void WriteLine(bool value)
{
Out.WriteLine(value);
}
public static void WriteLine(char value)
{
Out.WriteLine(value);
}
public static void WriteLine(char[] value)
{
Out.WriteLine(value);
}
public static void WriteLine(char[] value, int index, int count)
{
Out.WriteLine(value, index, count);
}
#if CONFIG_EXTENDED_NUMERICS
public static void WriteLine(double value)
{
Out.WriteLine(value);
}
public static void WriteLine(Decimal value)
{
Out.WriteLine(value);
}
public static void WriteLine(float value)
{
Out.WriteLine(value);
}
#endif
public static void WriteLine(int value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
public static void WriteLine(uint value)
{
Out.WriteLine(value);
}
public static void WriteLine(long value)
{
Out.WriteLine(value);
}
[CLSCompliant(false)]
public static void WriteLine(ulong value)
{
Out.WriteLine(value);
}
public static void WriteLine(Object value)
{
Out.WriteLine(value);
}
public static void WriteLine(String value)
{
Out.WriteLine(value);
}
#else // CONFIG_SMALL_CONSOLE
// This class cannot be instantiated.
private Console() {}
// Read a line from the standard input stream.
public static String ReadLine()
{
StringBuilder builder = new StringBuilder();
int ch;
NormalMode();
while((ch = Stdio.StdRead(0)) != -1 && ch != '\n')
{
if(ch != '\r')
{
builder.Append((char)ch);
}
}
if(ch == -1 && builder.Length == 0)
{
return null;
}
else
{
return builder.ToString();
}
}
// Write a formatted string to standard output.
public static void Write(String format, Object arg0)
{
Stdio.StdWrite(1, String.Format(format, arg0));
}
public static void Write(String format, Object arg0, Object arg1)
{
Stdio.StdWrite(1, String.Format(format, arg0, arg1));
}
public static void Write(String format, Object arg0, Object arg1,
Object arg2)
{
Stdio.StdWrite(1, String.Format(format, arg0, arg1, arg2));
}
public static void Write(String format, params Object[] args)
{
Stdio.StdWrite(1, String.Format(format, args));
}
// Write primitive values to standard output.
public static void Write(char value)
{
Stdio.StdWrite(1, value);
}
public static void Write(char[] value)
{
if(value == null)
{
throw new ArgumentNullException("null");
}
foreach(char ch in value)
{
Stdio.StdWrite(1, ch);
}
}
public static void Write(char[] value, int index, int count)
{
if(value == null)
{
throw new ArgumentNullException("null");
}
if(index < 0 || index > value.Length)
{
throw new ArgumentOutOfRangeException
("index", _("ArgRange_StringIndex"));
}
if(count < 0 || count > (value.Length - index))
{
throw new ArgumentOutOfRangeException
("count", _("ArgRange_StringRange"));
}
while(count > 0)
{
Stdio.StdWrite(1, value[index]);
++index;
--count;
}
}
public static void Write(int value)
{
Stdio.StdWrite(1, value.ToString());
}
public static void Write(Object value)
{
if(value != null)
{
Stdio.StdWrite(1, value.ToString());
}
}
public static void Write(String value)
{
Stdio.StdWrite(1, value);
}
// Write a newline to standard output.
public static void WriteLine()
{
Stdio.StdWrite(1, Environment.NewLine);
}
// Write a formatted string to standard output followed by a newline.
public static void WriteLine(String format, Object arg0)
{
Write(format, arg0);
WriteLine();
}
public static void WriteLine(String format, Object arg0, Object arg1)
{
Write(format, arg0, arg1);
WriteLine();
}
public static void WriteLine(String format, Object arg0, Object arg1,
Object arg2)
{
Write(format, arg0, arg1, arg2);
WriteLine();
}
public static void WriteLine(String format, params Object[] args)
{
Write(format, args);
WriteLine();
}
// Write primitive values to standard output followed by a newline.
public static void WriteLine(char value)
{
Stdio.StdWrite(1, value);
WriteLine();
}
public static void WriteLine(char[] value)
{
Write(value);
WriteLine();
}
public static void WriteLine(int value)
{
Write(value);
WriteLine();
}
public static void WriteLine(Object value)
{
Write(value);
WriteLine();
}
public static void WriteLine(String value)
{
Stdio.StdWrite(1, value);
WriteLine();
}
#endif // CONFIG_SMALL_CONSOLE
#if CONFIG_EXTENDED_CONSOLE
// Global state for the extended console.
private static String title = String.Empty;
private static bool specialMode = false;
private static bool treatControlCAsInput = false;
private static Object readLock = new Object();
private static int defaultAttrs = 0x07;
private static int currentAttrs = 0x07;
// Enable the "normal" input mode on the console.
private static void NormalMode()
{
lock(typeof(Console))
{
if(specialMode)
{
specialMode = false;
Stdio.SetConsoleMode(Stdio.MODE_NORMAL);
}
}
}
// Enable the "special" character-at-a-time input mode on the console.
private static void SpecialMode()
{
lock(typeof(Console))
{
if(!specialMode)
{
specialMode = true;
if(treatControlCAsInput)
{
Stdio.SetConsoleMode(Stdio.MODE_RAW);
}
else
{
Stdio.SetConsoleMode(Stdio.MODE_CBREAK);
}
defaultAttrs = Stdio.GetTextAttributes();
currentAttrs = defaultAttrs;
}
}
}
// Output a beep on the console.
public static void Beep()
{
Beep(800, 200);
}
public static void Beep(int frequency, int duration)
{
if(frequency < 37 || frequency > 32767)
{
throw new ArgumentOutOfRangeException
("frequency", _("ArgRange_BeepFrequency"));
}
if(duration <= 0)
{
throw new ArgumentOutOfRangeException
("duration", _("ArgRange_PositiveNonZero"));
}
lock(typeof(Console))
{
SpecialMode();
Stdio.Beep(frequency, duration);
}
}
// Clear the display to the current foreground and background color.
// If "Clear" is the first extended console method called, then it
// indicates that the terminal should enter the "alternative" mode
// used for programs like "vi". Returning to the normal mode will
// restore what used to be displayed previously.
public static void Clear()
{
lock(typeof(Console))
{
if(!specialMode)
{
specialMode = true;
if(treatControlCAsInput)
{
Stdio.SetConsoleMode(Stdio.MODE_RAW_ALT);
}
else
{
Stdio.SetConsoleMode(Stdio.MODE_CBREAK_ALT);
}
defaultAttrs = Stdio.GetTextAttributes();
currentAttrs = defaultAttrs;
}
Stdio.Clear();
}
}
// Move an area of the screen buffer to a new location.
public static void MoveBufferArea(int sourceLeft, int sourceTop,
int sourceWidth, int sourceHeight,
int targetLeft, int targetTop)
{
MoveBufferArea(sourceLeft, sourceTop,
sourceWidth, sourceHeight,
targetLeft, targetTop, ' ',
ForegroundColor, BackgroundColor);
}
public static void MoveBufferArea(int sourceLeft, int sourceTop,
int sourceWidth, int sourceHeight,
int targetLeft, int targetTop,
char sourceChar,
ConsoleColor sourceForeColor,
ConsoleColor sourceBackColor)
{
lock(typeof(Console))
{
SpecialMode();
int width, height;
Stdio.GetBufferSize(out width, out height);
if(sourceLeft < 0 || sourceLeft >= width)
{
throw new ArgumentOutOfRangeException
("sourceLeft", _("ArgRange_XCoordinate"));
}
if(sourceTop < 0 || sourceTop >= height)
{
throw new ArgumentOutOfRangeException
("sourceTop", _("ArgRange_YCoordinate"));
}
if(sourceWidth < 0 || (sourceLeft + sourceWidth) > width)
{
throw new ArgumentOutOfRangeException
("sourceWidth", _("ArgRange_Width"));
}
if(sourceHeight < 0 || (sourceTop + sourceHeight) > height)
{
throw new ArgumentOutOfRangeException
("sourceHeight", _("ArgRange_Height"));
}
if(targetLeft < 0 || targetLeft >= width)
{
throw new ArgumentOutOfRangeException
("targetLeft", _("ArgRange_XCoordinate"));
}
if(targetTop < 0 || targetTop >= height)
{
throw new ArgumentOutOfRangeException
("targetTop", _("ArgRange_YCoordinate"));
}
if((((int)sourceForeColor) & ~0x0F) != 0)
{
throw new ArgumentException
(_("Arg_InvalidColor"), "sourceForeColor");
}
if((((int)sourceBackColor) & ~0x0F) != 0)
{
throw new ArgumentException
(_("Arg_InvalidColor"), "sourceBackColor");
}
Stdio.MoveBufferArea(sourceLeft, sourceTop,
sourceWidth, sourceHeight,
targetLeft, targetTop,
sourceChar,
((int)(sourceForeColor)) |
(((int)(sourceBackColor)) << 4));
}
}
// Read a key from the console. If "intercept" is "false",
// then the key is echoed to the console.
public static ConsoleKeyInfo ReadKey()
{
return ReadKey(false);
}
public static ConsoleKeyInfo ReadKey(bool intercept)
{
lock(typeof(Console))
{
SpecialMode();
}
lock(readLock)
{
char ch;
int key, modifiers;
for(;;)
{
Stdio.ReadKey(out ch, out key, out modifiers);
if(key == 0x1202) // Interrupt
{
HandleCancel(ConsoleSpecialKey.ControlC);
continue;
}
else if(key == 0x1203) // CtrlBreak
{
HandleCancel(ConsoleSpecialKey.ControlBreak);
continue;
}
if(!intercept && ch != '\0')
{
Stdio.StdWrite(1, ch);
}
return new ConsoleKeyInfo
(ch, (ConsoleKey)key, (ConsoleModifiers)modifiers);
}
}
}
// Reset the foreground and background colors to the defaults.
public static void ResetColor()
{
lock(typeof(Console))
{
SpecialMode();
currentAttrs = defaultAttrs;
Stdio.SetTextAttributes(defaultAttrs);
}
}
// Set the buffer size.
public static void SetBufferSize(int width, int height)
{
lock(typeof(Console))
{
SpecialMode();
int wleft, wtop, wwidth, wheight;
Stdio.GetWindowSize
(out wleft, out wtop, out wwidth, out wheight);
if(width <= 0 || width > 32767 || width < (wleft + wwidth))
{
throw new ArgumentOutOfRangeException
("width", _("ArgRange_Width"));
}
if(height <= 0 || height > 32767 ||
height < (wtop + wheight))
{
throw new ArgumentOutOfRangeException
("height", _("ArgRange_Height"));
}
Stdio.SetBufferSize(width, height);
}
}
// Set the cursor position.
public static void SetCursorPosition(int left, int top)
{
lock(typeof(Console))
{
SpecialMode();
int width, height;
Stdio.GetBufferSize(out width, out height);
if(left < 0 || left >= width)
{
throw new ArgumentOutOfRangeException
("left", _("ArgRange_XCoordinate"));
}
if(top < 0 || top >= height)
{
throw new ArgumentOutOfRangeException
("top", _("ArgRange_YCoordinate"));
}
Stdio.SetCursorPosition(left, top);
}
}
// Set the window position.
public static void SetWindowPosition(int left, int top)
{
lock(typeof(Console))
{
SpecialMode();
int width, height;
Stdio.GetBufferSize(out width, out height);
int wleft, wtop, wwidth, wheight;
Stdio.GetWindowSize
(out wleft, out wtop, out wwidth, out wheight);
if(left < 0 || (left + wwidth) > width)
{
throw new ArgumentOutOfRangeException
("left", _("ArgRange_XCoordinate"));
}
if(top < 0 || (left + wheight) > height)
{
throw new ArgumentOutOfRangeException
("left", _("ArgRange_YCoordinate"));
}
Stdio.SetWindowSize(left, top, wwidth, wheight);
}
}
// Set the window size.
public static void SetWindowSize(int width, int height)
{
lock(typeof(Console))
{
SpecialMode();
int bwidth, bheight;
Stdio.GetBufferSize(out bwidth, out bheight);
int wleft, wtop, wwidth, wheight;
Stdio.GetWindowSize
(out wleft, out wtop, out wwidth, out wheight);
if(width <= 0 || (wleft + width) > bwidth)
{
throw new ArgumentOutOfRangeException
("width", _("ArgRange_Width"));
}
if(height <= 0 || (wtop + height) > bheight)
{
throw new ArgumentOutOfRangeException
("height", _("ArgRange_Height"));
}
Stdio.SetWindowSize(wleft, wtop, width, height);
}
}
// Console properties.
public static ConsoleColor BackgroundColor
{
get
{
lock(typeof(Console))
{
SpecialMode();
return (ConsoleColor)((currentAttrs >> 4) & 0x0F);
}
}
set
{
if((((int)value) & ~0x0F) != 0)
{
throw new ArgumentException
(_("Arg_InvalidColor"), "value");
}
lock(typeof(Console))
{
SpecialMode();
currentAttrs = (currentAttrs & 0x0F) |
(((int)value) << 4);
Stdio.SetTextAttributes(currentAttrs);
}
}
}
public static int BufferHeight
{
get
{
lock(typeof(Console))
{
SpecialMode();
int width, height;
Stdio.GetBufferSize(out width, out height);
return height;
}
}
}
public static int BufferWidth
{
get
{
lock(typeof(Console))
{
SpecialMode();
int width, height;
Stdio.GetBufferSize(out width, out height);
return width;
}
}
}
public static bool CapsLock
{
get
{
lock(typeof(Console))
{
SpecialMode();
return ((Stdio.GetLockState() & Stdio.CapsLock) != 0);
}
}
}
public static int CursorLeft
{
get
{
lock(typeof(Console))
{
SpecialMode();
int x, y;
Stdio.GetCursorPosition(out x, out y);
return x;
}
}
set
{
SetCursorPosition(value, CursorTop);
}
}
public static int CursorSize
{
get
{
lock(typeof(Console))
{
SpecialMode();
return Stdio.GetCursorSize();
}
}
set
{
if(value < 1 || value > 100)
{
throw new ArgumentOutOfRangeException
("value", _("ArgRange_CursorSize"));
}
lock(typeof(Console))
{
SpecialMode();
Stdio.SetCursorSize(value);
}
}
}
public static int CursorTop
{
get
{
lock(typeof(Console))
{
SpecialMode();
int x, y;
Stdio.GetCursorPosition(out x, out y);
return y;
}
}
set
{
SetCursorPosition(CursorLeft, value);
}
}
public static bool CursorVisible
{
get
{
lock(typeof(Console))
{
SpecialMode();
return Stdio.GetCursorVisible();
}
}
set
{
lock(typeof(Console))
{
SpecialMode();
Stdio.SetCursorVisible(value);
}
}
}
public static ConsoleColor ForegroundColor
{
get
{
lock(typeof(Console))
{
SpecialMode();
return (ConsoleColor)(currentAttrs & 0x0F);
}
}
set
{
if((((int)value) & ~0x0F) != 0)
{
throw new ArgumentException
(_("Arg_InvalidColor"), "value");
}
lock(typeof(Console))
{
SpecialMode();
currentAttrs = (currentAttrs & 0xF0) | ((int)value);
Stdio.SetTextAttributes(currentAttrs);
}
}
}
public static bool KeyAvailable
{
get
{
lock(typeof(Console))
{
SpecialMode();
}
lock(readLock)
{
return Stdio.KeyAvailable();
}
}
}
public static int LargestWindowHeight
{
get
{
lock(typeof(Console))
{
SpecialMode();
int width, height;
Stdio.GetLargestWindowSize(out width, out height);
return width;
}
}
}
public static int LargestWindowWidth
{
get
{
lock(typeof(Console))
{
SpecialMode();
int width, height;
Stdio.GetLargestWindowSize(out width, out height);
return height;
}
}
}
public static bool NumberLock
{
get
{
lock(typeof(Console))
{
SpecialMode();
return ((Stdio.GetLockState() & Stdio.NumLock) != 0);
}
}
}
public static String Title
{
get
{
// Note: we never query the initial console title
// from the system because it may contain sensitive
// data that we don't want the program to have access to.
lock(typeof(Console))
{
return title;
}
}
set
{
if(value == null)
{
throw new ArgumentNullException("value");
}
lock(typeof(Console))
{
SpecialMode();
title = value;
Stdio.SetConsoleTitle(title);
}
}
}
public static bool TreatControlCAsInput
{
get
{
lock(typeof(Console))
{
return treatControlCAsInput;
}
}
set
{
lock(typeof(Console))
{
if(treatControlCAsInput != value)
{
specialMode = false;
treatControlCAsInput = value;
SpecialMode();
}
}
}
}
public static int WindowHeight
{
get
{
lock(typeof(Console))
{
SpecialMode();
int left, top, width, height;
Stdio.GetWindowSize
(out left, out top, out width, out height);
return height;
}
}
}
public static int WindowLeft
{
get
{
lock(typeof(Console))
{
SpecialMode();
int left, top, width, height;
Stdio.GetWindowSize
(out left, out top, out width, out height);
return left;
}
}
}
public static int WindowTop
{
get
{
lock(typeof(Console))
{
SpecialMode();
int left, top, width, height;
Stdio.GetWindowSize
(out left, out top, out width, out height);
return top;
}
}
}
public static int WindowWidth
{
get
{
lock(typeof(Console))
{
SpecialMode();
int left, top, width, height;
Stdio.GetWindowSize
(out left, out top, out width, out height);
return width;
}
}
}
// Event that is emitted for cancel keycodes like CTRL+C.
public static event ConsoleCancelEventHandler CancelKeyPress;
// Method that is called to handle "cancel" events.
private static void HandleCancel(ConsoleSpecialKey specialKeys)
{
ConsoleCancelEventArgs args;
args = new ConsoleCancelEventArgs(specialKeys);
if(CancelKeyPress != null)
{
CancelKeyPress(null, args);
}
if(!(args.Cancel))
{
NormalMode();
Environment.Exit(1);
}
}
#else // !CONFIG_EXTENDED_CONSOLE
// Enable the "normal" input mode on the console.
private static void NormalMode()
{
// Nothing to do if we don't have an extended console.
}
#endif // !CONFIG_EXTENDED_CONSOLE
}; // class Console
}; // namespace System
| |
/*
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT License. See License.txt in the project root for license information.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using Adxstudio.Xrm.Cms;
using Adxstudio.Xrm.Security;
using Adxstudio.Xrm.Services.Query;
using Adxstudio.Xrm.Web.UI.JsonConfiguration;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Security;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Query;
using Action = System.Action;
using Adxstudio.Xrm.ContentAccess;
using Adxstudio.Xrm.Services;
using Adxstudio.Xrm.Web;
namespace Adxstudio.Xrm.EntityList
{
public abstract class EntityListDataAdapter
{
protected EntityListDataAdapter(EntityReference entityList, EntityReference view, IDataAdapterDependencies dependencies)
{
if (entityList == null) throw new ArgumentNullException("entityList");
if (view == null) throw new ArgumentNullException("view");
if (dependencies == null) throw new ArgumentNullException("dependencies");
EntityList = entityList;
View = view;
Dependencies = dependencies;
}
protected IDataAdapterDependencies Dependencies { get; private set; }
protected EntityReference EntityList { get; private set; }
protected EntityReference View { get; private set; }
protected bool EntityPermissionDenied { get; set; }
protected virtual void AssertEntityListAccess()
{
var serviceContext = Dependencies.GetServiceContext();
var website = Dependencies.GetWebsite();
var securityProvider = Dependencies.GetSecurityProvider();
var fetch = new Fetch
{
Entity = new FetchEntity("adx_webpage")
{
Filters = new[]
{
new Filter
{
Conditions = new[]
{
new Condition("adx_websiteid", ConditionOperator.Equal, website.Id),
new Condition("adx_entitylist", ConditionOperator.Equal, EntityList.Id)
}
}
}
}
};
var webPages = serviceContext.RetrieveMultiple(fetch).Entities;
if (!webPages.Any(e => securityProvider.TryAssert(serviceContext, e, CrmEntityRight.Read)))
{
throw new SecurityException("Read permission to this entity list is denied ({0}:{1}).".FormatWith(EntityList.LogicalName, EntityList.Id));
}
}
protected void AddPermissionFilterToFetch(Fetch fetch, EntityListSettings settings, OrganizationServiceContext serviceContext, CrmEntityPermissionRight right)
{
if (!settings.EntityPermissionsEnabled)
{
return;
}
var crmEntityPermissionProvider = new CrmEntityPermissionProvider();
var result = crmEntityPermissionProvider.TryApplyRecordLevelFiltersToFetch(serviceContext, right, fetch);
// Apply Content Access Level filtering
var contentAccessLevelProvider = new ContentAccessLevelProvider();
contentAccessLevelProvider.TryApplyRecordLevelFiltersToFetch(right, fetch);
// Apply Product filtering
var productAccessProvider = new ProductAccessProvider();
productAccessProvider.TryApplyRecordLevelFiltersToFetch(right, fetch);
EntityPermissionDenied = !result.GlobalPermissionGranted && !result.PermissionGranted;
}
protected void AddSearchFilterToFetchEntity(FetchEntity fetchEntity, EntityListSettings settings, string search, IEnumerable<string> searchableAttributes)
{
if (!settings.SearchEnabled || string.IsNullOrWhiteSpace(search))
{
return;
}
var serviceContext = Dependencies.GetServiceContext();
var response = (RetrieveEntityResponse)serviceContext.Execute(new RetrieveEntityRequest
{
LogicalName = fetchEntity.Name,
EntityFilters = EntityFilters.Attributes,
});
var entityMetadata = response.EntityMetadata;
var query = search.Trim().Replace("*", "%");
var conditions = searchableAttributes
.Select(attribute => GetSearchFilterConditionForAttribute(attribute, query, entityMetadata))
.Where(condition => condition != null)
.ToList();
if (!conditions.Any())
{
return;
}
fetchEntity.Filters.Add(new Filter
{
Type = LogicalOperator.Or,
Conditions = conditions
});
}
protected void AddSelectableFilterToFetchEntity(FetchEntity fetchEntity, EntityListSettings settings, string filter)
{
var user = Dependencies.GetPortalUser();
foreach (var condition in GetConditions(fetchEntity).Where(condition => condition.UiType == "contact"))
{
condition.Value = user == null ? Guid.Empty : user.Id;
}
var userAccount = GetPortalUserAccount(user);
foreach (var condition in GetConditions(fetchEntity).Where(condition => condition.UiType == "account"))
{
condition.Value = userAccount == null ? Guid.Empty : userAccount.Id;
}
// Build dictionary of available selectable filters.
var filters = new Dictionary<string, Action>(StringComparer.InvariantCultureIgnoreCase);
if (!string.IsNullOrWhiteSpace(settings.FilterPortalUserFieldName))
{
filters["user"] = () => AddEntityReferenceFilterToFetchEntity(fetchEntity, settings.FilterPortalUserFieldName, user);
}
if (!string.IsNullOrWhiteSpace(settings.FilterAccountFieldName))
{
filters["account"] = () => AddEntityReferenceFilterToFetchEntity(fetchEntity, settings.FilterAccountFieldName, userAccount);
}
// If there are no filters, apply nothing.
if (filters.Count < 1)
{
return;
}
// If there is only one filter defined, apply it automatically.
if (filters.Count == 1)
{
filters.Single().Value();
return;
}
Action applyFilter;
// Try look up the specified filter in the filter dictionary. Apply it if found.
if (filter != null && filters.TryGetValue(filter, out applyFilter))
{
applyFilter();
return;
}
// If the specified filter is not found, try apply the user filter.
if (filters.TryGetValue("user", out applyFilter))
{
applyFilter();
return;
}
// If the user filter is not found, try apply the account filter.
if (filters.TryGetValue("account", out applyFilter))
{
applyFilter();
return;
}
}
protected void AddWebsiteFilterToFetchEntity(FetchEntity fetchEntity, EntityListSettings settings)
{
if (string.IsNullOrWhiteSpace(settings.FilterWebsiteFieldName))
{
return;
}
var website = Dependencies.GetWebsite();
foreach (var condition in GetConditions(fetchEntity).Where(condition => condition.UiType == "adx_website"))
{
condition.Value = website == null ? Guid.Empty : website.Id;
}
if (website == null)
{
return;
}
fetchEntity.Filters.Add(new Filter
{
Type = LogicalOperator.And,
Conditions = new List<Condition>
{
new Condition(settings.FilterWebsiteFieldName, ConditionOperator.Equal, website.Id),
}
});
}
protected virtual IEnumerable<Entity> FetchEntities(OrganizationServiceContext serviceContext, Fetch fetch)
{
if (fetch == null || this.EntityPermissionDenied)
{
return Enumerable.Empty<Entity>();
}
var entityResult = new List<Entity>();
fetch.PageNumber = 1;
while (true)
{
var response = (RetrieveMultipleResponse)serviceContext.Execute(fetch.ToRetrieveMultipleRequest());
entityResult.AddRange(response.EntityCollection.Entities);
if (!response.EntityCollection.MoreRecords || string.IsNullOrEmpty(response.EntityCollection.PagingCookie))
{
break;
}
fetch.PageNumber++;
fetch.PagingCookie = response.EntityCollection.PagingCookie;
}
return entityResult;
}
protected EntityReference GetPortalUserAccount(EntityReference user)
{
if (user == null)
{
return null;
}
var portalOrganizationService = Dependencies.GetRequestContext().HttpContext.GetOrganizationService();
var contact = portalOrganizationService.RetrieveSingle(
user.LogicalName,
new[] { "parentcustomerid" },
new[] {
new Condition("statecode", ConditionOperator.Equal, 0),
new Condition("contactid", ConditionOperator.Equal, user.Id)
});
return contact == null ? null : contact.GetAttributeValue<EntityReference>("parentcustomerid");
}
protected static void AddAttributesToFetchEntity(FetchEntity fetchEntity, EntityListSettings settings)
{
foreach (var attribute in settings.DefinedAttributes)
{
if (fetchEntity.Attributes.Any(a => a.Name == attribute))
{
continue;
}
fetchEntity.Attributes.Add(new FetchAttribute(attribute));
}
}
protected static void AddEntityReferenceFilterToFetchEntity(FetchEntity fetchEntity, string attribute, EntityReference entity)
{
fetchEntity.Filters.Add(new Filter
{
Type = LogicalOperator.And,
Conditions = new List<Condition>
{
new Condition(attribute, ConditionOperator.Equal, entity == null ? Guid.Empty : entity.Id)
}
});
}
protected static IEnumerable<Condition> GetConditions(FetchEntity fetchEntity)
{
if (fetchEntity == null)
{
yield break;
}
if (fetchEntity.Filters != null)
{
foreach (var condition in fetchEntity.Filters.SelectMany(GetConditions))
{
yield return condition;
}
}
if (fetchEntity.Links != null)
{
foreach (var condition in fetchEntity.Links.SelectMany(GetConditions))
{
yield return condition;
}
}
}
protected static IEnumerable<Condition> GetConditions(Filter filter)
{
if (filter == null)
{
yield break;
}
if (filter.Conditions != null)
{
foreach (var condition in filter.Conditions)
{
yield return condition;
}
}
if (filter.Filters != null)
{
foreach (var condition in filter.Filters.SelectMany(GetConditions))
{
yield return condition;
}
}
}
protected static IEnumerable<Condition> GetConditions(Link link)
{
if (link == null)
{
yield break;
}
if (link.Filters != null)
{
foreach (var condition in link.Filters.SelectMany(GetConditions))
{
yield return condition;
}
}
if (link.Links != null)
{
foreach (var condition in link.Links.SelectMany(GetConditions))
{
yield return condition;
}
}
}
protected static Condition GetSearchFilterConditionForAttribute(string attribute, string query, EntityMetadata entityMetadata)
{
var attributeMetadata = entityMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attribute);
if (attributeMetadata == null)
{
return null;
}
switch (attributeMetadata.AttributeType)
{
case AttributeTypeCode.String:
return new Condition(attribute, ConditionOperator.Like, "{0}%".FormatWith(query));
case AttributeTypeCode.Lookup:
case AttributeTypeCode.Customer:
case AttributeTypeCode.Picklist:
case AttributeTypeCode.State:
case AttributeTypeCode.Status:
case AttributeTypeCode.Owner:
return new Condition("{0}name".FormatWith(attribute), ConditionOperator.Like, "{0}%".FormatWith(query));
case AttributeTypeCode.BigInt:
long parsedLong;
return long.TryParse(query, out parsedLong)
? new Condition(attribute, ConditionOperator.Equal, parsedLong)
: null;
case AttributeTypeCode.Integer:
int parsedInt;
return int.TryParse(query, out parsedInt)
? new Condition(attribute, ConditionOperator.Equal, parsedInt)
: null;
case AttributeTypeCode.Double:
double parsedDouble;
return double.TryParse(query, out parsedDouble)
? new Condition(attribute, ConditionOperator.Equal, parsedDouble)
: null;
case AttributeTypeCode.Decimal:
case AttributeTypeCode.Money:
decimal parsedDecimal;
return decimal.TryParse(query, out parsedDecimal)
? new Condition(attribute, ConditionOperator.Equal, parsedDecimal)
: null;
case AttributeTypeCode.DateTime:
DateTime parsedDate;
return DateTime.TryParse(query, out parsedDate)
? new Condition(attribute, ConditionOperator.On, parsedDate.ToString("yyyy-MM-dd"))
: null;
default:
return null;
}
}
protected static bool TryGetEntityList(OrganizationServiceContext serviceContext, EntityReference entityListReference, out Entity entityList)
{
entityList = serviceContext.RetrieveSingle(
"adx_entitylist",
FetchAttribute.All,
new Condition("adx_entitylistid", ConditionOperator.Equal, entityListReference.Id));
return entityList != null;
}
protected static bool TryGetView(OrganizationServiceContext serviceContext, Entity entityList, EntityReference viewReference, out Entity view)
{
Guid? viewId;
if (!TryGetViewId(entityList, viewReference, out viewId) || viewId == null)
{
view = null;
return false;
}
view = serviceContext.CreateQuery("savedquery")
.FirstOrDefault(e => e.GetAttributeValue<Guid>("savedqueryid") == viewId.Value
&& e.GetAttributeValue<string>("returnedtypecode") == entityList.GetAttributeValue<string>("adx_entityname"));
return view != null;
}
protected static bool TryGetViewId(Entity entityList, EntityReference viewReference, out Guid? viewId)
{
// First, try get the view from the newer view configuration JSON.
var viewMetadataJson = entityList.GetAttributeValue<string>("adx_views");
if (!string.IsNullOrWhiteSpace(viewMetadataJson))
{
try
{
var viewMetadata = ViewMetadata.Parse(viewMetadataJson);
var view = viewMetadata.Views.FirstOrDefault(e => e.ViewId == viewReference.Id);
if (view != null)
{
viewId = view.ViewId;
return true;
}
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error parsing adx_views JSON: {0}", e.ToString()));
}
}
// Fall back to the legacy comma-delimited list of IDs.
var viewIds = (entityList.GetAttributeValue<string>("adx_view") ?? string.Empty)
.Split(',')
.Select(s =>
{
Guid id;
return Guid.TryParse(s, out id) ? new Guid?(id) : null;
})
.Where(id => id != null);
viewId = viewIds.FirstOrDefault(id => id == viewReference.Id);
return viewId != null;
}
protected class EntityListSettings
{
private static readonly string[] AttributeMappings =
{
"adx_calendar_startdatefieldname",
"adx_calendar_enddatefieldname",
"adx_calendar_summaryfieldname",
"adx_calendar_descriptionfieldname",
"adx_calendar_organizerfieldname",
"adx_calendar_locationfieldname",
"adx_calendar_alldayfieldname"
};
private readonly IDictionary<string, string> _attributeMap;
public EntityListSettings(Entity entityList)
{
if (entityList == null) throw new ArgumentNullException("entityList");
_attributeMap = AttributeMappings.ToDictionary(a => a, entityList.GetAttributeValue<string>);
CalendarViewEnabled = entityList.GetAttributeValue<bool?>("adx_calendar_enabled").GetValueOrDefault(false);
TimeZoneDisplayMode = GetTimeZoneDisplayMode(entityList.GetAttributeValue<OptionSetValue>("adx_calendar_timezonemode"));
DisplayTimeZone = entityList.GetAttributeValue<int?>("adx_calendar_timezone");
FilterAccountFieldName = entityList.GetAttributeValue<string>("adx_filteraccount");
FilterPortalUserFieldName = entityList.GetAttributeValue<string>("adx_filterportaluser");
FilterWebsiteFieldName = entityList.GetAttributeValue<string>("adx_filterwebsite");
IdQueryStringParameterName = entityList.GetAttributeValue<string>("adx_idquerystringparametername");
SearchEnabled = entityList.GetAttributeValue<bool?>("adx_searchenabled").GetValueOrDefault(false);
WebPageForDetailsView = entityList.GetAttributeValue<EntityReference>("adx_webpagefordetailsview");
EntityPermissionsEnabled = entityList.GetAttributeValue<bool?>("adx_entitypermissionsenabled").GetValueOrDefault(false);
}
public bool CalendarViewEnabled { get; private set; }
public IEnumerable<string> DefinedAttributes
{
get { return _attributeMap.Where(a => !string.IsNullOrWhiteSpace(a.Value)).Select(a => a.Value); }
}
public string DescriptionFieldName
{
get { return _attributeMap["adx_calendar_descriptionfieldname"]; }
}
public int? DisplayTimeZone { get; private set; }
public string EndDateFieldName
{
get { return _attributeMap["adx_calendar_enddatefieldname"]; }
}
public bool EntityPermissionsEnabled { get; private set; }
public string FilterAccountFieldName { get; private set; }
public string FilterPortalUserFieldName { get; private set; }
public string FilterWebsiteFieldName { get; private set; }
public string IdQueryStringParameterName { get; private set; }
public string IsAllDayFieldName
{
get { return _attributeMap["adx_calendar_alldayfieldname"]; }
}
public string LocationFieldName
{
get { return _attributeMap["adx_calendar_locationfieldname"]; }
}
public string OrganizerFieldName
{
get { return _attributeMap["adx_calendar_organizerfieldname"]; }
}
public bool SearchEnabled { get; private set; }
public string StartDateFieldName
{
get { return _attributeMap["adx_calendar_startdatefieldname"]; }
}
public string SummaryFieldName
{
get { return _attributeMap["adx_calendar_summaryfieldname"]; }
}
public EntityListTimeZoneDisplayMode TimeZoneDisplayMode { get; private set; }
public EntityReference WebPageForDetailsView { get; private set; }
private static EntityListTimeZoneDisplayMode GetTimeZoneDisplayMode(OptionSetValue option)
{
if (option == null || !Enum.IsDefined(typeof(EntityListTimeZoneDisplayMode), option.Value))
{
return EntityListTimeZoneDisplayMode.UserLocalTimeZone;
}
return (EntityListTimeZoneDisplayMode)option.Value;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Thinktecture.Relay.Server.OnPremise;
namespace Thinktecture.Relay.Server.Http
{
// ReSharper disable JoinDeclarationAndInitializer
// ReSharper disable UnusedAutoPropertyAccessor.Local
[TestClass]
public class HttpResponseMessageBuilderTest
{
private class OnPremiseConnectorResponse : IOnPremiseConnectorResponse
{
public string RequestId { get; set; }
public Guid OriginId { get; set; }
public IReadOnlyDictionary<string, string> HttpHeaders { get; set; }
public HttpStatusCode StatusCode { get; set; }
public Stream Stream { get; set; }
public byte[] Body { get; set; }
public DateTime RequestStarted { get; set; }
public DateTime RequestFinished { get; set; }
public long ContentLength { get; set; }
}
[TestMethod]
public void GetResponseMessage_returns_on_premise_timeout_message_when_given_OnPremiseTargetResponse_is_null()
{
IHttpResponseMessageBuilder sut = new HttpResponseMessageBuilder(null);
using (var result = sut.BuildFromConnectorResponse(null, true, null))
{
result.StatusCode.Should().Be(HttpStatusCode.GatewayTimeout);
result.Content.Headers.Count().Should().Be(1);
result.Content.Headers.Single().Key.Should().Be("X-TTRELAY-TIMEOUT");
result.Content.Headers.Single().Value.First().Should().Be("On-Premise");
}
}
[TestMethod]
public async Task GetResponseMessage_returns_an_HttpResponseMessage_when_given_OnPremiseTargetResponse_is_null()
{
IHttpResponseMessageBuilder sut = new HttpResponseMessageBuilder(null);
var onPremiseTargetRequest = new OnPremise.OnPremiseConnectorResponse
{
StatusCode = HttpStatusCode.NotFound,
Body = new byte[] { 0, 0, 0, 0 },
HttpHeaders = new Dictionary<string, string>
{
["Content-Length"] = "4",
["X-Foo"] = "X-Bar",
},
ContentLength = 4,
};
using (var result = sut.BuildFromConnectorResponse(onPremiseTargetRequest, true, null))
{
var content = await result.Content.ReadAsByteArrayAsync();
result.StatusCode.Should().Be(HttpStatusCode.NotFound);
content.LongLength.Should().Be(4L);
result.Content.Headers.ContentLength.Should().Be(4L);
result.Content.Headers.GetValues("X-Foo").Single().Should().Be("X-Bar");
}
}
[TestMethod]
public void SetHttpHeaders_does_nothing_when_no_HttpHeaders_are_provided()
{
var sut = new HttpResponseMessageBuilder(null);
var httpContent = new ByteArrayContent(new byte[] { });
sut.AddContentHttpHeaders(httpContent, null);
httpContent.Headers.Should().BeEmpty();
}
[TestMethod]
public void SetHttpHeaders_transforms_HTTP_headers_correctly_from_a_given_OnPremiseTargetRequest_and_sets_them_on_a_given_HttpContent()
{
var sut = new HttpResponseMessageBuilder(null);
var httpHeaders = new Dictionary<string, string>
{
["Content-MD5"] = "Q2hlY2sgSW50ZWdyaXR5IQ==", // will be discarded
["Content-Range"] = "bytes 21010-47021/47022", // will be discarded
["Content-Disposition"] = "attachment",
["Content-Length"] = "300",
["Content-Location"] = "http://tt.invalid",
["Content-Type"] = "application/json",
["Expires"] = "Thu, 01 Dec 1994 16:00:00 GMT",
["Last-Modified"] = "Thu, 01 Dec 1994 15:00:00 GMT",
};
var httpContent = new ByteArrayContent(new byte[] { });
sut.AddContentHttpHeaders(httpContent, httpHeaders);
httpContent.Headers.Should().HaveCount(6);
httpContent.Headers.ContentMD5.Should().BeNull();
httpContent.Headers.ContentRange.Should().BeNull();
httpContent.Headers.ContentDisposition.Should().Be(ContentDispositionHeaderValue.Parse("attachment"));
httpContent.Headers.ContentLength.Should().Be(300L);
httpContent.Headers.ContentLocation.Should().Be("http://tt.invalid");
httpContent.Headers.ContentType.Should().Be(MediaTypeHeaderValue.Parse("application/json"));
httpContent.Headers.Expires.Should().Be(new DateTime(1994, 12, 1, 16, 0, 0));
httpContent.Headers.LastModified.Should().Be(new DateTime(1994, 12, 1, 15, 0, 0));
}
[TestMethod]
public void SetHttpHeaders_sets_unknown_HTTP_headers_without_validation_correctly_from_a_OnPremiseTargetRequest_on_a_given_HttpContent()
{
var sut = new HttpResponseMessageBuilder(null);
var httpHeaders = new Dictionary<string, string>
{
["X-Foo"] = "X-Bar",
["Foo"] = "Bar",
};
var httpContent = new ByteArrayContent(new byte[] { });
sut.AddContentHttpHeaders(httpContent, httpHeaders);
httpContent.Headers.Should().HaveCount(2);
httpContent.Headers.GetValues("X-Foo").Single().Should().Be("X-Bar");
httpContent.Headers.GetValues("Foo").Single().Should().Be("Bar");
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void GetResponseContentForOnPremiseTargetResponse_throws_an_exception_when_given_OnPremiseTargetResponse_is_null()
{
var sut = new HttpResponseMessageBuilder(null);
sut.GetResponseContentForOnPremiseTargetResponse(null, false);
}
[TestMethod]
public void GetResponseContentForOnPremiseTargetResponse_does_not_disclose_content_when_InternalServerError_occurred_and_ForwardOnPremiseTargetErrorResponse_is_turned_off()
{
var sut = new HttpResponseMessageBuilder(null);
var onPremiseTargetResponse = new OnPremiseConnectorResponse { StatusCode = HttpStatusCode.InternalServerError };
using (var result = sut.GetResponseContentForOnPremiseTargetResponse(onPremiseTargetResponse, false))
{
result.Should().BeNull();
}
}
[TestMethod]
public void GetResponseContentForOnPremiseTargetResponse_does_not_disclose_content_when_other_error_occurred_and_ForwardOnPremiseTargetErrorResponse_is_turned_off()
{
var sut = new HttpResponseMessageBuilder(null);
var onPremiseTargetResponse = new OnPremiseConnectorResponse { StatusCode = HttpStatusCode.NotImplemented };
using (var result = sut.GetResponseContentForOnPremiseTargetResponse(onPremiseTargetResponse, false))
{
result.Should().BeNull();
}
}
[TestMethod]
public async Task GetResponseContentForOnPremiseTargetResponse_discloses_content_when_InternalServerError_occurred_and_ForwardOnPremiseTargetErrorResponse_is_turned_on()
{
var sut = new HttpResponseMessageBuilder(null);
var onPremiseTargetResponse = new OnPremiseConnectorResponse { StatusCode = HttpStatusCode.InternalServerError, Body = new byte[] { 0, 0, 0 }, ContentLength = 3, };
using (var result = sut.GetResponseContentForOnPremiseTargetResponse(onPremiseTargetResponse, true))
{
var body = await result.ReadAsByteArrayAsync();
result.Should().NotBeNull();
body.LongLength.Should().Be(3L);
}
}
[TestMethod]
public async Task GetResponseContentForOnPremiseTargetResponse_discloses_content_when_other_error_occurred_and_ForwardOnPremiseTargetErrorResponse_is_turned_on()
{
var sut = new HttpResponseMessageBuilder(null);
var onPremiseTargetResponse = new OnPremiseConnectorResponse { StatusCode = HttpStatusCode.NotImplemented, Body = new byte[] { 0, 0, 0 }, ContentLength = 3, };
using (var result = sut.GetResponseContentForOnPremiseTargetResponse(onPremiseTargetResponse, true))
{
var body = await result.ReadAsByteArrayAsync();
result.Should().NotBeNull();
body.LongLength.Should().Be(3L);
}
}
[TestMethod]
public async Task GetResponseContentForOnPremiseTargetResponse_sets_StatusCode_accordingly_and_discloses_content()
{
var sut = new HttpResponseMessageBuilder(null);
var onPremiseTargetResponse = new OnPremiseConnectorResponse { StatusCode = HttpStatusCode.OK, Body = new byte[] { 0, 0, 0, 0 }, ContentLength = 4, };
using (var result = sut.GetResponseContentForOnPremiseTargetResponse(onPremiseTargetResponse, false))
{
var body = await result.ReadAsByteArrayAsync();
result.Should().NotBeNull();
body.LongLength.Should().Be(4L);
}
}
}
}
| |
S/W Version Information
Model: SM-R770
Tizen-Version: 2.3.2.1
Build-Number: R770XXU1APK6
Build-Date: 2016.11.25 15:41:21
Crash Information
Process Name: firsttizenhello
PID: 7160
Date: 2017-04-07 11:05:47-0400
Executable File Path: /opt/usr/apps/edu.umich.edu.yctung.firsttizenhellp/bin/firsttizenhello
Signal: 11
(SIGSEGV)
si_code: 1
address not mapped to object
si_addr = 0x6e707574
Register Information
r0 = 0x6e707574, r1 = 0x00000025
r2 = 0xfffef3a4, r3 = 0x0000feff
r4 = 0x6e707570, r5 = 0x6e707574
r6 = 0xfffef3a4, r7 = 0x25252525
r8 = 0x00000000, r9 = 0xfffef3a4
r10 = 0x6e707574, fp = 0xfffeee64
ip = 0x6e707574, sp = 0xfffee8e8
lr = 0xf7407f50, pc = 0xf74449cc
cpsr = 0x60000010
Memory Information
MemTotal: 714608 KB
MemFree: 9120 KB
Buffers: 56480 KB
Cached: 182300 KB
VmPeak: 84804 KB
VmSize: 82404 KB
VmLck: 0 KB
VmPin: 0 KB
VmHWM: 24688 KB
VmRSS: 24684 KB
VmData: 20692 KB
VmStk: 136 KB
VmExe: 8 KB
VmLib: 25176 KB
VmPTE: 104 KB
VmSwap: 0 KB
Threads Information
Threads: 2
PID = 7160 TID = 7160
7160 7163
Maps Information
aaaaa000 aaaac000 r-xp /opt/usr/apps/edu.umich.edu.yctung.firsttizenhellp/bin/firsttizenhello
aaabc000 aac66000 rw-p [heap]
f32f4000 f3af3000 rw-p [stack:7163]
f3bb8000 f3bcf000 r-xp /usr/lib/edje/modules/elm/linux-gnueabi-armv7l-1.0.0/module.so
f3d72000 f3d77000 r-xp /usr/lib/bufmgr/libtbm_exynos.so.0.0.0
f3d7f000 f3d8a000 r-xp /usr/lib/evas/modules/engines/software_generic/linux-gnueabi-armv7l-1.7.99/module.so
f40b2000 f40bc000 r-xp /lib/libnss_files-2.13.so
f40c5000 f4194000 r-xp /usr/lib/libscim-1.0.so.8.2.3
f41aa000 f41ce000 r-xp /usr/lib/ecore/immodules/libisf-imf-module.so
f41d7000 f42c9000 r-xp /usr/lib/libCOREGL.so.4.0
f42e9000 f42ee000 r-xp /usr/lib/libsystem.so.0.0.0
f42f8000 f42f9000 r-xp /usr/lib/libresponse.so.0.2.96
f4302000 f4307000 r-xp /usr/lib/libproc-stat.so.0.2.96
f4310000 f4317000 r-xp /usr/lib/libminizip.so.1.0.0
f431f000 f4321000 r-xp /usr/lib/libpkgmgr_installer_status_broadcast_server.so.0.1.0
f4329000 f4330000 r-xp /usr/lib/libpkgmgr_installer_client.so.0.1.0
f4339000 f435b000 r-xp /usr/lib/libpkgmgr-client.so.0.1.68
f4365000 f4368000 r-xp /lib/libattr.so.1.1.0
f4370000 f4378000 r-xp /usr/lib/libcapi-appfw-package-manager.so.0.0.59
f4380000 f4386000 r-xp /usr/lib/libcapi-appfw-app-manager.so.0.2.8
f438f000 f4394000 r-xp /usr/lib/libcapi-media-tool.so.0.1.5
f439c000 f43bd000 r-xp /usr/lib/libexif.so.12.3.3
f43d1000 f43d8000 r-xp /lib/libcrypt-2.13.so
f4408000 f440b000 r-xp /lib/libcap.so.2.21
f4413000 f4415000 r-xp /usr/lib/libiri.so
f441d000 f4436000 r-xp /usr/lib/libprivacy-manager-client.so.0.0.8
f443e000 f4443000 r-xp /usr/lib/libmmutil_imgp.so.0.0.0
f444c000 f4452000 r-xp /usr/lib/libmmutil_jpeg.so.0.0.0
f445a000 f4477000 r-xp /usr/lib/libsecurity-server-commons.so.1.0.0
f4480000 f4484000 r-xp /usr/lib/libogg.so.0.7.1
f448c000 f44ae000 r-xp /usr/lib/libvorbis.so.0.4.3
f44b7000 f44b9000 r-xp /usr/lib/libgmodule-2.0.so.0.3200.3
f44c1000 f44ef000 r-xp /usr/lib/libidn.so.11.5.44
f44f7000 f4500000 r-xp /usr/lib/libcares.so.2.1.0
f4509000 f450b000 r-xp /usr/lib/libXau.so.6.0.0
f4513000 f4515000 r-xp /usr/lib/libttrace.so.1.1
f451e000 f4520000 r-xp /usr/lib/libdri2.so.0.0.0
f4528000 f4530000 r-xp /usr/lib/libdrm.so.2.4.0
f4538000 f4539000 r-xp /usr/lib/libsecurity-privilege-checker.so.1.0.1
f4542000 f4545000 r-xp /usr/lib/libcapi-media-image-util.so.0.3.5
f454e000 f455d000 r-xp /usr/lib/libmdm-common.so.1.1.22
f4566000 f45fa000 r-xp /usr/lib/libstdc++.so.6.0.16
f460d000 f4611000 r-xp /usr/lib/libsmack.so.1.0.0
f461a000 f47c3000 r-xp /usr/lib/libcrypto.so.1.0.0
f47e4000 f482b000 r-xp /usr/lib/libssl.so.1.0.0
f4837000 f4866000 r-xp /usr/lib/libsecurity-server-client.so.1.0.1
f486e000 f48b5000 r-xp /usr/lib/libsndfile.so.1.0.26
f48c1000 f490a000 r-xp /usr/lib/pulseaudio/libpulsecommon-4.0.so
f4913000 f4918000 r-xp /usr/lib/libjson.so.0.0.1
f4921000 f4924000 r-xp /usr/lib/libtinycompress.so.0.0.0
f492c000 f492e000 r-xp /usr/lib/journal/libjournal.so.0.1.0
f4936000 f4946000 r-xp /lib/libresolv-2.13.so
f494a000 f4962000 r-xp /usr/lib/liblzma.so.5.0.3
f496b000 f496d000 r-xp /usr/lib/libsecurity-extension-common.so.1.0.1
f4975000 f4a48000 r-xp /usr/lib/libgio-2.0.so.0.3200.3
f4a53000 f4a58000 r-xp /usr/lib/libffi.so.5.0.10
f4a60000 f4aa4000 r-xp /usr/lib/libcurl.so.4.3.0
f4aae000 f4ad1000 r-xp /usr/lib/libjpeg.so.8.0.2
f4ae9000 f4afc000 r-xp /usr/lib/libxcb.so.1.1.0
f4b05000 f4b0b000 r-xp /usr/lib/libxcb-render.so.0.0.0
f4b13000 f4b14000 r-xp /usr/lib/libxcb-shm.so.0.0.0
f4b1d000 f4b35000 r-xp /usr/lib/libpng12.so.0.50.0
f4b3e000 f4b42000 r-xp /usr/lib/libEGL.so.1.4
f4b52000 f4b63000 r-xp /usr/lib/libGLESv2.so.2.0
f4b73000 f4b74000 r-xp /usr/lib/libecore_imf_evas.so.1.7.99
f4b7c000 f4b93000 r-xp /usr/lib/liblua-5.1.so
f4b9c000 f4ba3000 r-xp /usr/lib/libembryo.so.1.7.99
f4bac000 f4bb7000 r-xp /usr/lib/libtbm.so.1.0.0
f4bbf000 f4be2000 r-xp /usr/lib/libui-extension.so.0.1.0
f4beb000 f4c01000 r-xp /usr/lib/libtts.so
f4c0a000 f4c20000 r-xp /lib/libz.so.1.2.5
f4c28000 f4c3e000 r-xp /lib/libexpat.so.1.6.0
f4c49000 f4c4c000 r-xp /usr/lib/libecore_input_evas.so.1.7.99
f4c54000 f4c58000 r-xp /usr/lib/libecore_ipc.so.1.7.99
f4c61000 f4c66000 r-xp /usr/lib/libecore_fb.so.1.7.99
f4c6f000 f4c79000 r-xp /usr/lib/libXext.so.6.4.0
f4c82000 f4c86000 r-xp /usr/lib/libXtst.so.6.1.0
f4c8f000 f4c95000 r-xp /usr/lib/libXrender.so.1.3.0
f4c9d000 f4ca3000 r-xp /usr/lib/libXrandr.so.2.2.0
f4cab000 f4cac000 r-xp /usr/lib/libXinerama.so.1.0.0
f4cb5000 f4cb8000 r-xp /usr/lib/libXfixes.so.3.1.0
f4cc0000 f4cc2000 r-xp /usr/lib/libXgesture.so.7.0.0
f4cca000 f4ccc000 r-xp /usr/lib/libXcomposite.so.1.0.0
f4cd5000 f4cd7000 r-xp /usr/lib/libXdamage.so.1.1.0
f4cdf000 f4ce6000 r-xp /usr/lib/libXcursor.so.1.0.2
f4cee000 f4d36000 r-xp /usr/lib/libmdm.so.1.2.62
f65c8000 f66ce000 r-xp /usr/lib/libicuuc.so.57.1
f66e5000 f686d000 r-xp /usr/lib/libicui18n.so.57.1
f687d000 f687f000 r-xp /usr/lib/libSLP-db-util.so.0.1.0
f6888000 f6895000 r-xp /usr/lib/libail.so.0.1.0
f689e000 f68a1000 r-xp /usr/lib/libsyspopup_caller.so.0.1.0
f68a9000 f68e1000 r-xp /usr/lib/libpulse.so.0.16.2
f68e2000 f68e5000 r-xp /usr/lib/libpulse-simple.so.0.0.4
f68ee000 f694f000 r-xp /usr/lib/libasound.so.2.0.0
f6959000 f696f000 r-xp /usr/lib/libavsysaudio.so.0.0.1
f6977000 f697e000 r-xp /usr/lib/libmmfcommon.so.0.0.0
f6986000 f698a000 r-xp /usr/lib/libmmfsoundcommon.so.0.0.0
f6992000 f6993000 r-xp /usr/lib/libgthread-2.0.so.0.3200.3
f699c000 f69a7000 r-xp /usr/lib/libaudio-session-mgr.so.0.0.0
f69b4000 f69b8000 r-xp /usr/lib/libmmfsession.so.0.0.0
f69c1000 f69c7000 r-xp /lib/librt-2.13.so
f69d0000 f6a45000 r-xp /usr/lib/libsqlite3.so.0.8.6
f6a4f000 f6a69000 r-xp /usr/lib/libpkgmgr_parser.so.0.1.0
f6a72000 f6a90000 r-xp /usr/lib/libsystemd.so.0.4.0
f6a9a000 f6a9b000 r-xp /usr/lib/libsecurity-extension-interface.so.1.0.1
f6aa3000 f6aa8000 r-xp /usr/lib/libxdgmime.so.1.1.0
f6ab0000 f6ac7000 r-xp /usr/lib/libdbus-glib-1.so.2.2.2
f6acf000 f6ad1000 r-xp /usr/lib/libiniparser.so.0
f6adb000 f6b0f000 r-xp /usr/lib/libgobject-2.0.so.0.3200.3
f6b18000 f6b1e000 r-xp /usr/lib/libecore_imf.so.1.7.99
f6b26000 f6b29000 r-xp /usr/lib/libbundle.so.0.1.22
f6b31000 f6b37000 r-xp /usr/lib/libappsvc.so.0.1.0
f6b3f000 f6b95000 r-xp /usr/lib/libpixman-1.so.0.28.2
f6ba3000 f6bf9000 r-xp /usr/lib/libfreetype.so.6.11.3
f6c05000 f6c4a000 r-xp /usr/lib/libharfbuzz.so.0.10200.4
f6c53000 f6c66000 r-xp /usr/lib/libfribidi.so.0.3.1
f6c6e000 f6c88000 r-xp /usr/lib/libecore_con.so.1.7.99
f6c91000 f6cbb000 r-xp /usr/lib/libdbus-1.so.3.8.12
f6cc5000 f6cce000 r-xp /usr/lib/libedbus.so.1.7.99
f6cd6000 f6ce7000 r-xp /usr/lib/libecore_input.so.1.7.99
f6cef000 f6cf4000 r-xp /usr/lib/libecore_file.so.1.7.99
f6cfc000 f6d15000 r-xp /usr/lib/libeet.so.1.7.99
f6d26000 f6d2f000 r-xp /usr/lib/libXi.so.6.1.0
f6d38000 f6e19000 r-xp /usr/lib/libX11.so.6.3.0
f6e24000 f6edc000 r-xp /usr/lib/libcairo.so.2.11200.14
f6ee7000 f6f45000 r-xp /usr/lib/libedje.so.1.7.99
f6f4f000 f6f66000 r-xp /usr/lib/libecore.so.1.7.99
f6f7d000 f6fe6000 r-xp /lib/libm-2.13.so
f6fef000 f7001000 r-xp /usr/lib/libefl-assist.so.0.1.0
f7009000 f70d9000 r-xp /usr/lib/libglib-2.0.so.0.3200.3
f70da000 f71a6000 r-xp /usr/lib/libxml2.so.2.7.8
f71b3000 f71db000 r-xp /usr/lib/libfontconfig.so.1.8.0
f71dc000 f71e5000 r-xp /usr/lib/libvconf.so.0.2.45
f71ed000 f720f000 r-xp /usr/lib/libecore_evas.so.1.7.99
f7218000 f7268000 r-xp /usr/lib/libecore_x.so.1.7.99
f726a000 f726f000 r-xp /usr/lib/libcapi-system-info.so.0.2.0
f7277000 f728e000 r-xp /usr/lib/libmmfsound.so.0.1.0
f72a0000 f72b4000 r-xp /lib/libpthread-2.13.so
f72bf000 f7300000 r-xp /usr/lib/libeina.so.1.7.99
f7309000 f732c000 r-xp /usr/lib/libpkgmgr-info.so.0.0.17
f7334000 f7341000 r-xp /usr/lib/libaul.so.0.1.0
f734b000 f7350000 r-xp /usr/lib/libappcore-common.so.1.1
f7358000 f735e000 r-xp /usr/lib/libappcore-efl.so.1.1
f7366000 f7368000 r-xp /usr/lib/libcapi-appfw-app-common.so.0.3.2.5
f7371000 f7375000 r-xp /usr/lib/libcapi-appfw-app-control.so.0.3.2.5
f737e000 f7380000 r-xp /lib/libdl-2.13.so
f7389000 f7394000 r-xp /lib/libunwind.so.8.0.1
f73c1000 f73c9000 r-xp /lib/libgcc_s-4.6.so.1
f73ca000 f74ee000 r-xp /lib/libc-2.13.so
f74fc000 f75ca000 r-xp /usr/lib/libevas.so.1.7.99
f75ef000 f772b000 r-xp /usr/lib/libelementary.so.1.7.99
f7742000 f7763000 r-xp /usr/lib/libefl-extension.so.0.1.0
f776b000 f776d000 r-xp /usr/lib/libdlog.so.0.0.0
f7775000 f777d000 r-xp /usr/lib/libcapi-system-system-settings.so.0.0.2
f777e000 f7785000 r-xp /usr/lib/libcapi-media-audio-io.so.0.2.23
f778d000 f7793000 r-xp /usr/lib/libcapi-base-common.so.0.1.8
f779c000 f77a0000 r-xp /usr/lib/libcapi-appfw-application.so.0.3.2.5
f77aa000 f77b5000 r-xp /usr/lib/evas/modules/engines/software_x11/linux-gnueabi-armv7l-1.7.99/module.so
f77be000 f77c2000 r-xp /usr/lib/libsys-assert.so
f77cb000 f77e8000 r-xp /lib/ld-2.13.so
fffcf000 ffff0000 rw-p [stack]
End of Maps Information
Callstack Information (PID:7160)
Call Stack Count: 1
0: strchrnul + 0xb8 (0xf74449cc) [/lib/libc.so.6] + 0x7a9cc
End of Call Stack
Package Information
Package Name: edu.umich.edu.yctung.firsttizenhellp
Package ID : edu.umich.edu.yctung.firsttizenhellp
Version: 1.0.0
Package Type: rpm
App Name: firsttizenhello
App ID: edu.umich.edu.yctung.firsttizenhellp
Type: capp
Categories:
Latest Debug Message Information
--------- beginning of /dev/log_main
erList.cpp L: 171][_HIGH][RX]Clear PeerList. Count=0 pConnected=(nil)[0m
04-07 11:07:50.361-0400 W/WG-CONSUMER( 6703): [34m[F:ConnectionInfo.c L: 619][_HIGH][RX]State changed: SM_STATE_INITIATE->SM_STATE_INITIATE[0m
04-07 11:07:50.371-0400 I/CAPI_CONTENT_MEDIA_CONTENT( 6703): media_content.c: media_content_disconnect(958) > [32m[6703]ref count changed to: 0
04-07 11:07:50.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:50.481-0400 E/WG-CONSUMER( 6703): [31m[F:consumer-app.cpp L: 433][ERROR]Terminate main. nRet=0[0m
04-07 11:07:50.481-0400 W/WG-CONSUMER( 6703): [34m[F:ReceiverCtrl.cpp L: 88][_HIGH]CReceiverCtrl::~CReceiverCtrl()[0m
04-07 11:07:50.481-0400 W/WG-CONSUMER( 6703): [34m[F:PeerList.cpp L: 163][_HIGH][RX]CPeerList::~CPeerList(0xf772f574)[0m
04-07 11:07:50.481-0400 W/WG-CONSUMER( 6703): [34m[F:TransferCtrl.cpp L: 97][_HIGH]CTransferCtrl::~CTransferCtrl()[0m
04-07 11:07:50.481-0400 W/WG-CONSUMER( 6703): [34m[F:AlarmSvc.cpp L: 96][_HIGH]CAlarmSvc::~CAlarmSvc() hAlarm:0x00000000[0m
04-07 11:07:50.481-0400 E/WG-CONSUMER( 6703): [31m[F:ConnectionInfo.c L: 148][ERROR]Unegister db/wms/host_status/vendor is failed[0m
04-07 11:07:50.481-0400 W/WG-CONSUMER( 6703): [34m[F:BAPProxy.cpp L: 80][_HIGH]Destroying BAP Proxy Object. 0xf7729c00[0m
04-07 11:07:50.481-0400 W/WG-CONSUMER( 6703): [34m[F:PeerList.cpp L: 163][_HIGH][TX]CPeerList::~CPeerList(0xf772aa2c)[0m
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortIpcServer.cpp: OnReadMessage(739) > _MessagePortIpcServer::OnReadMessage
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortIpcServer.cpp: HandleReceivedMessage(578) > _MessagePortIpcServer::HandleReceivedMessage
04-07 11:07:50.501-0400 E/MESSAGE_PORT( 2429): MessagePortIpcServer.cpp: HandleReceivedMessage(588) > Connection closed
04-07 11:07:50.501-0400 E/MESSAGE_PORT( 2429): MessagePortIpcServer.cpp: HandleReceivedMessage(610) > All connections of client(6703) are closed. delete client info
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortStub.cpp: OnIpcClientDisconnected(178) > MessagePort Ipc disconnected
04-07 11:07:50.501-0400 E/MESSAGE_PORT( 2429): MessagePortStub.cpp: OnIpcClientDisconnected(181) > Unregister - client = 6703
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: UnregisterMessagePortByDiscon(273) > _MessagePortService::UnregisterMessagePortByDiscon
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.501-0400 I/MESSAGE_PORT( 2429): MessagePortService.cpp: unregistermessageport(257) > unregistermessageport
04-07 11:07:50.511-0400 W/AUL ( 7179): daemon-manager-release-agent.c: main(12) > release agent : [2:/com.samsung.w-gallery.consumer]
04-07 11:07:50.511-0400 W/AUL_AMD ( 2434): amd_request.c: __request_handler(669) > __request_handler: 23
04-07 11:07:50.511-0400 W/AUL_AMD ( 2434): amd_request.c: __send_result_to_client(91) > __send_result_to_client, pid: 0
04-07 11:07:50.511-0400 W/AUL_AMD ( 2434): amd_request.c: __request_handler(1032) > pkg_status: installed, dead pid: 6703
04-07 11:07:50.511-0400 W/AUL_AMD ( 2434): amd_request.c: __send_app_termination_signal(528) > send dead signal done
04-07 11:07:50.521-0400 I/AUL_AMD ( 2434): amd_main.c: __app_dead_handler(262) > __app_dead_handler, pid: 6703
04-07 11:07:50.521-0400 W/AUL ( 2434): app_signal.c: aul_send_app_terminated_signal(799) > aul_send_app_terminated_signal pid(6703)
04-07 11:07:50.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:50.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:50.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:51.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:51.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:51.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:51.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:51.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:52.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:52.311-0400 W/AUL_AMD ( 2434): amd_status.c: __app_terminate_timer_cb(168) > send SIGKILL: No such process
04-07 11:07:52.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:52.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:52.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:52.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:53.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:53.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:53.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:53.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:53.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:54.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:54.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:54.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:54.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:54.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:55.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:55.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:55.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:55.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:55.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:56.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:56.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:56.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:56.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:56.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:57.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:57.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:57.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:57.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:57.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:58.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:58.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:58.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:58.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:58.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:59.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:59.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:59.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:59.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:07:59.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:00.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:00.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:00.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:00.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:00.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:01.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:01.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:01.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:01.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:01.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:02.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:02.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:02.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:02.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:02.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:03.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:03.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:03.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:03.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:03.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:04.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:04.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:04.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:04.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:04.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:05.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:05.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:05.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:05.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:05.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:06.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:06.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:06.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:06.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:06.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:07.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:07.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:07.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:07.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:07.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:08.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:08.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:08.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:08.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:08.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:09.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:09.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:09.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:09.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:09.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:10.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:10.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:10.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:10.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:10.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:11.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:11.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:11.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:11.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:11.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:12.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:12.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:12.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:12.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:12.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:13.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:13.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:13.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:13.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:13.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:14.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:14.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:14.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:14.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:14.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:15.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:15.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:15.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:15.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:15.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:16.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:16.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:16.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:16.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:16.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:17.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:17.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:17.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:17.611-0400 D/chronograph( 2893): ChronographSweepSecond.cpp: _onSweep60sAnimationFinished(124) > [0;32mBEGIN >>>>[0;m
04-07 11:08:17.611-0400 D/chronograph( 2893): ChronographSweepSecond.cpp: _onSweep60sAnimationFinished(137) > mSweep60SStartValue[39.998001] mCurrentValue[17.627001]
04-07 11:08:17.611-0400 D/chronograph( 2893): ChronographSweepSecond.cpp: _onSweep60sAnimationFinished(171) > speed down by 6 degree in 60 seconds
04-07 11:08:17.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:17.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:18.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:18.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:18.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:18.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:18.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:19.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:19.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:19.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:19.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:19.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:20.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:20.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:20.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:20.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:20.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:21.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:21.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:21.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:21.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:21.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:22.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:22.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:22.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:22.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:22.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:23.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:23.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:23.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:23.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:23.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:24.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:24.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:24.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:24.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:24.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:25.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:25.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:25.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:25.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:25.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:26.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:26.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:26.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:26.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:26.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:27.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:27.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:27.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:27.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:27.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:28.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:28.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:28.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:28.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:28.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:29.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:29.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:29.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:29.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:29.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:30.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:30.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:30.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:30.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:30.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:31.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:31.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:31.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:31.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:31.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:32.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:32.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:32.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:32.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:32.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:33.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:33.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:33.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:33.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:33.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:34.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:34.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:34.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:34.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:34.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:35.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:35.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:35.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:35.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:35.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:36.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:36.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:36.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:36.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:36.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:37.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:37.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:37.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:37.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:37.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:38.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:38.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:38.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:38.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:38.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:39.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:39.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:39.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:39.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:39.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:40.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:40.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:40.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:40.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:40.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:41.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:41.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:41.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:41.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:41.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:42.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:42.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:42.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:42.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:42.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:43.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:43.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:43.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:43.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:43.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:44.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:44.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:44.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:44.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:44.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:45.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:45.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:45.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:45.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:45.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:46.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:46.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:46.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:46.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:46.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:47.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:47.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:47.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:47.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:47.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:48.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:48.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:48.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:48.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:48.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:49.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:49.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:49.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:49.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:49.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:50.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:50.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:50.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:50.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:50.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:51.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:51.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:51.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:51.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:51.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:52.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:52.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:52.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:52.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:52.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:53.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:53.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:53.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:53.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:53.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:54.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:54.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:54.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:54.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:54.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:55.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:55.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:55.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:55.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:55.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:56.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:56.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:56.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:56.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:56.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:57.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:57.391-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:57.591-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:57.791-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:57.991-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:58.191-0400 I/CAPI_WATCH_APPLICATION( 2893): watch_app_main.c: _watch_core_time_tick(313) > _watch_core_time_tick
04-07 11:08:58.341-0400 W/CRASH_MANAGER( 7184): worker.c: worker_job(1199) > 1107160666972149157754
| |
using DontPanic.TumblrSharp;
using DontPanic.TumblrSharp.Client;
using DontPanic.TumblrSharp.OAuth;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TestingTumblrSharp
{
[TestClass]
public class JsonConverters
{
// This ConsumerToken and AccessToken is only for testing!
private readonly string _consumerKey = "hGSKqgb24RJBnWkodL5GTFIeadgyOnWl0qsXi7APRC76HELnrE";
private readonly string _consumerSecret = "jdNWSSbG7bZ8tYJcYzmyfH33o5cq7ihmJeWMVntB3pUHNptqn3";
private readonly string _accessKey = "F1G7BF1JW4f1VKJ93xJSi7D66yZKN3Uj0bArn5i5riwVEnMHuU";
private readonly string _accessSecret = "O977YH42yg98IsS9BAk80r5e5grYQDY9HauVmgf0aEmceZ2UTz";
#region NoteConverter
[TestMethod]
public void NoteConverter_Theorie()
{
const string resultStr = "{\r\n \"title\": null,\r\n \"body\": \"testbody\",\r\n \"type\": \"all\",\r\n \"blog_name\": \"TestBlog\"," +
"\r\n \"id\": 12456789,\r\n \"post_url\": null,\r\n \"slug\": null,\r\n \"timestamp\": 0,\r\n \"state\": \"published\"," +
"\r\n \"format\": \"html\",\r\n \"reblog_key\": null,\r\n \"tags\": null,\r\n \"short_url\": null,\r\n \"summary\": null," +
"\r\n \"note_count\": 0,\r\n \"notes\": [\r\n {\r\n \"type\": \"like\",\r\n \"timestamp\": 0," +
"\r\n \"blog_name\": \"OtherBlock\",\r\n \"blog_uuid\": null,\r\n \"blog_url\": null,\r\n \"followed\": false," +
"\r\n \"avatar_shape\": \"circle\",\r\n \"reply_text\": null,\r\n \"post_id\": null," +
"\r\n \"reblog_parent_blog_name\": null\r\n }\r\n ],\r\n \"total_posts\": 0,\r\n \"trail\": []\r\n}";
TextPost basicTextPost = new TextPost
{
BlogName = "TestBlog",
Body = "testbody",
Id = 12456789,
Timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc),
Format = PostFormat.Html,
Trails = new List<Trail>()
};
basicTextPost.Notes = new List<BaseNote>
{
new BaseNote()
{
BlogName = "OtherBlock",
Type = NoteType.Like,
AvatarShape = AvatarShape.Circle,
Timestamp = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
}
};
// convert post
string json = JsonConvert.SerializeObject(basicTextPost, Formatting.Indented);
Assert.AreEqual(resultStr, json);
TextPost tp = JsonConvert.DeserializeObject<TextPost>(json);
Assert.AreEqual(basicTextPost.Notes[0].BlogName, tp.Notes[0].BlogName);
}
[TestMethod]
public async Task NoteConverter()
{
TumblrClient tc = new TumblrClientFactory().Create<TumblrClient>(_consumerKey, _consumerSecret, new Token(_accessKey, _accessSecret));
// find a post with notes
PhotoPost notePost = null;
bool findPostWithNotes = false;
long currentID = 0;
while (findPostWithNotes == false)
{
BasePost[] basePosts = await tc.GetDashboardPostsAsync(currentID, 0, 1, PostType.Photo, false, true);
for (int i = 0; i < basePosts.Count(); i++)
{
PhotoPost basePost = basePosts[i] as PhotoPost;
if (basePost.Notes?.Count() > 0)
{
findPostWithNotes = true;
notePost = basePost;
break;
}
currentID = basePost.Id;
}
}
// convert post
string json = JsonConvert.SerializeObject(notePost, Formatting.Indented);
// deserialize post
PhotoPost jsonPost = JsonConvert.DeserializeObject<PhotoPost>(json);
//testing
for (int i = 0; i < notePost.Notes.Count(); i++)
{
BaseNote baseNote = notePost.Notes[i];
BaseNote jsonNote = jsonPost.Notes[i];
Assert.AreEqual(baseNote, jsonNote);
}
}
#endregion
#region TrailConverter
[TestMethod]
public async Task TrailConverter()
{
TumblrClient tc = new TumblrClientFactory().Create<TumblrClient>(_consumerKey, _consumerSecret, new Token(_accessKey, _accessSecret));
// find a post with trials
BasePost post = null;
bool findPostWithTrials = false;
long currentID = 0;
while (findPostWithTrials == false)
{
BasePost[] basePosts = await tc.GetDashboardPostsAsync(currentID, 0, 20, PostType.All, false, true);
for (int i = 0; i < 20; i++)
{
BasePost basePost = basePosts[i];
if (basePost.Trails?.Count() > 0)
{
findPostWithTrials = true;
post = basePost;
break;
}
if (i == 19)
{
currentID = basePost.Id;
}
}
}
// convert post
string json = JsonConvert.SerializeObject(post, Formatting.Indented);
// deserialize post
BasePost jsonPost = JsonConvert.DeserializeObject<BasePost>(json);
//testing
for (int i = 0; i < post.Trails.Count(); i++)
{
Trail baseTrail = post.Trails[i];
Trail jsonTrail = jsonPost.Trails[i];
Assert.AreEqual(baseTrail, jsonTrail);
}
}
#endregion
#region TumblrErrorsConverter
[TestMethod]
public void TumblrErrorsConverter()
{
TumblrError te = new TumblrError
{
Code = 0,
Title = "Not Found",
Detail = "Da ist der Wurm drin. Versuche es noch mal."
};
string teStr = "{\r\n \"title\": \"Not Found\",\r\n \"code\": 0,\r\n \"detail\": \"Da ist der Wurm drin. Versuche es noch mal.\"\r\n}";
// test serialize
string json = JsonConvert.SerializeObject(te, Formatting.Indented);
Assert.AreEqual(teStr, json);
// test deserialize
TumblrError jsonTumblrError = JsonConvert.DeserializeObject<TumblrError>(teStr);
Assert.AreEqual(te, jsonTumblrError);
}
#endregion
#region BoolConverter
#region HelperClass
private class TestBoolClass
{
[JsonProperty(PropertyName = "error")]
[JsonConverter(typeof(BoolConverter))]
public bool Error { get; set; }
[JsonProperty(PropertyName = "success")]
[JsonConverter(typeof(BoolConverter))]
public bool Success { get; set; }
}
#endregion
[TestMethod]
[ExpectedException(typeof(JsonReaderException))]
public void BoolConverters_FalseBoolString()
{
string exceptString = "{\r\n \"error\": \"Yes\",\r\n \"success\": \"N\"\r\n}";
TestBoolClass jsonBool = JsonConvert.DeserializeObject<TestBoolClass>(exceptString);
}
[TestMethod]
public void BoolConverters()
{
TestBoolClass exceptBoolClass = new TestBoolClass()
{
Error = true,
Success = false
};
string exceptString = "{\r\n \"error\": \"Y\",\r\n \"success\": \"N\"\r\n}";
TestBoolClass jsonBool = JsonConvert.DeserializeObject<TestBoolClass>(exceptString);
Assert.AreEqual(exceptBoolClass.Error, jsonBool.Error);
Assert.AreEqual(exceptBoolClass.Success, jsonBool.Success);
string jsonString = JsonConvert.SerializeObject(exceptBoolClass, Formatting.Indented);
Assert.AreEqual(exceptString, jsonString);
}
#endregion
#region EnumStringConverter
#region HelperClass
private class TEnumStringHelperClass
{
[JsonProperty(PropertyName = "posttype")]
[JsonConverter(typeof(EnumStringConverter))]
public PostType PostType { get; set; }
[JsonProperty(PropertyName = "notetype")]
[JsonConverter(typeof(EnumStringConverter))]
public NoteType NoteType { get; set; }
[JsonProperty(PropertyName = "blogtype")]
[JsonConverter(typeof(EnumStringConverter))]
public BlogType BlogType { get; set; }
public override bool Equals(object obj)
{
return obj is TEnumStringHelperClass @class &&
PostType == @class.PostType &&
NoteType == @class.NoteType &&
BlogType == @class.BlogType;
}
public override int GetHashCode()
{
return HashCode.Combine(PostType, NoteType, BlogType);
}
}
#endregion
[TestMethod]
public void EnumStringConverter()
{
TEnumStringHelperClass exceptClass = new TEnumStringHelperClass()
{
PostType = PostType.Photo,
NoteType = NoteType.Posted,
BlogType = BlogType.Public
};
string exceptString = "{\r\n \"posttype\": \"photo\",\r\n \"notetype\": \"posted\",\r\n \"blogtype\": \"public\"\r\n}";
string jsonString = JsonConvert.SerializeObject(exceptClass, Formatting.Indented);
Assert.AreEqual(exceptString, jsonString);
TEnumStringHelperClass jsonClass = JsonConvert.DeserializeObject<TEnumStringHelperClass>(exceptString);
Assert.AreEqual(exceptClass, jsonClass);
}
#endregion
#region PostArrayConverter
#region PostArrayConverterHelperClass
private class PostArrayConverterHelperClass
{
[JsonProperty(PropertyName = "posts")]
[JsonConverter(typeof(PostArrayConverter))]
public BasePost[] Posts { get; set; }
public override bool Equals(object obj)
{
if (!(obj is PostArrayConverterHelperClass compareObj))
{
return false;
}
else
{
if (Posts.Count() != compareObj.Posts.Count())
{
return false;
}
for (int i = 0; i < Posts.Count(); i++)
{
if (Posts[i].Equals(compareObj.Posts[i]) == false)
{
return false;
}
}
}
return true;
}
public override int GetHashCode()
{
return HashCode.Combine(Posts);
}
}
#endregion
[TestMethod]
public void PostArrayConverter_EmptyArray()
{
PostArrayConverterHelperClass exceptClass = new PostArrayConverterHelperClass
{
Posts = new BasePost[0]
};
string exceptString = "{\r\n \"posts\": []\r\n}";
string jsonString = JsonConvert.SerializeObject(exceptClass, Formatting.Indented);
Assert.AreEqual(exceptString, jsonString);
PostArrayConverterHelperClass jsonClass = JsonConvert.DeserializeObject<PostArrayConverterHelperClass>(exceptString);
Assert.AreEqual(exceptClass.Posts.Count(), jsonClass.Posts.Count());
}
[TestMethod]
public void PostArrayConverter_Values()
{
DateTime timeStamp = DateTime.Now;
string timeStampStr = DateTimeHelper.ToTimestamp(timeStamp).ToString();
PostArrayConverterHelperClass exceptClass = new PostArrayConverterHelperClass
{
Posts = new BasePost[1]
{
new TextPost()
{
Type = PostType.Text,
Title = "Testpost",
Body = "this a textpost",
BlogName = "IrgendeinBlog",
Id = 1234563,
Tags = new string[0],
Timestamp = timeStamp,
Notes = new List<BaseNote>(),
Trails = new List<Trail>()
}
}
};
string exceptString = "{\r\n \"posts\": [\r\n {\r\n \"title\": \"Testpost\",\r\n \"body\": \"this a textpost\"," +
"\r\n \"type\": \"text\",\r\n \"blog_name\": \"IrgendeinBlog\",\r\n \"id\": 1234563,\r\n \"post_url\": null," +
"\r\n \"slug\": null,\r\n \"timestamp\": " + timeStampStr + ",\r\n \"state\": \"published\"," +
"\r\n \"format\": \"html\",\r\n \"reblog_key\": null,\r\n \"tags\": [],\r\n \"short_url\": null," +
"\r\n \"summary\": null,\r\n \"note_count\": 0,\r\n \"notes\": [],\r\n \"total_posts\": 0," +
"\r\n \"trail\": []\r\n }\r\n ]\r\n}";
string jsonString = JsonConvert.SerializeObject(exceptClass, Formatting.Indented);
Assert.AreEqual(exceptString, jsonString);
PostArrayConverterHelperClass jsonClass = JsonConvert.DeserializeObject<PostArrayConverterHelperClass>(exceptString);
Assert.AreEqual(exceptClass.Posts.Count(), jsonClass.Posts.Count());
}
#endregion
#region TimestampConverter
#region HelperClass
private class TimestampConverterHelper
{
[JsonProperty(PropertyName = "timestamp")]
[JsonConverter(typeof(TimestampConverter))]
public DateTime Timestamp { get; set; }
}
#endregion
[TestMethod]
public void TimestampConverter()
{
TimestampConverterHelper exceptClass = new TimestampConverterHelper
{
Timestamp = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
};
string exceptString = "{\r\n \"timestamp\": 0\r\n}";
string json = JsonConvert.SerializeObject(exceptClass, Formatting.Indented);
Assert.AreEqual(exceptString, json);
}
public void TimestampConverter_1()
{
TimestampConverterHelper exceptClass = new TimestampConverterHelper
{
Timestamp = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
};
string exceptString = "{\r\n \"timestamp\": 0\r\n}";
TimestampConverterHelper jsonClass = JsonConvert.DeserializeObject<TimestampConverterHelper>(exceptString);
Assert.AreEqual(exceptClass.Timestamp.ToUniversalTime(), jsonClass.Timestamp.ToUniversalTime());
}
public void TimestampConverter_2()
{
TimestampConverterHelper exceptClass = new TimestampConverterHelper
{
Timestamp = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
};
exceptClass.Timestamp = new DateTime(2000, 1, 1, 0, 0, 0, DateTimeKind.Local);
string exceptString = "{\r\n \"timestamp\": 946681200\r\n}";
string json = JsonConvert.SerializeObject(exceptClass, Formatting.Indented);
Assert.AreEqual(exceptString, json);
var jsonClass = JsonConvert.DeserializeObject<TimestampConverterHelper>(exceptString);
Assert.AreEqual(exceptClass.Timestamp.ToLocalTime(), jsonClass.Timestamp.ToLocalTime());
}
#endregion
}
}
| |
using Gaming.Game;
using Gaming.Graphics;
using MatterHackers.Agg;
using MatterHackers.Agg.UI;
using MatterHackers.VectorMath;
using System;
using System.Diagnostics;
namespace RockBlaster
{
public class TimedInterpolator
{
private static Stopwatch runningTime = new Stopwatch();
public enum Repeate { NONE, LOOP, PINGPONG };
public enum InterpolationType { LINEAR, EASE_IN, EASE_OUT, EASE_IN_OUT };
private double timeStartedAt;
private double numSeconds;
private double startValue;
private double endValue;
private double distance;
private Repeate repeateType = Repeate.NONE;
private InterpolationType interpolationType = InterpolationType.LINEAR;
private bool haveStarted = false;
private bool done = false;
public TimedInterpolator()
{
if (!runningTime.IsRunning)
{
runningTime.Start();
}
}
public TimedInterpolator(double in_numSeconds, double in_startValue, double in_endValue, Repeate in_repeateType, InterpolationType in_interpolationType)
: this()
{
numSeconds = in_numSeconds;
startValue = in_startValue;
endValue = in_endValue;
distance = endValue - startValue;
repeateType = in_repeateType;
interpolationType = in_interpolationType;
}
public void Reset()
{
done = false;
haveStarted = false;
}
public double GetInterpolatedValue(double compleatedRatio0To1)
{
switch (interpolationType)
{
case InterpolationType.LINEAR:
return startValue + distance * compleatedRatio0To1;
case InterpolationType.EASE_IN:
return distance * Math.Pow(compleatedRatio0To1, 3) + startValue;
case InterpolationType.EASE_OUT:
return distance * (Math.Pow(compleatedRatio0To1 - 1, 3) + 1) + startValue;
case InterpolationType.EASE_IN_OUT:
if (compleatedRatio0To1 < .5)
{
return distance / 2 * Math.Pow(compleatedRatio0To1 * 2, 3) + startValue;
}
else
{
return distance / 2 * (Math.Pow(compleatedRatio0To1 * 2 - 2, 3) + 2) + startValue;
}
default:
throw new NotImplementedException();
}
}
public double Read()
{
if (done)
{
return endValue;
}
if (!haveStarted)
{
timeStartedAt = runningTime.Elapsed.TotalSeconds;
haveStarted = true;
}
double timePassed = runningTime.Elapsed.TotalSeconds - timeStartedAt;
double compleatedRatio = timePassed / numSeconds;
switch (repeateType)
{
case Repeate.NONE:
if (compleatedRatio > 1)
{
done = true;
return endValue;
}
return GetInterpolatedValue(compleatedRatio);
case Repeate.LOOP:
{
int compleatedRatioInt = (int)compleatedRatio;
compleatedRatio = compleatedRatio - compleatedRatioInt;
return GetInterpolatedValue(compleatedRatio);
}
case Repeate.PINGPONG:
{
int compleatedRatioInt = (int)compleatedRatio;
compleatedRatio = compleatedRatio - compleatedRatioInt;
if ((compleatedRatioInt & 1) == 1)
{
return GetInterpolatedValue(1 - compleatedRatio);
}
else
{
return GetInterpolatedValue(compleatedRatio);
}
}
default:
throw new NotImplementedException();
}
}
};
/// <summary>
/// Description of MainMenu.
/// </summary>
public class MainMenu : GuiWidget
{
public delegate void StartGameEventHandler(GuiWidget button);
public event StartGameEventHandler StartGame;
public delegate void ShowCreditsEventHandler(GuiWidget button);
public event ShowCreditsEventHandler ShowCredits;
public delegate void ExitGameEventHandler(GuiWidget button);
public event ExitGameEventHandler ExitGame;
private TimedInterpolator shipRatio = new TimedInterpolator(1, 1.0 / 8.0, 3.0 / 8.0, TimedInterpolator.Repeate.PINGPONG, TimedInterpolator.InterpolationType.EASE_IN_OUT);
private TimedInterpolator planetRatio = new TimedInterpolator(.5, 0, 1, TimedInterpolator.Repeate.LOOP, TimedInterpolator.InterpolationType.LINEAR);
public MainMenu(RectangleDouble bounds)
{
BoundsRelativeToParent = bounds;
ImageSequence startButtonSequence = (ImageSequence)DataAssetCache.Instance.GetAsset(typeof(ImageSequence), "MainMenuStartButton");
Button StartGameButton = new Button(400, 310, new ButtonViewThreeImage(startButtonSequence.GetImageByIndex(0), startButtonSequence.GetImageByIndex(1), startButtonSequence.GetImageByIndex(2)));
AddChild(StartGameButton);
StartGameButton.Click += OnStartGameButton;
ImageSequence creditsButtonSequence = (ImageSequence)DataAssetCache.Instance.GetAsset(typeof(ImageSequence), "MainMenuCreditsButton");
Button creditsGameButton = new Button(400, 230, new ButtonViewThreeImage(creditsButtonSequence.GetImageByIndex(0), creditsButtonSequence.GetImageByIndex(1), creditsButtonSequence.GetImageByIndex(2)));
AddChild(creditsGameButton);
creditsGameButton.Click += OnShowCreditsButton;
ImageSequence exitButtonSequence = (ImageSequence)DataAssetCache.Instance.GetAsset(typeof(ImageSequence), "MainMenuExitButton");
Button exitGameButton = new Button(400, 170, new ButtonViewThreeImage(exitButtonSequence.GetImageByIndex(0), exitButtonSequence.GetImageByIndex(1), exitButtonSequence.GetImageByIndex(2)));
AddChild(exitGameButton);
exitGameButton.Click += OnExitGameButton;
}
public override void OnDraw(Graphics2D graphics2D)
{
ImageSequence menuBackground = (ImageSequence)DataAssetCache.Instance.GetAsset(typeof(ImageSequence), "MainMenuBackground");
graphics2D.Render(menuBackground.GetImageByIndex(0), 0, 0);
ImageSequence planetOnMenu = (ImageSequence)DataAssetCache.Instance.GetAsset(typeof(ImageSequence), "PlanetOnMenu");
graphics2D.Render(planetOnMenu.GetImageByRatio(planetRatio.Read()), 620, 360);
ImageSequence shipOnMenu = (ImageSequence)DataAssetCache.Instance.GetAsset(typeof(ImageSequence), "Player1Ship");
int numFrames = shipOnMenu.NumFrames;
double animationRatio0to1 = shipRatio.Read();
double curFrameDouble = (numFrames - 1) * animationRatio0to1;
int curFrameInt = shipOnMenu.GetFrameIndexByRatio(animationRatio0to1);
double curFrameRemainder = curFrameDouble - curFrameInt;
double anglePerFrame = MathHelper.Tau / numFrames;
double angleForThisFrame = curFrameRemainder * anglePerFrame;
graphics2D.Render(shipOnMenu.GetImageByIndex(curFrameInt), 177, 156, angleForThisFrame, 1, 1);
base.OnDraw(graphics2D);
}
private void OnStartGameButton(object sender, EventArgs mouseEvent)
{
if (StartGame != null)
{
StartGame(this);
}
}
private void OnShowCreditsButton(object sender, EventArgs mouseEent)
{
if (ShowCredits != null)
{
ShowCredits(this);
}
}
private void OnExitGameButton(object sender, EventArgs mouseEvent)
{
if (ExitGame != null)
{
ExitGame(this);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NDesk.Options;
using GitTfs.Core;
using GitTfs.Util;
using GitTfs.Core.TfsInterop;
namespace GitTfs.Commands
{
public class InitBranch : GitTfsCommand
{
private readonly Globals _globals;
private readonly Help _helper;
private RemoteOptions _remoteOptions;
public string TfsUsername { get; set; }
public string TfsPassword { get; set; }
public string IgnoreRegex { get; set; }
public string ExceptRegex { get; set; }
public bool CloneAllBranches { get; set; }
public bool NoFetch { get; set; }
public bool DontCreateGitBranch { get; set; }
public IGitTfsRemote RemoteCreated { get; private set; }
public InitBranch(Globals globals, Help helper, AuthorsFile authors)
{
_globals = globals;
_helper = helper;
}
public OptionSet OptionSet
{
get
{
return new OptionSet
{
{ "all", "Clone all the TFS branches (For TFS 2010 and later)", v => CloneAllBranches = (v.ToLower() == "all") },
{ "u|username=", "TFS username", v => TfsUsername = v },
{ "p|password=", "TFS password", v => TfsPassword = v },
{ "ignore-regex=", "A regex of files to ignore", v => IgnoreRegex = v },
{ "except-regex=", "A regex of exceptions to ignore-regex", v => ExceptRegex = v},
{ "no-fetch", "Create the new TFS remote but don't fetch any changesets", v => NoFetch = (v != null) }
};
}
}
public int Run()
{
return Run(null, null);
}
public int Run(string tfsBranchPath)
{
return Run(tfsBranchPath, null);
}
public int Run(string tfsBranchPath, string gitBranchNameExpected)
{
if (!CloneAllBranches && tfsBranchPath == null)
{
_helper.Run(this);
return GitTfsExitCodes.Help;
}
if (CloneAllBranches)
{
return CloneAll(tfsBranchPath);
}
else
{
return CloneBranch(tfsBranchPath, gitBranchNameExpected);
}
}
private int CloneBranch(string tfsBranchPath, string gitBranchNameExpected)
{
var defaultRemote = InitFromDefaultRemote();
// TFS representations of repository paths do not have trailing slashes
tfsBranchPath = (tfsBranchPath ?? string.Empty).TrimEnd('/');
if (!tfsBranchPath.IsValidTfsPath())
{
var remotes = _globals.Repository.GetLastParentTfsCommits(tfsBranchPath);
if (!remotes.Any())
{
throw new Exception("error: No TFS branch found!");
}
tfsBranchPath = remotes.First().Remote.TfsRepositoryPath;
}
tfsBranchPath.AssertValidTfsPath();
var allRemotes = _globals.Repository.ReadAllTfsRemotes();
var remote = allRemotes.FirstOrDefault(r => r.TfsRepositoryPath.ToLower() == tfsBranchPath.ToLower());
if (remote != null && remote.MaxChangesetId != 0)
{
Trace.TraceInformation("warning : There is already a remote for this tfs branch. Branch ignored!");
return GitTfsExitCodes.InvalidArguments;
}
IList<RootBranch> creationBranchData = defaultRemote.Tfs.GetRootChangesetForBranch(tfsBranchPath);
IFetchResult fetchResult;
InitBranchSupportingRename(tfsBranchPath, gitBranchNameExpected, creationBranchData, defaultRemote, out fetchResult);
return GitTfsExitCodes.OK;
}
private IGitTfsRemote InitBranchSupportingRename(string tfsBranchPath, string gitBranchNameExpected, IList<RootBranch> creationBranchData, IGitTfsRemote defaultRemote, out IFetchResult fetchResult)
{
fetchResult = null;
RemoveAlreadyFetchedBranches(creationBranchData, defaultRemote);
Trace.TraceInformation("Branches to Initialize successively :");
foreach (var branch in creationBranchData)
Trace.TraceInformation("-" + branch.TfsBranchPath + " (" + branch.SourceBranchChangesetId + ")");
IGitTfsRemote branchTfsRemote = null;
var remoteToDelete = new List<IGitTfsRemote>();
foreach (var rootBranch in creationBranchData)
{
Trace.WriteLine("Processing " + (rootBranch.IsRenamedBranch ? "renamed " : string.Empty) + "branch :"
+ rootBranch.TfsBranchPath + " (" + rootBranch.SourceBranchChangesetId + ")");
var cbd = new BranchCreationDatas() { RootChangesetId = rootBranch.SourceBranchChangesetId, TfsRepositoryPath = rootBranch.TfsBranchPath };
if (cbd.TfsRepositoryPath == tfsBranchPath)
cbd.GitBranchNameExpected = gitBranchNameExpected;
branchTfsRemote = defaultRemote.InitBranch(_remoteOptions, cbd.TfsRepositoryPath, cbd.RootChangesetId, !NoFetch, cbd.GitBranchNameExpected, fetchResult);
if (branchTfsRemote == null)
{
throw new GitTfsException("error: Couldn't fetch parent branch\n");
}
// If this branch's branch point is past the first commit, indicate this so Fetch can start from that point
if (rootBranch.TargetBranchChangesetId > -1)
{
branchTfsRemote.SetFirstChangeset(rootBranch.TargetBranchChangesetId);
}
if (rootBranch.IsRenamedBranch || !NoFetch)
{
fetchResult = FetchRemote(branchTfsRemote, false, !DontCreateGitBranch && !rootBranch.IsRenamedBranch, fetchResult, rootBranch.TargetBranchChangesetId);
if (fetchResult.IsSuccess && rootBranch.IsRenamedBranch)
remoteToDelete.Add(branchTfsRemote);
}
else
Trace.WriteLine("Not fetching changesets, --no-fetch option specified");
}
foreach (var gitTfsRemote in remoteToDelete)
{
_globals.Repository.DeleteTfsRemote(gitTfsRemote);
}
return RemoteCreated = branchTfsRemote;
}
private static void RemoveAlreadyFetchedBranches(IList<RootBranch> creationBranchData, IGitTfsRemote defaultRemote)
{
for (int i = creationBranchData.Count - 1; i > 0; i--)
{
var branch = creationBranchData[i];
if (defaultRemote.Repository.FindCommitHashByChangesetId(branch.SourceBranchChangesetId) != null)
{
for (int j = 0; j < i; j++)
{
creationBranchData.RemoveAt(0);
}
break;
}
}
}
private class BranchCreationDatas
{
public string TfsRepositoryPath { get; set; }
public string GitBranchNameExpected { get; set; }
public int RootChangesetId { get; set; }
}
[DebuggerDisplay("{TfsRepositoryPath} C{RootChangesetId}")]
private class BranchDatas
{
public string TfsRepositoryPath { get; set; }
public IGitTfsRemote TfsRemote { get; set; }
public bool IsEntirelyFetched { get; set; }
public int RootChangesetId { get; set; }
public IList<RootBranch> CreationBranchData { get; set; }
public Exception Error { get; set; }
}
private int CloneAll(string gitRemote)
{
if (CloneAllBranches && NoFetch)
throw new GitTfsException("error: --no-fetch cannot be used with --all");
_globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, false);
var defaultRemote = InitFromDefaultRemote();
List<BranchDatas> childBranchesToInit;
if (gitRemote == null)
{
childBranchesToInit = GetChildBranchesToInit(defaultRemote);
}
else
{
var gitRepositoryBranchRemotes = defaultRemote.Repository.GetGitRemoteBranches(gitRemote);
var childBranchPaths = new Dictionary<string, BranchDatas>();
foreach (var branchRemote in gitRepositoryBranchRemotes)
{
var branchRemoteChangesetInfos = _globals.Repository.GetLastParentTfsCommits(branchRemote);
var firstRemoteChangesetInfo = branchRemoteChangesetInfos.FirstOrDefault();
if (firstRemoteChangesetInfo == null)
{
continue;
}
var branchRemoteTfsPath = firstRemoteChangesetInfo.Remote.TfsRepositoryPath;
if (!childBranchPaths.ContainsKey(branchRemoteTfsPath))
childBranchPaths.Add(branchRemoteTfsPath, new BranchDatas { TfsRepositoryPath = branchRemoteTfsPath });
}
childBranchesToInit = childBranchPaths.Values.ToList();
}
if (!childBranchesToInit.Any())
{
Trace.TraceInformation("No other Tfs branches found.");
}
else
{
return InitializeBranches(defaultRemote, childBranchesToInit) ? GitTfsExitCodes.OK : GitTfsExitCodes.SomeDataCouldNotHaveBeenRetrieved;
}
return GitTfsExitCodes.OK;
}
private static List<BranchDatas> GetChildBranchesToInit(IGitTfsRemote defaultRemote)
{
var rootBranch = defaultRemote.Tfs.GetRootTfsBranchForRemotePath(defaultRemote.TfsRepositoryPath);
if (rootBranch == null)
throw new GitTfsException("error: The use of the option '--branches=all' to init all the branches is only possible when 'git tfs clone' was done from the trunk!!! '"
+ defaultRemote.TfsRepositoryPath + "' is not a TFS branch!");
return rootBranch.GetAllChildrenOfBranch(defaultRemote.TfsRepositoryPath).Select(b => new BranchDatas { TfsRepositoryPath = b.Path }).ToList();
}
private bool InitializeBranches(IGitTfsRemote defaultRemote, List<BranchDatas> childBranchPaths)
{
Trace.TraceInformation("Tfs branches found:");
var branchesToProcess = new List<BranchDatas>();
foreach (var childBranchPath in childBranchPaths)
{
Trace.TraceInformation("- " + childBranchPath.TfsRepositoryPath);
var branchDatas = new BranchDatas
{
TfsRepositoryPath = childBranchPath.TfsRepositoryPath,
TfsRemote = _globals.Repository.ReadAllTfsRemotes().FirstOrDefault(r => r.TfsRepositoryPath == childBranchPath.TfsRepositoryPath)
};
try
{
branchDatas.CreationBranchData = defaultRemote.Tfs.GetRootChangesetForBranch(childBranchPath.TfsRepositoryPath);
}
catch (Exception ex)
{
branchDatas.Error = ex;
}
branchesToProcess.Add(branchDatas);
}
branchesToProcess.Add(new BranchDatas { TfsRepositoryPath = defaultRemote.TfsRepositoryPath, TfsRemote = defaultRemote, RootChangesetId = -1 });
bool isSomethingDone;
do
{
isSomethingDone = false;
var branchesToFetch = branchesToProcess.Where(b => !b.IsEntirelyFetched && b.Error == null).ToList();
foreach (var tfsBranch in branchesToFetch)
{
Trace.TraceInformation("=> Working on TFS branch : " + tfsBranch.TfsRepositoryPath);
if (tfsBranch.TfsRemote == null || tfsBranch.TfsRemote.MaxChangesetId == 0)
{
try
{
IFetchResult fetchResult;
tfsBranch.TfsRemote = InitBranchSupportingRename(tfsBranch.TfsRepositoryPath, null, tfsBranch.CreationBranchData, defaultRemote,
out fetchResult);
if (tfsBranch.TfsRemote != null)
{
tfsBranch.IsEntirelyFetched = fetchResult.IsSuccess;
isSomethingDone = true;
}
}
catch (Exception ex)
{
Trace.TraceInformation("error: an error occurs when initializing the branch. Branch is ignored and continuing...");
tfsBranch.Error = ex;
}
}
else
{
try
{
var lastFetchedChangesetId = tfsBranch.TfsRemote.MaxChangesetId;
Trace.WriteLine("Fetching remote :" + tfsBranch.TfsRemote.Id);
var fetchResult = FetchRemote(tfsBranch.TfsRemote, true);
tfsBranch.IsEntirelyFetched = fetchResult.IsSuccess;
if (fetchResult.NewChangesetCount != 0)
isSomethingDone = true;
}
catch (Exception ex)
{
Trace.TraceInformation("error: an error occurs when fetching changeset. Fetching is stopped and continuing...");
tfsBranch.Error = ex;
}
}
}
} while (branchesToProcess.Any(b => !b.IsEntirelyFetched && b.Error == null) && isSomethingDone);
_globals.Repository.GarbageCollect();
bool success = true;
if (branchesToProcess.Any(b => !b.IsEntirelyFetched))
{
success = false;
Trace.TraceWarning("warning: Some Tfs branches could not have been initialized:");
foreach (var branchNotInited in branchesToProcess.Where(b => !b.IsEntirelyFetched))
{
Trace.TraceInformation("- " + branchNotInited.TfsRepositoryPath);
}
Trace.TraceInformation("\nPlease report this case to the git-tfs developers! (report here : https://github.com/git-tfs/git-tfs/issues/461 )");
}
if (branchesToProcess.Any(b => b.Error != null))
{
success = false;
Trace.TraceWarning("warning: Some Tfs branches could not have been initialized or entirely fetched due to errors:");
foreach (var branchWithErrors in branchesToProcess.Where(b => b.Error != null))
{
Trace.TraceInformation("- " + branchWithErrors.TfsRepositoryPath);
if (_globals.DebugOutput)
Trace.WriteLine(" =>error:" + branchWithErrors.Error);
else
Trace.TraceInformation(" =>error:" + branchWithErrors.Error.Message);
}
Trace.TraceInformation("\nPlease report this case to the git-tfs developers! (report here : https://github.com/git-tfs/git-tfs/issues )");
return false;
}
return success;
}
private IGitTfsRemote InitFromDefaultRemote()
{
IGitTfsRemote defaultRemote;
if (_globals.Repository.HasRemote(GitTfsConstants.DefaultRepositoryId))
defaultRemote = _globals.Repository.ReadTfsRemote(GitTfsConstants.DefaultRepositoryId);
else
defaultRemote = _globals.Repository.ReadAllTfsRemotes()
.Where(x => x != null && x.RemoteInfo != null && !string.IsNullOrEmpty(x.RemoteInfo.Url))
.OrderBy(x => x.RemoteInfo.Url.Length).FirstOrDefault();
if (defaultRemote == null)
throw new GitTfsException("error: No git-tfs repository found. Please try to clone first...\n");
_remoteOptions = new RemoteOptions();
if (!string.IsNullOrWhiteSpace(TfsUsername))
{
_remoteOptions.Username = TfsUsername;
_remoteOptions.Password = TfsPassword;
}
else
{
_remoteOptions.Username = defaultRemote.TfsUsername;
_remoteOptions.Password = defaultRemote.TfsPassword;
}
if (IgnoreRegex != null)
_remoteOptions.IgnoreRegex = IgnoreRegex;
else
_remoteOptions.IgnoreRegex = defaultRemote.IgnoreRegexExpression;
if (ExceptRegex != null)
_remoteOptions.ExceptRegex = ExceptRegex;
else
_remoteOptions.ExceptRegex = defaultRemote.IgnoreExceptRegexExpression;
return defaultRemote;
}
/// <summary>
/// Fetch changesets from <paramref name="tfsRemote"/>, optionally stopping on failed merge commits.
/// </summary>
/// <param name="tfsRemote">The TFS Remote from which to fetch changesets.</param>
/// <param name="stopOnFailMergeCommit">
/// Indicates whether to stop fetching when encountering a failed merge commit.
/// </param>
/// <param name="createBranch">
/// If <c>true</c>, create a local Git branch starting from the earliest possible changeset in the given
/// <paramref name="tfsRemote"/>.
/// </param>
/// <param name="renameResult"></param>
/// <param name="startingChangesetId"></param>
/// <returns>A <see cref="IFetchResult"/>.</returns>
private IFetchResult FetchRemote(IGitTfsRemote tfsRemote, bool stopOnFailMergeCommit, bool createBranch = true, IRenameResult renameResult = null, int startingChangesetId = -1)
{
try
{
Trace.WriteLine("Try fetching changesets...");
var fetchResult = tfsRemote.Fetch(stopOnFailMergeCommit, renameResult: renameResult);
Trace.WriteLine("Changesets fetched!");
if (fetchResult.IsSuccess && createBranch && tfsRemote.Id != GitTfsConstants.DefaultRepositoryId)
{
Trace.WriteLine("Try creating the local branch...");
var branchRef = tfsRemote.Id.ToLocalGitRef();
if (!_globals.Repository.HasRef(branchRef))
{
if (!_globals.Repository.CreateBranch(branchRef, tfsRemote.MaxCommitHash))
Trace.TraceWarning("warning: Fail to create local branch ref file!");
else
Trace.WriteLine("Local branch created!");
}
else
{
Trace.TraceInformation("info: local branch ref already exists!");
}
}
return fetchResult;
}
finally
{
Trace.WriteLine("Cleaning...");
tfsRemote.CleanupWorkspaceDirectory();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Description;
using FunBookMobile.Cloud.WebApi.Areas.HelpPage.ModelDescriptions;
using FunBookMobile.Cloud.WebApi.Areas.HelpPage.Models;
namespace FunBookMobile.Cloud.WebApi.Areas.HelpPage
{
public static class HelpPageConfigurationExtensions
{
private const string ApiModelPrefix = "MS_HelpPageApiModel_";
/// <summary>
/// Sets the documentation provider for help page.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="documentationProvider">The documentation provider.</param>
public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider)
{
config.Services.Replace(typeof(IDocumentationProvider), documentationProvider);
}
/// <summary>
/// Sets the objects that will be used by the formatters to produce sample requests/responses.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleObjects">The sample objects.</param>
public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects)
{
config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects;
}
/// <summary>
/// Sets the sample request directly for the specified media type and action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type and action with parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample request.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample request directly for the specified media type of the action.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample);
}
/// <summary>
/// Sets the sample response directly for the specified media type of the action with specific parameters.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample response.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample);
}
/// <summary>
/// Sets the sample directly for all actions with the specified type and media type.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sample">The sample.</param>
/// <param name="mediaType">The media type.</param>
/// <param name="type">The parameter type or return type of an action.</param>
public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type)
{
config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate request samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type);
}
/// <summary>
/// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action.
/// The help page will use this information to produce more accurate response samples.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="type">The type.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="parameterNames">The parameter names.</param>
public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames)
{
config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type);
}
/// <summary>
/// Gets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <returns>The help page sample generator.</returns>
public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config)
{
return (HelpPageSampleGenerator)config.Properties.GetOrAdd(
typeof(HelpPageSampleGenerator),
k => new HelpPageSampleGenerator());
}
/// <summary>
/// Sets the help page sample generator.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="sampleGenerator">The help page sample generator.</param>
public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator)
{
config.Properties.AddOrUpdate(
typeof(HelpPageSampleGenerator),
k => sampleGenerator,
(k, o) => sampleGenerator);
}
/// <summary>
/// Gets the model description generator.
/// </summary>
/// <param name="config">The configuration.</param>
/// <returns>The <see cref="ModelDescriptionGenerator"/></returns>
public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config)
{
return (ModelDescriptionGenerator)config.Properties.GetOrAdd(
typeof(ModelDescriptionGenerator),
k => InitializeModelDescriptionGenerator(config));
}
/// <summary>
/// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls.
/// </summary>
/// <param name="config">The <see cref="HttpConfiguration"/>.</param>
/// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param>
/// <returns>
/// An <see cref="HelpPageApiModel"/>
/// </returns>
public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId)
{
object model;
string modelId = ApiModelPrefix + apiDescriptionId;
if (!config.Properties.TryGetValue(modelId, out model))
{
Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions;
ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase));
if (apiDescription != null)
{
model = GenerateApiModel(apiDescription, config);
config.Properties.TryAdd(modelId, model);
}
}
return (HelpPageApiModel)model;
}
private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config)
{
HelpPageApiModel apiModel = new HelpPageApiModel()
{
ApiDescription = apiDescription,
};
ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator();
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
GenerateUriParameters(apiModel, modelGenerator);
GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator);
GenerateResourceDescription(apiModel, modelGenerator);
GenerateSamples(apiModel, sampleGenerator);
return apiModel;
}
private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromUri)
{
HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor;
Type parameterType = null;
ModelDescription typeDescription = null;
ComplexTypeModelDescription complexTypeDescription = null;
if (parameterDescriptor != null)
{
parameterType = parameterDescriptor.ParameterType;
typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
complexTypeDescription = typeDescription as ComplexTypeModelDescription;
}
// Example:
// [TypeConverter(typeof(PointConverter))]
// public class Point
// {
// public Point(int x, int y)
// {
// X = x;
// Y = y;
// }
// public int X { get; set; }
// public int Y { get; set; }
// }
// Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection.
//
// public class Point
// {
// public int X { get; set; }
// public int Y { get; set; }
// }
// Regular complex class Point will have properties X and Y added to UriParameters collection.
if (complexTypeDescription != null
&& !IsBindableWithTypeConverter(parameterType))
{
foreach (ParameterDescription uriParameter in complexTypeDescription.Properties)
{
apiModel.UriParameters.Add(uriParameter);
}
}
else if (parameterDescriptor != null)
{
ParameterDescription uriParameter =
AddParameterDescription(apiModel, apiParameter, typeDescription);
if (!parameterDescriptor.IsOptional)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" });
}
object defaultValue = parameterDescriptor.DefaultValue;
if (defaultValue != null)
{
uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) });
}
}
else
{
Debug.Assert(parameterDescriptor == null);
// If parameterDescriptor is null, this is an undeclared route parameter which only occurs
// when source is FromUri. Ignored in request model and among resource parameters but listed
// as a simple string here.
ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string));
AddParameterDescription(apiModel, apiParameter, modelDescription);
}
}
}
}
private static bool IsBindableWithTypeConverter(Type parameterType)
{
if (parameterType == null)
{
return false;
}
return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string));
}
private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel,
ApiParameterDescription apiParameter, ModelDescription typeDescription)
{
ParameterDescription parameterDescription = new ParameterDescription
{
Name = apiParameter.Name,
Documentation = apiParameter.Documentation,
TypeDescription = typeDescription,
};
apiModel.UriParameters.Add(parameterDescription);
return parameterDescription;
}
private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator)
{
ApiDescription apiDescription = apiModel.ApiDescription;
foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions)
{
if (apiParameter.Source == ApiParameterSource.FromBody)
{
Type parameterType = apiParameter.ParameterDescriptor.ParameterType;
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
apiModel.RequestDocumentation = apiParameter.Documentation;
}
else if (apiParameter.ParameterDescriptor != null &&
apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))
{
Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
if (parameterType != null)
{
apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
}
}
private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator)
{
ResponseDescription response = apiModel.ApiDescription.ResponseDescription;
Type responseType = response.ResponseType ?? response.DeclaredType;
if (responseType != null && responseType != typeof(void))
{
apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType);
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")]
private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator)
{
try
{
foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription))
{
apiModel.SampleRequests.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription))
{
apiModel.SampleResponses.Add(item.Key, item.Value);
LogInvalidSampleAsError(apiModel, item.Value);
}
}
catch (Exception e)
{
apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture,
"An exception has occurred while generating the sample. Exception message: {0}",
HelpPageSampleGenerator.UnwrapException(e).Message));
}
}
private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType)
{
parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault(
p => p.Source == ApiParameterSource.FromBody ||
(p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)));
if (parameterDescription == null)
{
resourceType = null;
return false;
}
resourceType = parameterDescription.ParameterDescriptor.ParameterType;
if (resourceType == typeof(HttpRequestMessage))
{
HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator();
resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription);
}
if (resourceType == null)
{
parameterDescription = null;
return false;
}
return true;
}
private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config)
{
ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config);
Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions;
foreach (ApiDescription api in apis)
{
ApiParameterDescription parameterDescription;
Type parameterType;
if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType))
{
modelGenerator.GetOrCreateModelDescription(parameterType);
}
}
return modelGenerator;
}
private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample)
{
InvalidSample invalidSample = sample as InvalidSample;
if (invalidSample != null)
{
apiModel.ErrorMessages.Add(invalidSample.ErrorMessage);
}
}
}
}
| |
// 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.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.API;
using osu.Game.Online.Rooms;
using osu.Game.Scoring;
using osu.Game.Screens.Ranking;
namespace osu.Game.Screens.OnlinePlay.Playlists
{
public class PlaylistsResultsScreen : ResultsScreen
{
private readonly long roomId;
private readonly PlaylistItem playlistItem;
protected LoadingSpinner LeftSpinner { get; private set; }
protected LoadingSpinner CentreSpinner { get; private set; }
protected LoadingSpinner RightSpinner { get; private set; }
private MultiplayerScores higherScores;
private MultiplayerScores lowerScores;
[Resolved]
private IAPIProvider api { get; set; }
[Resolved]
private ScoreManager scoreManager { get; set; }
public PlaylistsResultsScreen(ScoreInfo score, long roomId, PlaylistItem playlistItem, bool allowRetry, bool allowWatchingReplay = true)
: base(score, allowRetry, allowWatchingReplay)
{
this.roomId = roomId;
this.playlistItem = playlistItem;
}
[BackgroundDependencyLoader]
private void load()
{
AddInternal(new Container
{
RelativeSizeAxes = Axes.Both,
Padding = new MarginPadding { Bottom = TwoLayerButton.SIZE_EXTENDED.Y },
Children = new Drawable[]
{
LeftSpinner = new PanelListLoadingSpinner(ScorePanelList)
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.Centre,
},
CentreSpinner = new PanelListLoadingSpinner(ScorePanelList)
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
State = { Value = Score == null ? Visibility.Visible : Visibility.Hidden },
},
RightSpinner = new PanelListLoadingSpinner(ScorePanelList)
{
Anchor = Anchor.CentreRight,
Origin = Anchor.Centre,
},
}
});
}
protected override APIRequest FetchScores(Action<IEnumerable<ScoreInfo>> scoresCallback)
{
// This performs two requests:
// 1. A request to show the user's score (and scores around).
// 2. If that fails, a request to index the room starting from the highest score.
var userScoreReq = new ShowPlaylistUserScoreRequest(roomId, playlistItem.ID, api.LocalUser.Value.Id);
userScoreReq.Success += userScore =>
{
var allScores = new List<MultiplayerScore> { userScore };
if (userScore.ScoresAround?.Higher != null)
{
allScores.AddRange(userScore.ScoresAround.Higher.Scores);
higherScores = userScore.ScoresAround.Higher;
Debug.Assert(userScore.Position != null);
setPositions(higherScores, userScore.Position.Value, -1);
}
if (userScore.ScoresAround?.Lower != null)
{
allScores.AddRange(userScore.ScoresAround.Lower.Scores);
lowerScores = userScore.ScoresAround.Lower;
Debug.Assert(userScore.Position != null);
setPositions(lowerScores, userScore.Position.Value, 1);
}
performSuccessCallback(scoresCallback, allScores);
};
// On failure, fallback to a normal index.
userScoreReq.Failure += _ => api.Queue(createIndexRequest(scoresCallback));
return userScoreReq;
}
protected override APIRequest FetchNextPage(int direction, Action<IEnumerable<ScoreInfo>> scoresCallback)
{
Debug.Assert(direction == 1 || direction == -1);
MultiplayerScores pivot = direction == -1 ? higherScores : lowerScores;
if (pivot?.Cursor == null)
return null;
if (pivot == higherScores)
LeftSpinner.Show();
else
RightSpinner.Show();
return createIndexRequest(scoresCallback, pivot);
}
/// <summary>
/// Creates a <see cref="IndexPlaylistScoresRequest"/> with an optional score pivot.
/// </summary>
/// <remarks>Does not queue the request.</remarks>
/// <param name="scoresCallback">The callback to perform with the resulting scores.</param>
/// <param name="pivot">An optional score pivot to retrieve scores around. Can be null to retrieve scores from the highest score.</param>
/// <returns>The indexing <see cref="APIRequest"/>.</returns>
private APIRequest createIndexRequest(Action<IEnumerable<ScoreInfo>> scoresCallback, [CanBeNull] MultiplayerScores pivot = null)
{
var indexReq = pivot != null
? new IndexPlaylistScoresRequest(roomId, playlistItem.ID, pivot.Cursor, pivot.Params)
: new IndexPlaylistScoresRequest(roomId, playlistItem.ID);
indexReq.Success += r =>
{
if (pivot == lowerScores)
{
lowerScores = r;
setPositions(r, pivot, 1);
}
else
{
higherScores = r;
setPositions(r, pivot, -1);
}
performSuccessCallback(scoresCallback, r.Scores, r);
};
indexReq.Failure += _ => hideLoadingSpinners(pivot);
return indexReq;
}
/// <summary>
/// Transforms returned <see cref="MultiplayerScores"/> into <see cref="ScoreInfo"/>s, ensure the <see cref="ScorePanelList"/> is put into a sane state, and invokes a given success callback.
/// </summary>
/// <param name="callback">The callback to invoke with the final <see cref="ScoreInfo"/>s.</param>
/// <param name="scores">The <see cref="MultiplayerScore"/>s that were retrieved from <see cref="APIRequest"/>s.</param>
/// <param name="pivot">An optional pivot around which the scores were retrieved.</param>
private void performSuccessCallback([NotNull] Action<IEnumerable<ScoreInfo>> callback, [NotNull] List<MultiplayerScore> scores, [CanBeNull] MultiplayerScores pivot = null)
{
var scoreInfos = scores.Select(s => s.CreateScoreInfo(playlistItem)).ToArray();
// Score panels calculate total score before displaying, which can take some time. In order to count that calculation as part of the loading spinner display duration,
// calculate the total scores locally before invoking the success callback.
scoreManager.OrderByTotalScoreAsync(scoreInfos).ContinueWith(_ => Schedule(() =>
{
// Select a score if we don't already have one selected.
// Note: This is done before the callback so that the panel list centres on the selected score before panels are added (eliminating initial scroll).
if (SelectedScore.Value == null)
{
Schedule(() =>
{
// Prefer selecting the local user's score, or otherwise default to the first visible score.
SelectedScore.Value = scoreInfos.FirstOrDefault(s => s.User.Id == api.LocalUser.Value.Id) ?? scoreInfos.FirstOrDefault();
});
}
// Invoke callback to add the scores. Exclude the user's current score which was added previously.
callback.Invoke(scoreInfos.Where(s => s.OnlineScoreID != Score?.OnlineScoreID));
hideLoadingSpinners(pivot);
}));
}
private void hideLoadingSpinners([CanBeNull] MultiplayerScores pivot = null)
{
CentreSpinner.Hide();
if (pivot == lowerScores)
RightSpinner.Hide();
else if (pivot == higherScores)
LeftSpinner.Hide();
}
/// <summary>
/// Applies positions to all <see cref="MultiplayerScore"/>s referenced to a given pivot.
/// </summary>
/// <param name="scores">The <see cref="MultiplayerScores"/> to set positions on.</param>
/// <param name="pivot">The pivot.</param>
/// <param name="increment">The amount to increment the pivot position by for each <see cref="MultiplayerScore"/> in <paramref name="scores"/>.</param>
private void setPositions([NotNull] MultiplayerScores scores, [CanBeNull] MultiplayerScores pivot, int increment)
=> setPositions(scores, pivot?.Scores[^1].Position ?? 0, increment);
/// <summary>
/// Applies positions to all <see cref="MultiplayerScore"/>s referenced to a given pivot.
/// </summary>
/// <param name="scores">The <see cref="MultiplayerScores"/> to set positions on.</param>
/// <param name="pivotPosition">The pivot position.</param>
/// <param name="increment">The amount to increment the pivot position by for each <see cref="MultiplayerScore"/> in <paramref name="scores"/>.</param>
private void setPositions([NotNull] MultiplayerScores scores, int pivotPosition, int increment)
{
foreach (var s in scores.Scores)
{
pivotPosition += increment;
s.Position = pivotPosition;
}
}
private class PanelListLoadingSpinner : LoadingSpinner
{
private readonly ScorePanelList list;
/// <summary>
/// Creates a new <see cref="PanelListLoadingSpinner"/>.
/// </summary>
/// <param name="list">The list to track.</param>
/// <param name="withBox">Whether the spinner should have a surrounding black box for visibility.</param>
public PanelListLoadingSpinner(ScorePanelList list, bool withBox = true)
: base(withBox)
{
this.list = list;
}
protected override void Update()
{
base.Update();
float panelOffset = list.DrawWidth / 2 - ScorePanel.EXPANDED_WIDTH;
if ((Anchor & Anchor.x0) > 0)
X = (float)(panelOffset - list.Current);
else if ((Anchor & Anchor.x2) > 0)
X = (float)(list.ScrollableExtent - list.Current - panelOffset);
}
}
}
}
| |
// ReSharper disable All
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Frapid.ApplicationState.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Frapid.Account.DataAccess;
using Frapid.Account.Api.Fakes;
using Frapid.DataAccess;
using Frapid.DataAccess.Models;
using Xunit;
namespace Frapid.Account.Api.Tests
{
public class FbAccessTokenTests
{
public static FbAccessTokenController Fixture()
{
FbAccessTokenController controller = new FbAccessTokenController(new FbAccessTokenRepository());
return controller;
}
[Fact]
[Conditional("Debug")]
public void CountEntityColumns()
{
EntityView entityView = Fixture().GetEntityView();
Assert.Null(entityView.Columns);
}
[Fact]
[Conditional("Debug")]
public void Count()
{
long count = Fixture().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetAll()
{
int count = Fixture().GetAll().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Export()
{
int count = Fixture().Export().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void Get()
{
Frapid.Account.Entities.FbAccessToken fbAccessToken = Fixture().Get(0);
Assert.NotNull(fbAccessToken);
}
[Fact]
[Conditional("Debug")]
public void First()
{
Frapid.Account.Entities.FbAccessToken fbAccessToken = Fixture().GetFirst();
Assert.NotNull(fbAccessToken);
}
[Fact]
[Conditional("Debug")]
public void Previous()
{
Frapid.Account.Entities.FbAccessToken fbAccessToken = Fixture().GetPrevious(0);
Assert.NotNull(fbAccessToken);
}
[Fact]
[Conditional("Debug")]
public void Next()
{
Frapid.Account.Entities.FbAccessToken fbAccessToken = Fixture().GetNext(0);
Assert.NotNull(fbAccessToken);
}
[Fact]
[Conditional("Debug")]
public void Last()
{
Frapid.Account.Entities.FbAccessToken fbAccessToken = Fixture().GetLast();
Assert.NotNull(fbAccessToken);
}
[Fact]
[Conditional("Debug")]
public void GetMultiple()
{
IEnumerable<Frapid.Account.Entities.FbAccessToken> fbAccessTokens = Fixture().Get(new int[] { });
Assert.NotNull(fbAccessTokens);
}
[Fact]
[Conditional("Debug")]
public void GetPaginatedResult()
{
int count = Fixture().GetPaginatedResult().Count();
Assert.Equal(1, count);
count = Fixture().GetPaginatedResult(1).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountWhere()
{
long count = Fixture().CountWhere(new JArray());
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetWhere()
{
int count = Fixture().GetWhere(1, new JArray()).Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void CountFiltered()
{
long count = Fixture().CountFiltered("");
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetFiltered()
{
int count = Fixture().GetFiltered(1, "").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetDisplayFields()
{
int count = Fixture().GetDisplayFields().Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void GetCustomFields()
{
int count = Fixture().GetCustomFields().Count();
Assert.Equal(1, count);
count = Fixture().GetCustomFields("").Count();
Assert.Equal(1, count);
}
[Fact]
[Conditional("Debug")]
public void AddOrEdit()
{
try
{
var form = new JArray { null, null };
Fixture().AddOrEdit(form);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Add()
{
try
{
Fixture().Add(null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void Edit()
{
try
{
Fixture().Edit(0, null);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.MethodNotAllowed, ex.Response.StatusCode);
}
}
[Fact]
[Conditional("Debug")]
public void BulkImport()
{
var collection = new JArray { null, null, null, null };
var actual = Fixture().BulkImport(collection);
Assert.NotNull(actual);
}
[Fact]
[Conditional("Debug")]
public void Delete()
{
try
{
Fixture().Delete(0);
}
catch (HttpResponseException ex)
{
Assert.Equal(HttpStatusCode.InternalServerError, ex.Response.StatusCode);
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using MGTK.Services;
namespace MGTK.Controls
{
public class NumericUpDown : Control
{
protected InnerTextBox innerTextBox;
protected Button btnUp;
protected Button btnDown;
private decimal _value = 0;
private decimal increment = 1;
private decimal maximum = 100;
private decimal minimum = 0;
private int MsToNextIndex = 150;
private double TotalMilliseconds = 0;
private string previousText;
public decimal Maximum
{
get
{
return maximum;
}
set
{
if (maximum != value)
{
maximum = value;
CheckValueBoundaries();
}
}
}
public decimal Minimum
{
get
{
return minimum;
}
set
{
if (minimum != value)
{
minimum = value;
CheckValueBoundaries();
}
}
}
public decimal Increment
{
get
{
return increment;
}
set
{
if (increment != value)
increment = value;
}
}
public decimal Value
{
get
{
return _value;
}
set
{
if (_value != value)
{
_value = value;
CheckValueBoundaries();
if (ValueChanged != null)
ValueChanged(this, new EventArgs());
UpdateTextBox();
}
}
}
public event EventHandler ValueChanged;
public NumericUpDown(Form formowner)
: base(formowner)
{
btnUp = new Button(formowner);
btnDown = new Button(formowner);
innerTextBox = new InnerTextBox(formowner);
btnUp.Parent = btnDown.Parent = innerTextBox.Parent = this;
innerTextBox.MultiLine = false;
btnUp.Image = Theme.NumericUpDownUpButton;
btnDown.Image = Theme.NumericUpDownDownButton;
btnUp.MouseLeftDown += new EventHandler(btn_MouseLeftDown);
btnDown.MouseLeftDown += new EventHandler(btn_MouseLeftDown);
btnUp.MouseLeftPressed += new EventHandler(btn_MouseLeftPressed);
btnDown.MouseLeftPressed += new EventHandler(btn_MouseLeftPressed);
this.Controls.AddRange(new Control[] { btnUp, btnDown, innerTextBox });
this.Init += new EventHandler(NumericUpDown_Init);
innerTextBox.TextChanged += new EventHandler(innerTextBox_TextChanged);
}
void innerTextBox_TextChanged(object sender, EventArgs e)
{
string t = innerTextBox.Text.Replace(Environment.NewLine, "");
if (previousText != t)
{
if (t.Trim().Length > 0)
{
if (!Regex.Match(t, @"^[-+]?\d+(,\d+)?$").Success)
UpdateTextBox();
else
Value = Convert.ToDecimal(t);
}
previousText = t;
}
}
void btn_MouseLeftPressed(object sender, EventArgs e)
{
(sender as Button).Tag = (double)0;
}
private void UpdateTextBox()
{
innerTextBox.Text = Value.ToString();
}
private void CheckValueBoundaries()
{
if (Value > Maximum) Value = Maximum;
if (Value < Minimum) Value = Minimum;
}
void btn_MouseLeftDown(object sender, EventArgs e)
{
Button btn = (sender as Button);
if (TotalMilliseconds - (double)btn.Tag > MsToNextIndex)
{
Value += Increment * (sender == btnDown ? -1 : 1);
btn.Tag = TotalMilliseconds;
}
}
void NumericUpDown_Init(object sender, EventArgs e)
{
ConfigureCoordinatesAndSizes();
UpdateTextBox();
}
public override void Draw()
{
DrawingService.DrawFrame(SpriteBatchProvider, Theme.NumericUpDownFrame, OwnerX + X, OwnerY + Y,
Width, Height, Z - 0.001f);
base.Draw();
}
public override void Update()
{
TotalMilliseconds = gameTime.TotalGameTime.TotalMilliseconds;
btnUp.Z = Z - 0.0015f;
btnDown.Z = Z - 0.0015f;
base.Update();
}
private void ConfigureCoordinatesAndSizes()
{
btnUp.Y = 2;
btnUp.Height = (Height - 4) / 2;
btnUp.Width = btnUp.Height * 2;
btnUp.X = Width - btnUp.Width - 2;
btnUp.Anchor = AnchorStyles.Right;
btnDown.Y = 2 + btnUp.Height;
btnDown.Height = (Height - 4) / 2;
btnDown.Width = btnDown.Height * 2;
btnDown.X = Width - btnDown.Width - 2;
btnDown.Anchor = AnchorStyles.Right;
innerTextBox.Y = 2;
innerTextBox.X = 2;
innerTextBox.Width = Width - btnUp.Width - 2 - 3;
innerTextBox.Height = Height - 4;
innerTextBox.Anchor = AnchorStyles.Right | AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Bottom;
}
}
}
| |
using Aspose.Slides.Web.API.Clients.DTO.Response;
using Aspose.Slides.Web.API.Clients.Enums;
using Aspose.Slides.Web.API.Models;
using Aspose.Slides.Web.Interfaces.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
namespace Aspose.Slides.Web.API.Controllers
{
/// <summary>
/// Common API controller.
/// </summary>
[ApiController]
public sealed class CommonController : ControllerBase
{
private const int StartingFileIndex = 1;
private const int MaxFileIndex = 999;
private readonly ILogger _logger;
private readonly IFileValidatorService _fileValidatorService;
private readonly ISourceStorage _sourceStorage;
private readonly IProcessedStorage _processedStorage;
private readonly ITemporaryStorage _temporaryStorage;
private readonly IFileStreamProvider _fileStreamProvider;
/// <summary>
/// Constructor
/// </summary>
/// <param name="logger"></param>
/// <param name="fileValidatorService">File validator instance.</param>
/// <param name="sourceStorage">Source cloud storage instance.</param>
/// <param name="processedStorage">Processed cloud storage instance.</param>
/// <param name="temporaryStorage">Temporary storage instance.</param>
/// <param name="fileStreamProvider">File stream provider instance.</param>
public CommonController(
ILogger<CommonController> logger,
IFileValidatorService fileValidatorService,
ISourceStorage sourceStorage,
IProcessedStorage processedStorage,
ITemporaryStorage temporaryStorage,
IFileStreamProvider fileStreamProvider)
{
_logger = logger;
_fileValidatorService = fileValidatorService;
_sourceStorage = sourceStorage;
_processedStorage = processedStorage;
_temporaryStorage = temporaryStorage;
_fileStreamProvider = fileStreamProvider;
}
/// <summary>
/// Uploads files.
/// Returns collection of upload id and filename.
/// </summary>
/// <returns>Files upload results.</returns>
[HttpPost]
[Route("api/common/UploadFiles")]
public async Task<IEnumerable<FileSafeResult>> UploadFiles(
[FromForm] UploadRequest request,
#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
CancellationToken cancellationToken = default
#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
)
{
try
{
using var inputFolder = _temporaryStorage.GetTemporaryFolder();
var tasks = request.UploadFileInput.Select(
async file =>
{
await using var stream = file.OpenReadStream();
await inputFolder.SaveAsync(stream, file.FileName, cancellationToken);
}
);
await Task.WhenAll(tasks);
var idUpload = request.idUpload;
var skipped = new List<string>();
var filteredFiles = await FilterFolderAsync(inputFolder.ToString(), skipped, cancellationToken);
var uploaded = await UploadFolderAsync(idUpload, filteredFiles, cancellationToken);
_logger.LogInformation(
"Multiple files were uploaded successfully: idUpload {@idUpload}, folder: {@folder}",
idUpload, idUpload
);
cancellationToken.ThrowIfCancellationRequested();
var result = uploaded.Select(
filename =>
new FileSafeResult
{
id = idUpload,
FileName = Path.GetFileName(filename),
idUpload = idUpload
}
).ToList();
result.AddRange(skipped.Select(
filename =>
new FileSafeResult
{
id = idUpload,
FileName = Path.GetFileName(filename),
idUpload = idUpload,
IsSuccess = false,
idError = ErrorKeys.InvalidFile.ToString(),
Message = "Invalid file"
})
);
return result;
}
catch (OperationCanceledException oce)
{
_logger.LogInformation(oce, "UploadMultipleFiles was canceled");
return new[]
{
new FileSafeResult
{
IsSuccess = false,
idError = ErrorKeys.BadRequest.ToString(),
Message = oce.Message
}
};
}
}
/// <summary>
/// Downloads file with specified upload id and filename.
/// </summary>
/// <param name="id">Download id.</param>
/// <param name="file">File name.</param>
/// <returns>Binary stream mime type application/octet-stream</returns>
[HttpGet]
[Route("api/common/DownloadFile/{id}")]
public async Task<IActionResult> DownloadFile(
string id, string file,
#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
CancellationToken cancellationToken = default
#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
)
{
await using var stream = await _processedStorage.GetStreamAsync(id, file, cancellationToken);
if (stream == null)
{
return NotFound();
}
var outputStream = new MemoryStream();
await stream.CopyToAsync(outputStream, cancellationToken);
outputStream.Seek(0, SeekOrigin.Begin);
_logger.LogInformation("File was downloaded successfully: filename {@filename}, folder: {@folder}", file, id);
return File(outputStream, "application/octet-stream", file);
}
/// <summary>
/// Sends download url to specified email.
/// </summary>
/// <param name="action">Action.</param>
/// <param name="id">Download id.</param>
/// <param name="file">File name.</param>
/// <param name="email">Email.</param>
[HttpPost]
[Route("api/common/UrlToEmail")]
public IActionResult UrlToEmail(
string action, string id, string file, string email,
#pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
CancellationToken cancellationToken = default
#pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do)
) => Ok(SendDownloadUrlToEmail(action, id, file, email, cancellationToken));
/// <summary>
/// Test fail inside controller.
/// If code not specified - returns NotImplemented
/// </summary>
/// <param name="id">HTTP code</param>
/// <param name="message">Optional message</param>
/// <returns>Throws exception</returns>
[HttpGet]
[Route("api/common/TestFail")]
public ObjectResult TestFail(int? id = null, string message = null)
{
int httpStatusCode = id.HasValue ? id.Value : (int)HttpStatusCode.NotImplemented;
return StatusCode(httpStatusCode, message);
}
private async Task<List<string>> FilterFolderAsync(string folder, IList<string> notValidFiles, CancellationToken cancellationToken)
{
var filteredFiles = new List<string>();
foreach (var file in Directory.EnumerateFiles(folder))
{
if (await _fileValidatorService.IsValidFileAsync(file, cancellationToken))
{
filteredFiles.Add(file);
}
else
{
System.IO.File.Delete(file);
notValidFiles.Add(file);
_logger.LogInformation($"The upload file: {Path.GetFileName(file)} was removed from server!");
}
}
return filteredFiles;
}
private async Task<IEnumerable<string>> UploadFolderAsync(string folderName, List<string> files, CancellationToken cancellationToken)
{
var existingFiles = (await _sourceStorage.ListFilesAsync(folderName, cancellationToken)).ToList();
var uploads = files
.Select(
path => new
{
Path = path,
Filename = GetAvailableFileName(Path.GetFileName(path), existingFiles)
}
).ToList();
var tasks = uploads.Select(
async file =>
{
using var stream = _fileStreamProvider.GetStream(file.Path);
await _sourceStorage.UploadAsync(folderName, file.Filename, stream, cancellationToken);
}
);
await Task.WhenAll(tasks);
return uploads.Select(u => u.Filename);
}
private static string GetAvailableFileName(string filename, List<string> busy, int index = 1)
{
var filenameWithIndex = index == StartingFileIndex
? filename
: $"{Path.GetFileNameWithoutExtension(filename)}_{index}{Path.GetExtension(filename)}";
if (!busy.Contains(filenameWithIndex) || index >= MaxFileIndex)
{
busy.Add(filenameWithIndex);
return filenameWithIndex;
}
return GetAvailableFileName(filename, busy, index + 1);
}
private string SendDownloadUrlToEmail(
string action,
string folder,
string file,
string email,
CancellationToken cancellationToken = default
)
{
throw new NotImplementedException("Too many dependencies from Resources. Need to refactor first.");
//var pathProcessor = new PathProcessor(folder, file: file);
//var url = this.Url?.Link(
// "DefaultApi",
// new
// {
// Controller = nameof(CommonController),
// Action = nameof(Download),
// folder,
// file
// }
//) ?? "localhostUrl";
//var productTitle = Resources[$"{product}{action}Title"];
//var successMessage = Resources[$"{action}SuccessMessage"];
//var emailBody = EmailManager.PopulateBody(productTitle, url, successMessage);
//EmailManager.SendEmail(email, Configuration.FromEmailAddress, Resources["EmailTitle"], emailBody, "");
//return Resources["SendEmailToDownloadLink"];
}
}
}
| |
/*
* 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 ecs-2014-11-13.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.ECS.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ECS.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for ContainerDefinition Object
/// </summary>
public class ContainerDefinitionUnmarshaller : IUnmarshaller<ContainerDefinition, XmlUnmarshallerContext>, IUnmarshaller<ContainerDefinition, JsonUnmarshallerContext>
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
ContainerDefinition IUnmarshaller<ContainerDefinition, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context)
{
throw new NotImplementedException();
}
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public ContainerDefinition Unmarshall(JsonUnmarshallerContext context)
{
context.Read();
if (context.CurrentTokenType == JsonToken.Null)
return null;
ContainerDefinition unmarshalledObject = new ContainerDefinition();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("command", targetDepth))
{
var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
unmarshalledObject.Command = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("cpu", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.Cpu = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("disableNetworking", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.DisableNetworking = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("dnsSearchDomains", targetDepth))
{
var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
unmarshalledObject.DnsSearchDomains = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("dnsServers", targetDepth))
{
var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
unmarshalledObject.DnsServers = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("dockerLabels", targetDepth))
{
var unmarshaller = new DictionaryUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance);
unmarshalledObject.DockerLabels = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("dockerSecurityOptions", targetDepth))
{
var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
unmarshalledObject.DockerSecurityOptions = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("entryPoint", targetDepth))
{
var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
unmarshalledObject.EntryPoint = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("environment", targetDepth))
{
var unmarshaller = new ListUnmarshaller<KeyValuePair, KeyValuePairUnmarshaller>(KeyValuePairUnmarshaller.Instance);
unmarshalledObject.Environment = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("essential", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.Essential = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("extraHosts", targetDepth))
{
var unmarshaller = new ListUnmarshaller<HostEntry, HostEntryUnmarshaller>(HostEntryUnmarshaller.Instance);
unmarshalledObject.ExtraHosts = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("hostname", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Hostname = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("image", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Image = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("links", targetDepth))
{
var unmarshaller = new ListUnmarshaller<string, StringUnmarshaller>(StringUnmarshaller.Instance);
unmarshalledObject.Links = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("logConfiguration", targetDepth))
{
var unmarshaller = LogConfigurationUnmarshaller.Instance;
unmarshalledObject.LogConfiguration = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("memory", targetDepth))
{
var unmarshaller = IntUnmarshaller.Instance;
unmarshalledObject.Memory = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("mountPoints", targetDepth))
{
var unmarshaller = new ListUnmarshaller<MountPoint, MountPointUnmarshaller>(MountPointUnmarshaller.Instance);
unmarshalledObject.MountPoints = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("name", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.Name = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("portMappings", targetDepth))
{
var unmarshaller = new ListUnmarshaller<PortMapping, PortMappingUnmarshaller>(PortMappingUnmarshaller.Instance);
unmarshalledObject.PortMappings = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("privileged", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.Privileged = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("readonlyRootFilesystem", targetDepth))
{
var unmarshaller = BoolUnmarshaller.Instance;
unmarshalledObject.ReadonlyRootFilesystem = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ulimits", targetDepth))
{
var unmarshaller = new ListUnmarshaller<Ulimit, UlimitUnmarshaller>(UlimitUnmarshaller.Instance);
unmarshalledObject.Ulimits = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("user", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.User = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("volumesFrom", targetDepth))
{
var unmarshaller = new ListUnmarshaller<VolumeFrom, VolumeFromUnmarshaller>(VolumeFromUnmarshaller.Instance);
unmarshalledObject.VolumesFrom = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("workingDirectory", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
unmarshalledObject.WorkingDirectory = unmarshaller.Unmarshall(context);
continue;
}
}
return unmarshalledObject;
}
private static ContainerDefinitionUnmarshaller _instance = new ContainerDefinitionUnmarshaller();
/// <summary>
/// Gets the singleton.
/// </summary>
public static ContainerDefinitionUnmarshaller Instance
{
get
{
return _instance;
}
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: operations/rooms/room_key_issued_notification.proto
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace HOLMS.Types.Operations.Rooms {
/// <summary>Holder for reflection information generated from operations/rooms/room_key_issued_notification.proto</summary>
public static partial class RoomKeyIssuedNotificationReflection {
#region Descriptor
/// <summary>File descriptor for operations/rooms/room_key_issued_notification.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static RoomKeyIssuedNotificationReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"CjNvcGVyYXRpb25zL3Jvb21zL3Jvb21fa2V5X2lzc3VlZF9ub3RpZmljYXRp",
"b24ucHJvdG8SHGhvbG1zLnR5cGVzLm9wZXJhdGlvbnMucm9vbXMaLmJvb2tp",
"bmcvaW5kaWNhdG9ycy9yZXNlcnZhdGlvbl9pbmRpY2F0b3IucHJvdG8aJW9w",
"ZXJhdGlvbnMvcm9vbXMvcm9vbV9pbmRpY2F0b3IucHJvdG8i4QEKGVJvb21L",
"ZXlJc3N1ZWROb3RpZmljYXRpb24SEQoJal93X3Rva2VuGAEgASgJEjkKBHJv",
"b20YAiABKAsyKy5ob2xtcy50eXBlcy5vcGVyYXRpb25zLnJvb21zLlJvb21J",
"bmRpY2F0b3ISSQoLcmVzZXJ2YXRpb24YAyABKAsyNC5ob2xtcy50eXBlcy5i",
"b29raW5nLmluZGljYXRvcnMuUmVzZXJ2YXRpb25JbmRpY2F0b3ISEgoKaXNf",
"bmV3X2tleRgEIAEoCBIXCg9xdWFudGl0eV9pc3N1ZWQYBSABKA1CH6oCHEhP",
"TE1TLlR5cGVzLk9wZXJhdGlvbnMuUm9vbXNiBnByb3RvMw=="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Operations.Rooms.RoomIndicatorReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Operations.Rooms.RoomKeyIssuedNotification), global::HOLMS.Types.Operations.Rooms.RoomKeyIssuedNotification.Parser, new[]{ "JWToken", "Room", "Reservation", "IsNewKey", "QuantityIssued" }, null, null, null)
}));
}
#endregion
}
#region Messages
public sealed partial class RoomKeyIssuedNotification : pb::IMessage<RoomKeyIssuedNotification> {
private static readonly pb::MessageParser<RoomKeyIssuedNotification> _parser = new pb::MessageParser<RoomKeyIssuedNotification>(() => new RoomKeyIssuedNotification());
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<RoomKeyIssuedNotification> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::HOLMS.Types.Operations.Rooms.RoomKeyIssuedNotificationReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomKeyIssuedNotification() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomKeyIssuedNotification(RoomKeyIssuedNotification other) : this() {
jWToken_ = other.jWToken_;
Room = other.room_ != null ? other.Room.Clone() : null;
Reservation = other.reservation_ != null ? other.Reservation.Clone() : null;
isNewKey_ = other.isNewKey_;
quantityIssued_ = other.quantityIssued_;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public RoomKeyIssuedNotification Clone() {
return new RoomKeyIssuedNotification(this);
}
/// <summary>Field number for the "j_w_token" field.</summary>
public const int JWTokenFieldNumber = 1;
private string jWToken_ = "";
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public string JWToken {
get { return jWToken_; }
set {
jWToken_ = pb::ProtoPreconditions.CheckNotNull(value, "value");
}
}
/// <summary>Field number for the "room" field.</summary>
public const int RoomFieldNumber = 2;
private global::HOLMS.Types.Operations.Rooms.RoomIndicator room_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Operations.Rooms.RoomIndicator Room {
get { return room_; }
set {
room_ = value;
}
}
/// <summary>Field number for the "reservation" field.</summary>
public const int ReservationFieldNumber = 3;
private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation {
get { return reservation_; }
set {
reservation_ = value;
}
}
/// <summary>Field number for the "is_new_key" field.</summary>
public const int IsNewKeyFieldNumber = 4;
private bool isNewKey_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool IsNewKey {
get { return isNewKey_; }
set {
isNewKey_ = value;
}
}
/// <summary>Field number for the "quantity_issued" field.</summary>
public const int QuantityIssuedFieldNumber = 5;
private uint quantityIssued_;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public uint QuantityIssued {
get { return quantityIssued_; }
set {
quantityIssued_ = value;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as RoomKeyIssuedNotification);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(RoomKeyIssuedNotification other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
if (JWToken != other.JWToken) return false;
if (!object.Equals(Room, other.Room)) return false;
if (!object.Equals(Reservation, other.Reservation)) return false;
if (IsNewKey != other.IsNewKey) return false;
if (QuantityIssued != other.QuantityIssued) return false;
return true;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (JWToken.Length != 0) hash ^= JWToken.GetHashCode();
if (room_ != null) hash ^= Room.GetHashCode();
if (reservation_ != null) hash ^= Reservation.GetHashCode();
if (IsNewKey != false) hash ^= IsNewKey.GetHashCode();
if (QuantityIssued != 0) hash ^= QuantityIssued.GetHashCode();
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
if (JWToken.Length != 0) {
output.WriteRawTag(10);
output.WriteString(JWToken);
}
if (room_ != null) {
output.WriteRawTag(18);
output.WriteMessage(Room);
}
if (reservation_ != null) {
output.WriteRawTag(26);
output.WriteMessage(Reservation);
}
if (IsNewKey != false) {
output.WriteRawTag(32);
output.WriteBool(IsNewKey);
}
if (QuantityIssued != 0) {
output.WriteRawTag(40);
output.WriteUInt32(QuantityIssued);
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (JWToken.Length != 0) {
size += 1 + pb::CodedOutputStream.ComputeStringSize(JWToken);
}
if (room_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Room);
}
if (reservation_ != null) {
size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation);
}
if (IsNewKey != false) {
size += 1 + 1;
}
if (QuantityIssued != 0) {
size += 1 + pb::CodedOutputStream.ComputeUInt32Size(QuantityIssued);
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(RoomKeyIssuedNotification other) {
if (other == null) {
return;
}
if (other.JWToken.Length != 0) {
JWToken = other.JWToken;
}
if (other.room_ != null) {
if (room_ == null) {
room_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator();
}
Room.MergeFrom(other.Room);
}
if (other.reservation_ != null) {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
Reservation.MergeFrom(other.Reservation);
}
if (other.IsNewKey != false) {
IsNewKey = other.IsNewKey;
}
if (other.QuantityIssued != 0) {
QuantityIssued = other.QuantityIssued;
}
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
input.SkipLastField();
break;
case 10: {
JWToken = input.ReadString();
break;
}
case 18: {
if (room_ == null) {
room_ = new global::HOLMS.Types.Operations.Rooms.RoomIndicator();
}
input.ReadMessage(room_);
break;
}
case 26: {
if (reservation_ == null) {
reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator();
}
input.ReadMessage(reservation_);
break;
}
case 32: {
IsNewKey = input.ReadBool();
break;
}
case 40: {
QuantityIssued = input.ReadUInt32();
break;
}
}
}
}
}
#endregion
}
#endregion Designer generated code
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 0.17.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.DataLake.Analytics
{
using System;
using System.Linq;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Rest;
using Microsoft.Rest.Serialization;
using Newtonsoft.Json;
using Microsoft.Rest.Azure;
using Models;
/// <summary>
/// Creates an Azure Data Lake Analytics account management client.
/// </summary>
public partial class DataLakeAnalyticsAccountManagementClient : ServiceClient<DataLakeAnalyticsAccountManagementClient>, IDataLakeAnalyticsAccountManagementClient, IAzureClient
{
/// <summary>
/// The base URI of the service.
/// </summary>
public Uri BaseUri { get; set; }
/// <summary>
/// Gets or sets json serialization settings.
/// </summary>
public JsonSerializerSettings SerializationSettings { get; private set; }
/// <summary>
/// Gets or sets json deserialization settings.
/// </summary>
public JsonSerializerSettings DeserializationSettings { get; private set; }
/// <summary>
/// Credentials needed for the client to connect to Azure.
/// </summary>
public ServiceClientCredentials Credentials { get; private set; }
/// <summary>
/// Get subscription credentials which uniquely identify Microsoft Azure
/// subscription. The subscription ID forms part of the URI for every service
/// call.
/// </summary>
public string SubscriptionId { get; set; }
/// <summary>
/// Client Api Version.
/// </summary>
public string ApiVersion { get; private set; }
/// <summary>
/// Gets or sets the preferred language for the response.
/// </summary>
public string AcceptLanguage { get; set; }
/// <summary>
/// Gets or sets the retry timeout in seconds for Long Running Operations.
/// Default value is 30.
/// </summary>
public int? LongRunningOperationRetryTimeout { get; set; }
/// <summary>
/// When set to true a unique x-ms-client-request-id value is generated and
/// included in each request. Default is true.
/// </summary>
public bool? GenerateClientRequestId { get; set; }
/// <summary>
/// Gets the IStorageAccountsOperations.
/// </summary>
public virtual IStorageAccountsOperations StorageAccounts { get; private set; }
/// <summary>
/// Gets the IDataLakeStoreAccountsOperations.
/// </summary>
public virtual IDataLakeStoreAccountsOperations DataLakeStoreAccounts { get; private set; }
/// <summary>
/// Gets the IAccountOperations.
/// </summary>
public virtual IAccountOperations Account { get; private set; }
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DataLakeAnalyticsAccountManagementClient(params DelegatingHandler[] handlers) : base(handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
protected DataLakeAnalyticsAccountManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers)
{
this.Initialize();
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected DataLakeAnalyticsAccountManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
protected DataLakeAnalyticsAccountManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
this.BaseUri = baseUri;
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsAccountManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsAccountManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsAccountManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// Initializes a new instance of the DataLakeAnalyticsAccountManagementClient class.
/// </summary>
/// <param name='baseUri'>
/// Optional. The base URI of the service.
/// </param>
/// <param name='credentials'>
/// Required. Credentials needed for the client to connect to Azure.
/// </param>
/// <param name='rootHandler'>
/// Optional. The http client handler used to handle http transport.
/// </param>
/// <param name='handlers'>
/// Optional. The delegating handlers to add to the http client pipeline.
/// </param>
/// <exception cref="ArgumentNullException">
/// Thrown when a required parameter is null
/// </exception>
internal DataLakeAnalyticsAccountManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers)
{
if (baseUri == null)
{
throw new ArgumentNullException("baseUri");
}
if (credentials == null)
{
throw new ArgumentNullException("credentials");
}
this.BaseUri = baseUri;
this.Credentials = credentials;
if (this.Credentials != null)
{
this.Credentials.InitializeServiceClient(this);
}
}
/// <summary>
/// An optional partial-method to perform custom initialization.
/// </summary>
partial void CustomInitialize();
/// <summary>
/// Initializes client properties.
/// </summary>
private void Initialize()
{
this.StorageAccounts = new StorageAccountsOperations(this);
this.DataLakeStoreAccounts = new DataLakeStoreAccountsOperations(this);
this.Account = new AccountOperations(this);
this.BaseUri = new Uri("https://management.azure.com");
this.ApiVersion = "2016-11-01";
this.AcceptLanguage = "en-US";
this.LongRunningOperationRetryTimeout = 30;
this.GenerateClientRequestId = true;
SerializationSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
SerializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings = new JsonSerializerSettings
{
DateFormatHandling = DateFormatHandling.IsoDateFormat,
DateTimeZoneHandling = DateTimeZoneHandling.Utc,
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
ContractResolver = new ReadOnlyJsonContractResolver(),
Converters = new List<JsonConverter>
{
new Iso8601TimeSpanConverter()
}
};
CustomInitialize();
DeserializationSettings.Converters.Add(new TransformationJsonConverter());
DeserializationSettings.Converters.Add(new CloudErrorJsonConverter());
}
}
}
| |
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2015 FUJIWARA, Yusuke
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#endregion -- License Terms --
#if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT
#define UNITY
#endif
using System;
using System.Collections;
using System.Collections.Generic;
#if !UNITY
#if XAMIOS || XAMDROID
using Contract = MsgPack.MPContract;
#else
using System.Diagnostics.Contracts;
#endif // XAMIOS || XAMDROID
#endif // !UNITY
namespace MsgPack
{
partial class MessagePackObjectDictionary
{
/// <summary>
/// Enumerates the elements of a <see cref="MessagePackObjectDictionary"/> in order.
/// </summary>
public struct Enumerator : IEnumerator<KeyValuePair<MessagePackObject, MessagePackObject>>, IDictionaryEnumerator
{
private const int BeforeHead = -1;
private const int IsDictionary = -2;
private const int End = -3;
private readonly MessagePackObjectDictionary _underlying;
private Dictionary<MessagePackObject, MessagePackObject>.Enumerator _enumerator;
private KeyValuePair<MessagePackObject, MessagePackObject> _current;
private int _position;
private int _initialVersion;
/// <summary>
/// Gets the element at the current position of the enumerator.
/// </summary>
/// <value>
/// The element in the underlying collection at the current position of the enumerator.
/// </value>
public KeyValuePair<MessagePackObject, MessagePackObject> Current
{
get
{
this.VerifyVersion();
return this._current;
}
}
/// <summary>
/// Gets the element at the current position of the enumerator.
/// </summary>
/// <value>
/// The element in the collection at the current position of the enumerator, as an <see cref="Object"/>.
/// </value>
/// <exception cref="InvalidOperationException">
/// The enumerator is positioned before the first element of the collection or after the last element.
/// </exception>
object IEnumerator.Current
{
get { return this.GetCurrentStrict(); }
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
var entry = this.GetCurrentStrict();
return new DictionaryEntry( entry.Key, entry.Value );
}
}
object IDictionaryEnumerator.Key
{
get { return this.GetCurrentStrict().Key; }
}
object IDictionaryEnumerator.Value
{
get { return this.GetCurrentStrict().Value; }
}
internal KeyValuePair<MessagePackObject, MessagePackObject> GetCurrentStrict()
{
this.VerifyVersion();
if ( this._position == BeforeHead || this._position == End )
{
throw new InvalidOperationException( "The enumerator is positioned before the first element of the collection or after the last element." );
}
return this._current;
}
internal Enumerator( MessagePackObjectDictionary dictionary )
: this()
{
#if !UNITY
Contract.Assert( dictionary != null, "dictionary != null" );
#endif // !UNITY
this = default( Enumerator );
this._underlying = dictionary;
this.ResetCore();
}
internal void VerifyVersion()
{
if ( this._underlying != null && this._underlying._version != this._initialVersion )
{
throw new InvalidOperationException( "The collection was modified after the enumerator was created." );
}
}
/// <summary>
/// Releases all resources used by the this instance.
/// </summary>
public void Dispose()
{
this._enumerator.Dispose();
}
/// <summary>
/// Advances the enumerator to the next element of the underlying collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public bool MoveNext()
{
if ( this._position == End )
{
return false;
}
if ( this._position == IsDictionary )
{
if ( !this._enumerator.MoveNext() )
{
return false;
}
this._current = this._enumerator.Current;
return true;
}
if ( this._position == BeforeHead )
{
if ( this._underlying._keys.Count == 0 )
{
this._position = End;
return false;
}
// First
this._position = 0;
}
else
{
this._position++;
}
if ( this._position == this._underlying._keys.Count )
{
this._position = End;
return false;
}
this._current = new KeyValuePair<MessagePackObject, MessagePackObject>( this._underlying._keys[ this._position ], this._underlying._values[ this._position ] );
return true;
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
void IEnumerator.Reset()
{
this.ResetCore();
}
internal void ResetCore()
{
this._initialVersion = this._underlying._version;
this._current = default( KeyValuePair<MessagePackObject, MessagePackObject> );
this._initialVersion = this._underlying._version;
if ( this._underlying._dictionary != null )
{
this._enumerator = this._underlying._dictionary.GetEnumerator();
this._position = IsDictionary;
}
else
{
this._position = BeforeHead;
}
}
}
/// <summary>
/// Enumerates the elements of a <see cref="MessagePackObjectDictionary"/> in order.
/// </summary>
private struct DictionaryEnumerator : IDictionaryEnumerator
{
private IDictionaryEnumerator _underlying;
/// <summary>
/// Gets the element at the current position of the enumerator.
/// </summary>
/// <value>
/// The element in the collection at the current position of the enumerator, as an <see cref="Object"/>.
/// </value>
/// <exception cref="InvalidOperationException">
/// The enumerator is positioned before the first element of the collection or after the last element.
/// </exception>
public object Current
{
get { return this._underlying.Entry; }
}
/// <summary>
/// Gets the element at the current position of the enumerator.
/// </summary>
/// <returns>
/// The element in the dictionary at the current position of the enumerator, as a <see cref="T:System.Collections.DictionaryEntry"/>.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The enumerator is positioned before the first element of the collection or after the last element.
/// </exception>
public DictionaryEntry Entry
{
get { return this._underlying.Entry; }
}
/// <summary>
/// Gets the key of the element at the current position of the enumerator.
/// </summary>
/// <returns>
/// The key of the element in the dictionary at the current position of the enumerator.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The enumerator is positioned before the first element of the collection or after the last element.
/// </exception>
public object Key
{
get { return this.Entry.Key; }
}
/// <summary>
/// Gets the value of the element at the current position of the enumerator.
/// </summary>
/// <returns>
/// The value of the element in the dictionary at the current position of the enumerator.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The enumerator is positioned before the first element of the collection or after the last element.
/// </exception>
public object Value
{
get { return this.Entry.Value; }
}
internal DictionaryEnumerator( MessagePackObjectDictionary dictionary )
: this()
{
#if !UNITY
Contract.Assert( dictionary != null, "dictionary != null" );
#endif // !UNITY
this._underlying = new Enumerator( dictionary );
}
/// <summary>
/// Advances the enumerator to the next element of the underlying collection.
/// </summary>
/// <returns>
/// <c>true</c> if the enumerator was successfully advanced to the next element;
/// <c>false</c> if the enumerator has passed the end of the collection.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
public bool MoveNext()
{
return this._underlying.MoveNext();
}
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the collection.
/// </summary>
/// <exception cref="T:System.InvalidOperationException">
/// The collection was modified after the enumerator was created.
/// </exception>
void IEnumerator.Reset()
{
this._underlying.Reset();
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Microsoft.Internal;
using Microsoft.Internal.Collections;
namespace System.ComponentModel.Composition.Hosting
{
// This class guarantees thread-safety under the following conditions:
// - Each composition is executed on a single thread
// - No recomposition ever takes place
// - The class is created with isThreadSafe=true
public partial class ImportEngine : ICompositionService, IDisposable
{
private const int MaximumNumberOfCompositionIterations = 100;
private volatile bool _isDisposed;
private ExportProvider _sourceProvider;
private readonly Stack<PartManager> _recursionStateStack = new Stack<PartManager>();
private ConditionalWeakTable<ComposablePart, PartManager> _partManagers = new ConditionalWeakTable<ComposablePart, PartManager>();
private RecompositionManager _recompositionManager = new RecompositionManager();
private readonly CompositionLock _lock = null;
private readonly CompositionOptions _compositionOptions;
/// <summary>
/// Initializes a new instance of the <see cref="ImportEngine"/> class.
/// </summary>
/// <param name="sourceProvider">
/// The <see cref="ExportProvider"/> which provides the
/// <see cref="ImportEngine"/> access to <see cref="Export"/>s.
/// </param>
public ImportEngine(ExportProvider sourceProvider)
: this(sourceProvider, CompositionOptions.Default)
{
}
public ImportEngine(ExportProvider sourceProvider, bool isThreadSafe)
: this(sourceProvider, isThreadSafe ? CompositionOptions.IsThreadSafe : CompositionOptions.Default)
{
}
public ImportEngine(ExportProvider sourceProvider, CompositionOptions compositionOptions)
{
Requires.NotNull(sourceProvider, nameof(sourceProvider));
_compositionOptions = compositionOptions;
_sourceProvider = sourceProvider;
_sourceProvider.ExportsChanging += OnExportsChanging;
_lock = new CompositionLock(compositionOptions.HasFlag(CompositionOptions.IsThreadSafe));
}
/// <summary>
/// Previews all the required imports for the given <see cref="ComposablePart"/> to
/// ensure they can all be satisified. The preview does not actually set the imports
/// only ensures that they exist in the source provider. If the preview succeeds then
/// the <see cref="ImportEngine"/> also enforces that changes to exports in the source
/// provider will not break any of the required imports. If this enforcement needs to be
/// lifted for this part then <see cref="ReleaseImports"/> needs to be called for this
/// <see cref="ComposablePart"/>.
/// </summary>
/// <param name="part">
/// The <see cref="ComposablePart"/> to preview the required imports.
/// </param>
/// <param name="atomicComposition"></param>
/// <exception cref="CompositionException">
/// An error occurred during previewing and <paramref name="atomicComposition"/> is null.
/// <see cref="CompositionException.Errors"/> will contain a collection of errors that occurred.
/// The pre-existing composition is in an unknown state, depending on the errors that occured.
/// </exception>
/// <exception cref="ChangeRejectedException">
/// An error occurred during the previewing and <paramref name="atomicComposition"/> is not null.
/// <see cref="CompositionException.Errors"/> will contain a collection of errors that occurred.
/// The pre-existing composition remains in valid state.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="ImportEngine"/> has been disposed of.
/// </exception>
public void PreviewImports(ComposablePart part, AtomicComposition atomicComposition)
{
ThrowIfDisposed();
Requires.NotNull(part, nameof(part));
// Do not do any previewing if SilentRejection is disabled.
if (_compositionOptions.HasFlag(CompositionOptions.DisableSilentRejection))
{
return;
}
// NOTE : this is a very intricate area threading-wise, please use caution when changing, otherwise state corruption or deadlocks will ensue
// The gist of what we are doing is as follows:
// We need to lock the composition, as we will proceed modifying our internal state. The tricky part is when we release the lock
// Due to the fact that some actions will take place AFTER we leave this method, we need to KEEP THAT LOCK HELD until the transation is commiited or rolled back
// This is the reason we CAN'T use "using here.
// Instead, if the transaction is present we will queue up the release of the lock, otherwise we will release it when we exit this method
// We add the "release" lock to BOTH Commit and Revert queues, because they are mutually exclusive, and we need to release the lock regardless.
// This will take the lock, if necesary
IDisposable compositionLockHolder = _lock.IsThreadSafe ? _lock.LockComposition() : null;
bool compositionLockTaken = (compositionLockHolder != null);
try
{
// revert actions are processed in the reverse order, so we have to add the "release lock" action now
if (compositionLockTaken && (atomicComposition != null))
{
atomicComposition.AddRevertAction(() => compositionLockHolder.Dispose());
}
var partManager = GetPartManager(part, true);
var result = TryPreviewImportsStateMachine(partManager, part, atomicComposition);
result.ThrowOnErrors(atomicComposition);
StartSatisfyingImports(partManager, atomicComposition);
// Add the "release lock" to the commit actions
if (compositionLockTaken && (atomicComposition != null))
{
atomicComposition.AddCompleteAction(() => compositionLockHolder.Dispose());
}
}
finally
{
// We haven't updated the queues, so we can release the lock now
if (compositionLockTaken && (atomicComposition == null))
{
compositionLockHolder.Dispose();
}
}
}
/// <summary>
/// Satisfies the imports of the specified composable part. If the satisfy succeeds then
/// the <see cref="ImportEngine"/> also enforces that changes to exports in the source
/// provider will not break any of the required imports. If this enforcement needs to be
/// lifted for this part then <see cref="ReleaseImports"/> needs to be called for this
/// <see cref="ComposablePart"/>.
/// </summary>
/// <param name="part">
/// The <see cref="ComposablePart"/> to set the imports.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="part"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="CompositionException">
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="ImportEngine"/> has been disposed of.
/// </exception>
public void SatisfyImports(ComposablePart part)
{
ThrowIfDisposed();
Requires.NotNull(part, nameof(part));
// NOTE : the following two calls use the state lock
PartManager partManager = GetPartManager(part, true);
if (partManager.State == ImportState.Composed)
{
return;
}
using (_lock.LockComposition())
{
var result = TrySatisfyImports(partManager, part, true);
result.ThrowOnErrors(); // throw CompositionException not ChangeRejectedException
}
}
/// <summary>
/// Sets the imports of the specified composable part exactly once and they will not
/// ever be recomposed.
/// </summary>
/// <param name="part">
/// The <see cref="ComposablePart"/> to set the imports.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="part"/> is <see langword="null"/>.
/// </exception>
/// <exception cref="CompositionException">
/// An error occurred during composition. <see cref="CompositionException.Errors"/> will
/// contain a collection of errors that occurred.
/// </exception>
/// <exception cref="ObjectDisposedException">
/// The <see cref="ICompositionService"/> has been disposed of.
/// </exception>
public void SatisfyImportsOnce(ComposablePart part)
{
ThrowIfDisposed();
Requires.NotNull(part, nameof(part));
// NOTE : the following two calls use the state lock
PartManager partManager = GetPartManager(part, true);
if (partManager.State == ImportState.Composed)
{
return;
}
using (_lock.LockComposition())
{
var result = TrySatisfyImports(partManager, part, false);
result.ThrowOnErrors(); // throw CompositionException not ChangeRejectedException
}
}
/// <summary>
/// Removes any state stored in the <see cref="ImportEngine"/> for the associated
/// <see cref="ComposablePart"/> and releases all the <see cref="Export"/>s used to
/// satisfy the imports on the <see cref="ComposablePart"/>.
///
/// Also removes the enforcement for changes that would break a required import on
/// <paramref name="part"/>.
/// </summary>
/// <param name="part">
/// The <see cref="ComposablePart"/> to release the imports on.
/// </param>
/// <param name="atomicComposition">
/// The <see cref="AtomicComposition"/> that the release imports is running under.
/// </param>
public void ReleaseImports(ComposablePart part, AtomicComposition atomicComposition)
{
ThrowIfDisposed();
Requires.NotNull(part, nameof(part));
using (_lock.LockComposition())
{
PartManager partManager = GetPartManager(part, false);
if (partManager != null)
{
StopSatisfyingImports(partManager, atomicComposition);
}
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Releases unmanaged and - optionally - managed resources
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (!_isDisposed)
{
bool disposeLock = false;
ExportProvider sourceProviderToUnsubscribeFrom = null;
using (_lock.LockStateForWrite())
{
if (!_isDisposed)
{
sourceProviderToUnsubscribeFrom = _sourceProvider;
_sourceProvider = null;
_recompositionManager = null;
_partManagers = null;
_isDisposed = true;
disposeLock = true;
}
}
if (sourceProviderToUnsubscribeFrom != null)
{
sourceProviderToUnsubscribeFrom.ExportsChanging -= OnExportsChanging;
}
if (disposeLock)
{
_lock.Dispose();
}
}
}
}
private CompositionResult TryPreviewImportsStateMachine(PartManager partManager,
ComposablePart part, AtomicComposition atomicComposition)
{
var result = CompositionResult.SucceededResult;
if (partManager.State == ImportState.ImportsPreviewing)
{
// We shouldn't nomally ever hit this case but if we do
// then we should just error with a cycle error.
return new CompositionResult(ErrorBuilder.CreatePartCycle(part));
}
// Transition from NoImportsStatisified to ImportsPreviewed
if (partManager.State == ImportState.NoImportsSatisfied)
{
partManager.State = ImportState.ImportsPreviewing;
var requiredImports = part.ImportDefinitions.Where(IsRequiredImportForPreview);
// If this atomicComposition gets rolledback for any reason we need to reset our state
atomicComposition.AddRevertActionAllowNull(() => partManager.State = ImportState.NoImportsSatisfied);
result = result.MergeResult(
TrySatisfyImportSubset(partManager, requiredImports, atomicComposition));
if (!result.Succeeded)
{
partManager.State = ImportState.NoImportsSatisfied;
return result;
}
partManager.State = ImportState.ImportsPreviewed;
}
return result;
}
private CompositionResult TrySatisfyImportsStateMachine(PartManager partManager, ComposablePart part)
{
var result = CompositionResult.SucceededResult;
while (partManager.State < ImportState.Composed)
{
var previousState = partManager.State;
switch (partManager.State)
{
// "ed" states which represent a some sort of steady state and will
// attempt to do a state transition
case ImportState.NoImportsSatisfied:
case ImportState.ImportsPreviewed:
{
partManager.State = ImportState.PreExportImportsSatisfying;
var prereqImports = part.ImportDefinitions.Where(import => import.IsPrerequisite);
result = result.MergeResult(
TrySatisfyImportSubset(partManager, prereqImports, null));
partManager.State = ImportState.PreExportImportsSatisfied;
break;
}
case ImportState.PreExportImportsSatisfied:
{
partManager.State = ImportState.PostExportImportsSatisfying;
var requiredImports = part.ImportDefinitions.Where(import => !import.IsPrerequisite);
result = result.MergeResult(
TrySatisfyImportSubset(partManager, requiredImports, null));
partManager.State = ImportState.PostExportImportsSatisfied;
break;
}
case ImportState.PostExportImportsSatisfied:
{
partManager.State = ImportState.ComposedNotifying;
partManager.ClearSavedImports();
result = result.MergeResult(partManager.TryOnComposed());
partManager.State = ImportState.Composed;
break;
}
// "ing" states which represent some sort of cycle
// These state should always return, error or not, instead of breaking
case ImportState.ImportsPreviewing:
{
// We shouldn't nomally ever hit this case but if we do
// then we should just error with a cycle error.
return new CompositionResult(ErrorBuilder.CreatePartCycle(part));
}
case ImportState.PreExportImportsSatisfying:
case ImportState.PostExportImportsSatisfying:
{
if (InPrerequisiteLoop())
{
return result.MergeError(ErrorBuilder.CreatePartCycle(part));
}
// Cycles in post export imports are allowed so just return in that case
return result;
}
case ImportState.ComposedNotifying:
{
// We are currently notifying so don't notify again just return
return result;
}
}
// if an error occured while doing a state transition
if (!result.Succeeded)
{
// revert to the previous state and return the error
partManager.State = previousState;
return result;
}
}
return result;
}
private CompositionResult TrySatisfyImports(PartManager partManager, ComposablePart part, bool shouldTrackImports)
{
if (part == null)
{
throw new ArgumentNullException(nameof(part));
}
var result = CompositionResult.SucceededResult;
// get out if the part is already composed
if (partManager.State == ImportState.Composed)
{
return result;
}
// Track number of recursive iterations and throw an exception before the stack
// fills up and debugging the root cause becomes tricky
if (_recursionStateStack.Count >= MaximumNumberOfCompositionIterations)
{
return result.MergeError(
ErrorBuilder.ComposeTookTooManyIterations(MaximumNumberOfCompositionIterations));
}
// Maintain the stack to detect whether recursive loops cross prerequisites
_recursionStateStack.Push(partManager);
try
{
result = result.MergeResult(
TrySatisfyImportsStateMachine(partManager, part));
}
finally
{
_recursionStateStack.Pop();
}
if (shouldTrackImports)
{
StartSatisfyingImports(partManager, null);
}
return result;
}
private CompositionResult TrySatisfyImportSubset(PartManager partManager,
IEnumerable<ImportDefinition> imports, AtomicComposition atomicComposition)
{
CompositionResult result = CompositionResult.SucceededResult;
var part = partManager.Part;
foreach (ImportDefinition import in imports)
{
var exports = partManager.GetSavedImport(import);
if (exports == null)
{
CompositionResult<IEnumerable<Export>> exportsResult = TryGetExports(
_sourceProvider, part, import, atomicComposition);
if (!exportsResult.Succeeded)
{
result = result.MergeResult(exportsResult.ToResult());
continue;
}
exports = exportsResult.Value.AsArray();
}
if (atomicComposition == null)
{
result = result.MergeResult(
partManager.TrySetImport(import, exports));
}
else
{
partManager.SetSavedImport(import, exports, atomicComposition);
}
}
return result;
}
private void OnExportsChanging(object sender, ExportsChangeEventArgs e)
{
CompositionResult result = CompositionResult.SucceededResult;
// Prepare for the recomposition effort by minimizing the amount of work we'll have to do later
AtomicComposition atomicComposition = e.AtomicComposition;
IEnumerable<PartManager> affectedParts = _recompositionManager.GetAffectedParts(e.ChangedContractNames);
// When in a atomicComposition account for everything that isn't yet reflected in the
// index
if (atomicComposition != null)
{
EngineContext engineContext;
if (atomicComposition.TryGetValue(this, out engineContext))
{
// always added the new part managers to see if they will also be
// affected by these changes
affectedParts = affectedParts.ConcatAllowingNull(engineContext.GetAddedPartManagers())
.Except(engineContext.GetRemovedPartManagers());
}
}
var changedExports = e.AddedExports.ConcatAllowingNull(e.RemovedExports);
foreach (var partManager in affectedParts)
{
result = result.MergeResult(TryRecomposeImports(partManager, changedExports, atomicComposition));
}
result.ThrowOnErrors(atomicComposition);
}
private CompositionResult TryRecomposeImports(PartManager partManager,
IEnumerable<ExportDefinition> changedExports, AtomicComposition atomicComposition)
{
var result = CompositionResult.SucceededResult;
switch (partManager.State)
{
case ImportState.ImportsPreviewed:
case ImportState.Composed:
// Validate states to continue.
break;
default:
{
// All other states are invalid and for recomposition.
return new CompositionResult(ErrorBuilder.InvalidStateForRecompposition(partManager.Part));
}
}
var affectedImports = RecompositionManager.GetAffectedImports(partManager.Part, changedExports);
bool partComposed = (partManager.State == ImportState.Composed);
bool recomposedImport = false;
foreach (var import in affectedImports)
{
result = result.MergeResult(
TryRecomposeImport(partManager, partComposed, import, atomicComposition));
recomposedImport = true;
}
// Knowing that the part has already been composed before and that the only possible
// changes are to recomposable imports, we can safely go ahead and do this now or
// schedule it for later
if (result.Succeeded && recomposedImport && partComposed)
{
if (atomicComposition == null)
{
result = result.MergeResult(partManager.TryOnComposed());
}
else
{
atomicComposition.AddCompleteAction(() => partManager.TryOnComposed().ThrowOnErrors());
}
}
return result;
}
private CompositionResult TryRecomposeImport(PartManager partManager, bool partComposed,
ImportDefinition import, AtomicComposition atomicComposition)
{
if (partComposed && !import.IsRecomposable)
{
return new CompositionResult(ErrorBuilder.PreventedByExistingImport(partManager.Part, import));
}
// During recomposition you must always requery with the new atomicComposition you cannot use any
// cached value in the part manager
var exportsResult = TryGetExports(_sourceProvider, partManager.Part, import, atomicComposition);
if (!exportsResult.Succeeded)
{
return exportsResult.ToResult();
}
var exports = exportsResult.Value.AsArray();
if (partComposed)
{
// Knowing that the part has already been composed before and that the only possible
// changes are to recomposable imports, we can safely go ahead and do this now or
// schedule it for later
if (atomicComposition == null)
{
return partManager.TrySetImport(import, exports);
}
else
{
atomicComposition.AddCompleteAction(() => partManager.TrySetImport(import, exports).ThrowOnErrors());
}
}
else
{
partManager.SetSavedImport(import, exports, atomicComposition);
}
return CompositionResult.SucceededResult;
}
private void StartSatisfyingImports(PartManager partManager, AtomicComposition atomicComposition)
{
// When not running in a atomicCompositional state, schedule reindexing after ensuring
// that this isn't a redundant addition
if (atomicComposition == null)
{
if (!partManager.TrackingImports)
{
partManager.TrackingImports = true;
_recompositionManager.AddPartToIndex(partManager);
}
}
else
{
// While in a atomicCompositional state use a less efficient but effective means
// of achieving the same results
GetEngineContext(atomicComposition).AddPartManager(partManager);
}
}
private void StopSatisfyingImports(PartManager partManager, AtomicComposition atomicComposition)
{
// When not running in a atomicCompositional state, schedule reindexing after ensuring
// that this isn't a redundant removal
if (atomicComposition == null)
{
ConditionalWeakTable<ComposablePart, PartManager> partManagers = null;
RecompositionManager recompositionManager = null;
using (_lock.LockStateForRead())
{
partManagers = _partManagers;
recompositionManager = _recompositionManager;
}
if (partManagers != null) // Disposal race may have been won by dispose
{
partManagers.Remove(partManager.Part);
// Take care of lifetime requirements
partManager.DisposeAllDependencies();
if (partManager.TrackingImports)
{
partManager.TrackingImports = false;
recompositionManager.AddPartToUnindex(partManager);
}
}
}
else
{
// While in a atomicCompositional state use a less efficient but effective means
// of achieving the same results
GetEngineContext(atomicComposition).RemovePartManager(partManager);
}
}
private PartManager GetPartManager(ComposablePart part, bool createIfNotpresent)
{
PartManager partManager = null;
using (_lock.LockStateForRead())
{
if (_partManagers.TryGetValue(part, out partManager))
{
return partManager;
}
}
if (createIfNotpresent)
{
using (_lock.LockStateForWrite())
{
if (!_partManagers.TryGetValue(part, out partManager))
{
partManager = new PartManager(this, part);
_partManagers.Add(part, partManager);
}
}
}
return partManager;
}
private EngineContext GetEngineContext(AtomicComposition atomicComposition)
{
if (atomicComposition == null)
{
throw new ArgumentNullException(nameof(atomicComposition));
}
EngineContext engineContext;
if (!atomicComposition.TryGetValue(this, true, out engineContext))
{
EngineContext parentContext;
atomicComposition.TryGetValue(this, false, out parentContext);
engineContext = new EngineContext(this, parentContext);
atomicComposition.SetValue(this, engineContext);
atomicComposition.AddCompleteAction(engineContext.Complete);
}
return engineContext;
}
private bool InPrerequisiteLoop()
{
PartManager firstPart = _recursionStateStack.First();
PartManager lastPart = null;
foreach (PartManager testPart in _recursionStateStack.Skip(1))
{
if (testPart.State == ImportState.PreExportImportsSatisfying)
{
return true;
}
if (testPart == firstPart)
{
lastPart = testPart;
break;
}
}
// This should only be called when a loop has been detected - so it should always be on the stack
if (lastPart != firstPart)
{
throw new Exception(SR.Diagnostic_InternalExceptionMessage);
}
return false;
}
[DebuggerStepThrough]
private void ThrowIfDisposed()
{
if (_isDisposed)
{
throw ExceptionBuilder.CreateObjectDisposed(this);
}
}
private static CompositionResult<IEnumerable<Export>> TryGetExports(ExportProvider provider,
ComposablePart part, ImportDefinition definition, AtomicComposition atomicComposition)
{
try
{
IEnumerable<Export> exports = null;
if (provider != null)
{
exports = provider.GetExports(definition, atomicComposition).AsArray();
}
return new CompositionResult<IEnumerable<Export>>(exports);
}
catch (ImportCardinalityMismatchException ex)
{
// Either not enough or too many exports that match the definition
CompositionException exception = new CompositionException(ErrorBuilder.CreateImportCardinalityMismatch(ex, definition));
return new CompositionResult<IEnumerable<Export>>(
ErrorBuilder.CreatePartCannotSetImport(part, definition, exception));
}
}
internal static bool IsRequiredImportForPreview(ImportDefinition import)
{
return import.Cardinality == ImportCardinality.ExactlyOne;
}
// Ordering of this enum is important so be sure to use caution if you
// try to reorder them.
private enum ImportState
{
NoImportsSatisfied = 0,
ImportsPreviewing = 1,
ImportsPreviewed = 2,
PreExportImportsSatisfying = 3,
PreExportImportsSatisfied = 4,
PostExportImportsSatisfying = 5,
PostExportImportsSatisfied = 6,
ComposedNotifying = 7,
Composed = 8,
}
}
}
| |
/*
Project Orleans Cloud Service SDK ver. 1.0
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 System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using Orleans.CodeGeneration;
using Orleans.Core;
using Orleans.Runtime;
namespace Orleans
{
using System.Threading.Tasks;
/// <summary>
/// Factory for accessing grains.
/// </summary>
public class GrainFactory : IGrainFactory
{
/// <summary>
/// The collection of <see cref="IGrainObserver"/> <c>CreateObjectReference</c> delegates.
/// </summary>
private readonly ConcurrentDictionary<Type, Delegate> referenceCreators =
new ConcurrentDictionary<Type, Delegate>();
/// <summary>
/// The collection of <see cref="IGrainObserver"/> <c>DeleteObjectReference</c> delegates.
/// </summary>
private readonly ConcurrentDictionary<Type, Delegate> referenceDestoyers =
new ConcurrentDictionary<Type, Delegate>();
// Make this internal so that client code is forced to access the IGrainFactory using the
// GrainClient (to make sure they don't forget to initialize the client).
internal GrainFactory()
{
}
/// <summary>
/// Gets a reference to a grain.
/// </summary>
/// <typeparam name="TGrainInterface">The interface to get.</typeparam>
/// <param name="primaryKey">The primary key of the grain.</param>
/// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param>
/// <returns></returns>
public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithGuidKey
{
return Cast<TGrainInterface>(
GrainFactoryBase.MakeGrainReference_FromType(
baseTypeCode => TypeCodeMapper.ComposeGrainId(baseTypeCode, primaryKey, typeof(TGrainInterface)),
typeof(TGrainInterface),
grainClassNamePrefix));
}
/// <summary>
/// Gets a reference to a grain.
/// </summary>
/// <typeparam name="TGrainInterface">The interface to get.</typeparam>
/// <param name="primaryKey">The primary key of the grain.</param>
/// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param>
/// <returns></returns>
public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithIntegerKey
{
return Cast<TGrainInterface>(
GrainFactoryBase.MakeGrainReference_FromType(
baseTypeCode => TypeCodeMapper.ComposeGrainId(baseTypeCode, primaryKey, typeof(TGrainInterface)),
typeof(TGrainInterface),
grainClassNamePrefix));
}
/// <summary>
/// Gets a reference to a grain.
/// </summary>
/// <typeparam name="TGrainInterface">The interface to get.</typeparam>
/// <param name="primaryKey">The primary key of the grain.</param>
/// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param>
/// <returns></returns>
public TGrainInterface GetGrain<TGrainInterface>(string primaryKey, string grainClassNamePrefix = null) where TGrainInterface : IGrainWithStringKey
{
return Cast<TGrainInterface>(
GrainFactoryBase.MakeGrainReference_FromType(
baseTypeCode => TypeCodeMapper.ComposeGrainId(baseTypeCode, primaryKey, typeof(TGrainInterface)),
typeof(TGrainInterface),
grainClassNamePrefix));
}
/// <summary>
/// Gets a reference to a grain.
/// </summary>
/// <typeparam name="TGrainInterface">The interface to get.</typeparam>
/// <param name="primaryKey">The primary key of the grain.</param>
/// <param name="keyExtension">The key extention of the grain.</param>
/// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param>
/// <returns></returns>
public TGrainInterface GetGrain<TGrainInterface>(Guid primaryKey, string keyExtension, string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithGuidCompoundKey
{
GrainFactoryBase.DisallowNullOrWhiteSpaceKeyExtensions(keyExtension);
return Cast<TGrainInterface>(
GrainFactoryBase.MakeGrainReference_FromType(
baseTypeCode => TypeCodeMapper.ComposeGrainId(baseTypeCode, primaryKey, typeof(TGrainInterface), keyExtension),
typeof(TGrainInterface),
grainClassNamePrefix));
}
/// <summary>
/// Gets a reference to a grain.
/// </summary>
/// <typeparam name="TGrainInterface">The interface to get.</typeparam>
/// <param name="primaryKey">The primary key of the grain.</param>
/// <param name="keyExtension">The key extention of the grain.</param>
/// <param name="grainClassNamePrefix">An optional class name prefix used to find the runtime type of the grain.</param>
/// <returns></returns>
public TGrainInterface GetGrain<TGrainInterface>(long primaryKey, string keyExtension, string grainClassNamePrefix = null)
where TGrainInterface : IGrainWithIntegerCompoundKey
{
GrainFactoryBase.DisallowNullOrWhiteSpaceKeyExtensions(keyExtension);
return Cast<TGrainInterface>(
GrainFactoryBase.MakeGrainReference_FromType(
baseTypeCode => TypeCodeMapper.ComposeGrainId(baseTypeCode, primaryKey, typeof(TGrainInterface), keyExtension),
typeof(TGrainInterface),
grainClassNamePrefix));
}
/// <summary>
/// Creates a reference to the provided <paramref name="obj"/>.
/// </summary>
/// <typeparam name="TGrainObserverInterface">
/// The specific <see cref="IGrainObserver"/> type of <paramref name="obj"/>.
/// </typeparam>
/// <param name="obj">The object to create a reference to.</param>
/// <returns>The reference to <paramref name="obj"/>.</returns>
public Task<TGrainObserverInterface> CreateObjectReference<TGrainObserverInterface>(IGrainObserver obj)
where TGrainObserverInterface : IGrainObserver
{
return CreateObjectReferenceImpl<TGrainObserverInterface>(obj);
}
internal Task<TGrainObserverInterface> CreateObjectReference<TGrainObserverInterface>(IAddressable obj)
where TGrainObserverInterface : IAddressable
{
return CreateObjectReferenceImpl<TGrainObserverInterface>(obj);
}
private Task<TGrainObserverInterface> CreateObjectReferenceImpl<TGrainObserverInterface>(object obj)
{
var interfaceType = typeof(TGrainObserverInterface);
if (!interfaceType.IsInterface)
{
throw new ArgumentException(
string.Format(
"The provided type parameter must be an interface. '{0}' is not an interface.",
interfaceType.FullName));
}
if (!interfaceType.IsInstanceOfType(obj))
{
throw new ArgumentException(
string.Format("The provided object must implement '{0}'.", interfaceType.FullName),
"obj");
}
Delegate creator;
if (!referenceCreators.TryGetValue(interfaceType, out creator))
{
creator = referenceCreators.GetOrAdd(interfaceType, MakeCreateObjectReferenceDelegate);
}
var resultTask = ((Func<TGrainObserverInterface, Task<TGrainObserverInterface>>)creator)((TGrainObserverInterface)obj);
return resultTask;
}
/// <summary>
/// Deletes the provided object reference.
/// </summary>
/// <typeparam name="TGrainObserverInterface">
/// The specific <see cref="IGrainObserver"/> type of <paramref name="obj"/>.
/// </typeparam>
/// <param name="obj">The reference being deleted.</param>
/// <returns>A <see cref="Task"/> representing the work performed.</returns>
public Task DeleteObjectReference<TGrainObserverInterface>(
IGrainObserver obj) where TGrainObserverInterface : IGrainObserver
{
var interfaceType = typeof(TGrainObserverInterface);
if (!interfaceType.IsInterface)
{
throw new ArgumentException(
string.Format(
"The provided type parameter must be an interface. '{0}' is not an interface.",
interfaceType.FullName));
}
if (!interfaceType.IsInstanceOfType(obj))
{
throw new ArgumentException(
string.Format("The provided object must implement '{0}'.", interfaceType.FullName),
"obj");
}
Delegate destroyer;
if (!referenceDestoyers.TryGetValue(interfaceType, out destroyer))
{
destroyer = referenceDestoyers.GetOrAdd(interfaceType, MakeDeleteObjectReferenceDelegate);
}
return ((Func<TGrainObserverInterface, Task>)destroyer)((TGrainObserverInterface)obj);
}
#region IGrainObserver Methods
private static Delegate MakeCreateObjectReferenceDelegate(Type interfaceType)
{
var delegateType = typeof(Func<,>).MakeGenericType(interfaceType, typeof(Task<>).MakeGenericType(interfaceType));
return MakeFactoryDelegate(interfaceType, "CreateObjectReference", delegateType);
}
private static Delegate MakeDeleteObjectReferenceDelegate(Type interfaceType)
{
var delegateType = typeof(Func<,>).MakeGenericType(interfaceType, typeof(Task));
return MakeFactoryDelegate(interfaceType, "DeleteObjectReference", delegateType);
}
#endregion
#region Interface Casting
private readonly ConcurrentDictionary<Type, Func<IAddressable, object>> casters
= new ConcurrentDictionary<Type, Func<IAddressable, object>>();
internal TGrainInterface Cast<TGrainInterface>(IAddressable grain)
{
var interfaceType = typeof(TGrainInterface);
Func<IAddressable, object> caster;
if (!casters.TryGetValue(interfaceType, out caster))
{
caster = casters.GetOrAdd(interfaceType, MakeCaster);
}
return (TGrainInterface)caster(grain);
}
private static Func<IAddressable, object> MakeCaster(Type interfaceType)
{
var delegateType = typeof(Func<IAddressable, object>);
return (Func<IAddressable, object>)MakeFactoryDelegate(interfaceType, "Cast", delegateType);
}
#endregion
#region SystemTargets
private readonly Dictionary<Tuple<GrainId,Type>, Dictionary<SiloAddress, ISystemTarget>> typedSystemTargetReferenceCache =
new Dictionary<Tuple<GrainId, Type>, Dictionary<SiloAddress, ISystemTarget>>();
internal TGrainInterface GetSystemTarget<TGrainInterface>(GrainId grainId, SiloAddress destination)
where TGrainInterface : ISystemTarget
{
Dictionary<SiloAddress, ISystemTarget> cache;
Tuple<GrainId, Type> key = Tuple.Create(grainId, typeof(TGrainInterface));
lock (typedSystemTargetReferenceCache)
{
if (typedSystemTargetReferenceCache.ContainsKey(key))
cache = typedSystemTargetReferenceCache[key];
else
{
cache = new Dictionary<SiloAddress, ISystemTarget>();
typedSystemTargetReferenceCache[key] = cache;
}
}
ISystemTarget reference;
lock (cache)
{
if (cache.ContainsKey(destination))
{
reference = cache[destination];
}
else
{
reference = Cast<TGrainInterface>(GrainReference.FromGrainId(grainId, null, destination));
cache[destination] = reference; // Store for next time
}
}
return (TGrainInterface) reference;
}
#endregion
#region Utility functions
/// <summary>
/// Creates a delegate for calling into the static method named <paramref name="methodName"/> on the generated
/// factory for <paramref name="interfaceType"/>.
/// </summary>
/// <param name="interfaceType">The interface type.</param>
/// <param name="methodName">The name of the static factory method.</param>
/// <param name="delegateType">The type of delegate to create.</param>
/// <returns>The created delegate.</returns>
private static Delegate MakeFactoryDelegate(Type interfaceType, string methodName, Type delegateType)
{
var grainFactoryName = TypeUtils.GetSimpleTypeName(interfaceType, t => false);
if (interfaceType.IsInterface && grainFactoryName.Length > 1 && grainFactoryName[0] == 'I'
&& char.IsUpper(grainFactoryName[1]))
{
grainFactoryName = grainFactoryName.Substring(1);
}
grainFactoryName = grainFactoryName + "Factory";
if (interfaceType.IsGenericType)
{
grainFactoryName = grainFactoryName + "`" + interfaceType.GetGenericArguments().Length;
}
// expect grain reference to be generated into same namespace that interface is declared within
if (!string.IsNullOrEmpty(interfaceType.Namespace))
{
grainFactoryName = interfaceType.Namespace + "." + grainFactoryName;
}
var grainFactoryType = interfaceType.Assembly.GetType(grainFactoryName);
if (grainFactoryType == null)
{
throw new InvalidOperationException(
string.Format("Cannot find generated factory type for interface '{0}'", interfaceType));
}
if (interfaceType.IsGenericType)
{
grainFactoryType = grainFactoryType.MakeGenericType(interfaceType.GetGenericArguments());
}
var method = grainFactoryType.GetMethod(
methodName,
System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic
| System.Reflection.BindingFlags.Public);
if (method == null)
{
throw new InvalidOperationException(
string.Format("Cannot find '{0}' method for interface '{1}'", methodName, interfaceType));
}
return method.CreateDelegate(delegateType);
}
#endregion
}
}
| |
using System;
using UnityEngine;
using UnityStandardAssets.Utility;
using Random = UnityEngine.Random;
namespace UnityStandardAssets.Characters.FirstPerson
{
[RequireComponent(typeof (CharacterController))]
[RequireComponent(typeof (AudioSource))]
public class FirstPersonController : MonoBehaviour
{
[SerializeField] private bool m_IsWalking;
[SerializeField] private float m_WalkSpeed;
[SerializeField] private float m_RunSpeed;
[SerializeField] [Range(0f, 1f)] private float m_RunstepLenghten;
[SerializeField] private float m_JumpSpeed;
[SerializeField] private float m_StickToGroundForce;
[SerializeField] private float m_GravityMultiplier;
[SerializeField] private MouseLook m_MouseLook;
[SerializeField] private bool m_UseFovKick;
[SerializeField] private FOVKick m_FovKick = new FOVKick();
[SerializeField] private bool m_UseHeadBob;
[SerializeField] private CurveControlledBob m_HeadBob = new CurveControlledBob();
[SerializeField] private LerpControlledBob m_JumpBob = new LerpControlledBob();
[SerializeField] private float m_StepInterval;
[SerializeField] private AudioClip[] m_FootstepSounds; // an array of footstep sounds that will be randomly selected from.
[SerializeField] private AudioClip m_JumpSound; // the sound played when character leaves the ground.
[SerializeField] private AudioClip m_LandSound; // the sound played when character touches back on ground.
private Camera m_Camera;
private bool m_Jump;
private float m_YRotation;
private Vector2 m_Input;
private Vector3 m_MoveDir = Vector3.zero;
private CharacterController m_CharacterController;
private CollisionFlags m_CollisionFlags;
private bool m_PreviouslyGrounded;
private Vector3 m_OriginalCameraPosition;
private float m_StepCycle;
private float m_NextStep;
private bool m_Jumping;
private AudioSource m_AudioSource;
// Use this for initialization
private void Start()
{
m_CharacterController = GetComponent<CharacterController>();
m_Camera = Camera.main;
m_OriginalCameraPosition = m_Camera.transform.localPosition;
m_FovKick.Setup(m_Camera);
m_HeadBob.Setup(m_Camera, m_StepInterval);
m_StepCycle = 0f;
m_NextStep = m_StepCycle/2f;
m_Jumping = false;
m_AudioSource = GetComponent<AudioSource>();
m_MouseLook.Init(transform , m_Camera.transform);
}
// Update is called once per frame
private void Update()
{
RotateView();
// the jump state needs to read here to make sure it is not missed
if (!m_Jump)
{
m_Jump = Input.GetButtonDown("Jump");
}
if (!m_PreviouslyGrounded && m_CharacterController.isGrounded)
{
StartCoroutine(m_JumpBob.DoBobCycle());
PlayLandingSound();
m_MoveDir.y = 0f;
m_Jumping = false;
}
if (!m_CharacterController.isGrounded && !m_Jumping && m_PreviouslyGrounded)
{
m_MoveDir.y = 0f;
}
m_PreviouslyGrounded = m_CharacterController.isGrounded;
}
private void PlayLandingSound()
{
m_AudioSource.clip = m_LandSound;
m_AudioSource.Play();
m_NextStep = m_StepCycle + .5f;
}
private void FixedUpdate()
{
float speed;
GetInput(out speed);
// always move along the camera forward as it is the direction that it being aimed at
Vector3 desiredMove = transform.forward*m_Input.y + transform.right*m_Input.x;
// get a normal for the surface that is being touched to move along it
RaycastHit hitInfo;
Physics.SphereCast(transform.position, m_CharacterController.radius, Vector3.down, out hitInfo,
m_CharacterController.height/2f, Physics.AllLayers, QueryTriggerInteraction.Ignore);
desiredMove = Vector3.ProjectOnPlane(desiredMove, hitInfo.normal).normalized;
m_MoveDir.x = desiredMove.x*speed;
m_MoveDir.z = desiredMove.z*speed;
if (m_CharacterController.isGrounded)
{
m_MoveDir.y = -m_StickToGroundForce;
if (m_Jump)
{
m_MoveDir.y = m_JumpSpeed;
PlayJumpSound();
m_Jump = false;
m_Jumping = true;
}
}
else
{
m_MoveDir += Physics.gravity*m_GravityMultiplier*Time.fixedDeltaTime;
}
m_CollisionFlags = m_CharacterController.Move(m_MoveDir*Time.fixedDeltaTime);
ProgressStepCycle(speed);
UpdateCameraPosition(speed);
m_MouseLook.UpdateCursorLock();
}
private void PlayJumpSound()
{
m_AudioSource.clip = m_JumpSound;
m_AudioSource.Play();
}
private void ProgressStepCycle(float speed)
{
if (m_CharacterController.velocity.sqrMagnitude > 0 && (m_Input.x != 0 || m_Input.y != 0))
{
m_StepCycle += (m_CharacterController.velocity.magnitude + (speed*(m_IsWalking ? 1f : m_RunstepLenghten)))*
Time.fixedDeltaTime;
}
if (!(m_StepCycle > m_NextStep))
{
return;
}
m_NextStep = m_StepCycle + m_StepInterval;
PlayFootStepAudio();
}
private void PlayFootStepAudio()
{
if (!m_CharacterController.isGrounded)
{
return;
}
// pick & play a random footstep sound from the array,
// excluding sound at index 0
int n = Random.Range(1, m_FootstepSounds.Length);
m_AudioSource.clip = m_FootstepSounds[n];
m_AudioSource.PlayOneShot(m_AudioSource.clip);
// move picked sound to index 0 so it's not picked next time
m_FootstepSounds[n] = m_FootstepSounds[0];
m_FootstepSounds[0] = m_AudioSource.clip;
}
private void UpdateCameraPosition(float speed)
{
Vector3 newCameraPosition;
/* if (!m_UseHeadBob)
{
return;
}*/
if (m_CharacterController.velocity.magnitude > 0 && m_CharacterController.isGrounded)
{
m_Camera.transform.localPosition =
m_HeadBob.DoHeadBob(m_CharacterController.velocity.magnitude +
(speed*(m_IsWalking ? 1f : m_RunstepLenghten)));
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_Camera.transform.localPosition.y - m_JumpBob.Offset();
}
else
{
newCameraPosition = m_Camera.transform.localPosition;
newCameraPosition.y = m_OriginalCameraPosition.y - m_JumpBob.Offset();
}
m_Camera.transform.localPosition = newCameraPosition;
}
private void GetInput(out float speed)
{
// Read input
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
bool waswalking = m_IsWalking;
// On standalone builds, walk/run speed is modified by a key press.
// keep track of whether or not the character is walking or running
m_IsWalking = !Input.GetKey(KeyCode.LeftShift);
// set the desired speed to be walking or running
speed = m_IsWalking ? m_WalkSpeed : m_RunSpeed;
m_Input = new Vector2(horizontal, vertical);
// normalize input if it exceeds 1 in combined length:
if (m_Input.sqrMagnitude > 1)
{
m_Input.Normalize();
}
// handle speed change to give an fov kick
// only if the player is going to a run, is running and the fovkick is to be used
if (m_IsWalking != waswalking && m_UseFovKick && m_CharacterController.velocity.sqrMagnitude > 0)
{
StopAllCoroutines();
StartCoroutine(!m_IsWalking ? m_FovKick.FOVKickUp() : m_FovKick.FOVKickDown());
}
}
private void RotateView()
{
m_MouseLook.LookRotation (transform, m_Camera.transform);
}
private void OnControllerColliderHit(ControllerColliderHit hit)
{
Rigidbody body = hit.collider.attachedRigidbody;
//dont move the rigidbody if the character is on top of it
if (m_CollisionFlags == CollisionFlags.Below)
{
return;
}
if (body == null || body.isKinematic)
{
return;
}
body.AddForceAtPosition(m_CharacterController.velocity*0.1f, hit.point, ForceMode.Impulse);
}
}
}
| |
using System;
using System.Data;
using System.Data.OleDb;
using PCSComUtils.Common;
using PCSComUtils.DataAccess;
using PCSComUtils.PCSExc;
namespace PCSComSale.Order.DS
{
/// <summary>
/// Summary description for SO_InvoiceMasterDS.
/// </summary>
public class SO_InvoiceMasterDS
{
private const string THIS = "PCSComSale.Order.DS.SO_InvoiceMasterDS";
//**************************************************************************
/// <Description>
/// This method uses to get master vo
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// Nguyen An Duong - iSphere software
/// </Authors>
/// <History>
/// Thursday, October 28, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet GetCommitedDelSchLines(int pintSOMasterID, string strGateIDs)
{
const string METHOD_NAME = THIS + ".GetCommitedDelSchLines()";
DataSet dstPCS = new DataSet();
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
strSql = " SELECT"
+ " C.Code, B.SaleOrderLine, A.Line,"
+
" D.Code PartNo, D.Description, D.Revision, CA.Code ITM_CategoryCode, F.Code UMCode, B.SaleOrderDetailID, A.DeliveryScheduleID, D.ProductID, "
+
" IsNull((SELECT SUM(CommitQuantity) FROM SO_CommitInventoryDetail E WHERE E.DeliveryScheduleID = A.DeliveryScheduleID AND IsNull(E.Shipped,0) = 0),0) CommittedQuantity,"
+
" 0.0 InvoiceQty, 0.0 OldInvoiceQty, 0.0 AvailableQty, B.UnitPrice Price, B.VATPercent, 0.0 VATAmount,G.Code SO_GateCode,"
+ " CID.LocationID, CID.BINID "
+ " FROM "
+ " SO_DeliverySchedule A INNER JOIN SO_SaleOrderDetail B ON A.SaleOrderDetailID = B.SaleOrderDetailID"
+ " INNER JOIN SO_SaleOrderMaster C ON B.SaleOrderMasterID = C.SaleOrderMasterID"
+ " INNER JOIN ITM_Product D ON B.ProductID = D.ProductID"
+ " LEFT JOIN ITM_Category CA ON CA.CategoryID = D.CategoryID"
+ " LEFT JOIN SO_CommitInventoryDetail CID ON CID.DeliveryScheduleID = A.DeliveryScheduleID"
+ " LEFT JOIN SO_Gate G ON G.GateID = A.GateID"
+ " INNER JOIN MST_UnitOfMeasure F ON B.SellingUMID = F.UnitOfMeasureID"
+ " WHERE C.SaleOrderMasterID = ?"
+
" AND IsNull((SELECT SUM(CommitQuantity) FROM SO_CommitInventoryDetail E WHERE E.DeliveryScheduleID = A.DeliveryScheduleID AND IsNull(E.Shipped,0) = 0),0) > 0";
if (strGateIDs != string.Empty)
{
strSql += " AND A." + SO_DeliveryScheduleTable.GATEID_FLD + " IN (" + strGateIDs + ")";
}
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
ocmdPCS.Connection.Open();
ocmdPCS.Parameters.AddWithValue(SO_SaleOrderMasterTable.SALEORDERMASTERID_FLD, pintSOMasterID);
OleDbDataAdapter odadPCS = new OleDbDataAdapter(ocmdPCS);
odadPCS.Fill(dstPCS);
return dstPCS;
}
catch (OleDbException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public Object GetObjectVO(int pintID)
{
throw new NotImplementedException();
}
public DataSet List()
{
throw new NotImplementedException();
}
public void Delete(int pintID)
{
throw new NotImplementedException();
}
public void Update(Object pobjObjecVO)
{
const string METHOD_NAME = THIS + ".Update()";
SO_InvoiceMasterVO objObject = (SO_InvoiceMasterVO) pobjObjecVO;
//prepare value for parameters
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
try
{
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand(strSql, oconPCS);
strSql = "UPDATE SO_InvoiceMaster SET "
+ SO_InvoiceMasterTable.CONFIRMSHIPNO_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.SHIPPEDDATE_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.SALEORDERMASTERID_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.MASTERLOCATIONID_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.CURRENCYID_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.EXCHANGERATE_FLD + "= ?" + ","
//+ SO_InvoiceMasterTable.GATEID_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.SHIPCODE_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.FROMPORT_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.CNO_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.MEASUREMENT_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.GROSSWEIGHT_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.NETWEIGHT_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.ISSUINGBANK_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.LCNO_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.VESSELNAME_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.COMMENT_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.REFERENCENO_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.INVOICENO_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.LCDATE_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.ONBOARDDATE_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.INVOICEDATE_FLD + "= ?" + ","
+ SO_InvoiceMasterTable.CCNID_FLD + "= ?"
+ " WHERE " + SO_InvoiceMasterTable.INVOICEMASTERID_FLD + "= ?";
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.CONFIRMSHIPNO_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.CONFIRMSHIPNO_FLD].Value = objObject.ConfirmShipNo;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.SHIPPEDDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[SO_InvoiceMasterTable.SHIPPEDDATE_FLD].Value = objObject.ShippedDate;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.SALEORDERMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_InvoiceMasterTable.SALEORDERMASTERID_FLD].Value = objObject.SaleOrderMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.MASTERLOCATIONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_InvoiceMasterTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.CURRENCYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_InvoiceMasterTable.CURRENCYID_FLD].Value = objObject.CurrencyID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.EXCHANGERATE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[SO_InvoiceMasterTable.EXCHANGERATE_FLD].Value = objObject.ExchangeRate;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.SHIPCODE_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.SHIPCODE_FLD].Value = objObject.ShipCode;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.FROMPORT_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.FROMPORT_FLD].Value = objObject.FromPort;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.CNO_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.CNO_FLD].Value = objObject.CNo;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.MEASUREMENT_FLD, OleDbType.Decimal));
if (objObject.Measurement != 0)
{
ocmdPCS.Parameters[SO_InvoiceMasterTable.MEASUREMENT_FLD].Value = objObject.Measurement;
}
else
ocmdPCS.Parameters[SO_InvoiceMasterTable.MEASUREMENT_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.GROSSWEIGHT_FLD, OleDbType.Decimal));
if (objObject.GrossWeight != 0)
{
ocmdPCS.Parameters[SO_InvoiceMasterTable.GROSSWEIGHT_FLD].Value = objObject.GrossWeight;
}
else
ocmdPCS.Parameters[SO_InvoiceMasterTable.GROSSWEIGHT_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.NETWEIGHT_FLD, OleDbType.Decimal));
if (objObject.NetWeight != 0)
{
ocmdPCS.Parameters[SO_InvoiceMasterTable.NETWEIGHT_FLD].Value = objObject.NetWeight;
}
else
ocmdPCS.Parameters[SO_InvoiceMasterTable.NETWEIGHT_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.ISSUINGBANK_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.ISSUINGBANK_FLD].Value = objObject.IssuingBank;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.LCNO_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.LCNO_FLD].Value = objObject.LCNo;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.VESSELNAME_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.VESSELNAME_FLD].Value = objObject.VesselName;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.COMMENT_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.COMMENT_FLD].Value = objObject.Comment;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.REFERENCENO_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.REFERENCENO_FLD].Value = objObject.ReferenceNo;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.INVOICENO_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.INVOICENO_FLD].Value = objObject.InvoiceNo;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.LCDATE_FLD, OleDbType.Date));
if (objObject.LCDate != DateTime.MinValue)
{
ocmdPCS.Parameters[SO_InvoiceMasterTable.LCDATE_FLD].Value = objObject.LCDate;
}
else
ocmdPCS.Parameters[SO_InvoiceMasterTable.LCDATE_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.ONBOARDDATE_FLD, OleDbType.Date));
if (objObject.OnBoardDate != DateTime.MinValue)
{
ocmdPCS.Parameters[SO_InvoiceMasterTable.ONBOARDDATE_FLD].Value = objObject.OnBoardDate;
}
else
ocmdPCS.Parameters[SO_InvoiceMasterTable.ONBOARDDATE_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.INVOICEDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[SO_InvoiceMasterTable.INVOICEDATE_FLD].Value = objObject.InvoiceDate;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.CCNID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_InvoiceMasterTable.CCNID_FLD].Value = objObject.CCNID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.INVOICEMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_InvoiceMasterTable.INVOICEMASTERID_FLD].Value = objObject.InvoiceMasterID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
ocmdPCS.ExecuteNonQuery();
}
catch (OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
}
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
{
if (oconPCS.State != ConnectionState.Closed)
{
oconPCS.Close();
}
}
}
}
public void Add(Object pobjObjectVO)
{
throw new NotImplementedException();
}
public void UpdateDataSet(DataSet pData)
{
throw new NotImplementedException();
}
//**************************************************************************
/// <Description>
/// This method uses to add data to SO_InvoiceMaster
/// </Description>
/// <Inputs>
/// SO_InvoiceMasterVO
/// </Inputs>
/// <Outputs>
/// newly inserted primarkey value
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// DuongNA
/// </Authors>
/// <History>
/// Friday, October 28, 2005
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int AddReturnID(object pobjObjectVO)
{
const string METHOD_NAME = THIS + ".AddReturnID()";
OleDbConnection oconPCS = null;
OleDbCommand ocmdPCS = null;
object objScalar = null;
try
{
SO_InvoiceMasterVO objObject = (SO_InvoiceMasterVO) pobjObjectVO;
string strSql = String.Empty;
Utils utils = new Utils();
oconPCS = new OleDbConnection(Utils.Instance.OleDbConnectionString);
ocmdPCS = new OleDbCommand("", oconPCS);
strSql = "INSERT INTO SO_InvoiceMaster("
+ SO_InvoiceMasterTable.CONFIRMSHIPNO_FLD + ","
+ SO_InvoiceMasterTable.SHIPPEDDATE_FLD + ","
+ SO_InvoiceMasterTable.SALEORDERMASTERID_FLD + ","
+ SO_InvoiceMasterTable.MASTERLOCATIONID_FLD + ","
+ SO_InvoiceMasterTable.CURRENCYID_FLD + ","
+ SO_InvoiceMasterTable.EXCHANGERATE_FLD + ","
+ SO_InvoiceMasterTable.SHIPCODE_FLD + ","
+ SO_InvoiceMasterTable.FROMPORT_FLD + ","
+ SO_InvoiceMasterTable.CNO_FLD + ","
+ SO_InvoiceMasterTable.MEASUREMENT_FLD + ","
+ SO_InvoiceMasterTable.GROSSWEIGHT_FLD + ","
+ SO_InvoiceMasterTable.NETWEIGHT_FLD + ","
+ SO_InvoiceMasterTable.ISSUINGBANK_FLD + ","
+ SO_InvoiceMasterTable.LCNO_FLD + ","
+ SO_InvoiceMasterTable.VESSELNAME_FLD + ","
+ SO_InvoiceMasterTable.COMMENT_FLD + ","
+ SO_InvoiceMasterTable.REFERENCENO_FLD + ","
+ SO_InvoiceMasterTable.INVOICENO_FLD + ","
+ SO_InvoiceMasterTable.LCDATE_FLD + ","
+ SO_InvoiceMasterTable.ONBOARDDATE_FLD + ","
+ SO_InvoiceMasterTable.INVOICEDATE_FLD + ","
+ SO_InvoiceMasterTable.CCNID_FLD + ")"
+ "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
+ " SELECT @@IDENTITY";
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.CONFIRMSHIPNO_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.CONFIRMSHIPNO_FLD].Value = objObject.ConfirmShipNo;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.SHIPPEDDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[SO_InvoiceMasterTable.SHIPPEDDATE_FLD].Value = objObject.ShippedDate;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.SALEORDERMASTERID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_InvoiceMasterTable.SALEORDERMASTERID_FLD].Value = objObject.SaleOrderMasterID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.MASTERLOCATIONID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_InvoiceMasterTable.MASTERLOCATIONID_FLD].Value = objObject.MasterLocationID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.CURRENCYID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_InvoiceMasterTable.CURRENCYID_FLD].Value = objObject.CurrencyID;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.EXCHANGERATE_FLD, OleDbType.Decimal));
ocmdPCS.Parameters[SO_InvoiceMasterTable.EXCHANGERATE_FLD].Value = objObject.ExchangeRate;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.SHIPCODE_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.SHIPCODE_FLD].Value = objObject.ShipCode;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.FROMPORT_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.FROMPORT_FLD].Value = objObject.FromPort;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.CNO_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.CNO_FLD].Value = objObject.CNo;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.MEASUREMENT_FLD, OleDbType.Decimal));
if (objObject.Measurement != 0)
{
ocmdPCS.Parameters[SO_InvoiceMasterTable.MEASUREMENT_FLD].Value = objObject.Measurement;
}
else
ocmdPCS.Parameters[SO_InvoiceMasterTable.MEASUREMENT_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.GROSSWEIGHT_FLD, OleDbType.Decimal));
if (objObject.GrossWeight != 0)
{
ocmdPCS.Parameters[SO_InvoiceMasterTable.GROSSWEIGHT_FLD].Value = objObject.GrossWeight;
}
else
ocmdPCS.Parameters[SO_InvoiceMasterTable.GROSSWEIGHT_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.NETWEIGHT_FLD, OleDbType.Decimal));
if (objObject.NetWeight != 0)
{
ocmdPCS.Parameters[SO_InvoiceMasterTable.NETWEIGHT_FLD].Value = objObject.NetWeight;
}
else
ocmdPCS.Parameters[SO_InvoiceMasterTable.NETWEIGHT_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.ISSUINGBANK_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.ISSUINGBANK_FLD].Value = objObject.IssuingBank;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.LCNO_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.LCNO_FLD].Value = objObject.LCNo;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.VESSELNAME_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.VESSELNAME_FLD].Value = objObject.VesselName;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.COMMENT_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.COMMENT_FLD].Value = objObject.Comment;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.REFERENCENO_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.REFERENCENO_FLD].Value = objObject.ReferenceNo;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.INVOICENO_FLD, OleDbType.WChar));
ocmdPCS.Parameters[SO_InvoiceMasterTable.INVOICENO_FLD].Value = objObject.InvoiceNo;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.LCDATE_FLD, OleDbType.Date));
if (objObject.LCDate != DateTime.MinValue)
{
ocmdPCS.Parameters[SO_InvoiceMasterTable.LCDATE_FLD].Value = objObject.LCDate;
}
else
ocmdPCS.Parameters[SO_InvoiceMasterTable.LCDATE_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.ONBOARDDATE_FLD, OleDbType.Date));
if (objObject.OnBoardDate != DateTime.MinValue)
{
ocmdPCS.Parameters[SO_InvoiceMasterTable.ONBOARDDATE_FLD].Value = objObject.OnBoardDate;
}
else
ocmdPCS.Parameters[SO_InvoiceMasterTable.ONBOARDDATE_FLD].Value = DBNull.Value;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.INVOICEDATE_FLD, OleDbType.Date));
ocmdPCS.Parameters[SO_InvoiceMasterTable.INVOICEDATE_FLD].Value = objObject.InvoiceDate;
ocmdPCS.Parameters.Add(new OleDbParameter(SO_InvoiceMasterTable.CCNID_FLD, OleDbType.Integer));
ocmdPCS.Parameters[SO_InvoiceMasterTable.CCNID_FLD].Value = objObject.CCNID;
ocmdPCS.CommandText = strSql;
ocmdPCS.Connection.Open();
objScalar = ocmdPCS.ExecuteScalar();
return int.Parse(objScalar.ToString());
}
catch (OleDbException ex)
{
if (ex.Errors.Count > 1)
{
if (ex.Errors[1].NativeError == ErrorCode.SQLDUPLICATE_KEYCODE)
throw new PCSDBException(ErrorCode.DUPLICATE_KEY, METHOD_NAME, ex);
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
else
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (InvalidOperationException ex)
{
throw new PCSDBException(ErrorCode.ERROR_DB, METHOD_NAME, ex);
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
finally
{
if (oconPCS != null)
if (oconPCS.State != ConnectionState.Closed)
oconPCS.Close();
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Abp.Application.Features;
using Abp.Authorization.Roles;
using Abp.Configuration;
using Abp.Configuration.Startup;
using Abp.Dependency;
using Abp.Domain.Repositories;
using Abp.Domain.Services;
using Abp.Domain.Uow;
using Abp.Extensions;
using Abp.IdentityFramework;
using Abp.Localization;
using Abp.MultiTenancy;
using Abp.Runtime.Caching;
using Abp.Runtime.Security;
using Abp.Runtime.Session;
using Abp.Timing;
using Abp.Zero;
using Abp.Zero.Configuration;
using Microsoft.AspNet.Identity;
namespace Abp.Authorization.Users
{
/// <summary>
/// Extends <see cref="UserManager{TUser,TKey}"/> of ASP.NET Identity Framework.
/// </summary>
public abstract class AbpUserManager<TTenant, TRole, TUser>
: UserManager<TUser, long>,
IDomainService
where TTenant : AbpTenant<TTenant, TUser>
where TRole : AbpRole<TTenant, TUser>, new()
where TUser : AbpUser<TTenant, TUser>
{
private IUserPermissionStore<TTenant, TUser> UserPermissionStore
{
get
{
if (!(Store is IUserPermissionStore<TTenant, TUser>))
{
throw new AbpException("Store is not IUserPermissionStore");
}
return Store as IUserPermissionStore<TTenant, TUser>;
}
}
public ILocalizationManager LocalizationManager { get; set; }
public IAbpSession AbpSession { get; set; }
public FeatureDependencyContext FeatureDependencyContext { get; set; }
protected AbpRoleManager<TTenant, TRole, TUser> RoleManager { get; private set; }
protected ISettingManager SettingManager { get; private set; }
protected AbpUserStore<TTenant, TRole, TUser> AbpStore { get; private set; }
private readonly IPermissionManager _permissionManager;
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly IUserManagementConfig _userManagementConfig;
private readonly IIocResolver _iocResolver;
private readonly IRepository<TTenant> _tenantRepository;
private readonly IMultiTenancyConfig _multiTenancyConfig;
private readonly ICacheManager _cacheManager;
protected AbpUserManager(
AbpUserStore<TTenant, TRole, TUser> userStore,
AbpRoleManager<TTenant, TRole, TUser> roleManager,
IRepository<TTenant> tenantRepository,
IMultiTenancyConfig multiTenancyConfig,
IPermissionManager permissionManager,
IUnitOfWorkManager unitOfWorkManager,
ISettingManager settingManager,
IUserManagementConfig userManagementConfig,
IIocResolver iocResolver,
ICacheManager cacheManager)
: base(userStore)
{
AbpStore = userStore;
RoleManager = roleManager;
SettingManager = settingManager;
_tenantRepository = tenantRepository;
_multiTenancyConfig = multiTenancyConfig;
_permissionManager = permissionManager;
_unitOfWorkManager = unitOfWorkManager;
_userManagementConfig = userManagementConfig;
_iocResolver = iocResolver;
_cacheManager = cacheManager;
LocalizationManager = NullLocalizationManager.Instance;
}
public override async Task<IdentityResult> CreateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
if (AbpSession.TenantId.HasValue)
{
user.TenantId = AbpSession.TenantId.Value;
}
return await base.CreateAsync(user);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permissionName">Permission name</param>
public virtual async Task<bool> IsGrantedAsync(long userId, string permissionName)
{
return await IsGrantedAsync(
userId,
_permissionManager.GetPermission(permissionName)
);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual Task<bool> IsGrantedAsync(TUser user, Permission permission)
{
return IsGrantedAsync(user.Id, permission);
}
/// <summary>
/// Check whether a user is granted for a permission.
/// </summary>
/// <param name="userId">User id</param>
/// <param name="permission">Permission</param>
public virtual async Task<bool> IsGrantedAsync(long userId, Permission permission)
{
//Check for multi-tenancy side
if (!permission.MultiTenancySides.HasFlag(AbpSession.MultiTenancySide))
{
return false;
}
//Check for depended features
if (permission.DependedFeature != null && AbpSession.MultiTenancySide == MultiTenancySides.Tenant)
{
if (!await permission.DependedFeature.IsSatisfiedAsync(FeatureDependencyContext))
{
return false;
}
}
//Get cached user permissions
var cacheItem = await GetUserPermissionCacheItemAsync(userId);
//Check for user-specific value
if (cacheItem.GrantedPermissions.Contains(permission.Name))
{
return true;
}
if (cacheItem.ProhibitedPermissions.Contains(permission.Name))
{
return false;
}
//Check for roles
foreach (var roleId in cacheItem.RoleIds)
{
if (await RoleManager.IsGrantedAsync(roleId, permission))
{
return true;
}
}
return false;
}
/// <summary>
/// Gets granted permissions for a user.
/// </summary>
/// <param name="user">Role</param>
/// <returns>List of granted permissions</returns>
public virtual async Task<IReadOnlyList<Permission>> GetGrantedPermissionsAsync(TUser user)
{
var permissionList = new List<Permission>();
foreach (var permission in _permissionManager.GetAllPermissions())
{
if (await IsGrantedAsync(user.Id, permission))
{
permissionList.Add(permission);
}
}
return permissionList;
}
/// <summary>
/// Sets all granted permissions of a user at once.
/// Prohibits all other permissions.
/// </summary>
/// <param name="user">The user</param>
/// <param name="permissions">Permissions</param>
public virtual async Task SetGrantedPermissionsAsync(TUser user, IEnumerable<Permission> permissions)
{
var oldPermissions = await GetGrantedPermissionsAsync(user);
var newPermissions = permissions.ToArray();
foreach (var permission in oldPermissions.Where(p => !newPermissions.Contains(p)))
{
await ProhibitPermissionAsync(user, permission);
}
foreach (var permission in newPermissions.Where(p => !oldPermissions.Contains(p)))
{
await GrantPermissionAsync(user, permission);
}
}
/// <summary>
/// Prohibits all permissions for a user.
/// </summary>
/// <param name="user">User</param>
public async Task ProhibitAllPermissionsAsync(TUser user)
{
foreach (var permission in _permissionManager.GetAllPermissions())
{
await ProhibitPermissionAsync(user, permission);
}
}
/// <summary>
/// Resets all permission settings for a user.
/// It removes all permission settings for the user.
/// User will have permissions according to his roles.
/// This method does not prohibit all permissions.
/// For that, use <see cref="ProhibitAllPermissionsAsync"/>.
/// </summary>
/// <param name="user">User</param>
public async Task ResetAllPermissionsAsync(TUser user)
{
await UserPermissionStore.RemoveAllPermissionSettingsAsync(user);
}
/// <summary>
/// Grants a permission for a user if not already granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task GrantPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
if (await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
}
/// <summary>
/// Prohibits a permission for a user if it's granted.
/// </summary>
/// <param name="user">User</param>
/// <param name="permission">Permission</param>
public virtual async Task ProhibitPermissionAsync(TUser user, Permission permission)
{
await UserPermissionStore.RemovePermissionAsync(user, new PermissionGrantInfo(permission.Name, true));
if (!await IsGrantedAsync(user.Id, permission))
{
return;
}
await UserPermissionStore.AddPermissionAsync(user, new PermissionGrantInfo(permission.Name, false));
}
public virtual async Task<TUser> FindByNameOrEmailAsync(string userNameOrEmailAddress)
{
return await AbpStore.FindByNameOrEmailAsync(userNameOrEmailAddress);
}
public virtual Task<List<TUser>> FindAllAsync(UserLoginInfo login)
{
return AbpStore.FindAllAsync(login);
}
[UnitOfWork]
public virtual async Task<AbpLoginResult> LoginAsync(UserLoginInfo login, string tenancyName = null)
{
if (login == null || login.LoginProvider.IsNullOrEmpty() || login.ProviderKey.IsNullOrEmpty())
{
throw new ArgumentException("login");
}
//Get and check tenant
TTenant tenant = null;
if (!_multiTenancyConfig.IsEnabled)
{
tenant = await GetDefaultTenantAsync();
}
else if (!string.IsNullOrWhiteSpace(tenancyName))
{
tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName);
if (tenant == null)
{
return new AbpLoginResult(AbpLoginResultType.InvalidTenancyName);
}
if (!tenant.IsActive)
{
return new AbpLoginResult(AbpLoginResultType.TenantIsNotActive);
}
}
using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))
{
var user = await AbpStore.FindAsync(tenant == null ? (int?)null : tenant.Id, login);
if (user == null)
{
return new AbpLoginResult(AbpLoginResultType.UnknownExternalLogin);
}
return await CreateLoginResultAsync(user);
}
}
[UnitOfWork]
public virtual async Task<AbpLoginResult> LoginAsync(string userNameOrEmailAddress, string plainPassword, string tenancyName = null)
{
if (userNameOrEmailAddress.IsNullOrEmpty())
{
throw new ArgumentNullException("userNameOrEmailAddress");
}
if (plainPassword.IsNullOrEmpty())
{
throw new ArgumentNullException("plainPassword");
}
//Get and check tenant
TTenant tenant = null;
if (!_multiTenancyConfig.IsEnabled)
{
tenant = await GetDefaultTenantAsync();
}
else if (!string.IsNullOrWhiteSpace(tenancyName))
{
tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == tenancyName);
if (tenant == null)
{
return new AbpLoginResult(AbpLoginResultType.InvalidTenancyName);
}
if (!tenant.IsActive)
{
return new AbpLoginResult(AbpLoginResultType.TenantIsNotActive);
}
}
using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.MayHaveTenant))
{
var loggedInFromExternalSource = await TryLoginFromExternalAuthenticationSources(userNameOrEmailAddress, plainPassword, tenant);
var user = await AbpStore.FindByNameOrEmailAsync(tenant == null ? (int?)null : tenant.Id, userNameOrEmailAddress);
// var user = await AbpStore.FindByEmailAsync(userNameOrEmailAddress);
if (user == null)
{
return new AbpLoginResult(AbpLoginResultType.InvalidUserNameOrEmailAddress);
}
if (!loggedInFromExternalSource)
{
var verificationResult = new PasswordHasher().VerifyHashedPassword(user.Password, plainPassword);
if (verificationResult != PasswordVerificationResult.Success)
{
return new AbpLoginResult(AbpLoginResultType.InvalidPassword);
}
}
return await CreateLoginResultAsync(user);
}
}
private async Task<AbpLoginResult> CreateLoginResultAsync(TUser user)
{
if (!user.IsActive)
{
return new AbpLoginResult(AbpLoginResultType.UserIsNotActive);
}
if (await IsEmailConfirmationRequiredForLoginAsync(user.TenantId) && !user.IsEmailConfirmed)
{
return new AbpLoginResult(AbpLoginResultType.UserEmailIsNotConfirmed);
}
user.LastLoginTime = Clock.Now;
await Store.UpdateAsync(user);
await _unitOfWorkManager.Current.SaveChangesAsync();
return new AbpLoginResult(user, await CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie));
}
private async Task<bool> TryLoginFromExternalAuthenticationSources(string userNameOrEmailAddress, string plainPassword, TTenant tenant)
{
if (!_userManagementConfig.ExternalAuthenticationSources.Any())
{
return false;
}
foreach (var sourceType in _userManagementConfig.ExternalAuthenticationSources)
{
using (var source = _iocResolver.ResolveAsDisposable<IExternalAuthenticationSource<TTenant, TUser>>(sourceType))
{
if (await source.Object.TryAuthenticateAsync(userNameOrEmailAddress, plainPassword, tenant))
{
var tenantId = tenant == null ? (int?)null : tenant.Id;
var user = await AbpStore.FindByNameOrEmailAsync(tenantId, userNameOrEmailAddress);
if (user == null)
{
user = await source.Object.CreateUserAsync(userNameOrEmailAddress, tenant);
user.Tenant = tenant;
user.AuthenticationSource = source.Object.Name;
user.Password = new PasswordHasher().HashPassword(Guid.NewGuid().ToString("N").Left(16)); //Setting a random password since it will not be used
user.Roles = new List<UserRole>();
foreach (var defaultRole in RoleManager.Roles.Where(r => r.TenantId == tenantId && r.IsDefault).ToList())
{
user.Roles.Add(new UserRole { RoleId = defaultRole.Id });
}
await Store.CreateAsync(user);
}
else
{
await source.Object.UpdateUserAsync(user, tenant);
user.AuthenticationSource = source.Object.Name;
await Store.UpdateAsync(user);
}
await _unitOfWorkManager.Current.SaveChangesAsync();
return true;
}
}
}
return false;
}
/// <summary>
/// Gets a user by given id.
/// Throws exception if no user found with given id.
/// </summary>
/// <param name="userId">User id</param>
/// <returns>User</returns>
/// <exception cref="AbpException">Throws exception if no user found with given id</exception>
public virtual async Task<TUser> GetUserByIdAsync(long userId)
{
var user = await FindByIdAsync(userId);
if (user == null)
{
throw new AbpException("There is no user with id: " + userId);
}
return user;
}
public async override Task<ClaimsIdentity> CreateIdentityAsync(TUser user, string authenticationType)
{
var identity = await base.CreateIdentityAsync(user, authenticationType);
if (user.TenantId.HasValue)
{
identity.AddClaim(new Claim(AbpClaimTypes.TenantId, user.TenantId.Value.ToString(CultureInfo.InvariantCulture)));
}
return identity;
}
public async override Task<IdentityResult> UpdateAsync(TUser user)
{
var result = await CheckDuplicateUsernameOrEmailAddressAsync(user.Id, user.UserName, user.EmailAddress);
if (!result.Succeeded)
{
return result;
}
var oldUserName = (await GetUserByIdAsync(user.Id)).UserName;
if (oldUserName == AbpUser<TTenant, TUser>.AdminUserName && user.UserName != AbpUser<TTenant, TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotRenameAdminUser"), AbpUser<TTenant, TUser>.AdminUserName));
}
return await base.UpdateAsync(user);
}
public async override Task<IdentityResult> DeleteAsync(TUser user)
{
if (user.UserName == AbpUser<TTenant, TUser>.AdminUserName)
{
return AbpIdentityResult.Failed(string.Format(L("CanNotDeleteAdminUser"), AbpUser<TTenant, TUser>.AdminUserName));
}
return await base.DeleteAsync(user);
}
public virtual async Task<IdentityResult> ChangePasswordAsync(TUser user, string newPassword)
{
var result = await PasswordValidator.ValidateAsync(newPassword);
if (!result.Succeeded)
{
return result;
}
await AbpStore.SetPasswordHashAsync(user, PasswordHasher.HashPassword(newPassword));
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> CheckDuplicateUsernameOrEmailAddressAsync(long? expectedUserId, string userName, string emailAddress)
{
var user = (await FindByNameAsync(userName));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateName"), userName));
}
user = (await FindByEmailAsync(emailAddress));
if (user != null && user.Id != expectedUserId)
{
return AbpIdentityResult.Failed(string.Format(L("Identity.DuplicateEmail"), emailAddress));
}
return IdentityResult.Success;
}
public virtual async Task<IdentityResult> SetRoles(TUser user, string[] roleNames)
{
//Remove from removed roles
foreach (var userRole in user.Roles.ToList())
{
var role = await RoleManager.FindByIdAsync(userRole.RoleId);
if (roleNames.All(roleName => role.Name != roleName))
{
var result = await RemoveFromRoleAsync(user.Id, role.Name);
if (!result.Succeeded)
{
return result;
}
}
}
//Add to added roles
foreach (var roleName in roleNames)
{
var role = await RoleManager.GetRoleByNameAsync(roleName);
if (user.Roles.All(ur => ur.RoleId != role.Id))
{
var result = await AddToRoleAsync(user.Id, roleName);
if (!result.Succeeded)
{
return result;
}
}
}
return IdentityResult.Success;
}
private async Task<bool> IsEmailConfirmationRequiredForLoginAsync(int? tenantId)
{
if (tenantId.HasValue)
{
return await SettingManager.GetSettingValueForTenantAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin, tenantId.Value);
}
return await SettingManager.GetSettingValueForApplicationAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin);
}
private async Task<TTenant> GetDefaultTenantAsync()
{
var tenant = await _tenantRepository.FirstOrDefaultAsync(t => t.TenancyName == AbpTenant<TTenant, TUser>.DefaultTenantName);
if (tenant == null)
{
throw new AbpException("There should be a 'Default' tenant if multi-tenancy is disabled!");
}
return tenant;
}
private async Task<UserPermissionCacheItem> GetUserPermissionCacheItemAsync(long userId)
{
return await _cacheManager.GetUserPermissionCache().GetAsync(userId, async () =>
{
var newCacheItem = new UserPermissionCacheItem(userId);
foreach (var roleName in await GetRolesAsync(userId))
{
newCacheItem.RoleIds.Add((await RoleManager.GetRoleByNameAsync(roleName)).Id);
}
foreach (var permissionInfo in await UserPermissionStore.GetPermissionsAsync(userId))
{
if (permissionInfo.IsGranted)
{
newCacheItem.GrantedPermissions.Add(permissionInfo.Name);
}
else
{
newCacheItem.ProhibitedPermissions.Add(permissionInfo.Name);
}
}
return newCacheItem;
});
}
private string L(string name)
{
return LocalizationManager.GetString(AbpZeroConsts.LocalizationSourceName, name);
}
public class AbpLoginResult
{
public AbpLoginResultType Result { get; private set; }
public TUser User { get; private set; }
public ClaimsIdentity Identity { get; private set; }
public AbpLoginResult(AbpLoginResultType result)
{
Result = result;
}
public AbpLoginResult(TUser user, ClaimsIdentity identity)
: this(AbpLoginResultType.Success)
{
User = user;
Identity = identity;
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Orleans.Runtime.Configuration;
using Orleans.Runtime.Scheduler;
namespace Orleans.Runtime.GrainDirectory
{
/// <summary>
/// Most methods of this class are synchronized since they might be called both
/// from LocalGrainDirectory on CacheValidator.SchedulingContext and from RemoteGrainDirectory.
/// </summary>
internal class GrainDirectoryHandoffManager
{
private const int HANDOFF_CHUNK_SIZE = 500;
private readonly LocalGrainDirectory localDirectory;
private readonly ISiloStatusOracle siloStatusOracle;
private readonly Dictionary<SiloAddress, GrainDirectoryPartition> directoryPartitionsMap;
private readonly List<SiloAddress> silosHoldingMyPartition;
private readonly Dictionary<SiloAddress, Task> lastPromise;
private readonly Logger logger;
internal GrainDirectoryHandoffManager(LocalGrainDirectory localDirectory, ISiloStatusOracle siloStatusOracle)
{
logger = LogManager.GetLogger(this.GetType().FullName);
this.localDirectory = localDirectory;
this.siloStatusOracle = siloStatusOracle;
directoryPartitionsMap = new Dictionary<SiloAddress, GrainDirectoryPartition>();
silosHoldingMyPartition = new List<SiloAddress>();
lastPromise = new Dictionary<SiloAddress, Task>();
}
internal List<ActivationAddress> GetHandedOffInfo(GrainId grain)
{
lock (this)
{
foreach (var partition in directoryPartitionsMap.Values)
{
var result = partition.LookUpActivations(grain);
if (result.Addresses != null)
return result.Addresses;
}
}
return null;
}
private async Task HandoffMyPartitionUponStop(Dictionary<GrainId, IGrainInfo> batchUpdate, bool isFullCopy)
{
if (batchUpdate.Count == 0 || silosHoldingMyPartition.Count == 0)
{
if (logger.IsVerbose) logger.Verbose((isFullCopy ? "FULL" : "DELTA") + " handoff finished with empty delta (nothing to send)");
return;
}
if (logger.IsVerbose) logger.Verbose("Sending {0} items to my {1}: (ring status is {2})",
batchUpdate.Count, silosHoldingMyPartition.ToStrings(), localDirectory.RingStatusToString());
var tasks = new List<Task>();
var n = 0;
var chunk = new Dictionary<GrainId, IGrainInfo>();
// Note that batchUpdate will not change while this method is executing
foreach (var pair in batchUpdate)
{
chunk[pair.Key] = pair.Value;
n++;
if ((n % HANDOFF_CHUNK_SIZE != 0) && (n != batchUpdate.Count))
{
// If we haven't filled in a chunk yet, keep looping.
continue;
}
foreach (SiloAddress silo in silosHoldingMyPartition)
{
SiloAddress captureSilo = silo;
Dictionary<GrainId, IGrainInfo> captureChunk = chunk;
bool captureIsFullCopy = isFullCopy;
if (logger.IsVerbose) logger.Verbose("Sending handed off partition to " + captureSilo);
Task pendingRequest;
if (lastPromise.TryGetValue(captureSilo, out pendingRequest))
{
try
{
await pendingRequest;
}
catch (Exception)
{
}
}
Task task = localDirectory.Scheduler.RunOrQueueTask(
() => localDirectory.GetDirectoryReference(captureSilo).AcceptHandoffPartition(
localDirectory.MyAddress,
captureChunk,
captureIsFullCopy),
localDirectory.RemoteGrainDirectory.SchedulingContext);
lastPromise[captureSilo] = task;
tasks.Add(task);
}
// We need to use a new Dictionary because the call to AcceptHandoffPartition, which reads the current Dictionary,
// happens asynchronously (and typically after some delay).
chunk = new Dictionary<GrainId, IGrainInfo>();
// This is a quick temporary solution. We send a full copy by sending one chunk as a full copy and follow-on chunks as deltas.
// Obviously, this will really mess up if there's a failure after the first chunk but before the others are sent, since on a
// full copy receive the follower dumps all old data and replaces it with the new full copy.
// On the other hand, over time things should correct themselves, and of course, losing directory data isn't necessarily catastrophic.
isFullCopy = false;
}
await Task.WhenAll(tasks);
}
internal void ProcessSiloRemoveEvent(SiloAddress removedSilo)
{
lock (this)
{
if (logger.IsVerbose) logger.Verbose("Processing silo remove event for " + removedSilo);
// Reset our follower list to take the changes into account
ResetFollowers();
// check if this is one of our successors (i.e., if I hold this silo's copy)
// (if yes, adjust local and/or handoffed directory partitions)
if (!directoryPartitionsMap.ContainsKey(removedSilo)) return;
// at least one predcessor should exist, which is me
SiloAddress predecessor = localDirectory.FindPredecessors(removedSilo, 1)[0];
if (localDirectory.MyAddress.Equals(predecessor))
{
if (logger.IsVerbose) logger.Verbose("Merging my partition with the copy of silo " + removedSilo);
// now I am responsible for this directory part
localDirectory.DirectoryPartition.Merge(directoryPartitionsMap[removedSilo]);
// no need to send our new partition to all others, as they
// will realize the change and combine their copies without any additional communication (see below)
}
else
{
if (logger.IsVerbose) logger.Verbose("Merging partition of " + predecessor + " with the copy of silo " + removedSilo);
// adjust copy for the predecessor of the failed silo
directoryPartitionsMap[predecessor].Merge(directoryPartitionsMap[removedSilo]);
}
localDirectory.GsiActivationMaintainer.TrackDoubtfulGrains(directoryPartitionsMap[removedSilo].GetItems());
if (logger.IsVerbose) logger.Verbose("Removed copied partition of silo " + removedSilo);
directoryPartitionsMap.Remove(removedSilo);
}
}
internal void ProcessSiloStoppingEvent()
{
lock (this)
{
ProcessSiloStoppingEvent_Impl();
}
}
private async void ProcessSiloStoppingEvent_Impl()
{
if (logger.IsVerbose) logger.Verbose("Processing silo stopping event");
// Select our nearest predecessor to receive our hand-off, since that's the silo that will wind up owning our partition (assuming
// that it doesn't also fail and that no other silo joins during the transition period).
if (silosHoldingMyPartition.Count == 0)
{
silosHoldingMyPartition.AddRange(localDirectory.FindPredecessors(localDirectory.MyAddress, 1));
}
// take a copy of the current directory partition
Dictionary<GrainId, IGrainInfo> batchUpdate = localDirectory.DirectoryPartition.GetItems();
try
{
await HandoffMyPartitionUponStop(batchUpdate, true);
localDirectory.MarkStopPreparationCompleted();
}
catch (Exception exc)
{
localDirectory.MarkStopPreparationFailed(exc);
}
}
internal void ProcessSiloAddEvent(SiloAddress addedSilo)
{
lock (this)
{
if (logger.IsVerbose) logger.Verbose("Processing silo add event for " + addedSilo);
// Reset our follower list to take the changes into account
ResetFollowers();
// check if this is one of our successors (i.e., if I should hold this silo's copy)
// (if yes, adjust local and/or copied directory partitions by splitting them between old successors and the new one)
// NOTE: We need to move part of our local directory to the new silo if it is an immediate successor.
List<SiloAddress> successors = localDirectory.FindSuccessors(localDirectory.MyAddress, 1);
if (!successors.Contains(addedSilo)) return;
// check if this is an immediate successor
if (successors[0].Equals(addedSilo))
{
// split my local directory and send to my new immediate successor his share
if (logger.IsVerbose) logger.Verbose("Splitting my partition between me and " + addedSilo);
GrainDirectoryPartition splitPart = localDirectory.DirectoryPartition.Split(
grain =>
{
var s = localDirectory.CalculateTargetSilo(grain);
return (s != null) && !localDirectory.MyAddress.Equals(s);
}, false);
List<ActivationAddress> splitPartListSingle = splitPart.ToListOfActivations(true);
List<ActivationAddress> splitPartListMulti = splitPart.ToListOfActivations(false);
if (splitPartListSingle.Count > 0)
{
if (logger.IsVerbose) logger.Verbose("Sending " + splitPartListSingle.Count + " single activation entries to " + addedSilo);
localDirectory.Scheduler.QueueTask(async () =>
{
await localDirectory.GetDirectoryReference(successors[0]).RegisterMany(splitPartListSingle, singleActivation:true);
splitPartListSingle.ForEach(
activationAddress =>
localDirectory.DirectoryPartition.RemoveGrain(activationAddress.Grain));
}, localDirectory.RemoteGrainDirectory.SchedulingContext).Ignore();
}
if (splitPartListMulti.Count > 0)
{
if (logger.IsVerbose) logger.Verbose("Sending " + splitPartListMulti.Count + " entries to " + addedSilo);
localDirectory.Scheduler.QueueTask(async () =>
{
await localDirectory.GetDirectoryReference(successors[0]).RegisterMany(splitPartListMulti, singleActivation:false);
splitPartListMulti.ForEach(
activationAddress =>
localDirectory.DirectoryPartition.RemoveGrain(activationAddress.Grain));
}, localDirectory.RemoteGrainDirectory.SchedulingContext).Ignore();
}
}
else
{
// adjust partitions by splitting them accordingly between new and old silos
SiloAddress predecessorOfNewSilo = localDirectory.FindPredecessors(addedSilo, 1)[0];
if (!directoryPartitionsMap.ContainsKey(predecessorOfNewSilo))
{
// we should have the partition of the predcessor of our new successor
logger.Warn(ErrorCode.DirectoryPartitionPredecessorExpected, "This silo is expected to hold directory partition of " + predecessorOfNewSilo);
}
else
{
if (logger.IsVerbose) logger.Verbose("Splitting partition of " + predecessorOfNewSilo + " and creating a copy for " + addedSilo);
GrainDirectoryPartition splitPart = directoryPartitionsMap[predecessorOfNewSilo].Split(
grain =>
{
// Need to review the 2nd line condition.
var s = localDirectory.CalculateTargetSilo(grain);
return (s != null) && !predecessorOfNewSilo.Equals(s);
}, true);
directoryPartitionsMap[addedSilo] = splitPart;
}
}
// remove partition of one of the old successors that we do not need to now
SiloAddress oldSuccessor = directoryPartitionsMap.FirstOrDefault(pair => !successors.Contains(pair.Key)).Key;
if (oldSuccessor == null) return;
if (logger.IsVerbose) logger.Verbose("Removing copy of the directory partition of silo " + oldSuccessor + " (holding copy of " + addedSilo + " instead)");
directoryPartitionsMap.Remove(oldSuccessor);
}
}
internal void AcceptHandoffPartition(SiloAddress source, Dictionary<GrainId, IGrainInfo> partition, bool isFullCopy)
{
if (logger.IsVerbose) logger.Verbose("Got request to register " + (isFullCopy ? "FULL" : "DELTA") + " directory partition with " + partition.Count + " elements from " + source);
if (!directoryPartitionsMap.ContainsKey(source))
{
if (!isFullCopy)
{
logger.Warn(ErrorCode.DirectoryUnexpectedDelta,
String.Format("Got delta of the directory partition from silo {0} (Membership status {1}) while not holding a full copy. Membership active cluster size is {2}",
source, this.siloStatusOracle.GetApproximateSiloStatus(source),
this.siloStatusOracle.GetApproximateSiloStatuses(true).Count));
}
directoryPartitionsMap[source] = new GrainDirectoryPartition(this.siloStatusOracle);
}
if (isFullCopy)
{
directoryPartitionsMap[source].Set(partition);
}
else
{
directoryPartitionsMap[source].Update(partition);
}
localDirectory.GsiActivationMaintainer.TrackDoubtfulGrains(partition);
}
internal void RemoveHandoffPartition(SiloAddress source)
{
if (logger.IsVerbose) logger.Verbose("Got request to unregister directory partition copy from " + source);
directoryPartitionsMap.Remove(source);
}
private void ResetFollowers()
{
var copyList = silosHoldingMyPartition.ToList();
foreach (var follower in copyList)
{
RemoveOldFollower(follower);
}
}
private void RemoveOldFollower(SiloAddress silo)
{
if (logger.IsVerbose) logger.Verbose("Removing my copy from silo " + silo);
// release this old copy, as we have got a new one
silosHoldingMyPartition.Remove(silo);
localDirectory.Scheduler.QueueTask(() =>
localDirectory.GetDirectoryReference(silo).RemoveHandoffPartition(localDirectory.MyAddress),
localDirectory.RemoteGrainDirectory.SchedulingContext).Ignore();
}
}
}
| |
// Copyright 2017 (c) [Denis Da Silva]. All rights reserved.
// See License.txt in the project root for license information.
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using System;
using System.Threading.Tasks;
using Prolix.Identity;
namespace Prolix.Identity.AspNet
{
public class IdentityManager : IIdentityManager
{
public IdentityManager(IOwinContext owinContext)
{
OwinContext = owinContext;
}
IOwinContext OwinContext { get; }
UserManager<IdentityUser> UserManager => OwinContext?.GetUserManager<UserManager<IdentityUser>>();
IAuthenticationManager AuthManager => OwinContext?.Authentication;
async public Task<IdentityAccount> Get(string id, string userName)
{
IdentityUser user = null;
if (string.IsNullOrWhiteSpace(id))
user = await UserManager.FindByIdAsync(id);
else if (string.IsNullOrWhiteSpace(userName))
user = await UserManager.FindByNameAsync(userName);
IdentityAccount result = null;
if (user != null)
{
result = new IdentityAccount(user.Id, user.UserName);
result.IsLocked = await UserManager.IsLockedOutAsync(user.Id);
result.HasPassword = await UserManager.HasPasswordAsync(user.Id);
}
return result;
}
async public Task Add(IdentityAccount account)
{
if (account == null)
throw new ArgumentNullException(nameof(account));
var user = new IdentityUser
{
UserName = account.UserName,
Email = account.UserName
};
IdentityResult result = await UserManager.CreateAsync(user);
if (!result.Succeeded)
throw new IdentityException(result.Errors);
}
async public Task Update(IdentityAccount account)
{
if (account == null)
throw new ArgumentNullException(nameof(account));
var user = new IdentityUser
{
UserName = account.UserName,
Email = account.UserName
};
IdentityResult result = await UserManager.UpdateAsync(user);
if (!result.Succeeded)
throw new IdentityException(result.Errors);
}
async public Task Delete(IdentityAccount account)
{
if (account == null)
throw new ArgumentNullException(nameof(account));
var user = new IdentityUser
{
UserName = account.UserName,
Email = account.UserName
};
IdentityResult result = await UserManager.DeleteAsync(user);
if (!result.Succeeded)
throw new IdentityException(result.Errors);
}
async public Task<string> Register(string userName, string password)
{
if (string.IsNullOrWhiteSpace(userName))
throw new ArgumentNullException(nameof(userName));
if (string.IsNullOrWhiteSpace(password))
throw new ArgumentNullException(nameof(password));
var user = new IdentityUser
{
UserName = userName,
Email = userName
};
IdentityResult result = await UserManager.CreateAsync(user, password);
if (!result.Succeeded)
throw new IdentityException(result.Errors);
await Unlock(user.Id);
string token = IssueToken(user.Id);
return token;
}
async public Task<string> Login(string userName, string password)
{
if (string.IsNullOrWhiteSpace(userName))
throw new ArgumentNullException(nameof(userName));
if (string.IsNullOrWhiteSpace(password))
throw new ArgumentNullException(nameof(password));
var user = await UserManager.FindByNameAsync(userName);
if (user == null)
{
throw new IdentityException(IdentityError.AccountNotFound);
}
if (string.IsNullOrWhiteSpace(user.PasswordHash))
{
throw new IdentityException(IdentityError.AccountNotActive);
}
if (user.LockoutEnabled)
{
throw new IdentityException(IdentityError.AccountLocked);
}
var success = await UserManager.CheckPasswordAsync(user, password);
if (success)
{
await Unlock(user.Id);
}
else
{
var attempts = user.AccessFailedCount + 1;
IdentityError error = IdentityError.Generic;
if (attempts >= UserManager.MaxFailedAccessAttemptsBeforeLockout)
{
await UserManager.SetLockoutEnabledAsync(user.Id, true);
error = IdentityError.AccountLocked;
}
else
{
await UserManager.AccessFailedAsync(user.Id);
error = IdentityError.InvalidPassword;
}
await UserManager.UpdateAsync(user);
throw new IdentityException(error);
}
var token = IssueToken(user.Id);
return token;
}
public void Logout()
{
AuthManager.SignOut(CookieAuthenticationDefaults.AuthenticationType);
}
public string IssueToken(string id)
{
string userId = $"{id}";
return IdentityServer.IssueToken(userId);
}
async public Task Lock(string id)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentNullException(nameof(id));
await UserManager.ResetAccessFailedCountAsync(id);
await UserManager.SetLockoutEnabledAsync(id, true);
}
async public Task Unlock(string id)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentNullException(nameof(id));
await UserManager.ResetAccessFailedCountAsync(id);
await UserManager.SetLockoutEnabledAsync(id, false);
}
async public Task ChangePassword(string id, string oldPassword, string newPassword)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrWhiteSpace(oldPassword))
throw new ArgumentNullException(nameof(oldPassword));
if (string.IsNullOrWhiteSpace(newPassword))
throw new ArgumentNullException(nameof(newPassword));
if (string.Equals(oldPassword, newPassword))
throw new IdentityException(IdentityError.InvalidPassword);
IdentityResult result = await UserManager.ChangePasswordAsync(id, oldPassword, newPassword);
if (!result.Succeeded)
{
throw new IdentityException(result.Errors);
}
}
async public Task ResetPassword(string id, string newPassword)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentNullException(nameof(id));
if (string.IsNullOrWhiteSpace(newPassword))
throw new ArgumentNullException(nameof(newPassword));
var user = await UserManager.FindByIdAsync(id);
if (user == null)
throw new IdentityException(IdentityError.AccountNotFound);
var hasPassword = await UserManager.HasPasswordAsync(id);
IdentityResult result = null;
if (hasPassword)
{
if (UserManager.UserTokenProvider != null)
{
var token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
result = await UserManager.ResetPasswordAsync(user.Id, token, newPassword);
}
else
{
string newHash = UserManager.PasswordHasher.HashPassword(newPassword);
user.PasswordHash = newHash;
result = await UserManager.UpdateAsync(user);
}
}
else
{
result = await UserManager.AddPasswordAsync(user.Id, newPassword);
}
if (!result.Succeeded)
{
throw new IdentityException(result.Errors);
}
}
}
}
| |
using System;
using System.IO;
using System.Runtime.InteropServices;
using SQLite.Net.Interop;
using System.Reflection;
namespace SQLite.Net.Platform.OSX
{
internal static class SQLiteApiOSXInternal
{
static SQLiteApiOSXInternal()
{
}
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_open", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_open([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_open([MarshalAs(UnmanagedType.LPStr)] string filename, out IntPtr db,
int flags,
IntPtr zvfs);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_open16", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_open16([MarshalAs(UnmanagedType.LPWStr)] string filename, out IntPtr db);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_enable_load_extension",
CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_enable_load_extension(IntPtr db, int onoff);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_close", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_close(IntPtr db);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_initialize", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_initialize();
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_shutdown", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_shutdown();
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_config", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_config(ConfigOption option);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_win32_set_directory",
CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern int sqlite3_win32_set_directory(uint directoryType, string directoryPath);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_busy_timeout",
CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_busy_timeout(IntPtr db, int milliseconds);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_changes", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_changes(IntPtr db);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_prepare16_v2", CallingConvention = CallingConvention.Cdecl)
]
public static extern Result sqlite3_prepare16_v2(IntPtr db, [MarshalAs(UnmanagedType.LPWStr)] string sql,
int numBytes,
out IntPtr stmt, IntPtr pzTail);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_step", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_step(IntPtr stmt);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_reset", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_reset(IntPtr stmt);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_finalize", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_finalize(IntPtr stmt);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_last_insert_rowid",
CallingConvention = CallingConvention.Cdecl)]
public static extern long sqlite3_last_insert_rowid(IntPtr db);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_errmsg16", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr sqlite3_errmsg16(IntPtr db);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_bind_parameter_index",
CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_bind_parameter_index(IntPtr stmt, [MarshalAs(UnmanagedType.LPStr)] string name);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_bind_null", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_bind_null(IntPtr stmt, int index);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_bind_int", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_bind_int(IntPtr stmt, int index, int val);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_bind_int64", CallingConvention = CallingConvention.Cdecl)
]
public static extern int sqlite3_bind_int64(IntPtr stmt, int index, long val);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_bind_double", CallingConvention = CallingConvention.Cdecl
)]
public static extern int sqlite3_bind_double(IntPtr stmt, int index, double val);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_bind_text16", CallingConvention = CallingConvention.Cdecl,
CharSet = CharSet.Unicode)]
public static extern int sqlite3_bind_text16(IntPtr stmt, int index,
[MarshalAs(UnmanagedType.LPWStr)] string val,
int n,
IntPtr free);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_bind_blob", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_bind_blob(IntPtr stmt, int index, byte[] val, int n, IntPtr free);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_column_count",
CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_column_count(IntPtr stmt);
// [DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_column_name", CallingConvention = CallingConvention.Cdecl)]
// private extern IntPtr ColumnNameInternal(IntPtr stmt, int index);
// [DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_column_name", CallingConvention = CallingConvention.Cdecl)]
// public string ColumnName(IntPtr stmt, int index)
// {
// return ColumnNameInternal(stmt, index);
// }
public static string ColumnName16(IntPtr stmt, int index)
{
return Marshal.PtrToStringUni(sqlite3_column_name16(stmt, index));
}
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_column_type", CallingConvention = CallingConvention.Cdecl
)]
public static extern ColType sqlite3_column_type(IntPtr stmt, int index);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_column_int", CallingConvention = CallingConvention.Cdecl)
]
public static extern int sqlite3_column_int(IntPtr stmt, int index);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_column_int64",
CallingConvention = CallingConvention.Cdecl)]
public static extern long sqlite3_column_int64(IntPtr stmt, int index);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_column_double",
CallingConvention = CallingConvention.Cdecl)]
public static extern double sqlite3_column_double(IntPtr stmt, int index);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_column_text16",
CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr sqlite3_column_text16(IntPtr stmt, int index);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_column_blob", CallingConvention = CallingConvention.Cdecl
)]
public static extern byte[] ColumnBlob(IntPtr stmt, int index);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_column_blob", CallingConvention = CallingConvention.Cdecl
)]
public static extern IntPtr sqlite3_column_blob(IntPtr stmt, int index);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_column_bytes",
CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_column_bytes(IntPtr stmt, int index);
public static byte[] ColumnByteArray(IntPtr stmt, int index)
{
int length = sqlite3_column_bytes(stmt, index);
var result = new byte[length];
if (length > 0)
{
Marshal.Copy(sqlite3_column_blob(stmt, index), result, 0, length);
}
return result;
}
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_open_v2", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_open_v2(byte[] filename, out IntPtr db, int flags, IntPtr zvfs);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_column_name16",
CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr sqlite3_column_name16(IntPtr stmt, int index);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_extended_errcode", CallingConvention = CallingConvention.Cdecl)]
public static extern ExtendedResult sqlite3_extended_errcode(IntPtr db);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_libversion_number", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_libversion_number();
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_sourceid", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr sqlite3_sourceid();
#region Backup
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_backup_init", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr sqlite3_backup_init(IntPtr destDB,
[MarshalAs(UnmanagedType.LPStr)] string destName,
IntPtr srcDB,
[MarshalAs(UnmanagedType.LPStr)] string srcName);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_backup_step", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_backup_step(IntPtr backup, int pageCount);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_backup_finish", CallingConvention = CallingConvention.Cdecl)]
public static extern Result sqlite3_backup_finish(IntPtr backup);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_backup_remaining", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_backup_remaining(IntPtr backup);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_backup_pagecount", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_backup_pagecount(IntPtr backup);
[DllImport("libsqlite3_for_net", EntryPoint = "sqlite3_sleep", CallingConvention = CallingConvention.Cdecl)]
public static extern int sqlite3_sleep(int millis);
#endregion
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Diagnostics;
namespace System.IO.Compression
{
// Strictly speaking this class is not a HuffmanTree, this class is
// a lookup table combined with a HuffmanTree. The idea is to speed up
// the lookup for short symbols (they should appear more frequently ideally.)
// However we don't want to create a huge table since it might take longer to
// build the table than decoding (Deflate usually generates new tables frequently.)
//
// Jean-loup Gailly and Mark Adler gave a very good explanation about this.
// The full text (algorithm.txt) can be found inside
// ftp://ftp.uu.net/pub/archiving/zip/zlib/zlib.zip.
//
// Following paper explains decoding in details:
// Hirschberg and Lelewer, "Efficient decoding of prefix codes,"
// Comm. ACM, 33,4, April 1990, pp. 449-459.
//
internal sealed class HuffmanTree
{
internal const int MaxLiteralTreeElements = 288;
internal const int MaxDistTreeElements = 32;
internal const int EndOfBlockCode = 256;
internal const int NumberOfCodeLengthTreeElements = 19;
private readonly int _tableBits;
private readonly short[] _table;
private readonly short[] _left;
private readonly short[] _right;
private readonly byte[] _codeLengthArray;
#if DEBUG
private uint[] _codeArrayDebug;
#endif
private readonly int _tableMask;
// huffman tree for static block
public static HuffmanTree StaticLiteralLengthTree { get; } = new HuffmanTree(GetStaticLiteralTreeLength());
public static HuffmanTree StaticDistanceTree { get; } = new HuffmanTree(GetStaticDistanceTreeLength());
public HuffmanTree(byte[] codeLengths)
{
Debug.Assert(
codeLengths.Length == MaxLiteralTreeElements ||
codeLengths.Length == MaxDistTreeElements ||
codeLengths.Length == NumberOfCodeLengthTreeElements,
"we only expect three kinds of Length here");
_codeLengthArray = codeLengths;
if (_codeLengthArray.Length == MaxLiteralTreeElements)
{
// bits for Literal/Length tree table
_tableBits = 9;
}
else
{
// bits for distance tree table and code length tree table
_tableBits = 7;
}
_tableMask = (1 << _tableBits) - 1;
_table = new short[1 << _tableBits];
// I need to find proof that left and right array will always be
// enough. I think they are.
_left = new short[2 * _codeLengthArray.Length];
_right = new short[2 * _codeLengthArray.Length];
CreateTable();
}
// Generate the array contains huffman codes lengths for static huffman tree.
// The data is in RFC 1951.
private static byte[] GetStaticLiteralTreeLength()
{
byte[] literalTreeLength = new byte[MaxLiteralTreeElements];
for (int i = 0; i <= 143; i++)
literalTreeLength[i] = 8;
for (int i = 144; i <= 255; i++)
literalTreeLength[i] = 9;
for (int i = 256; i <= 279; i++)
literalTreeLength[i] = 7;
for (int i = 280; i <= 287; i++)
literalTreeLength[i] = 8;
return literalTreeLength;
}
private static byte[] GetStaticDistanceTreeLength()
{
byte[] staticDistanceTreeLength = new byte[MaxDistTreeElements];
for (int i = 0; i < MaxDistTreeElements; i++)
{
staticDistanceTreeLength[i] = 5;
}
return staticDistanceTreeLength;
}
// Calculate the huffman code for each character based on the code length for each character.
// This algorithm is described in standard RFC 1951
private uint[] CalculateHuffmanCode()
{
uint[] bitLengthCount = new uint[17];
foreach (int codeLength in _codeLengthArray)
{
bitLengthCount[codeLength]++;
}
bitLengthCount[0] = 0; // clear count for length 0
uint[] nextCode = new uint[17];
uint tempCode = 0;
for (int bits = 1; bits <= 16; bits++)
{
tempCode = (tempCode + bitLengthCount[bits - 1]) << 1;
nextCode[bits] = tempCode;
}
uint[] code = new uint[MaxLiteralTreeElements];
for (int i = 0; i < _codeLengthArray.Length; i++)
{
int len = _codeLengthArray[i];
if (len > 0)
{
code[i] = FastEncoderStatics.BitReverse(nextCode[len], len);
nextCode[len]++;
}
}
return code;
}
private void CreateTable()
{
uint[] codeArray = CalculateHuffmanCode();
#if DEBUG
_codeArrayDebug = codeArray;
#endif
short avail = (short)_codeLengthArray.Length;
for (int ch = 0; ch < _codeLengthArray.Length; ch++)
{
// length of this code
int len = _codeLengthArray[ch];
if (len > 0)
{
// start value (bit reversed)
int start = (int)codeArray[ch];
if (len <= _tableBits)
{
// If a particular symbol is shorter than nine bits,
// then that symbol's translation is duplicated
// in all those entries that start with that symbol's bits.
// For example, if the symbol is four bits, then it's duplicated
// 32 times in a nine-bit table. If a symbol is nine bits long,
// it appears in the table once.
//
// Make sure that in the loop below, code is always
// less than table_size.
//
// On last iteration we store at array index:
// initial_start_at + (locs-1)*increment
// = initial_start_at + locs*increment - increment
// = initial_start_at + (1 << tableBits) - increment
// = initial_start_at + table_size - increment
//
// Therefore we must ensure:
// initial_start_at + table_size - increment < table_size
// or: initial_start_at < increment
//
int increment = 1 << len;
if (start >= increment)
{
throw new InvalidDataException(SR.InvalidHuffmanData);
}
// Note the bits in the table are reverted.
int locs = 1 << (_tableBits - len);
for (int j = 0; j < locs; j++)
{
_table[start] = (short)ch;
start += increment;
}
}
else
{
// For any code which has length longer than num_elements,
// build a binary tree.
int overflowBits = len - _tableBits; // the nodes we need to respent the data.
int codeBitMask = 1 << _tableBits; // mask to get current bit (the bits can't fit in the table)
// the left, right table is used to repesent the
// the rest bits. When we got the first part (number bits.) and look at
// tbe table, we will need to follow the tree to find the real character.
// This is in place to avoid bloating the table if there are
// a few ones with long code.
int index = start & ((1 << _tableBits) - 1);
short[] array = _table;
do
{
short value = array[index];
if (value == 0)
{
// set up next pointer if this node is not used before.
array[index] = (short)-avail; // use next available slot.
value = (short)-avail;
avail++;
}
if (value > 0)
{
// prevent an IndexOutOfRangeException from array[index]
throw new InvalidDataException(SR.InvalidHuffmanData);
}
Debug.Assert(value < 0, "CreateTable: Only negative numbers are used for tree pointers!");
if ((start & codeBitMask) == 0)
{
// if current bit is 0, go change the left array
array = _left;
}
else
{
// if current bit is 1, set value in the right array
array = _right;
}
index = -value; // go to next node
codeBitMask <<= 1;
overflowBits--;
} while (overflowBits != 0);
array[index] = (short)ch;
}
}
}
}
//
// This function will try to get enough bits from input and
// try to decode the bits.
// If there are no enought bits in the input, this function will return -1.
//
public int GetNextSymbol(InputBuffer input)
{
// Try to load 16 bits into input buffer if possible and get the bitBuffer value.
// If there aren't 16 bits available we will return all we have in the
// input buffer.
uint bitBuffer = input.TryLoad16Bits();
if (input.AvailableBits == 0)
{ // running out of input.
return -1;
}
// decode an element
int symbol = _table[bitBuffer & _tableMask];
if (symbol < 0)
{ // this will be the start of the binary tree
// navigate the tree
uint mask = (uint)1 << _tableBits;
do
{
symbol = -symbol;
if ((bitBuffer & mask) == 0)
symbol = _left[symbol];
else
symbol = _right[symbol];
mask <<= 1;
} while (symbol < 0);
}
int codeLength = _codeLengthArray[symbol];
// huffman code lengths must be at least 1 bit long
if (codeLength <= 0)
{
throw new InvalidDataException(SR.InvalidHuffmanData);
}
//
// If this code is longer than the # bits we had in the bit buffer (i.e.
// we read only part of the code), we can hit the entry in the table or the tree
// for another symbol. However the length of another symbol will not match the
// available bits count.
if (codeLength > input.AvailableBits)
{
// We already tried to load 16 bits and maximum length is 15,
// so this means we are running out of input.
return -1;
}
input.SkipBits(codeLength);
return symbol;
}
}
}
| |
// 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.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Principal;
namespace System.Net.Security
{
//
// The class does the real work in authentication and
// user data encryption with NEGO SSPI package.
//
// This is part of the NegotiateStream PAL.
//
internal static partial class NegotiateStreamPal
{
internal static IIdentity GetIdentity(NTAuthentication context)
{
IIdentity result = null;
string name = context.IsServer ? context.AssociatedName : context.Spn;
string protocol = context.ProtocolName;
if (context.IsServer)
{
SecurityContextTokenHandle token = null;
try
{
SecurityStatusPal status;
SafeDeleteContext securityContext = context.GetContext(out status);
if (status.ErrorCode != SecurityStatusPalErrorCode.OK)
{
throw new Win32Exception((int)SecurityStatusAdapterPal.GetInteropFromSecurityStatusPal(status));
}
// This will return a client token when conducted authentication on server side.
// This token can be used for impersonation. We use it to create a WindowsIdentity and hand it out to the server app.
Interop.SECURITY_STATUS winStatus = (Interop.SECURITY_STATUS)SSPIWrapper.QuerySecurityContextToken(
GlobalSSPI.SSPIAuth,
securityContext,
out token);
if (winStatus != Interop.SECURITY_STATUS.OK)
{
throw new Win32Exception((int)winStatus);
}
string authtype = context.ProtocolName;
// TODO #5241:
// The following call was also specifying WindowsAccountType.Normal, true.
// WindowsIdentity.IsAuthenticated is no longer supported in CoreFX.
result = new WindowsIdentity(token.DangerousGetHandle(), authtype);
return result;
}
catch (SecurityException)
{
// Ignore and construct generic Identity if failed due to security problem.
}
finally
{
token?.Dispose();
}
}
// On the client we don't have access to the remote side identity.
result = new GenericIdentity(name, protocol);
return result;
}
internal static string QueryContextAssociatedName(SafeDeleteContext securityContext)
{
return SSPIWrapper.QueryStringContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_NAMES);
}
internal static void ValidateImpersonationLevel(TokenImpersonationLevel impersonationLevel)
{
if (impersonationLevel != TokenImpersonationLevel.Identification &&
impersonationLevel != TokenImpersonationLevel.Impersonation &&
impersonationLevel != TokenImpersonationLevel.Delegation)
{
throw new ArgumentOutOfRangeException(nameof(impersonationLevel), impersonationLevel.ToString(), SR.net_auth_supported_impl_levels);
}
}
internal static int Encrypt(
SafeDeleteContext securityContext,
byte[] buffer,
int offset,
int count,
bool isConfidential,
bool isNtlm,
ref byte[] output,
uint sequenceNumber)
{
SecPkgContext_Sizes sizes = default;
bool success = SSPIWrapper.QueryBlittableContextAttributes(GlobalSSPI.SSPIAuth, securityContext, Interop.SspiCli.ContextAttribute.SECPKG_ATTR_SIZES, ref sizes);
Debug.Assert(success);
try
{
int maxCount = checked(int.MaxValue - 4 - sizes.cbBlockSize - sizes.cbSecurityTrailer);
if (count > maxCount || count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.net_io_out_range, maxCount));
}
}
catch (Exception e) when (!ExceptionCheck.IsFatal(e))
{
NetEventSource.Fail(null, "Arguments out of range.");
throw;
}
int resultSize = count + sizes.cbSecurityTrailer + sizes.cbBlockSize;
if (output == null || output.Length < resultSize + 4)
{
output = new byte[resultSize + 4];
}
// Make a copy of user data for in-place encryption.
Buffer.BlockCopy(buffer, offset, output, 4 + sizes.cbSecurityTrailer, count);
// Prepare buffers TOKEN(signature), DATA and Padding.
ThreeSecurityBuffers buffers = default;
var securityBuffer = MemoryMarshal.CreateSpan(ref buffers._item0, 3);
securityBuffer[0] = new SecurityBuffer(output, 4, sizes.cbSecurityTrailer, SecurityBufferType.SECBUFFER_TOKEN);
securityBuffer[1] = new SecurityBuffer(output, 4 + sizes.cbSecurityTrailer, count, SecurityBufferType.SECBUFFER_DATA);
securityBuffer[2] = new SecurityBuffer(output, 4 + sizes.cbSecurityTrailer + count, sizes.cbBlockSize, SecurityBufferType.SECBUFFER_PADDING);
int errorCode;
if (isConfidential)
{
errorCode = SSPIWrapper.EncryptMessage(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber);
}
else
{
if (isNtlm)
{
securityBuffer[1].type |= SecurityBufferType.SECBUFFER_READONLY;
}
errorCode = SSPIWrapper.MakeSignature(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, 0);
}
if (errorCode != 0)
{
Exception e = new Win32Exception(errorCode);
if (NetEventSource.IsEnabled) NetEventSource.Error(null, e);
throw e;
}
// Compacting the result.
resultSize = securityBuffer[0].size;
bool forceCopy = false;
if (resultSize != sizes.cbSecurityTrailer)
{
forceCopy = true;
Buffer.BlockCopy(output, securityBuffer[1].offset, output, 4 + resultSize, securityBuffer[1].size);
}
resultSize += securityBuffer[1].size;
if (securityBuffer[2].size != 0 && (forceCopy || resultSize != (count + sizes.cbSecurityTrailer)))
{
Buffer.BlockCopy(output, securityBuffer[2].offset, output, 4 + resultSize, securityBuffer[2].size);
}
resultSize += securityBuffer[2].size;
unchecked
{
output[0] = (byte)((resultSize) & 0xFF);
output[1] = (byte)(((resultSize) >> 8) & 0xFF);
output[2] = (byte)(((resultSize) >> 16) & 0xFF);
output[3] = (byte)(((resultSize) >> 24) & 0xFF);
}
return resultSize + 4;
}
internal static int Decrypt(
SafeDeleteContext securityContext,
byte[] buffer,
int offset,
int count,
bool isConfidential,
bool isNtlm,
out int newOffset,
uint sequenceNumber)
{
if (offset < 0 || offset > (buffer == null ? 0 : buffer.Length))
{
NetEventSource.Fail(null, "Argument 'offset' out of range.");
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (count < 0 || count > (buffer == null ? 0 : buffer.Length - offset))
{
NetEventSource.Fail(null, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
if (isNtlm)
{
return DecryptNtlm(securityContext, buffer, offset, count, isConfidential, out newOffset, sequenceNumber);
}
//
// Kerberos and up
//
TwoSecurityBuffers buffers = default;
var securityBuffer = MemoryMarshal.CreateSpan(ref buffers._item0, 2);
securityBuffer[0] = new SecurityBuffer(buffer, offset, count, SecurityBufferType.SECBUFFER_STREAM);
securityBuffer[1] = new SecurityBuffer(0, SecurityBufferType.SECBUFFER_DATA);
int errorCode;
if (isConfidential)
{
errorCode = SSPIWrapper.DecryptMessage(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber);
}
else
{
errorCode = SSPIWrapper.VerifySignature(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber);
}
if (errorCode != 0)
{
Exception e = new Win32Exception(errorCode);
if (NetEventSource.IsEnabled) NetEventSource.Error(null, e);
throw e;
}
if (securityBuffer[1].type != SecurityBufferType.SECBUFFER_DATA)
{
throw new InternalException(securityBuffer[1].type);
}
newOffset = securityBuffer[1].offset;
return securityBuffer[1].size;
}
private static int DecryptNtlm(
SafeDeleteContext securityContext,
byte[] buffer,
int offset,
int count,
bool isConfidential,
out int newOffset,
uint sequenceNumber)
{
const int ntlmSignatureLength = 16;
// For the most part the arguments are verified in Decrypt().
if (count < ntlmSignatureLength)
{
NetEventSource.Fail(null, "Argument 'count' out of range.");
throw new ArgumentOutOfRangeException(nameof(count));
}
TwoSecurityBuffers buffers = default;
var securityBuffer = MemoryMarshal.CreateSpan(ref buffers._item0, 2);
securityBuffer[0] = new SecurityBuffer(buffer, offset, ntlmSignatureLength, SecurityBufferType.SECBUFFER_TOKEN);
securityBuffer[1] = new SecurityBuffer(buffer, offset + ntlmSignatureLength, count - ntlmSignatureLength, SecurityBufferType.SECBUFFER_DATA);
int errorCode;
SecurityBufferType realDataType = SecurityBufferType.SECBUFFER_DATA;
if (isConfidential)
{
errorCode = SSPIWrapper.DecryptMessage(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber);
}
else
{
realDataType |= SecurityBufferType.SECBUFFER_READONLY;
securityBuffer[1].type = realDataType;
errorCode = SSPIWrapper.VerifySignature(GlobalSSPI.SSPIAuth, securityContext, securityBuffer, sequenceNumber);
}
if (errorCode != 0)
{
Exception e = new Win32Exception(errorCode);
if (NetEventSource.IsEnabled) NetEventSource.Error(null, e);
throw new Win32Exception(errorCode);
}
if (securityBuffer[1].type != realDataType)
{
throw new InternalException(securityBuffer[1].type);
}
newOffset = securityBuffer[1].offset;
return securityBuffer[1].size;
}
}
}
| |
#if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms.
using System;
using UnityEngine;
namespace AK.Wwise
{
[Serializable]
///@brief This type represents the base for all Wwise Types that require a GUID.
public class BaseType
{
#if UNITY_EDITOR
public byte[] valueGuid = new byte[16];
#endif
public int ID = 0;
protected uint GetID() { return (uint)ID; }
protected virtual bool IsValid()
{
return ID != 0;
}
public bool Validate()
{
if (IsValid())
return true;
Debug.LogWarning("Wwise ID has not been resolved. Consider picking a new " + GetType().Name + ".");
return false;
}
protected void Verify(AKRESULT result)
{
#if UNITY_EDITOR
if (result != AKRESULT.AK_Success)
Debug.LogWarning("Unsuccessful call made on " + GetType().Name + ".");
#endif
}
}
[Serializable]
///@brief This type represents the base for all Wwise Types that also require a group GUID, such as State and Switch.
public class BaseGroupType : BaseType
{
#if UNITY_EDITOR
public byte[] groupGuid = new byte[16];
#endif
public int groupID = 0;
protected uint GetGroupID() { return (uint)groupID; }
protected override bool IsValid() { return base.IsValid() && groupID != 0; }
}
[Serializable]
///@brief This type represents the values of the flags used when posting an Event with a callback.
public class CallbackFlags
{
public uint value = 0;
}
[Serializable]
///@brief This type can be used to post events to the sound engine.
public class Event : BaseType
{
private void VerifyPlayingID(uint playingId)
{
#if UNITY_EDITOR
if (playingId == AkSoundEngine.AK_INVALID_PLAYING_ID)
Debug.LogError("Could not post event ID \"" + GetID() + "\". Did you make sure to load the appropriate SoundBank?");
#endif
}
/// <summary>
/// Posts this event on a gameobject.
/// </summary>
/// <param name="gameObject">The GameObject</param>
/// <returns>Returns the playing ID.</returns>
public uint Post(GameObject gameObject)
{
if (!IsValid())
return AkSoundEngine.AK_INVALID_PLAYING_ID;
uint playingId = AkSoundEngine.PostEvent(GetID(), gameObject);
VerifyPlayingID(playingId);
return playingId;
}
/// <summary>
/// Posts this event on a gameobject.
/// </summary>
/// <param name="gameObject">The GameObject</param>
/// <param name="flags"></param>
/// <param name="callback"></param>
/// <param name="cookie">Optional cookie received by the callback</param>
/// <returns>Returns the playing ID.</returns>
public uint Post(GameObject gameObject, CallbackFlags flags, AkCallbackManager.EventCallback callback, object cookie = null)
{
if (!IsValid())
return AkSoundEngine.AK_INVALID_PLAYING_ID;
uint playingId = AkSoundEngine.PostEvent(GetID(), gameObject, flags.value, callback, cookie);
VerifyPlayingID(playingId);
return playingId;
}
/// <summary>
/// Posts this event on a gameobject.
/// </summary>
/// <param name="gameObject">The GameObject</param>
/// <param name="flags"></param>
/// <param name="callback"></param>
/// <param name="cookie">Optional cookie received by the callback</param>
/// <returns>Returns the playing ID.</returns>
public uint Post(GameObject gameObject, uint flags, AkCallbackManager.EventCallback callback, object cookie = null)
{
if (!IsValid())
return AkSoundEngine.AK_INVALID_PLAYING_ID;
uint playingId = AkSoundEngine.PostEvent(GetID(), gameObject, flags, callback, cookie);
VerifyPlayingID(playingId);
return playingId;
}
public void Stop(GameObject gameObject, int transitionDuration = 0, AkCurveInterpolation curveInterpolation = AkCurveInterpolation.AkCurveInterpolation_Linear)
{
ExecuteAction(gameObject, AkActionOnEventType.AkActionOnEventType_Stop, transitionDuration, curveInterpolation);
}
/// <summary>
/// Executes various actions on this event associated with a gameobject.
/// </summary>
/// <param name="gameObject">The GameObject</param>
/// <param name="actionOnEventType"></param>
/// <param name="transitionDuration"></param>
/// <param name="curveInterpolation"></param>
public void ExecuteAction(GameObject gameObject, AkActionOnEventType actionOnEventType, int transitionDuration, AkCurveInterpolation curveInterpolation)
{
if (IsValid())
{
AKRESULT result = AkSoundEngine.ExecuteActionOnEvent(GetID(), actionOnEventType, gameObject, transitionDuration, curveInterpolation);
Verify(result);
}
}
}
[Serializable]
///@brief This type can be used to set game parameter values to the sound engine.
public class RTPC : BaseType
{
public void SetValue(GameObject gameObject, float value)
{
if (IsValid())
{
AKRESULT result = AkSoundEngine.SetRTPCValue(GetID(), value, gameObject);
Verify(result);
}
}
public void SetGlobalValue(float value)
{
if (IsValid())
{
AKRESULT result = AkSoundEngine.SetRTPCValue(GetID(), value);
Verify(result);
}
}
}
[Serializable]
///@brief This type can be used to post triggers to the sound engine.
public class Trigger : BaseType
{
public void Post(GameObject gameObject)
{
if (IsValid())
{
AKRESULT result = AkSoundEngine.PostTrigger(GetID(), gameObject);
Verify(result);
}
}
}
[Serializable]
///@brief This type can be used to set Wwise states.
public class State : BaseGroupType
{
public void SetValue()
{
if (IsValid())
{
AKRESULT result = AkSoundEngine.SetState(GetGroupID(), GetID());
Verify(result);
}
}
}
[Serializable]
///@brief This type can be used to set switch values on gameobjects.
public class Switch : BaseGroupType
{
public void SetValue(GameObject gameObject)
{
if (IsValid())
{
AKRESULT result = AkSoundEngine.SetSwitch(GetGroupID(), GetID(), gameObject);
Verify(result);
}
}
}
[Serializable]
///@brief This type represents an auxiliary send in the master-mixer hierarchy.
public class AuxBus : BaseType
{
}
[Serializable]
///@brief This type can be used to load/unload soundbanks.
public class Bank : BaseType
{
public string name;
public void Load(bool decodeBank = false, bool saveDecodedBank = false)
{
if (IsValid())
AkBankManager.LoadBank(name, decodeBank, saveDecodedBank);
}
public void LoadAsync(AkCallbackManager.BankCallback callback = null)
{
if (IsValid())
AkBankManager.LoadBankAsync(name, callback);
}
public void Unload()
{
if (IsValid())
AkBankManager.UnloadBank(name);
}
protected override bool IsValid() { return name.Length != 0 || base.IsValid(); }
}
}
#endif // #if ! (UNITY_DASHBOARD_WIDGET || UNITY_WEBPLAYER || UNITY_WII || UNITY_WIIU || UNITY_NACL || UNITY_FLASH || UNITY_BLACKBERRY) // Disable under unsupported platforms.
| |
/*
* EventLogEntry.cs - Implementation of the
* "System.Diagnostics.EventLogEntry" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
namespace System.Diagnostics
{
#if CONFIG_EXTENDED_DIAGNOSTICS
using System.ComponentModel;
using System.Runtime.Serialization;
[Serializable]
#if CONFIG_COMPONENT_MODEL
[DesignTimeVisible(false)]
[ToolboxItem(false)]
#endif
public sealed class EventLogEntry
#if CONFIG_COMPONENT_MODEL
: Component
#if CONFIG_SERIALIZATION
, ISerializable
#endif
#elif CONFIG_SERIALIZATION
: ISerializable
#endif
{
// Internal state.
internal String category;
internal short categoryNumber;
internal byte[] data;
internal EventLogEntryType entryType;
internal int eventID;
internal int index;
internal String machineName;
internal String message;
internal String[] replacementStrings;
internal String source;
internal DateTime timeGenerated;
internal DateTime timeWritten;
internal String userName;
// Constructor.
internal EventLogEntry() {}
#if CONFIG_SERIALIZATION
internal EventLogEntry(SerializationInfo info, StreamingContext context)
{
// The serialization uses a binary format which
// we don't yet know the details of.
throw new NotImplementedException();
}
#endif
// Event log properties.
[MonitoringDescription("LogEntryCategory")]
public String Category
{
get
{
return category;
}
}
[MonitoringDescription("LogEntryCategoryNumber")]
public short CategoryNumber
{
get
{
return categoryNumber;
}
}
[MonitoringDescription("LogEntryData")]
public byte[] Data
{
get
{
return data;
}
}
[MonitoringDescription("LogEntryEntryType")]
public EventLogEntryType EntryType
{
get
{
return entryType;
}
}
[MonitoringDescription("LogEntryEventID")]
public int EventID
{
get
{
return eventID;
}
}
[MonitoringDescription("LogEntryIndex")]
public int Index
{
get
{
return index;
}
}
[MonitoringDescription("LogEntryMachineName")]
public String MachineName
{
get
{
return machineName;
}
}
[MonitoringDescription("LogEntryMessage")]
#if CONFIG_COMPONENT_MODEL
[Editor("System.ComponentModel.Design.BinaryEditor, System.Design",
"System.Drawing.Design.UITypeEditor, System.Drawing")]
#endif
public String Message
{
get
{
return message;
}
}
[MonitoringDescription("LogEntryReplacementStrings")]
public String[] ReplacementStrings
{
get
{
return replacementStrings;
}
}
[MonitoringDescription("LogEntrySource")]
public String Source
{
get
{
return source;
}
}
[MonitoringDescription("LogEntryTimeGenerated")]
public DateTime TimeGenerated
{
get
{
return timeGenerated;
}
}
[MonitoringDescription("LogEntryTimeWritten")]
public DateTime TimeWritten
{
get
{
return timeWritten;
}
}
[MonitoringDescription("LogEntryUserName")]
public String UserName
{
get
{
return userName;
}
}
// Determine if two event log entries are equal.
public bool Equals(EventLogEntry otherEntry)
{
if(otherEntry == null)
{
return false;
}
if(category != otherEntry.category)
{
return false;
}
if(categoryNumber != otherEntry.categoryNumber)
{
return false;
}
if(data == null)
{
if(otherEntry.data != null)
{
return false;
}
}
else if(otherEntry.data == null)
{
return false;
}
else if(otherEntry.data.Length != data.Length)
{
return false;
}
else
{
int dposn;
for(dposn = 0; dposn < data.Length; ++dposn)
{
if(data[dposn] != otherEntry.data[dposn])
{
return false;
}
}
}
if(entryType != otherEntry.entryType)
{
return false;
}
if(eventID != otherEntry.eventID)
{
return false;
}
if(index != otherEntry.index)
{
return false;
}
if(machineName != otherEntry.machineName)
{
return false;
}
if(message != otherEntry.message)
{
return false;
}
if(replacementStrings == null)
{
if(otherEntry.replacementStrings != null)
{
return false;
}
}
else if(otherEntry.replacementStrings == null)
{
return false;
}
else if(otherEntry.replacementStrings.Length
!= replacementStrings.Length)
{
return false;
}
else
{
int rposn;
for(rposn = 0; rposn < replacementStrings.Length; ++rposn)
{
if(replacementStrings[rposn] !=
otherEntry.replacementStrings[rposn])
{
return false;
}
}
}
if(source != otherEntry.source)
{
return false;
}
if(timeGenerated != otherEntry.timeGenerated)
{
return false;
}
if(timeWritten != otherEntry.timeWritten)
{
return false;
}
if(userName != otherEntry.userName)
{
return false;
}
return true;
}
#if CONFIG_SERIALIZATION
// Implement the ISerializable interface.
void ISerializable.GetObjectData(SerializationInfo info,
StreamingContext context)
{
// The serialization uses a binary format which
// we don't yet know the details of.
throw new NotImplementedException();
}
#endif
}; // class EventLogEntry
#endif // CONFIG_EXTENDED_DIAGNOSTICS
}; // namespace System.Diagnostics
| |
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using FluentAssertions;
using Microsoft.Build.Construction;
using Microsoft.DotNet.Tools.Test.Utilities;
using Msbuild.Tests.Utilities;
using System;
using System.IO;
using System.Linq;
using Xunit;
namespace Microsoft.DotNet.Cli.Add.Reference.Tests
{
public class GivenDotnetAddReference : TestBase
{
private const string HelpText = @".NET Add Project to Project reference Command
Usage: dotnet add <PROJECT> reference [options] <args>
Arguments:
<PROJECT> The project file to operate on. If a file is not specified, the command will search the current directory for one.
<args> Project to project references to add
Options:
-h, --help Show help information.
-f, --framework <FRAMEWORK> Add reference only when targeting a specific framework
";
private const string AddCommandHelpText = @".NET Add Command
Usage: dotnet add [options] <PROJECT> [command]
Arguments:
<PROJECT> The project file to operate on. If a file is not specified, the command will search the current directory for one.
Options:
-h, --help Show help information.
Commands:
package <PACKAGE_NAME> .NET Add Package reference Command
reference <args> .NET Add Project to Project reference Command
";
const string FrameworkNet451Arg = "-f net451";
const string ConditionFrameworkNet451 = "== 'net451'";
const string FrameworkNetCoreApp10Arg = "-f netcoreapp1.0";
const string ConditionFrameworkNetCoreApp10 = "== 'netcoreapp1.0'";
const string ProjectNotCompatibleErrorMessageRegEx = "Project `[^`]*` cannot be added due to incompatible targeted frameworks between the two projects\\. Please review the project you are trying to add and verify that is compatible with the following targets\\:";
const string ProjectDoesNotTargetFrameworkErrorMessageRegEx = "Project `[^`]*` does not target framework `[^`]*`.";
static readonly string[] DefaultFrameworks = new string[] { "netcoreapp1.0", "net451" };
private TestSetup Setup([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(Setup), string identifier = "")
{
return new TestSetup(
TestAssets.Get(TestSetup.TestGroup, TestSetup.ProjectName)
.CreateInstance(callingMethod: callingMethod, identifier: identifier)
.WithSourceFiles()
.Root
.FullName);
}
private ProjDir NewDir([System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
return new ProjDir(TestAssets.CreateTestDirectory(callingMethod: callingMethod, identifier: identifier).FullName);
}
private ProjDir NewLib(string dir = null, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
var projDir = dir == null ? NewDir(callingMethod: callingMethod, identifier: identifier) : new ProjDir(dir);
try
{
string args = $"classlib -o \"{projDir.Path}\" --debug:ephemeral-hive --no-restore";
new NewCommandShim()
.WithWorkingDirectory(projDir.Path)
.ExecuteWithCapturedOutput(args)
.Should().Pass();
}
catch (System.ComponentModel.Win32Exception e)
{
throw new Exception($"Intermittent error in `dotnet new` occurred when running it in dir `{projDir.Path}`\nException:\n{e}");
}
return projDir;
}
private static void SetTargetFrameworks(ProjDir proj, string[] frameworks)
{
var csproj = proj.CsProj();
csproj.AddProperty("TargetFrameworks", string.Join(";", frameworks));
csproj.Save();
}
private ProjDir NewLibWithFrameworks(string dir = null, [System.Runtime.CompilerServices.CallerMemberName] string callingMethod = nameof(NewDir), string identifier = "")
{
var ret = NewLib(dir, callingMethod: callingMethod, identifier: identifier);
SetTargetFrameworks(ret, DefaultFrameworks);
return ret;
}
[Theory]
[InlineData("--help")]
[InlineData("-h")]
public void WhenHelpOptionIsPassedItPrintsUsage(string helpArg)
{
var cmd = new AddReferenceCommand().Execute(helpArg);
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Theory]
[InlineData("")]
[InlineData("unknownCommandName")]
public void WhenNoCommandIsPassedItPrintsError(string commandName)
{
var cmd = new DotnetCommand()
.ExecuteWithCapturedOutput($"add {commandName}");
cmd.Should().Fail();
cmd.StdErr.Should().Be("Required command was not provided.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(AddCommandHelpText);
}
[Fact]
public void WhenTooManyArgumentsArePassedItPrintsError()
{
var cmd = new AddReferenceCommand()
.WithProject("one two three")
.Execute("proj.csproj");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().BeVisuallyEquivalentTo(
"Unrecognized command or argument 'two'\r\nUnrecognized command or argument 'three'");
}
[Theory]
[InlineData("idontexist.csproj")]
[InlineData("ihave?inv@lid/char\\acters")]
public void WhenNonExistingProjectIsPassedItPrintsErrorAndUsage(string projName)
{
var setup = Setup();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(projName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be($"Could not find project or directory `{projName}`.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void WhenBrokenProjectIsPassedItPrintsErrorAndUsage()
{
string projName = "Broken/Broken.csproj";
var setup = Setup();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(projName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be("Project `Broken/Broken.csproj` is invalid.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void WhenMoreThanOneProjectExistsInTheDirectoryItPrintsErrorAndUsage()
{
var setup = Setup();
var workingDir = Path.Combine(setup.TestRoot, "MoreThanOne");
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(workingDir)
.Execute($"\"{setup.ValidRefCsprojRelToOtherProjPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be($"Found more than one project in `{workingDir + Path.DirectorySeparatorChar}`. Please specify which one to use.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void WhenNoProjectsExistsInTheDirectoryItPrintsErrorAndUsage()
{
var setup = Setup();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.ExitCode.Should().NotBe(0);
cmd.StdErr.Should().Be($"Could not find any project in `{setup.TestRoot + Path.DirectorySeparatorChar}`.");
cmd.StdOut.Should().BeVisuallyEquivalentTo(HelpText);
}
[Fact]
public void ItAddsRefWithoutCondAndPrintsStatus()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project.");
cmd.StdErr.Should().BeEmpty();
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void ItAddsRefWithCondAndPrintsStatus()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project.");
cmd.StdErr.Should().BeEmpty();
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void WhenRefWithoutCondIsPresentItAddsDifferentRefWithoutCond()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.LibCsprojPath}\"")
.Should().Pass();
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(lib.Path)
.WithProject(lib.CsProjName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void WhenRefWithCondIsPresentItAddsDifferentRefWithCond()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojPath}\"")
.Should().Pass();
int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void WhenRefWithCondIsPresentItAddsRefWithDifferentCond()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNetCoreApp10Arg} \"{setup.ValidRefCsprojPath}\"")
.Should().Pass();
int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void WhenRefWithConditionIsPresentItAddsDifferentRefWithoutCond()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojPath}\"")
.Should().Pass();
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void WhenRefWithNoCondAlreadyExistsItDoesntDuplicate()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\"")
.Should().Pass();
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(lib.Path)
.WithProject(lib.CsProjName)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Project already has a reference to `ValidRef\\ValidRef.csproj`.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void WhenRefWithCondOnItemAlreadyExistsItDoesntDuplicate()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithExistingRefCondOnItem"));
string contentBefore = proj.CsProjContent();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(proj.Path)
.WithProject(proj.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojRelPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Project already has a reference to `..\\Lib\\Lib.csproj`.");
proj.CsProjContent().Should().BeEquivalentTo(contentBefore);
}
[Fact]
public void WhenRefWithCondOnItemGroupAlreadyExistsItDoesntDuplicate()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\"")
.Should().Pass();
var csprojContentBefore = lib.CsProjContent();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Project already has a reference to `ValidRef\\ValidRef.csproj`.");
lib.CsProjContent().Should().BeEquivalentTo(csprojContentBefore);
}
[Fact]
public void WhenRefWithCondWithWhitespaceOnItemGroupExistsItDoesntDuplicate()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithExistingRefCondWhitespaces"));
string contentBefore = proj.CsProjContent();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(proj.Path)
.WithProject(proj.CsProjName)
.Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojRelPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Project already has a reference to `..\\Lib\\Lib.csproj`.");
proj.CsProjContent().Should().BeEquivalentTo(contentBefore);
}
[Fact]
public void WhenRefWithoutCondAlreadyExistsInNonUniformItemGroupItDoesntDuplicate()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithRefNoCondNonUniform"));
string contentBefore = proj.CsProjContent();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(proj.Path)
.WithProject(proj.CsProjName)
.Execute($"\"{setup.LibCsprojRelPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Project already has a reference to `..\\Lib\\Lib.csproj`.");
proj.CsProjContent().Should().BeEquivalentTo(contentBefore);
}
[Fact]
public void WhenRefWithoutCondAlreadyExistsInNonUniformItemGroupItAddsDifferentRefInDifferentGroup()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithRefNoCondNonUniform"));
int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `..\\ValidRef\\ValidRef.csproj` added to the project.");
var csproj = proj.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void WhenRefWithCondAlreadyExistsInNonUniformItemGroupItDoesntDuplicate()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithRefCondNonUniform"));
string contentBefore = proj.CsProjContent();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(proj.Path)
.WithProject(proj.CsProjName)
.Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojRelPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Project already has a reference to `..\\Lib\\Lib.csproj`.");
proj.CsProjContent().Should().BeEquivalentTo(contentBefore);
}
[Fact]
public void WhenRefWithCondAlreadyExistsInNonUniformItemGroupItAddsDifferentRefInDifferentGroup()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "WithRefCondNonUniform"));
int condBefore = proj.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `..\\ValidRef\\ValidRef.csproj` added to the project.");
var csproj = proj.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void WhenEmptyItemGroupPresentItAddsRefInIt()
{
var setup = Setup();
var proj = new ProjDir(Path.Combine(setup.TestRoot, "EmptyItemGroup"));
int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(proj.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `..\\ValidRef\\ValidRef.csproj` added to the project.");
var csproj = proj.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void ItAddsMultipleRefsNoCondToTheSameItemGroup()
{
const string OutputText = @"Reference `Lib\Lib.csproj` added to the project.
Reference `ValidRef\ValidRef.csproj` added to the project.";
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.LibCsprojPath}\" \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(OutputText);
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.LibCsprojName).Should().Be(1);
}
[Fact]
public void ItAddsMultipleRefsWithCondToTheSameItemGroup()
{
const string OutputText = @"Reference `Lib\Lib.csproj` added to the project.
Reference `ValidRef\ValidRef.csproj` added to the project.";
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{setup.LibCsprojPath}\" \"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().BeVisuallyEquivalentTo(OutputText);
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.ValidRefCsprojName, ConditionFrameworkNet451).Should().Be(1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(setup.LibCsprojName, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void WhenProjectNameIsNotPassedItFindsItAndAddsReference()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(lib.Path)
.Execute($"\"{setup.ValidRefCsprojPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project.");
cmd.StdErr.Should().BeEmpty();
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojName).Should().Be(1);
}
[Fact]
public void WhenPassedReferenceDoesNotExistItShowsAnError()
{
var lib = NewLibWithFrameworks();
var contentBefore = lib.CsProjContent();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(lib.Path)
.WithProject(lib.CsProjName)
.Execute("\"IDoNotExist.csproj\"");
cmd.Should().Fail();
cmd.StdErr.Should().Be("Reference IDoNotExist.csproj does not exist.");
lib.CsProjContent().Should().BeEquivalentTo(contentBefore);
}
[Fact]
public void WhenPassedMultipleRefsAndOneOfthemDoesNotExistItCancelsWholeOperation()
{
var lib = NewLibWithFrameworks();
var setup = Setup();
var contentBefore = lib.CsProjContent();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(lib.CsProjPath)
.Execute($"\"{setup.ValidRefCsprojPath}\" \"IDoNotExist.csproj\"");
cmd.Should().Fail();
cmd.StdErr.Should().Be("Reference IDoNotExist.csproj does not exist.");
lib.CsProjContent().Should().BeEquivalentTo(contentBefore);
}
[Fact]
public void WhenPassedReferenceIsUsingSlashesItNormalizesItToBackslashes()
{
var setup = Setup();
var lib = NewLibWithFrameworks(dir: setup.TestRoot);
int noCondBefore = lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(lib.Path)
.WithProject(lib.CsProjName)
.Execute($"\"{setup.ValidRefCsprojPath.Replace('\\', '/')}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `ValidRef\\ValidRef.csproj` added to the project.");
cmd.StdErr.Should().BeEmpty();
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojRelPath.Replace('/', '\\')).Should().Be(1);
}
[Fact]
public void WhenReferenceIsRelativeAndProjectIsNotInCurrentDirectoryReferencePathIsFixed()
{
var setup = Setup();
var proj = new ProjDir(setup.LibDir);
int noCondBefore = proj.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddReferenceCommand()
.WithWorkingDirectory(setup.TestRoot)
.WithProject(setup.LibCsprojPath)
.Execute($"\"{setup.ValidRefCsprojRelPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `..\\ValidRef\\ValidRef.csproj` added to the project.");
cmd.StdErr.Should().BeEmpty();
var csproj = proj.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(setup.ValidRefCsprojRelToOtherProjPath.Replace('/', '\\')).Should().Be(1);
}
[Fact]
public void ItCanAddReferenceWithConditionOnCompatibleFramework()
{
var setup = Setup();
var lib = new ProjDir(setup.LibDir);
var net45lib = new ProjDir(Path.Combine(setup.TestRoot, "Net45Lib"));
int condBefore = lib.CsProj().NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451);
var cmd = new AddReferenceCommand()
.WithProject(lib.CsProjPath)
.Execute($"{FrameworkNet451Arg} \"{net45lib.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `..\\Net45Lib\\Net45Lib.csproj` added to the project.");
var csproj = lib.CsProj();
csproj.NumberOfItemGroupsWithConditionContaining(ConditionFrameworkNet451).Should().Be(condBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeAndConditionContaining(net45lib.CsProjName, ConditionFrameworkNet451).Should().Be(1);
}
[Fact]
public void ItCanAddRefWithoutCondAndTargetingSupersetOfFrameworksAndOneOfReferencesCompatible()
{
var setup = Setup();
var lib = new ProjDir(setup.LibDir);
var net452netcoreapp10lib = new ProjDir(Path.Combine(setup.TestRoot, "Net452AndNetCoreApp10Lib"));
int noCondBefore = net452netcoreapp10lib.CsProj().NumberOfItemGroupsWithoutCondition();
var cmd = new AddReferenceCommand()
.WithProject(net452netcoreapp10lib.CsProjPath)
.Execute($"\"{lib.CsProjPath}\"");
cmd.Should().Pass();
cmd.StdOut.Should().Be("Reference `..\\Lib\\Lib.csproj` added to the project.");
var csproj = net452netcoreapp10lib.CsProj();
csproj.NumberOfItemGroupsWithoutCondition().Should().Be(noCondBefore + 1);
csproj.NumberOfProjectReferencesWithIncludeContaining(lib.CsProjName).Should().Be(1);
}
[Theory]
[InlineData("net45")]
[InlineData("net40")]
[InlineData("netcoreapp1.1")]
[InlineData("nonexistingframeworkname")]
public void WhenFrameworkSwitchIsNotMatchingAnyOfTargetedFrameworksItPrintsError(string framework)
{
var setup = Setup();
var lib = new ProjDir(setup.LibDir);
var net45lib = new ProjDir(Path.Combine(setup.TestRoot, "Net45Lib"));
var csProjContent = lib.CsProjContent();
var cmd = new AddReferenceCommand()
.WithProject(lib.CsProjPath)
.Execute($"-f {framework} \"{net45lib.CsProjPath}\"");
cmd.Should().Fail();
cmd.StdErr.Should().Be($"Project `{setup.LibCsprojPath}` does not target framework `{framework}`.");
lib.CsProjContent().Should().BeEquivalentTo(csProjContent);
}
[Theory]
[InlineData("")]
[InlineData("-f net45")]
public void WhenIncompatibleFrameworkDetectedItPrintsError(string frameworkArg)
{
var setup = Setup();
var lib = new ProjDir(setup.LibDir);
var net45lib = new ProjDir(Path.Combine(setup.TestRoot, "Net45Lib"));
var csProjContent = net45lib.CsProjContent();
var cmd = new AddReferenceCommand()
.WithProject(net45lib.CsProjPath)
.Execute($"{frameworkArg} \"{lib.CsProjPath}\"");
cmd.Should().Fail();
cmd.StdErr.Should().MatchRegex(ProjectNotCompatibleErrorMessageRegEx);
cmd.StdErr.Should().MatchRegex(" - net45");
net45lib.CsProjContent().Should().BeEquivalentTo(csProjContent);
}
}
}
| |
using System;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using UnityEngine;
using UnityEngine.Networking;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace FMODUnity
{
[AddComponentMenu("")]
public class RuntimeManager : MonoBehaviour
{
static SystemNotInitializedException initException = null;
static RuntimeManager instance;
static bool isQuitting = false;
bool loadAllSampleData = false;
[SerializeField]
FMODPlatform fmodPlatform;
static RuntimeManager Instance
{
get
{
if (initException != null)
{
throw initException;
}
if (isQuitting)
{
throw new Exception("FMOD Studio attempted access by script to RuntimeManager while application is quitting");
}
if (instance == null)
{
FMOD.RESULT initResult = FMOD.RESULT.OK; // Initialize can return an error code if it falls back to NO_SOUND, throw it as a non-cached exception
var existing = FindObjectOfType(typeof(RuntimeManager)) as RuntimeManager;
if (existing != null)
{
// Older versions of the integration may have leaked the runtime manager game object into the scene,
// which was then serialized. It won't have valid pointers so don't use it.
if (existing.cachedPointers[0] != 0)
{
instance = existing;
instance.studioSystem.handle = ((IntPtr)instance.cachedPointers[0]);
instance.lowlevelSystem.handle = ((IntPtr)instance.cachedPointers[1]);
return instance;
}
}
var gameObject = new GameObject("FMOD.UnityIntegration.RuntimeManager");
instance = gameObject.AddComponent<RuntimeManager>();
if (Application.isPlaying) // This class is used in edit mode by the Timeline auditioning system
{
DontDestroyOnLoad(gameObject);
}
gameObject.hideFlags = HideFlags.HideInHierarchy;
try
{
#if UNITY_ANDROID && !UNITY_EDITOR
// First, obtain the current activity context
AndroidJavaObject activity = null;
using (var activityClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer"))
{
activity = activityClass.GetStatic<AndroidJavaObject>("currentActivity");
}
using (var fmodJava = new AndroidJavaClass("org.fmod.FMOD"))
{
if (fmodJava != null)
{
fmodJava.CallStatic("init", activity);
}
else
{
UnityEngine.Debug.LogWarning("FMOD Studio: Cannot initialize Java wrapper");
}
}
#endif
RuntimeUtils.EnforceLibraryOrder();
initResult = instance.Initialize();
}
catch (Exception e)
{
initException = e as SystemNotInitializedException;
if (initException == null)
{
initException = new SystemNotInitializedException(e);
}
throw initException;
}
if (initResult != FMOD.RESULT.OK)
{
throw new SystemNotInitializedException(initResult, "Output forced to NO SOUND mode");
}
}
return instance;
}
}
public static FMOD.Studio.System StudioSystem
{
get { return Instance.studioSystem; }
}
public static FMOD.System LowlevelSystem
{
get { return Instance.lowlevelSystem; }
}
FMOD.Studio.System studioSystem;
FMOD.System lowlevelSystem;
FMOD.DSP mixerHead;
[SerializeField]
private long[] cachedPointers = new long[2];
struct LoadedBank
{
public FMOD.Studio.Bank Bank;
public int RefCount;
}
Dictionary<string, LoadedBank> loadedBanks = new Dictionary<string, LoadedBank>();
Dictionary<string, uint> loadedPlugins = new Dictionary<string, uint>();
// Explicit comparer to avoid issues on platforms that don't support JIT compilation
class GuidComparer : IEqualityComparer<Guid>
{
bool IEqualityComparer<Guid>.Equals(Guid x, Guid y)
{
return x.Equals(y);
}
int IEqualityComparer<Guid>.GetHashCode(Guid obj)
{
return obj.GetHashCode();
}
}
Dictionary<Guid, FMOD.Studio.EventDescription> cachedDescriptions = new Dictionary<Guid, FMOD.Studio.EventDescription>(new GuidComparer());
void CheckInitResult(FMOD.RESULT result, string cause)
{
if (result != FMOD.RESULT.OK)
{
if (studioSystem.isValid())
{
studioSystem.release();
studioSystem.clearHandle();
}
throw new SystemNotInitializedException(result, cause);
}
}
FMOD.RESULT Initialize()
{
#if UNITY_EDITOR
#if UNITY_2017_2_OR_NEWER
EditorApplication.playModeStateChanged += HandlePlayModeStateChange;
#elif UNITY_2017_1_OR_NEWER
EditorApplication.playmodeStateChanged += HandleOnPlayModeChanged;
#endif // UNITY_2017_2_OR_NEWER
#endif // UNITY_EDITOR
FMOD.RESULT result = FMOD.RESULT.OK;
FMOD.RESULT initResult = FMOD.RESULT.OK;
Settings fmodSettings = Settings.Instance;
fmodPlatform = RuntimeUtils.GetCurrentPlatform();
int sampleRate = fmodSettings.GetSampleRate(fmodPlatform);
int realChannels = Math.Min(fmodSettings.GetRealChannels(fmodPlatform), 256); // Prior to 1.08.10 we didn't clamp this properly in the settings screen
int virtualChannels = fmodSettings.GetVirtualChannels(fmodPlatform);
FMOD.SPEAKERMODE speakerMode = (FMOD.SPEAKERMODE)fmodSettings.GetSpeakerMode(fmodPlatform);
FMOD.OUTPUTTYPE outputType = FMOD.OUTPUTTYPE.AUTODETECT;
FMOD.ADVANCEDSETTINGS advancedSettings = new FMOD.ADVANCEDSETTINGS();
advancedSettings.randomSeed = (uint)DateTime.Now.Ticks;
#if UNITY_EDITOR || UNITY_STANDALONE
advancedSettings.maxVorbisCodecs = realChannels;
#elif UNITY_XBOXONE
advancedSettings.maxXMACodecs = realChannels;
#elif UNITY_PS4
advancedSettings.maxAT9Codecs = realChannels;
#else
advancedSettings.maxFADPCMCodecs = realChannels;
#endif
SetThreadAffinity();
#if UNITY_EDITOR || ((UNITY_STANDALONE_WIN || UNITY_STANDALONE_OSX) && DEVELOPMENT_BUILD)
result = FMOD.Debug.Initialize(FMOD.DEBUG_FLAGS.LOG, FMOD.DEBUG_MODE.FILE, null, RuntimeUtils.LogFileName);
if (result == FMOD.RESULT.ERR_FILE_NOTFOUND)
{
UnityEngine.Debug.LogWarningFormat("FMOD Studio: Cannot open FMOD debug log file '{0}', logs will be missing for this session.", System.IO.Path.Combine(Application.dataPath, RuntimeUtils.LogFileName));
}
else
{
CheckInitResult(result, "FMOD.Debug.Initialize");
}
#endif
FMOD.Studio.INITFLAGS studioInitFlags = FMOD.Studio.INITFLAGS.NORMAL | FMOD.Studio.INITFLAGS.DEFERRED_CALLBACKS;
if (fmodSettings.IsLiveUpdateEnabled(fmodPlatform))
{
studioInitFlags |= FMOD.Studio.INITFLAGS.LIVEUPDATE;
#if UNITY_5_0 || UNITY_5_1 // These versions of Unity shipped with FMOD4 profiling enabled consuming our port number.
UnityEngine.Debug.LogWarning("FMOD Studio: Live Update port in-use by Unity, switching to port 9265");
advancedSettings.profilePort = 9265;
#endif
}
retry:
result = FMOD.Studio.System.create(out studioSystem);
CheckInitResult(result, "FMOD.Studio.System.create");
result = studioSystem.getLowLevelSystem(out lowlevelSystem);
CheckInitResult(result, "FMOD.Studio.System.getLowLevelSystem");
result = lowlevelSystem.setOutput(outputType);
CheckInitResult(result, "FMOD.System.setOutput");
result = lowlevelSystem.setSoftwareChannels(realChannels);
CheckInitResult(result, "FMOD.System.setSoftwareChannels");
result = lowlevelSystem.setSoftwareFormat(sampleRate, speakerMode, 0);
CheckInitResult(result, "FMOD.System.setSoftwareFormat");
result = lowlevelSystem.setAdvancedSettings(ref advancedSettings);
CheckInitResult(result, "FMOD.System.setAdvancedSettings");
result = studioSystem.initialize(virtualChannels, studioInitFlags, FMOD.INITFLAGS.NORMAL, IntPtr.Zero);
if (result != FMOD.RESULT.OK && initResult == FMOD.RESULT.OK)
{
initResult = result; // Save this to throw at the end (we'll attempt NO SOUND to shield ourselves from unexpected device failures)
outputType = FMOD.OUTPUTTYPE.NOSOUND;
UnityEngine.Debug.LogErrorFormat("FMOD Studio: Studio::System::initialize returned {0}, defaulting to no-sound mode.", result.ToString());
goto retry;
}
CheckInitResult(result, "Studio::System::initialize");
// Test network functionality triggered during System::update
if ((studioInitFlags & FMOD.Studio.INITFLAGS.LIVEUPDATE) != 0)
{
studioSystem.flushCommands(); // Any error will be returned through Studio.System.update
result = studioSystem.update();
if (result == FMOD.RESULT.ERR_NET_SOCKET_ERROR)
{
studioInitFlags &= ~FMOD.Studio.INITFLAGS.LIVEUPDATE;
UnityEngine.Debug.LogWarning("FMOD Studio: Cannot open network port for Live Update (in-use), restarting with Live Update disabled.");
result = studioSystem.release();
CheckInitResult(result, "FMOD.Studio.System.Release");
goto retry;
}
}
LoadPlugins(fmodSettings);
LoadBanks(fmodSettings);
return initResult;
}
class AttachedInstance
{
public FMOD.Studio.EventInstance instance;
public Transform transform;
public Rigidbody rigidBody;
public Rigidbody2D rigidBody2D;
}
List<AttachedInstance> attachedInstances = new List<AttachedInstance>(128);
#if UNITY_EDITOR
List<FMOD.Studio.EventInstance> eventPositionWarnings = new List<FMOD.Studio.EventInstance>();
#endif
bool listenerWarningIssued = false;
void Update()
{
if (studioSystem.isValid())
{
studioSystem.update();
bool foundListener = false;
bool hasAllListeners = false;
int numListeners = 0;
for (int i = FMOD.CONSTANTS.MAX_LISTENERS - 1; i >= 0; i--)
{
if (!foundListener && HasListener[i])
{
numListeners = i + 1;
foundListener = true;
hasAllListeners = true;
}
if (!HasListener[i] && foundListener)
{
hasAllListeners = false;
}
}
if (foundListener)
{
studioSystem.setNumListeners(numListeners);
}
if (!hasAllListeners && !listenerWarningIssued)
{
listenerWarningIssued = true;
UnityEngine.Debug.LogWarning("FMOD Studio Integration: Please add an 'FMOD Studio Listener' component to your a camera in the scene for correct 3D positioning of sounds");
}
for (int i = 0; i < attachedInstances.Count; i++)
{
FMOD.Studio.PLAYBACK_STATE playbackState = FMOD.Studio.PLAYBACK_STATE.STOPPED;
attachedInstances[i].instance.getPlaybackState(out playbackState);
if (!attachedInstances[i].instance.isValid() ||
playbackState == FMOD.Studio.PLAYBACK_STATE.STOPPED ||
attachedInstances[i].transform == null // destroyed game object
)
{
attachedInstances.RemoveAt(i);
i--;
continue;
}
if (attachedInstances[i].rigidBody)
{
attachedInstances[i].instance.set3DAttributes(RuntimeUtils.To3DAttributes(attachedInstances[i].transform, attachedInstances[i].rigidBody));
}
else
{
attachedInstances[i].instance.set3DAttributes(RuntimeUtils.To3DAttributes(attachedInstances[i].transform, attachedInstances[i].rigidBody2D));
}
}
#if UNITY_EDITOR
MuteAllEvents(UnityEditor.EditorUtility.audioMasterMute);
for (int i = eventPositionWarnings.Count - 1; i >= 0; i--)
{
if (eventPositionWarnings[i].isValid())
{
FMOD.ATTRIBUTES_3D attribs;
eventPositionWarnings[i].get3DAttributes(out attribs);
if (attribs.position.x == 1e+18F &&
attribs.position.y == 1e+18F &&
attribs.position.z == 1e+18F)
{
string path;
FMOD.Studio.EventDescription desc;
eventPositionWarnings[i].getDescription(out desc);
desc.getPath(out path);
Debug.LogWarningFormat("FMOD Studio: Instance of Event {0} has not had EventInstance.set3DAttributes() called on it yet!", path);
}
}
eventPositionWarnings.RemoveAt(i);
}
#endif
}
}
public static void AttachInstanceToGameObject(FMOD.Studio.EventInstance instance, Transform transform, Rigidbody rigidBody)
{
var attachedInstance = new AttachedInstance();
attachedInstance.transform = transform;
attachedInstance.instance = instance;
attachedInstance.rigidBody = rigidBody;
Instance.attachedInstances.Add(attachedInstance);
}
public static void AttachInstanceToGameObject(FMOD.Studio.EventInstance instance, Transform transform, Rigidbody2D rigidBody2D)
{
var attachedInstance = new AttachedInstance();
attachedInstance.transform = transform;
attachedInstance.instance = instance;
attachedInstance.rigidBody2D = rigidBody2D;
attachedInstance.rigidBody = null;
Instance.attachedInstances.Add(attachedInstance);
}
public static void DetachInstanceFromGameObject(FMOD.Studio.EventInstance instance)
{
var manager = Instance;
for (int i = 0; i < manager.attachedInstances.Count; i++)
{
if (manager.attachedInstances[i].instance.handle == instance.handle)
{
manager.attachedInstances.RemoveAt(i);
return;
}
}
}
Rect windowRect = new Rect(10, 10, 300, 100);
void OnGUI()
{
if (studioSystem.isValid() && Settings.Instance.IsOverlayEnabled(fmodPlatform))
{
windowRect = GUI.Window(0, windowRect, DrawDebugOverlay, "FMOD Studio Debug");
}
}
string lastDebugText;
float lastDebugUpdate = 0;
void DrawDebugOverlay(int windowID)
{
if (lastDebugUpdate + 0.25f < Time.unscaledTime)
{
if (initException != null)
{
lastDebugText = initException.Message;
}
else
{
if (!mixerHead.hasHandle())
{
FMOD.ChannelGroup master;
lowlevelSystem.getMasterChannelGroup(out master);
master.getDSP(0, out mixerHead);
mixerHead.setMeteringEnabled(false, true);
}
StringBuilder debug = new StringBuilder();
FMOD.Studio.CPU_USAGE cpuUsage;
studioSystem.getCPUUsage(out cpuUsage);
debug.AppendFormat("CPU: dsp = {0:F1}%, studio = {1:F1}%\n", cpuUsage.dspusage, cpuUsage.studiousage);
int currentAlloc, maxAlloc;
FMOD.Memory.GetStats(out currentAlloc, out maxAlloc);
debug.AppendFormat("MEMORY: cur = {0}MB, max = {1}MB\n", currentAlloc >> 20, maxAlloc >> 20);
int realchannels, channels;
lowlevelSystem.getChannelsPlaying(out channels, out realchannels);
debug.AppendFormat("CHANNELS: real = {0}, total = {1}\n", realchannels, channels);
FMOD.DSP_METERING_INFO outputMetering;
mixerHead.getMeteringInfo(IntPtr.Zero, out outputMetering);
float rms = 0;
for (int i = 0; i < outputMetering.numchannels; i++)
{
rms += outputMetering.rmslevel[i] * outputMetering.rmslevel[i];
}
rms = Mathf.Sqrt(rms / (float)outputMetering.numchannels);
float db = rms > 0 ? 20.0f * Mathf.Log10(rms * Mathf.Sqrt(2.0f)) : -80.0f;
if (db > 10.0f) db = 10.0f;
debug.AppendFormat("VOLUME: RMS = {0:f2}db\n", db);
lastDebugText = debug.ToString();
lastDebugUpdate = Time.unscaledTime;
}
}
GUI.Label(new Rect(10, 20, 290, 100), lastDebugText);
GUI.DragWindow();
}
void OnDisable()
{
// If we're being torn down for a script reload - cache the native pointers in something unity can serialize
cachedPointers[0] = (long)studioSystem.handle;
cachedPointers[1] = (long)lowlevelSystem.handle;
}
void OnDestroy()
{
if (studioSystem.isValid())
{
if (loadAllSampleData)
{
UnloadAllBankSampleData();
}
studioSystem.release();
studioSystem.clearHandle();
}
initException = null;
instance = null;
isQuitting = true;
}
#if UNITY_EDITOR
public static void Destroy()
{
if (instance)
{
if (instance.studioSystem.isValid())
{
if (instance.loadAllSampleData)
{
instance.UnloadAllBankSampleData();
}
instance.studioSystem.release();
instance.studioSystem.clearHandle();
}
DestroyImmediate(instance.gameObject);
}
initException = null;
instance = null;
}
#if UNITY_2017_2_OR_NEWER
void HandlePlayModeStateChange(PlayModeStateChange state)
{
if (state == PlayModeStateChange.ExitingEditMode)
{
Destroy();
}
else if (state == PlayModeStateChange.EnteredEditMode)
{
isQuitting = false;
}
}
#elif UNITY_2017_1_OR_NEWER
void HandleOnPlayModeChanged()
{
if (EditorApplication.isPlayingOrWillChangePlaymode &&
!EditorApplication.isPlaying)
{
Destroy();
}
else if (!EditorApplication.isPlaying)
{
isQuitting = false;
}
}
#endif // UNITY_2017_2_OR_NEWER
#endif
void OnApplicationPause(bool pauseStatus)
{
if (studioSystem.isValid())
{
// Strings bank is always loaded
if (loadedBanks.Count > 1)
PauseAllEvents(pauseStatus);
if (pauseStatus)
{
lowlevelSystem.mixerSuspend();
}
else
{
lowlevelSystem.mixerResume();
}
}
}
private void loadedBankRegister(LoadedBank loadedBank, string bankPath, string bankName, bool loadSamples, FMOD.RESULT loadResult)
{
if (loadResult == FMOD.RESULT.OK)
{
loadedBank.RefCount = 1;
if (loadSamples)
{
loadedBank.Bank.loadSampleData();
}
Instance.loadedBanks.Add(bankName, loadedBank);
}
else if (loadResult == FMOD.RESULT.ERR_EVENT_ALREADY_LOADED)
{
// someone loaded this bank directly using the studio API
// TODO: will the null bank handle be an issue
loadedBank.RefCount = 2;
Instance.loadedBanks.Add(bankName, loadedBank);
}
else
{
throw new BankLoadException(bankPath, loadResult);
}
}
#if UNITY_WEBGL
IEnumerator loadFromWeb(string bankPath, string bankName, bool loadSamples)
{
byte[] loadWebResult;
FMOD.RESULT loadResult;
UnityEngine.Networking.UnityWebRequest www = UnityEngine.Networking.UnityWebRequest.Get(bankPath);
yield return www.SendWebRequest();
loadWebResult = www.downloadHandler.data;
LoadedBank loadedBank = new LoadedBank();
loadResult = Instance.studioSystem.loadBankMemory(loadWebResult, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out loadedBank.Bank);
if (loadResult != FMOD.RESULT.OK)
{
UnityEngine.Debug.LogWarningFormat("loadFromWeb. Path = {0}, result = {1}.", bankPath, loadResult);
}
loadedBankRegister(loadedBank, bankPath, bankName, loadSamples, loadResult);
Debug.LogFormat("Finished loading {0}", bankPath);
}
#endif
public static void LoadBank(string bankName, bool loadSamples = false)
{
if (Instance.loadedBanks.ContainsKey(bankName))
{
LoadedBank loadedBank = Instance.loadedBanks[bankName];
loadedBank.RefCount++;
if (loadSamples)
{
loadedBank.Bank.loadSampleData();
}
Instance.loadedBanks[bankName] = loadedBank;
}
else
{
string bankPath = RuntimeUtils.GetBankPath(bankName);
FMOD.RESULT loadResult;
#if UNITY_ANDROID && !UNITY_EDITOR
if (!bankPath.StartsWith("file:///android_asset"))
{
using (var www = new WWW(bankPath))
{
while (!www.isDone) { }
if (!String.IsNullOrEmpty(www.error))
{
throw new BankLoadException(bankPath, www.error);
}
else
{
LoadedBank loadedBank = new LoadedBank();
loadResult = Instance.studioSystem.loadBankMemory(www.bytes, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out loadedBank.Bank);
Instance.loadedBankRegister(loadedBank, bankPath, bankName, loadSamples, loadResult);
}
}
}
else
#elif UNITY_WEBGL
if (bankPath.Contains("://"))
{
Instance.StartCoroutine(Instance.loadFromWeb(bankPath, bankName, loadSamples));
}
else
#endif
{
LoadedBank loadedBank = new LoadedBank();
loadResult = Instance.studioSystem.loadBankFile(bankPath, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out loadedBank.Bank);
Instance.loadedBankRegister(loadedBank, bankPath, bankName, loadSamples, loadResult);
}
}
}
public static void LoadBank(TextAsset asset, bool loadSamples = false)
{
string bankName = asset.name;
if (Instance.loadedBanks.ContainsKey(bankName))
{
LoadedBank loadedBank = Instance.loadedBanks[bankName];
loadedBank.RefCount++;
if (loadSamples)
{
loadedBank.Bank.loadSampleData();
}
}
else
{
LoadedBank loadedBank = new LoadedBank();
FMOD.RESULT loadResult = Instance.studioSystem.loadBankMemory(asset.bytes, FMOD.Studio.LOAD_BANK_FLAGS.NORMAL, out loadedBank.Bank);
if (loadResult == FMOD.RESULT.OK)
{
loadedBank.RefCount = 1;
Instance.loadedBanks.Add(bankName, loadedBank);
if (loadSamples)
{
loadedBank.Bank.loadSampleData();
}
}
else if (loadResult == FMOD.RESULT.ERR_EVENT_ALREADY_LOADED)
{
// someone loaded this bank directly using the studio API
// TODO: will the null bank handle be an issue
loadedBank.RefCount = 2;
Instance.loadedBanks.Add(bankName, loadedBank);
}
else
{
throw new BankLoadException(bankName, loadResult);
}
}
}
private void LoadBanks(Settings fmodSettings)
{
if (fmodSettings.ImportType == ImportType.StreamingAssets)
{
// Always load strings bank
try
{
LoadBank(fmodSettings.MasterBank + ".strings");
if (fmodSettings.AutomaticEventLoading)
{
LoadBank(fmodSettings.MasterBank);
foreach (var bank in fmodSettings.Banks)
{
LoadBank(bank);
}
}
if (fmodSettings.AutomaticSampleLoading)
{
foreach (var keyPair in Instance.loadedBanks)
{
keyPair.Value.Bank.loadSampleData();
}
WaitForAllLoads();
}
}
catch (BankLoadException e)
{
UnityEngine.Debug.LogException(e);
}
}
loadAllSampleData = fmodSettings.AutomaticSampleLoading;
}
private void UnloadAllBankSampleData()
{
int bankCount;
Instance.studioSystem.getBankCount(out bankCount);
if (bankCount > 0)
{
FMOD.Studio.Bank[] bankArray = new FMOD.Studio.Bank[bankCount];
Instance.studioSystem.getBankList(out bankArray);
for (int i = 0; i < bankCount; i++)
{
int eventCount;
bankArray[i].getEventCount(out eventCount);
if (eventCount > 0)
{
FMOD.Studio.EventDescription[] eventArray = new FMOD.Studio.EventDescription[eventCount];
bankArray[i].getEventList(out eventArray);
for (int j = 0; j < eventCount; j++)
{
int instanceCount;
eventArray[j].getInstanceCount(out instanceCount);
if (instanceCount > 0)
{
FMOD.Studio.EventInstance[] instanceArray = new FMOD.Studio.EventInstance[instanceCount];
eventArray[j].getInstanceList(out instanceArray);
for (int k = 0; k < instanceCount; k++)
{
instanceArray[k].stop(FMOD.Studio.STOP_MODE.IMMEDIATE);
instanceArray[k].release();
}
}
}
}
}
for (int i = 0; i < bankCount; i++)
{
bankArray[i].unloadSampleData();
}
}
}
public static void UnloadBank(string bankName)
{
LoadedBank loadedBank;
if (Instance.loadedBanks.TryGetValue(bankName, out loadedBank))
{
loadedBank.RefCount--;
if (loadedBank.RefCount == 0)
{
loadedBank.Bank.unload();
Instance.loadedBanks.Remove(bankName);
return;
}
Instance.loadedBanks[bankName] = loadedBank;
}
}
public static bool AnyBankLoading()
{
bool loading = false;
foreach (LoadedBank bank in Instance.loadedBanks.Values)
{
FMOD.Studio.LOADING_STATE loadingState;
bank.Bank.getSampleLoadingState(out loadingState);
loading |= (loadingState == FMOD.Studio.LOADING_STATE.LOADING);
}
return loading;
}
public static void WaitForAllLoads()
{
Instance.studioSystem.flushSampleLoading();
}
public static Guid PathToGUID(string path)
{
Guid guid = Guid.Empty;
if (path.StartsWith("{"))
{
FMOD.Studio.Util.ParseID(path, out guid);
}
else
{
var result = Instance.studioSystem.lookupID(path, out guid);
if (result == FMOD.RESULT.ERR_EVENT_NOTFOUND)
{
throw new EventNotFoundException(path);
}
}
return guid;
}
public static FMOD.Studio.EventInstance CreateInstance(string path)
{
try
{
return CreateInstance(PathToGUID(path));
}
catch(EventNotFoundException)
{
// Switch from exception with GUID to exception with path
throw new EventNotFoundException(path);
}
}
public static FMOD.Studio.EventInstance CreateInstance(Guid guid)
{
FMOD.Studio.EventDescription eventDesc = GetEventDescription(guid);
FMOD.Studio.EventInstance newInstance;
eventDesc.createInstance(out newInstance);
#if UNITY_EDITOR
bool is3D = false;
eventDesc.is3D(out is3D);
if (is3D)
{
// Set position to 1e+18F, set3DAttributes should be called by the dev after this.
newInstance.set3DAttributes(RuntimeUtils.To3DAttributes(new Vector3(1e+18F, 1e+18F, 1e+18F)));
instance.eventPositionWarnings.Add(newInstance);
}
#endif
return newInstance;
}
public static void PlayOneShot(string path, Vector3 position = new Vector3())
{
try
{
PlayOneShot(PathToGUID(path), position);
}
catch (EventNotFoundException)
{
Debug.LogWarning("FMOD Event not found: " + path);
}
}
public static void PlayOneShot(Guid guid, Vector3 position = new Vector3())
{
var instance = CreateInstance(guid);
instance.set3DAttributes(RuntimeUtils.To3DAttributes(position));
instance.start();
instance.release();
}
public static void PlayOneShotAttached(string path, GameObject gameObject)
{
try
{
PlayOneShotAttached(PathToGUID(path), gameObject);
}
catch (EventNotFoundException)
{
Debug.LogWarning("FMOD Event not found: " + path);
}
}
public static void PlayOneShotAttached(Guid guid, GameObject gameObject)
{
var instance = CreateInstance(guid);
AttachInstanceToGameObject(instance, gameObject.transform, gameObject.GetComponent<Rigidbody>());
instance.start();
instance.release();
}
public static FMOD.Studio.EventDescription GetEventDescription(string path)
{
try
{
return GetEventDescription(PathToGUID(path));
}
catch (EventNotFoundException)
{
throw new EventNotFoundException(path);
}
}
public static FMOD.Studio.EventDescription GetEventDescription(Guid guid)
{
FMOD.Studio.EventDescription eventDesc;
if (Instance.cachedDescriptions.ContainsKey(guid) && Instance.cachedDescriptions[guid].isValid())
{
eventDesc = Instance.cachedDescriptions[guid];
}
else
{
var result = Instance.studioSystem.getEventByID(guid, out eventDesc);
if (result != FMOD.RESULT.OK)
{
throw new EventNotFoundException(guid);
}
if (eventDesc.isValid())
{
Instance.cachedDescriptions[guid] = eventDesc;
}
}
return eventDesc;
}
public static bool[] HasListener = new bool[FMOD.CONSTANTS.MAX_LISTENERS];
public static void SetListenerLocation(GameObject gameObject, Rigidbody rigidBody = null)
{
Instance.studioSystem.setListenerAttributes(0, RuntimeUtils.To3DAttributes(gameObject, rigidBody));
}
public static void SetListenerLocation(GameObject gameObject, Rigidbody2D rigidBody2D)
{
Instance.studioSystem.setListenerAttributes(0, RuntimeUtils.To3DAttributes(gameObject, rigidBody2D));
}
public static void SetListenerLocation(Transform transform)
{
Instance.studioSystem.setListenerAttributes(0, transform.To3DAttributes());
}
public static void SetListenerLocation(int listenerIndex, GameObject gameObject, Rigidbody rigidBody = null)
{
Instance.studioSystem.setListenerAttributes(listenerIndex, RuntimeUtils.To3DAttributes(gameObject, rigidBody));
}
public static void SetListenerLocation(int listenerIndex, GameObject gameObject, Rigidbody2D rigidBody2D)
{
Instance.studioSystem.setListenerAttributes(listenerIndex, RuntimeUtils.To3DAttributes(gameObject, rigidBody2D));
}
public static void SetListenerLocation(int listenerIndex, Transform transform)
{
Instance.studioSystem.setListenerAttributes(listenerIndex, transform.To3DAttributes());
}
public static FMOD.Studio.Bus GetBus(string path)
{
FMOD.Studio.Bus bus;
if (StudioSystem.getBus(path, out bus) != FMOD.RESULT.OK)
{
throw new BusNotFoundException(path);
}
return bus;
}
public static FMOD.Studio.VCA GetVCA(string path)
{
FMOD.Studio.VCA vca;
if (StudioSystem.getVCA(path, out vca) != FMOD.RESULT.OK)
{
throw new VCANotFoundException(path);
}
return vca;
}
public static void PauseAllEvents(bool paused)
{
GetBus("bus:/").setPaused(paused);
}
public static void MuteAllEvents(bool muted)
{
GetBus("bus:/").setMute(muted);
}
public static bool IsInitialized
{
get
{
return instance != null && instance.studioSystem.isValid();
}
}
#if UNITY_EDITOR
/* Only relavant to protect the Play-In-Editor to Editor transition. */
public static bool IsQuitting()
{
return isQuitting;
}
#endif
public static bool HasBanksLoaded
{
get
{
return Instance.loadedBanks.Count > 1;
}
}
public static bool HasBankLoaded(string loadedBank)
{
return (instance.loadedBanks.ContainsKey(loadedBank));
}
private void LoadPlugins(Settings fmodSettings)
{
#if (UNITY_IOS || UNITY_TVOS) && !UNITY_EDITOR
FmodUnityNativePluginInit(lowlevelSystem.handle);
#else
FMOD.RESULT result;
foreach (var pluginName in fmodSettings.Plugins)
{
if (string.IsNullOrEmpty(pluginName))
continue;
string pluginPath = RuntimeUtils.GetPluginPath(pluginName);
uint handle;
result = lowlevelSystem.loadPlugin(pluginPath, out handle);
#if UNITY_64 || UNITY_EDITOR_64
// Add a "64" suffix and try again
if (result == FMOD.RESULT.ERR_FILE_BAD || result == FMOD.RESULT.ERR_FILE_NOTFOUND)
{
string pluginPath64 = RuntimeUtils.GetPluginPath(pluginName + "64");
result = lowlevelSystem.loadPlugin(pluginPath64, out handle);
}
#endif
CheckInitResult(result, String.Format("Loading plugin '{0}' from '{1}'", pluginName, pluginPath));
loadedPlugins.Add(pluginName, handle);
}
#endif
}
private void SetThreadAffinity()
{
#if UNITY_PS4 && !UNITY_EDITOR
FMOD.PS4.THREADAFFINITY affinity = new FMOD.PS4.THREADAFFINITY
{
mixer = FMOD.PS4.THREAD.CORE0,
studioUpdate = FMOD.PS4.THREAD.CORE0,
studioLoadBank = FMOD.PS4.THREAD.CORE0,
studioLoadSample = FMOD.PS4.THREAD.CORE0
};
FMOD.RESULT result = FMOD.PS4.setThreadAffinity(ref affinity);
CheckInitResult(result, "FMOD.PS4.setThreadAffinity");
#elif UNITY_XBOXONE && !UNITY_EDITOR
FMOD.XboxOne.THREADAFFINITY affinity = new FMOD.XboxOne.THREADAFFINITY
{
mixer = FMOD.XboxOne.THREAD.CORE0,
studioUpdate = FMOD.XboxOne.THREAD.CORE0,
studioLoadBank = FMOD.XboxOne.THREAD.CORE0,
studioLoadSample = FMOD.XboxOne.THREAD.CORE0
};
FMOD.RESULT result = FMOD.XboxOne.setThreadAffinity(ref affinity);
CheckInitResult(result, "FMOD.XboxOne.setThreadAffinity");
#elif UNITY_SWITCH && !UNITY_EDITOR
FMOD.Switch.THREADAFFINITY affinity = new FMOD.Switch.THREADAFFINITY
{
mixer = FMOD.Switch.THREAD.CORE0,
studioUpdate = FMOD.Switch.THREAD.CORE0,
studioLoadBank = FMOD.Switch.THREAD.CORE0,
studioLoadSample = FMOD.Switch.THREAD.CORE0
};
FMOD.RESULT result = FMOD.Switch.setThreadAffinity(ref affinity);
CheckInitResult(result, "FMOD.Switch.setThreadAffinity");
#endif
}
#if (UNITY_IOS || UNITY_TVOS) && !UNITY_EDITOR
[DllImport("__Internal")]
private static extern FMOD.RESULT FmodUnityNativePluginInit(IntPtr system);
#endif
}
}
| |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Runspaces;
using System.Management.Automation.Help;
using System.Net;
using System.IO;
using System.Globalization;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation.Tracing;
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// The base class of all updatable help system cmdlets (Update-Help, Save-Help)
/// </summary>
public class UpdatableHelpCommandBase : PSCmdlet
{
internal const string PathParameterSetName = "Path";
internal const string LiteralPathParameterSetName = "LiteralPath";
internal UpdatableHelpCommandType _commandType;
internal UpdatableHelpSystem _helpSystem;
internal bool _stopping;
internal int activityId;
private Dictionary<string, UpdatableHelpExceptionContext> _exceptions;
#region Parameters
/// <summary>
/// Specifies the languages to update.
/// </summary>
[Parameter(Position = 2)]
[ValidateNotNull]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public CultureInfo[] UICulture
{
get
{
CultureInfo[] result = null;
if (_language != null)
{
result = new CultureInfo[_language.Length];
for (int index = 0; index < _language.Length; index++)
{
result[index] = new CultureInfo(_language[index]);
}
}
return result;
}
set
{
if (value == null) return;
_language = new string[value.Length];
for (int index = 0; index < value.Length; index++)
{
_language[index] = value[index].Name;
}
}
}
internal string[] _language;
/// <summary>
/// Gets or sets the credential parameter.
/// </summary>
[Parameter()]
[Credential()]
public PSCredential Credential
{
get { return _credential; }
set { _credential = value; }
}
internal PSCredential _credential;
/// <summary>
/// Directs System.Net.WebClient whether or not to use default credentials.
/// </summary>
[Parameter]
public SwitchParameter UseDefaultCredentials
{
get
{
return _useDefaultCredentials;
}
set
{
_useDefaultCredentials = value;
}
}
internal bool _useDefaultCredentials = false;
/// <summary>
/// Forces the operation to complete.
/// </summary>
[Parameter]
public SwitchParameter Force
{
get
{
return _force;
}
set
{
_force = value;
}
}
internal bool _force;
/// <summary>
/// Sets the scope to which help is saved.
/// </summary>
[Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true)]
public UpdateHelpScope Scope
{
get;
set;
}
#endregion
#region Events
/// <summary>
/// Handles help system progress events.
/// </summary>
/// <param name="sender">Event sender.</param>
/// <param name="e">Event arguments.</param>
private void HandleProgressChanged(object sender, UpdatableHelpProgressEventArgs e)
{
Debug.Assert(e.CommandType == UpdatableHelpCommandType.UpdateHelpCommand
|| e.CommandType == UpdatableHelpCommandType.SaveHelpCommand);
string activity = (e.CommandType == UpdatableHelpCommandType.UpdateHelpCommand) ?
HelpDisplayStrings.UpdateProgressActivityForModule : HelpDisplayStrings.SaveProgressActivityForModule;
ProgressRecord progress = new ProgressRecord(activityId, StringUtil.Format(activity, e.ModuleName), e.ProgressStatus);
progress.PercentComplete = e.ProgressPercent;
WriteProgress(progress);
}
#endregion
#region Constructor
private static Dictionary<string, string> s_metadataCache;
/// <summary>
/// Static constructor
///
/// NOTE: FWLinks for core PowerShell modules are needed since they get loaded as snapins in a Remoting Endpoint.
/// When we moved to modules in V3, we were not able to make this change as it was a risky change to make at that time.
/// </summary>
static UpdatableHelpCommandBase()
{
s_metadataCache = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
// TODO: assign real TechNet addresses
s_metadataCache.Add("Microsoft.PowerShell.Diagnostics", "https://go.microsoft.com/fwlink/?linkid=855954");
s_metadataCache.Add("Microsoft.PowerShell.Core", "https://go.microsoft.com/fwlink/?linkid=855953");
s_metadataCache.Add("Microsoft.PowerShell.Utility", "https://go.microsoft.com/fwlink/?linkid=855960");
s_metadataCache.Add("Microsoft.PowerShell.Host", "https://go.microsoft.com/fwlink/?linkid=855956");
s_metadataCache.Add("Microsoft.PowerShell.Management", "https://go.microsoft.com/fwlink/?linkid=855958");
s_metadataCache.Add("Microsoft.PowerShell.Security", "https://go.microsoft.com/fwlink/?linkid=855959");
s_metadataCache.Add("Microsoft.WSMan.Management", "https://go.microsoft.com/fwlink/?linkid=855961");
}
/// <summary>
/// Checks if a module is a system module, a module is a system module
/// if it exists in the metadata cache.
/// </summary>
/// <param name="module">Module name.</param>
/// <returns>True if system module, false if not.</returns>
internal static bool IsSystemModule(string module)
{
return s_metadataCache.ContainsKey(module);
}
/// <summary>
/// Class constructor.
/// </summary>
/// <param name="commandType">Command type.</param>
internal UpdatableHelpCommandBase(UpdatableHelpCommandType commandType)
{
_commandType = commandType;
_helpSystem = new UpdatableHelpSystem(this, _useDefaultCredentials);
_exceptions = new Dictionary<string, UpdatableHelpExceptionContext>();
_helpSystem.OnProgressChanged += new EventHandler<UpdatableHelpProgressEventArgs>(HandleProgressChanged);
Random rand = new Random();
activityId = rand.Next();
}
#endregion
#region Implementation
private void ProcessSingleModuleObject(PSModuleInfo module, ExecutionContext context, Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo> helpModules, bool noErrors)
{
if (InitialSessionState.IsEngineModule(module.Name) && !InitialSessionState.IsNestedEngineModule(module.Name))
{
WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", module.Name, module.Guid));
var keyTuple = new Tuple<string, Version>(module.Name, module.Version);
if (!helpModules.ContainsKey(keyTuple))
{
helpModules.Add(keyTuple, new UpdatableHelpModuleInfo(module.Name, module.Guid,
Utils.GetApplicationBase(context.ShellID), s_metadataCache[module.Name]));
}
return;
}
else if (InitialSessionState.IsNestedEngineModule(module.Name))
{
return;
}
if (string.IsNullOrEmpty(module.HelpInfoUri))
{
if (!noErrors)
{
ProcessException(module.Name, null, new UpdatableHelpSystemException(
"HelpInfoUriNotFound", StringUtil.Format(HelpDisplayStrings.HelpInfoUriNotFound),
ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
}
return;
}
if (!(module.HelpInfoUri.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || module.HelpInfoUri.StartsWith("https://", StringComparison.OrdinalIgnoreCase)))
{
if (!noErrors)
{
ProcessException(module.Name, null, new UpdatableHelpSystemException(
"InvalidHelpInfoUriFormat", StringUtil.Format(HelpDisplayStrings.InvalidHelpInfoUriFormat, module.HelpInfoUri),
ErrorCategory.NotSpecified, new Uri("HelpInfoUri", UriKind.Relative), null));
}
return;
}
var keyTuple2 = new Tuple<string, Version>(module.Name, module.Version);
if (!helpModules.ContainsKey(keyTuple2))
{
helpModules.Add(keyTuple2, new UpdatableHelpModuleInfo(module.Name, module.Guid, module.ModuleBase, module.HelpInfoUri));
}
}
/// <summary>
/// Gets a list of modules from the given pattern.
/// </summary>
/// <param name="context">Execution context.</param>
/// <param name="pattern">Pattern to search.</param>
/// <param name="fullyQualifiedName">Module Specification.</param>
/// <param name="noErrors">Do not generate errors for modules without HelpInfoUri.</param>
/// <returns>A list of modules.</returns>
private Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo> GetModuleInfo(ExecutionContext context, string pattern, ModuleSpecification fullyQualifiedName, bool noErrors)
{
List<PSModuleInfo> modules = null;
string moduleNamePattern = null;
if (pattern != null)
{
moduleNamePattern = pattern;
modules = Utils.GetModules(pattern, context);
}
else if (fullyQualifiedName != null)
{
moduleNamePattern = fullyQualifiedName.Name;
modules = Utils.GetModules(fullyQualifiedName, context);
}
var helpModules = new Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo>();
if (modules != null)
{
foreach (PSModuleInfo module in modules)
{
ProcessSingleModuleObject(module, context, helpModules, noErrors);
}
}
// Match wildcards
WildcardOptions wildcardOptions = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant;
IEnumerable<WildcardPattern> patternList = SessionStateUtilities.CreateWildcardsFromStrings(new string[1] { moduleNamePattern }, wildcardOptions);
foreach (KeyValuePair<string, string> name in s_metadataCache)
{
if (SessionStateUtilities.MatchesAnyWildcardPattern(name.Key, patternList, true))
{
// For core snapin, there are no GUIDs. So, we need to construct the HelpInfo slightly differently
if (!name.Key.Equals(InitialSessionState.CoreSnapin, StringComparison.OrdinalIgnoreCase))
{
var keyTuple = new Tuple<string, Version>(name.Key, new Version("1.0"));
if (!helpModules.ContainsKey(keyTuple))
{
List<PSModuleInfo> availableModules = Utils.GetModules(name.Key, context);
if (availableModules != null)
{
foreach (PSModuleInfo module in availableModules)
{
keyTuple = new Tuple<string, Version>(module.Name, module.Version);
if (!helpModules.ContainsKey(keyTuple))
{
WriteDebug(StringUtil.Format("Found engine module: {0}, {1}.", module.Name, module.Guid));
helpModules.Add(keyTuple, new UpdatableHelpModuleInfo(module.Name,
module.Guid, Utils.GetApplicationBase(context.ShellID), s_metadataCache[module.Name]));
}
}
}
}
}
else
{
var keyTuple2 = new Tuple<string, Version>(name.Key, new Version("1.0"));
if (!helpModules.ContainsKey(keyTuple2))
{
helpModules.Add(keyTuple2,
new UpdatableHelpModuleInfo(name.Key, Guid.Empty,
Utils.GetApplicationBase(context.ShellID),
name.Value));
}
}
}
}
return helpModules;
}
/// <summary>
/// Handles Ctrl+C.
/// </summary>
protected override void StopProcessing()
{
_stopping = true;
_helpSystem.CancelDownload();
}
/// <summary>
/// End processing.
/// </summary>
protected override void EndProcessing()
{
foreach (UpdatableHelpExceptionContext exception in _exceptions.Values)
{
UpdatableHelpExceptionContext e = exception;
if ((exception.Exception.FullyQualifiedErrorId == "HelpCultureNotSupported") &&
((exception.Cultures != null && exception.Cultures.Count > 1) ||
(exception.Modules != null && exception.Modules.Count > 1)))
{
// Win8: 744749 Rewriting the error message only in the case where either
// multiple cultures or multiple modules are involved.
e = new UpdatableHelpExceptionContext(new UpdatableHelpSystemException(
"HelpCultureNotSupported", StringUtil.Format(HelpDisplayStrings.CannotMatchUICulturePattern,
string.Join(", ", exception.Cultures)),
ErrorCategory.InvalidArgument, exception.Cultures, null));
e.Modules = exception.Modules;
e.Cultures = exception.Cultures;
}
WriteError(e.CreateErrorRecord(_commandType));
LogContext context = MshLog.GetLogContext(Context, MyInvocation);
context.Severity = "Error";
PSEtwLog.LogOperationalError(PSEventId.Pipeline_Detail, PSOpcode.Exception, PSTask.ExecutePipeline,
context, e.GetExceptionMessage(_commandType));
}
}
/// <summary>
/// Main cmdlet logic for processing module names or fully qualified module names.
/// </summary>
/// <param name="moduleNames">Module names given by the user.</param>
/// <param name="fullyQualifiedNames">FullyQualifiedNames.</param>
internal void Process(IEnumerable<string> moduleNames, IEnumerable<ModuleSpecification> fullyQualifiedNames)
{
_helpSystem.WebClient.UseDefaultCredentials = _useDefaultCredentials;
if (moduleNames != null)
{
foreach (string name in moduleNames)
{
if (_stopping)
{
break;
}
ProcessModuleWithGlobbing(name);
}
}
else if (fullyQualifiedNames != null)
{
foreach (var fullyQualifiedName in fullyQualifiedNames)
{
if (_stopping)
{
break;
}
ProcessModuleWithGlobbing(fullyQualifiedName);
}
}
else
{
foreach (KeyValuePair<Tuple<string, Version>, UpdatableHelpModuleInfo> module in GetModuleInfo("*", null, true))
{
if (_stopping)
{
break;
}
ProcessModule(module.Value);
}
}
}
/// <summary>
/// Processing module objects for Save-Help.
/// </summary>
/// <param name="modules">Module objects given by the user.</param>
internal void Process(IEnumerable<PSModuleInfo> modules)
{
if (modules == null || !modules.Any()) { return; }
var helpModules = new Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo>();
foreach (PSModuleInfo module in modules)
{
ProcessSingleModuleObject(module, Context, helpModules, false);
}
foreach (KeyValuePair<Tuple<string, Version>, UpdatableHelpModuleInfo> helpModule in helpModules)
{
ProcessModule(helpModule.Value);
}
}
/// <summary>
/// Processes a module with potential globbing.
/// </summary>
/// <param name="name">Module name with globbing.</param>
private void ProcessModuleWithGlobbing(string name)
{
if (string.IsNullOrEmpty(name))
{
PSArgumentException e = new PSArgumentException(StringUtil.Format(HelpDisplayStrings.ModuleNameNullOrEmpty));
WriteError(e.ErrorRecord);
return;
}
foreach (KeyValuePair<Tuple<string, Version>, UpdatableHelpModuleInfo> module in GetModuleInfo(name, null, false))
{
ProcessModule(module.Value);
}
}
/// <summary>
/// Processes a ModuleSpecification with potential globbing.
/// </summary>
/// <param name="fullyQualifiedName">ModuleSpecification.</param>
private void ProcessModuleWithGlobbing(ModuleSpecification fullyQualifiedName)
{
foreach (KeyValuePair<Tuple<string, Version>, UpdatableHelpModuleInfo> module in GetModuleInfo(null, fullyQualifiedName, false))
{
ProcessModule(module.Value);
}
}
/// <summary>
/// Processes a single module with multiple cultures.
/// </summary>
/// <param name="module">Module to process.</param>
private void ProcessModule(UpdatableHelpModuleInfo module)
{
_helpSystem.CurrentModule = module.ModuleName;
if (this is UpdateHelpCommand && !Directory.Exists(module.ModuleBase))
{
ProcessException(module.ModuleName, null,
new UpdatableHelpSystemException("ModuleBaseMustExist",
StringUtil.Format(HelpDisplayStrings.ModuleBaseMustExist),
ErrorCategory.InvalidOperation, null, null));
return;
}
// Win8: 572882 When the system locale is English and the UI is JPN,
// running "update-help" still downs English help content.
var cultures = _language ?? _helpSystem.GetCurrentUICulture();
foreach (string culture in cultures)
{
bool installed = true;
if (_stopping)
{
break;
}
try
{
ProcessModuleWithCulture(module, culture);
}
catch (IOException e)
{
ProcessException(module.ModuleName, culture, new UpdatableHelpSystemException("FailedToCopyFile",
e.Message, ErrorCategory.InvalidOperation, null, e));
}
catch (UnauthorizedAccessException e)
{
ProcessException(module.ModuleName, culture, new UpdatableHelpSystemException("AccessIsDenied",
e.Message, ErrorCategory.PermissionDenied, null, e));
}
#if !CORECLR
catch (WebException e)
{
if (e.InnerException != null && e.InnerException is UnauthorizedAccessException)
{
ProcessException(module.ModuleName, culture, new UpdatableHelpSystemException("AccessIsDenied",
e.InnerException.Message, ErrorCategory.PermissionDenied, null, e));
}
else
{
ProcessException(module.ModuleName, culture, e);
}
}
#endif
catch (UpdatableHelpSystemException e)
{
if (e.FullyQualifiedErrorId == "HelpCultureNotSupported")
{
installed = false;
if (_language != null)
{
// Display the error message only if we are not using the fallback chain
ProcessException(module.ModuleName, culture, e);
}
}
else
{
ProcessException(module.ModuleName, culture, e);
}
}
catch (Exception e)
{
ProcessException(module.ModuleName, culture, e);
}
finally
{
if (_helpSystem.Errors.Count != 0)
{
foreach (Exception error in _helpSystem.Errors)
{
ProcessException(module.ModuleName, culture, error);
}
_helpSystem.Errors.Clear();
}
}
// If -Language is not specified, we only install
// one culture from the fallback chain
if (_language == null && installed)
{
break;
}
}
}
/// <summary>
/// Process a single module with a given culture.
/// </summary>
/// <param name="module">Module to process.</param>
/// <param name="culture">Culture to use.</param>
/// <returns>True if the module has been processed, false if not.</returns>
internal virtual bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string culture)
{
return false;
}
#endregion
#region Common methods
/// <summary>
/// Gets a list of modules from the given pattern or ModuleSpecification.
/// </summary>
/// <param name="pattern">Pattern to match.</param>
/// <param name="fullyQualifiedName">ModuleSpecification.</param>
/// <param name="noErrors">Skip errors.</param>
/// <returns>A list of modules.</returns>
internal Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo> GetModuleInfo(string pattern, ModuleSpecification fullyQualifiedName, bool noErrors)
{
Dictionary<Tuple<string, Version>, UpdatableHelpModuleInfo> modules = GetModuleInfo(Context, pattern, fullyQualifiedName, noErrors);
if (modules.Count == 0 && _exceptions.Count == 0 && !noErrors)
{
var errorMessage = fullyQualifiedName != null ? StringUtil.Format(HelpDisplayStrings.ModuleNotFoundWithFullyQualifiedName, fullyQualifiedName)
: StringUtil.Format(HelpDisplayStrings.CannotMatchModulePattern, pattern);
ErrorRecord errorRecord = new ErrorRecord(new Exception(errorMessage),
"ModuleNotFound", ErrorCategory.InvalidArgument, pattern);
WriteError(errorRecord);
}
return modules;
}
/// <summary>
/// Checks if it is necessary to update help.
/// </summary>
/// <param name="module">ModuleInfo.</param>
/// <param name="currentHelpInfo">Current HelpInfo.xml.</param>
/// <param name="newHelpInfo">New HelpInfo.xml.</param>
/// <param name="culture">Current culture.</param>
/// <param name="force">Force update.</param>
/// <returns>True if it is necessary to update help, false if not.</returns>
internal bool IsUpdateNecessary(UpdatableHelpModuleInfo module, UpdatableHelpInfo currentHelpInfo,
UpdatableHelpInfo newHelpInfo, CultureInfo culture, bool force)
{
Debug.Assert(module != null);
if (newHelpInfo == null)
{
throw new UpdatableHelpSystemException("UnableToRetrieveHelpInfoXml",
StringUtil.Format(HelpDisplayStrings.UnableToRetrieveHelpInfoXml, culture.Name), ErrorCategory.ResourceUnavailable,
null, null);
}
// Culture check
if (!newHelpInfo.IsCultureSupported(culture))
{
throw new UpdatableHelpSystemException("HelpCultureNotSupported",
StringUtil.Format(HelpDisplayStrings.HelpCultureNotSupported,
culture.Name, newHelpInfo.GetSupportedCultures()), ErrorCategory.InvalidOperation, null, null);
}
// Version check
if (!force && currentHelpInfo != null && !currentHelpInfo.IsNewerVersion(newHelpInfo, culture))
{
return false;
}
return true;
}
/// <summary>
/// Checks if the user has attempted to update more than once per day per module.
/// </summary>
/// <param name="moduleName">Module name.</param>
/// <param name="path">Path to help info.</param>
/// <param name="filename">Help info file name.</param>
/// <param name="time">Current time (UTC).</param>
/// <param name="force">If -Force is specified.</param>
/// <returns>True if we are okay to update, false if not.</returns>
internal bool CheckOncePerDayPerModule(string moduleName, string path, string filename, DateTime time, bool force)
{
// Update if -Force is specified
if (force)
{
return true;
}
string helpInfoFilePath = SessionState.Path.Combine(path, filename);
// No HelpInfo.xml
if (!File.Exists(helpInfoFilePath))
{
return true;
}
DateTime lastModified = File.GetLastWriteTimeUtc(helpInfoFilePath);
TimeSpan difference = time - lastModified;
if (difference.Days >= 1)
{
return true;
}
if (_commandType == UpdatableHelpCommandType.UpdateHelpCommand)
{
WriteVerbose(StringUtil.Format(HelpDisplayStrings.UseForceToUpdateHelp, moduleName));
}
else if (_commandType == UpdatableHelpCommandType.SaveHelpCommand)
{
WriteVerbose(StringUtil.Format(HelpDisplayStrings.UseForceToSaveHelp, moduleName));
}
return false;
}
/// <summary>
/// Resolves a given path to a list of directories.
/// </summary>
/// <param name="path">Path to resolve.</param>
/// <param name="recurse">Resolve recursively?</param>
/// <param name="isLiteralPath">Treat the path / start path as a literal path?</param>///
/// <returns>A list of directories.</returns>
internal IEnumerable<string> ResolvePath(string path, bool recurse, bool isLiteralPath)
{
List<string> resolvedPaths = new List<string>();
if (isLiteralPath)
{
string newPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(path);
if (!Directory.Exists(newPath))
{
throw new UpdatableHelpSystemException("PathMustBeValidContainers",
StringUtil.Format(HelpDisplayStrings.PathMustBeValidContainers, path), ErrorCategory.InvalidArgument,
null, new ItemNotFoundException());
}
resolvedPaths.Add(newPath);
}
else
{
Collection<PathInfo> resolvedPathInfos = SessionState.Path.GetResolvedPSPathFromPSPath(path);
foreach (PathInfo resolvedPath in resolvedPathInfos)
{
ValidatePathProvider(resolvedPath);
resolvedPaths.Add(resolvedPath.ProviderPath);
}
}
foreach (string resolvedPath in resolvedPaths)
{
if (recurse)
{
foreach (string innerResolvedPath in RecursiveResolvePathHelper(resolvedPath))
{
yield return innerResolvedPath;
}
}
else
{
// Win8: 566738
CmdletProviderContext context = new CmdletProviderContext(this.Context);
// resolvedPath is already resolved..so no need to expand wildcards anymore
context.SuppressWildcardExpansion = true;
if (isLiteralPath || InvokeProvider.Item.IsContainer(resolvedPath, context))
{
yield return resolvedPath;
}
}
}
yield break;
}
/// <summary>
/// Resolves a given path to a list of directories recursively.
/// </summary>
/// <param name="path">Path to resolve.</param>
/// <returns>A list of directories.</returns>
private IEnumerable<string> RecursiveResolvePathHelper(string path)
{
if (System.IO.Directory.Exists(path))
{
yield return path;
foreach (string subDirectory in Directory.GetDirectories(path))
{
foreach (string subDirectory2 in RecursiveResolvePathHelper(subDirectory))
{
yield return subDirectory2;
}
}
}
yield break;
}
#endregion
#region Static methods
/// <summary>
/// Validates the provider of the path, only FileSystem provider is accepted.
/// </summary>
/// <param name="path">Path to validate.</param>
internal void ValidatePathProvider(PathInfo path)
{
if (path.Provider == null || path.Provider.Name != FileSystemProvider.ProviderName)
{
throw new PSArgumentException(StringUtil.Format(HelpDisplayStrings.ProviderIsNotFileSystem,
path.Path));
}
}
#endregion
#region Logging
/// <summary>
/// Logs a command message.
/// </summary>
/// <param name="message">Message to log.</param>
internal void LogMessage(string message)
{
#if !CORECLR // TODO:CORECLR Uncomment when we add PSEtwLog support
List<string> details = new List<string>();
details.Add(message);
PSEtwLog.LogPipelineExecutionDetailEvent(MshLog.GetLogContext(Context, Context.CurrentCommandProcessor.Command.MyInvocation), details);
#endif
}
#endregion
#region Exception processing
/// <summary>
/// Processes an exception for help cmdlets.
/// </summary>
/// <param name="moduleName">Module name.</param>
/// <param name="culture">Culture info.</param>
/// <param name="e">Exception to check.</param>
internal void ProcessException(string moduleName, string culture, Exception e)
{
UpdatableHelpSystemException except = null;
if (e is UpdatableHelpSystemException)
{
except = (UpdatableHelpSystemException)e;
}
#if !CORECLR
else if (e is WebException)
{
except = new UpdatableHelpSystemException("UnableToConnect",
StringUtil.Format(HelpDisplayStrings.UnableToConnect), ErrorCategory.InvalidOperation, null, e);
}
#endif
else if (e is PSArgumentException)
{
except = new UpdatableHelpSystemException("InvalidArgument",
e.Message, ErrorCategory.InvalidArgument, null, e);
}
else
{
except = new UpdatableHelpSystemException("UnknownErrorId",
e.Message, ErrorCategory.InvalidOperation, null, e);
}
if (!_exceptions.ContainsKey(except.FullyQualifiedErrorId))
{
_exceptions.Add(except.FullyQualifiedErrorId, new UpdatableHelpExceptionContext(except));
}
_exceptions[except.FullyQualifiedErrorId].Modules.Add(moduleName);
if (culture != null)
{
_exceptions[except.FullyQualifiedErrorId].Cultures.Add(culture);
}
}
#endregion
}
/// <summary>
/// Scope to which the help should be saved.
/// </summary>
public enum UpdateHelpScope
{
/// <summary>
/// Save the help content to the user directory.
CurrentUser,
/// <summary>
/// Save the help content to the module directory. This is the default behavior.
/// </summary>
AllUsers
}
}
| |
// <copyright file="VectorTests.Arithmetic.cs" company="Math.NET">
// Math.NET Numerics, part of the Math.NET Project
// http://numerics.mathdotnet.com
// http://github.com/mathnet/mathnet-numerics
// http://mathnetnumerics.codeplex.com
// Copyright (c) 2009-2010 Math.NET
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
// </copyright>
using MathNet.Numerics.LinearAlgebra;
using NUnit.Framework;
using System;
namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Single
{
/// <summary>
/// Abstract class with the common arithmetic set of vector tests.
/// </summary>
public abstract partial class VectorTests
{
/// <summary>
/// Can call unary "+" operator.
/// </summary>
[Test]
public void CanCallUnaryPlusOperator()
{
var vector = CreateVector(Data);
var other = +vector;
CollectionAssert.AreEqual(vector, other);
}
/// <summary>
/// Can add a scalar to a vector.
/// </summary>
[Test]
public void CanAddScalarToVector()
{
var copy = CreateVector(Data);
var vector = copy.Add(2.0f);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] + 2.0f, vector[i]);
}
vector.Add(0.0f);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] + 2.0f, vector[i]);
}
}
/// <summary>
/// Can add a scalar to a vector using result vector.
/// </summary>
[Test]
public void CanAddScalarToVectorIntoResultVector()
{
var vector = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Add(2.0f, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] + 2.0f, result[i]);
}
vector.Add(0.0f, result);
CollectionAssert.AreEqual(Data, result);
}
/// <summary>
/// Adding scalar to a vector using result vector with wrong size throws an exception.
/// </summary>
[Test]
public void AddingScalarWithWrongSizeResultVectorThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var result = CreateVector(Data.Length + 1);
Assert.That(() => vector.Add(0.0f, result), Throws.ArgumentException);
}
/// <summary>
/// Adding two vectors of different size throws an exception.
/// </summary>
[Test]
public void AddingTwoVectorsOfDifferentSizeThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var other = CreateVector(Data.Length + 1);
Assert.That(() => vector.Add(other), Throws.ArgumentException);
}
/// <summary>
/// Adding two vectors when a result vector is different size throws an exception.
/// </summary>
[Test]
public void AddingTwoVectorsAndResultIsDifferentSizeThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var other = CreateVector(Data.Length);
var result = CreateVector(Data.Length + 1);
Assert.That(() => vector.Add(other, result), Throws.ArgumentException);
}
/// <summary>
/// Addition operator throws <c>ArgumentException</c> if vectors are different size.
/// </summary>
[Test]
public void AdditionOperatorIfVectorsAreDifferentSizeThrowsArgumentException()
{
var a = CreateVector(Data.Length);
var b = CreateVector(Data.Length + 1);
Assert.That(() => a += b, Throws.ArgumentException);
}
/// <summary>
/// Can add two vectors.
/// </summary>
[Test]
public void CanAddTwoVectors()
{
var copy = CreateVector(Data);
var other = CreateVector(Data);
var vector = copy.Add(other);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0f, vector[i]);
}
}
/// <summary>
/// Can add two vectors using a result vector.
/// </summary>
[Test]
public void CanAddTwoVectorsIntoResultVector()
{
var vector = CreateVector(Data);
var other = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Add(other, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0f, result[i]);
}
}
/// <summary>
/// Can add two vectors using "+" operator.
/// </summary>
[Test]
public void CanAddTwoVectorsUsingOperator()
{
var vector = CreateVector(Data);
var other = CreateVector(Data);
var result = vector + other;
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0f, result[i]);
}
}
/// <summary>
/// Can add a vector to itself.
/// </summary>
[Test]
public void CanAddVectorToItself()
{
var copy = CreateVector(Data);
var vector = copy.Add(copy);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0f, vector[i]);
}
}
/// <summary>
/// Can add a vector to itself using a result vector.
/// </summary>
[Test]
public void CanAddVectorToItselfIntoResultVector()
{
var vector = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Add(vector, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0f, result[i]);
}
}
/// <summary>
/// Can add a vector to itself as result vector.
/// </summary>
[Test]
public void CanAddTwoVectorsUsingItselfAsResultVector()
{
var vector = CreateVector(Data);
var other = CreateVector(Data);
vector.Add(other, vector);
CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0f, vector[i]);
}
}
/// <summary>
/// Can negate a vector.
/// </summary>
[Test]
public void CanCallNegate()
{
var vector = CreateVector(Data);
var other = vector.Negate();
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(-Data[i], other[i]);
}
}
/// <summary>
/// Can call unary negation operator.
/// </summary>
[Test]
public void CanCallUnaryNegationOperator()
{
var vector = CreateVector(Data);
var other = -vector;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(-Data[i], other[i]);
}
}
/// <summary>
/// Can subtract a scalar from a vector.
/// </summary>
[Test]
public void CanSubtractScalarFromVector()
{
var copy = CreateVector(Data);
var vector = copy.Subtract(2.0f);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] - 2.0f, vector[i]);
}
vector.Subtract(0.0f);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] - 2.0f, vector[i]);
}
}
/// <summary>
/// Can subtract a scalar from a vector using a result vector.
/// </summary>
[Test]
public void CanSubtractScalarFromVectorIntoResultVector()
{
var vector = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Subtract(2.0f, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i], vector[i], "Making sure the original vector wasn't modified.");
Assert.AreEqual(Data[i] - 2.0f, result[i]);
}
vector.Subtract(0.0f, result);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i], result[i]);
}
}
/// <summary>
/// Subtracting a scalar with wrong size result vector throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SubtractingScalarWithWrongSizeResultVectorThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var result = CreateVector(Data.Length + 1);
Assert.That(() => vector.Subtract(0.0f, result), Throws.ArgumentException);
}
/// <summary>
/// Subtracting two vectors of differing size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SubtractingTwoVectorsOfDifferingSizeThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var other = CreateVector(Data.Length + 1);
Assert.That(() => vector.Subtract(other), Throws.ArgumentException);
}
/// <summary>
/// Subtracting two vectors when a result vector is different size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void SubtractingTwoVectorsAndResultIsDifferentSizeThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var other = CreateVector(Data.Length);
var result = CreateVector(Data.Length + 1);
Assert.That(() => vector.Subtract(other, result), Throws.ArgumentException);
}
/// <summary>
/// Subtraction operator throws <c>ArgumentException</c> if vectors are different size.
/// </summary>
[Test]
public void SubtractionOperatorIfVectorsAreDifferentSizeThrowsArgumentException()
{
var a = CreateVector(Data.Length);
var b = CreateVector(Data.Length + 1);
Assert.That(() => a -= b, Throws.ArgumentException);
}
/// <summary>
/// Can subtract two vectors.
/// </summary>
[Test]
public void CanSubtractTwoVectors()
{
var copy = CreateVector(Data);
var other = CreateVector(Data);
var vector = copy.Subtract(other);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(0.0f, vector[i]);
}
}
/// <summary>
/// Can subtract two vectors using a result vector.
/// </summary>
[Test]
public void CanSubtractTwoVectorsIntoResultVector()
{
var vector = CreateVector(Data);
var other = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Subtract(other, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(0.0f, result[i]);
}
}
/// <summary>
/// Can subtract two vectors using "-" operator.
/// </summary>
[Test]
public void CanSubtractTwoVectorsUsingOperator()
{
var vector = CreateVector(Data);
var other = CreateVector(Data);
var result = vector - other;
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(0.0f, result[i]);
}
}
/// <summary>
/// Can subtract a vector from itself.
/// </summary>
[Test]
public void CanSubtractVectorFromItself()
{
var copy = CreateVector(Data);
var vector = copy.Subtract(copy);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(0.0f, vector[i]);
}
}
/// <summary>
/// Can subtract a vector from itself using a result vector.
/// </summary>
[Test]
public void CanSubtractVectorFromItselfIntoResultVector()
{
var vector = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Subtract(vector, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(0.0f, result[i]);
}
}
/// <summary>
/// Can subtract two vectors using itself as result vector.
/// </summary>
[Test]
public void CanSubtractTwoVectorsUsingItselfAsResultVector()
{
var vector = CreateVector(Data);
var other = CreateVector(Data);
vector.Subtract(other, vector);
CollectionAssert.AreEqual(Data, other, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(0.0f, vector[i]);
}
}
/// <summary>
/// Can divide a vector by a scalar.
/// </summary>
[Test]
public void CanDivideVectorByScalar()
{
var copy = CreateVector(Data);
var vector = copy.Divide(2.0f);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] / 2.0f, vector[i]);
}
vector.Divide(1.0f);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] / 2.0f, vector[i]);
}
}
/// <summary>
/// Can divide a vector by a scalar using a result vector.
/// </summary>
[Test]
public void CanDivideVectorByScalarIntoResultVector()
{
var vector = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Divide(2.0f, result);
CollectionAssert.AreEqual(Data, vector, "Making sure the original vector wasn't modified.");
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] / 2.0f, result[i]);
}
vector.Divide(1.0f, result);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i], result[i]);
}
}
/// <summary>
/// Can multiply a vector by a scalar.
/// </summary>
[Test]
public void CanMultiplyVectorByScalar()
{
var copy = CreateVector(Data);
var vector = copy.Multiply(2.0f);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0f, vector[i]);
}
vector.Multiply(1.0f);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0f, vector[i]);
}
}
/// <summary>
/// Can multiply a vector by a scalar using a result vector.
/// </summary>
[Test]
public void CanMultiplyVectorByScalarIntoResultVector()
{
var vector = CreateVector(Data);
var result = CreateVector(Data.Length);
vector.Multiply(2.0f, result);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i], vector[i], "Making sure the original vector wasn't modified.");
Assert.AreEqual(Data[i] * 2.0f, result[i]);
}
vector.Multiply(1.0f, result);
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i], result[i]);
}
}
/// <summary>
/// Multiplying by scalar with wrong result vector size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void MultiplyingScalarWithWrongSizeResultVectorThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var result = CreateVector(Data.Length + 1);
Assert.That(() => vector.Multiply(0.0f, result), Throws.ArgumentException);
}
/// <summary>
/// Dividing by scalar with wrong result vector size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void DividingScalarWithWrongSizeResultVectorThrowsArgumentException()
{
var vector = CreateVector(Data.Length);
var result = CreateVector(Data.Length + 1);
Assert.That(() => vector.Divide(0.0f, result), Throws.ArgumentException);
}
/// <summary>
/// Can multiply a vector by scalar using operators.
/// </summary>
[Test]
public void CanMultiplyVectorByScalarUsingOperators()
{
var vector = CreateVector(Data);
vector = vector * 2.0f;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0f, vector[i]);
}
vector = vector * 1.0f;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0f, vector[i]);
}
vector = CreateVector(Data);
vector = 2.0f * vector;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0f, vector[i]);
}
vector = 1.0f * vector;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] * 2.0f, vector[i]);
}
}
/// <summary>
/// Can divide a vector by scalar using operators.
/// </summary>
[Test]
public void CanDivideVectorByScalarUsingOperators()
{
var vector = CreateVector(Data);
vector = vector / 2.0f;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] / 2.0f, vector[i]);
}
vector = vector / 1.0f;
for (var i = 0; i < Data.Length; i++)
{
Assert.AreEqual(Data[i] / 2.0f, vector[i]);
}
}
/// <summary>
/// Can calculate the dot product
/// </summary>
[Test]
public void CanDotProduct()
{
var dataA = CreateVector(Data);
var dataB = CreateVector(Data);
Assert.AreEqual(55.0f, dataA.DotProduct(dataB));
}
/// <summary>
/// Dot product throws <c>ArgumentException</c> when an argument has different size
/// </summary>
[Test]
public void DotProductWhenDifferentSizeThrowsArgumentException()
{
var dataA = CreateVector(Data);
var dataB = CreateVector(new float[] { 1, 2, 3, 4, 5, 6 });
Assert.That(() => dataA.DotProduct(dataB), Throws.ArgumentException);
}
/// <summary>
/// Can calculate the dot product using "*" operator.
/// </summary>
[Test]
public void CanDotProductUsingOperator()
{
var dataA = CreateVector(Data);
var dataB = CreateVector(Data);
Assert.AreEqual(55.0f, dataA * dataB);
}
/// <summary>
/// Operator "*" throws <c>ArgumentException</c> when the argument has different size.
/// </summary>
[Test]
public void OperatorDotProductWhenDifferentSizeThrowsArgumentException()
{
var dataA = CreateVector(Data);
var dataB = CreateVector(new float[] { 1, 2, 3, 4, 5, 6 });
Assert.Throws<ArgumentException>(() => { var d = dataA * dataB; });
}
/// <summary>
/// Can pointwise multiply two vectors.
/// </summary>
[Test]
public void CanPointwiseMultiply()
{
var vector1 = CreateVector(Data);
var vector2 = vector1.Clone();
var result = vector1.PointwiseMultiply(vector2);
for (var i = 0; i < vector1.Count; i++)
{
Assert.AreEqual(Data[i] * Data[i], result[i]);
}
}
/// <summary>
/// Can pointwise multiply two vectors using a result vector.
/// </summary>
[Test]
public void CanPointwiseMultiplyIntoResultVector()
{
var vector1 = CreateVector(Data);
var vector2 = vector1.Clone();
var result = CreateVector(vector1.Count);
vector1.PointwiseMultiply(vector2, result);
for (var i = 0; i < vector1.Count; i++)
{
Assert.AreEqual(Data[i] * Data[i], result[i]);
}
}
/// <summary>
/// Pointwise multiply with a result vector wrong size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void PointwiseMultiplyWithInvalidResultLengthThrowsArgumentException()
{
var vector1 = CreateVector(Data);
var vector2 = vector1.Clone();
var result = CreateVector(vector1.Count + 1);
Assert.That(() => vector1.PointwiseMultiply(vector2, result), Throws.ArgumentException);
}
/// <summary>
/// Can pointwise divide two vectors using a result vector.
/// </summary>
[Test]
public void CanPointWiseDivide()
{
var vector1 = CreateVector(Data);
var vector2 = vector1.Clone();
var result = vector1.PointwiseDivide(vector2);
for (var i = 0; i < vector1.Count; i++)
{
Assert.AreEqual(Data[i] / Data[i], result[i]);
}
}
/// <summary>
/// Can pointwise divide two vectors using a result vector.
/// </summary>
[Test]
public void CanPointWiseDivideIntoResultVector()
{
var vector1 = CreateVector(Data);
var vector2 = vector1.Clone();
var result = CreateVector(vector1.Count);
vector1.PointwiseDivide(vector2, result);
for (var i = 0; i < vector1.Count; i++)
{
Assert.AreEqual(Data[i] / Data[i], result[i]);
}
}
/// <summary>
/// Pointwise divide with a result vector wrong size throws <c>ArgumentException</c>.
/// </summary>
[Test]
public void PointwiseDivideWithInvalidResultLengthThrowsArgumentException()
{
var vector1 = CreateVector(Data);
var vector2 = vector1.Clone();
var result = CreateVector(vector1.Count + 1);
Assert.That(() => vector1.PointwiseDivide(vector2, result), Throws.ArgumentException);
}
/// <summary>
/// Can calculate the outer product of two vectors.
/// </summary>
[Test]
public void CanCalculateOuterProduct()
{
var vector1 = CreateVector(Data);
var vector2 = CreateVector(Data);
var m = Vector<float>.OuterProduct(vector1, vector2);
for (var i = 0; i < vector1.Count; i++)
{
for (var j = 0; j < vector2.Count; j++)
{
Assert.AreEqual(m[i, j], vector1[i] * vector2[j]);
}
}
}
/// <summary>
/// Can calculate the tensor multiply.
/// </summary>
[Test]
public void CanCalculateTensorMultiply()
{
var vector1 = CreateVector(Data);
var vector2 = CreateVector(Data);
var m = vector1.OuterProduct(vector2);
for (var i = 0; i < vector1.Count; i++)
{
for (var j = 0; j < vector2.Count; j++)
{
Assert.AreEqual(m[i, j], vector1[i] * vector2[j]);
}
}
}
[Test]
public void CanComputeRemainderUsingOperator()
{
var vector = CreateVector(Data);
var mod = vector % (-4.5f);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Remainder(Data[index], -4.5f), mod[index], 14);
}
}
[Test]
public void CanComputeRemainder()
{
var vector = CreateVector(Data);
var mod = vector.Remainder(-3.2f);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Remainder(Data[index], -3.2f), mod[index], 14);
}
}
[Test]
public void CanComputeRemainderUsingResultVector()
{
var vector = CreateVector(Data);
var mod = CreateVector(vector.Count);
vector.Remainder(-3.2f, mod);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Remainder(Data[index], -3.2f), mod[index], 14);
}
}
[Test]
public void CanComputeRemainderUsingSameResultVector()
{
var vector = CreateVector(Data);
vector.Remainder(-3.2f, vector);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Remainder(Data[index], -3.2f), vector[index], 14);
}
}
[Test]
public void CanComputeModulus()
{
var vector = CreateVector(Data);
var mod = vector.Modulus(-3.2f);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Modulus(Data[index], -3.2f), mod[index], 14);
}
}
[Test]
public void CanComputeModulusUsingResultVector()
{
var vector = CreateVector(Data);
var mod = CreateVector(vector.Count);
vector.Modulus(-3.2f, mod);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Modulus(Data[index], -3.2f), mod[index], 14);
}
}
[Test]
public void CanComputeModulusUsingSameResultVector()
{
var vector = CreateVector(Data);
vector.Modulus(-3.2f, vector);
for (var index = 0; index < Data.Length; index++)
{
AssertHelpers.AlmostEqualRelative(Euclid.Modulus(Data[index], -3.2f), vector[index], 14);
}
}
}
}
| |
////////////////////////////////////////////////////////////////////////////////
// //
// MIT X11 license, Copyright (c) 2005-2006 by: //
// //
// Authors: //
// Michael Dominic K. <michaldominik@gmail.com> //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included //
// in all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS //
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN //
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, //
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR //
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE //
// USE OR OTHER DEALINGS IN THE SOFTWARE. //
// //
////////////////////////////////////////////////////////////////////////////////
namespace Diva.Core {
using System;
using Gtk;
using Mono.Unix;
using Util;
using System.IO;
public class ExceptionalDialog : Gtk.Dialog {
// Translatable ////////////////////////////////////////////////
readonly static string titleSS = Catalog.GetString
("Fatal error");
readonly static string messageHeaderSS = Catalog.GetString
("Whoops...");
readonly static string messageBodySS = Catalog.GetString
("An unexpected, fatal error occured. " +
"Details about the failure were outputed to the error console. " +
"You might optionally save the crash log to a file and attach it to a bug report. " +
"\n\n" +
"The application is now most likely in an unstable state. " +
"You should save your work as soon as possible");
readonly static string detailsSS = Catalog.GetString
("Error details");
readonly static string saveLogSS = Catalog.GetString
("Save log");
// Fields //////////////////////////////////////////////////////
Exception exception; // The exception that triggered the error
static Gdk.Pixbuf grinPixbuf = null; // The pixbuf we display as a consolation
// Public methods //////////////////////////////////////////////
/* CONSTRUCTOR */
public ExceptionalDialog (Exception exception, Gtk.Window parent) : base (titleSS, parent, DialogFlags.Modal)
{
this.exception = exception;
BuildGUI ();
try {
WriteLog (Console.Error);
} catch {
}
}
// Static methods //////////////////////////////////////////////
// FIXME: This should be kind of conditional to some compile-time define
public static void Grab (Exception exception, Widget source)
{
Gtk.Window parent = GtkFu.GetParentForWidget (source);
ExceptionalDialog dialog = new ExceptionalDialog (exception, parent);
dialog.Run ();
dialog.Destroy ();
}
// Private methods ////////////////////////////////////////////
public void OnSaveLogClicked (object o, EventArgs args)
{
FileChooserDialog dialog = new FileChooserDialog
(saveLogSS, this, FileChooserAction.Save,
Stock.Cancel, ResponseType.Cancel,
Stock.Save, ResponseType.Accept);
dialog.SelectMultiple = false;
dialog.CurrentName = "crash.log";
dialog.DefaultResponse = ResponseType.Accept;
if (dialog.Run () == (int) ResponseType.Accept) {
// Save it
StreamWriter writer = null;
try {
writer = new StreamWriter (dialog.Filename, false);
WriteLog (writer);
} catch {
} finally {
if (writer != null)
writer.Close ();
}
}
dialog.Destroy ();
}
void BuildGUI ()
{
HasSeparator = false;
Resizable = false;
// Containers
HBox mainHBox = new HBox (false, 12);
VBox rightVBox = new VBox (false, 6);
VBox leftVBox = new VBox (false, 6);
// Devil pic
if (grinPixbuf == null)
grinPixbuf = new Gdk.Pixbuf (null, "bug.png");
Image grinImage = new Image (grinPixbuf);
// Label
Label messageLabel = new Label (String.Format ("<big><b>{0}</b></big>\n\n{1}",
messageHeaderSS, messageBodySS));
messageLabel.UseMarkup = true;
messageLabel.Wrap = true;
messageLabel.LineWrap = true;
messageLabel.Selectable = true;
// Error expander
Expander errorExpander = new Expander (String.Format ("<b>{0}</b>", detailsSS));
errorExpander.UseMarkup = true;
Label errorLabel = new Label (GenerateExcpString ());
errorLabel.Xalign = 0.0f;
errorLabel.Wrap = true;
errorLabel.LineWrap = true;
errorExpander.Child = errorLabel;
// Buttons
Button saveLogButton = new Button (saveLogSS);
saveLogButton.Clicked += OnSaveLogClicked;
ActionArea.Add (saveLogButton);
AddButton (Stock.Ok, ResponseType.Ok);
// Pack it all
leftVBox.PackStart (grinImage, false, false, 0);
rightVBox.PackStart (messageLabel, true, true, 0);
rightVBox.PackEnd (errorExpander, false, false, 0);
mainHBox.PackStart (leftVBox, false, false, 0);
mainHBox.PackEnd (rightVBox, true, true, 0);
VBox.PackStart (mainHBox, false, false, 6);
VBox.Spacing = 12;
VBox.ShowAll ();
}
/* Output a nicely formatted message log to the given writer.
* We try to be as safe as possible here */
void WriteLog (TextWriter writer)
{
writer.WriteLine (StringFu.CenteredLine ("CRASH LOG", '=', 78));
// Application version
string version = String.Empty;
try {
version = VersionFu.GetCallingVersion ();
} catch {
version = "<exception>";
} finally {
writer.WriteLine (StringFu.ReportLine ("Diva:", version, '.', 78));
}
// Runtime version
string runtimeVersion = String.Empty;
try {
runtimeVersion = Environment.Version.ToString ();
} catch {
runtimeVersion = "<exception>";
} finally {
writer.WriteLine (StringFu.ReportLine ("Runtime:", runtimeVersion, '.', 78));
}
// GStreamer version
string gstVersion = String.Empty;
try {
gstVersion = Gdv.Application.GStreamerVersion;
} catch {
gstVersion = "<exception>";
} finally {
writer.WriteLine (StringFu.ReportLine ("GStreamer:", gstVersion, '.', 78));
}
// OS
string osVersion = String.Empty;
try {
osVersion = Environment.OSVersion.ToString ();
} catch {
osVersion = "<exception>";
} finally {
writer.WriteLine (StringFu.ReportLine ("OS:", osVersion, '.', 78));
}
try {
Exception excp = exception;
while (excp != null) {
string header = String.Format ("\n [{0} {1}]", excp.GetType (), excp.Message);
writer.WriteLine (StringFu.Wrap (header, 78, 78));
string[] stack = excp.StackTrace.Split ('\n');
foreach (string stackString in stack)
writer.WriteLine ("* {0}", StringFu.Wrap (stackString, 76, 78));
excp = excp.InnerException;
}
} catch {
}
// Final line
writer.WriteLine (StringFu.CenteredLine ("END", '=', 78));
}
string GenerateExcpString ()
{
string created = String.Empty;
Exception excp = exception;
while (excp != null) {
created = created + String.Format ("{0} ({1})", excp.GetType (), excp.Message);
excp = excp.InnerException;
}
return created;
}
}
}
| |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
using OpenLiveWriter.Api;
using OpenLiveWriter.BlogClient;
using OpenLiveWriter.BlogClient.Providers;
using OpenLiveWriter.CoreServices.Diagnostics;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.Localization;
using OpenLiveWriter.PostEditor.ContentSources;
using OpenLiveWriter.PostEditor.OpenPost;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.PostEditor.PostHtmlEditing;
using OpenLiveWriter.PostEditor.PostHtmlEditing.Sidebar;
using System.Net;
namespace OpenLiveWriter.PostEditor
{
public interface IBlogPostEditingManager
{
void SwitchBlog(string blogId);
string CurrentBlog();
}
public class BlogPostEditingManager : IBlogPostEditingContext, IBlogPostPublishingContext, IDisposable, IBlogPostEditingManager
{
#region Initialization and Disposal
public BlogPostEditingManager(IBlogPostEditingSite editingSite, IBlogPostEditor[] postEditors, IPublishingContext publishingContext)
{
// save reference to owner
_mainFrameWindow = editingSite.FrameWindow;
_publishingContext = publishingContext;
// subscribe to weblog settings edited
_editingSite = editingSite;
_editingSite.GlobalWeblogSettingsChanged += new WeblogSettingsChangedHandler(editingSite_GlobalWeblogSettingsEdited);
// initialize post editors
_postEditors.Add(_forceDirtyPostEditor);
_postEditors.AddRange(postEditors);
}
public void Dispose()
{
if (_editingSite != null)
{
_editingSite.GlobalWeblogSettingsChanged -= new WeblogSettingsChangedHandler(editingSite_GlobalWeblogSettingsEdited);
_editingSite = null;
}
// dispose weblog
DisposeCurrentBlog();
ResetAutoSave();
GC.SuppressFinalize(this);
}
~BlogPostEditingManager()
{
Trace.Fail("Did not dispose BlogPostEditingManager!");
}
#endregion
#region Explicit Implementation of IBlogPostEditingContext
BlogPost IBlogPostEditingContext.BlogPost
{
get { return BlogPost; }
}
BlogPostSupportingFileStorage IBlogPostEditingContext.SupportingFileStorage
{
get
{
return SupportingFileStorage;
}
}
string IBlogPostEditingContext.ServerSupportingFileDirectory
{
get
{
return ServerSupportingFileDirectory;
}
}
BlogPostImageDataList IBlogPostEditingContext.ImageDataList
{
get
{
return ImageDataList;
}
}
BlogPostExtensionDataList IBlogPostEditingContext.ExtensionDataList
{
get
{
return ExtensionDataList;
}
}
ISupportingFileService IBlogPostEditingContext.SupportingFileService
{
get { return SupportingFileService; }
}
PostEditorFile IBlogPostEditingContext.LocalFile
{
get
{
return LocalFile;
}
}
#endregion
#region Explicit Implementation of IBlogPostPublishingContext
IBlogPostEditingContext IBlogPostPublishingContext.EditingContext
{
get { return this; }
}
BlogPost IBlogPostPublishingContext.GetBlogPostForPublishing()
{
BlogPost publishingPost = BlogPost.Clone() as BlogPost;
// trim leading and trailing whitespace from the post
string contents = publishingPost.Contents;
if (contents != String.Empty)
{
try
{
publishingPost.Contents = HTMLTrimmer.Trim(contents);
// remove \r\n sequences inserted when we called StringToHTMLDoc
// publishingPost.Contents = HtmlLinebreakStripper.RemoveLinebreaks(contents);
}
catch (Exception e)
{
Trace.Fail("Exception while trimming whitespace from post: " + e.ToString());
}
}
return publishingPost;
}
void IBlogPostPublishingContext.SetPublishingPostResult(BlogPostPublishingResult publishingResult)
{
// save reference to post result
_lastPublishingResult = publishingResult;
// update the blog post
BlogPost.Id = publishingResult.PostResult.PostId;
BlogPost.DatePublished = publishingResult.PostResult.DatePublished;
BlogPost.ETag = publishingResult.PostResult.ETag;
BlogPost.AtomRemotePost = publishingResult.PostResult.AtomRemotePost;
if (publishingResult.PostPermalink != null)
BlogPost.Permalink = publishingResult.PostPermalink;
if (publishingResult.Slug != null)
BlogPost.Slug = publishingResult.Slug;
BlogPost.ContentsVersionSignature = publishingResult.PostContentHash;
BlogPost.CommitPingUrls();
}
private BlogPostPublishingResult _lastPublishingResult = new BlogPostPublishingResult();
void INewCategoryContext.NewCategoryAdded(BlogPostCategory category)
{
// commit new category to blog post
BlogPost.CommitNewCategory(category);
// see if any of our blog post editors are new category contexts, if so
// then notify them of the new category being added. Note that this
// callback occurs during publishing so we don't want UI-layer errors
// to halt publishing -- catch and log them instead.
try
{
foreach (IBlogPostEditor postEditor in _postEditors)
if (postEditor is INewCategoryContext)
(postEditor as INewCategoryContext).NewCategoryAdded(category);
}
catch (Exception ex)
{
Trace.Fail("Unexpected exception during call to NewCategoryAdded: " + ex.ToString());
}
}
#endregion
public string CurrentBlog()
{
if (_blog != null)
{
return _blog.Id;
}
else
{
return null;
}
}
#region Public Interface: Current Blog
public string BlogId
{
get { return Blog.Id; }
}
public string BlogName
{
get { return Blog.Name; }
}
public Image BlogImage
{
get { return Blog.Image; }
}
public Icon BlogIcon
{
get { return Blog.Icon; }
}
public string BlogHomepageUrl
{
get { return Blog.HomepageUrl; }
}
public string BlogAdminUrl
{
get { return Blog.AdminUrl; }
}
public string BlogServiceName
{
get { return Blog.ServiceName; }
}
public string BlogServiceDisplayName
{
get { return Blog.ServiceDisplayName; }
}
public bool BlogIsAutoUpdatable
{
get
{
return PostEditorSettings.AllowSettingsAutoUpdate && Blog.ClientOptions.SupportsAutoUpdate;
}
}
public bool BlogRequiresTitles
{
get
{
return !Blog.ClientOptions.SupportsEmptyTitles;
}
}
public void SwitchBlog(string blogId)
{
Trace.Assert(_blog != null, "Can only call SwitchBlog after initialization!");
// only execute if we are truely switching blogs
if (Blog != null && blogId != Blog.Id)
{
// set current blog
SetCurrentBlog(blogId);
// reset post to new
_blogPost.ResetPostForNewBlog(Blog.ClientOptions);
// if we are stored in RecentPosts then sever this link
if (LocalFile.IsRecentPost)
LocalFile = PostEditorFile.CreateNew(PostEditorFile.DraftsFolder);
// notification that the weblog changed
OnBlogChanged();
}
}
public bool VerifyBlogCredentials()
{
return Blog.VerifyCredentials();
}
public void DisplayBlogClientOptions()
{
BlogClientOptions.ShowInNotepad(Blog.ClientOptions);
}
public event EventHandler BlogChanged;
public event WeblogSettingsChangedHandler BlogSettingsChanged;
#endregion
#region Public Interface: Current Post Properties
public bool PostIsDirty
{
get
{
// see if a post-editor is dirty
foreach (IBlogPostEditor postEditor in _postEditors)
{
if (postEditor.IsDirty)
{
if (ApplicationDiagnostics.AutomationMode || ApplicationDiagnostics.TestMode)
{
Trace.WriteLine(String.Format(CultureInfo.InvariantCulture, "IBlogPostEditor Dirty {0}", postEditor));
}
return true;
}
}
// none dirty, return false
return false;
}
}
/// <summary>
/// Doesn't indicate that the latest changes have been
/// saved, only that a file is on disk for this post.
/// </summary>
public bool PostIsSaved
{
get
{
return LocalFile.IsSaved;
}
}
public bool PostIsDraft
{
get
{
return LocalFile.IsDraft;
}
}
public bool EditingPage
{
get
{
return BlogPost.IsPage;
}
}
public DateTime? PostDateSaved
{
get
{
return LocalFile.DateSaved;
}
}
public DateTime PostDatePublished
{
get { return BlogPost.DatePublished; }
}
public string BlogPostId
{
get { return BlogPost.Id; }
}
public string GetPostSpellingContextDirectory()
{
return SupportingFileStorage.SpellingContextDirectory;
}
public event EventHandler EditingStatusChanged;
#endregion
#region Public Interface: Post Operations (New, Open, Edit, Save, Publish, View etc.)
public void NewPost()
{
// do the edit
DispatchEditPost(new BlogPost());
}
public void NewPage()
{
// new blog post
BlogPost blogPost = new BlogPost();
// add page support
if (Blog.ClientOptions.SupportsPages)
blogPost.IsPage = true;
else
Trace.Fail("Attempted to create a Page for a Weblog that does not support pages!");
// edit the post
DispatchEditPost(blogPost);
}
public void OpenPost(OpenPostForm.OpenMode openMode)
{
using (new WaitCursor())
{
using (OpenPostForm openPostForm = new OpenPostForm(openMode))
{
openPostForm.UserDeletedPost += new UserDeletedPostEventHandler(openPostForm_UserDeletedPost);
if (openPostForm.ShowDialog(_mainFrameWindow) == DialogResult.OK)
{
// get the editing context
OpenPost(openPostForm.BlogPostEditingContext);
}
openPostForm.UserDeletedPost -= new UserDeletedPostEventHandler(openPostForm_UserDeletedPost);
}
}
}
public void OpenLocalPost(PostInfo postInfo)
{
using (new WaitCursor())
{
// get file path
string postFilePath = postInfo.Id;
// screen non-existent files
if (!File.Exists(postFilePath))
{
DisplayMessage.Show(MessageId.PostFileNoExist, _mainFrameWindow, postInfo.Title);
}
// screen invalid files
else if (!PostEditorFile.IsValid(postInfo.Id))
{
DisplayMessage.Show(MessageId.PostFileInvalid, _mainFrameWindow, postInfo.Title);
}
else
{
PostEditorFile postEditorFile = PostEditorFile.GetExisting(new FileInfo(postInfo.Id));
IBlogPostEditingContext editingContext = postEditorFile.Load();
OpenPost(editingContext);
}
}
}
public void OpenPost(IBlogPostEditingContext editingContext)
{
using (new WaitCursor())
{
editingContext = RecentPostSynchronizer.Synchronize(_mainFrameWindow, editingContext);
DispatchEditPost(editingContext, false);
}
}
public void EditPost(IBlogPostEditingContext editingContext)
{
EditPost(editingContext, false);
}
public void EditPost(IBlogPostEditingContext editingContext, bool forceDirty)
{
// not yet initialized
_initialized = false;
// note start time of editing session
_editStartTime = DateTime.UtcNow;
// defend against invalid blog id
bool resetPostId = false;
string blogId = editingContext.BlogId;
if (!BlogSettings.BlogIdIsValid(blogId))
{
blogId = BlogSettings.DefaultBlogId;
resetPostId = true;
}
// initialize state
SetCurrentBlog(blogId);
BlogPost = editingContext.BlogPost;
LocalFile = editingContext.LocalFile;
_autoSaveLocalFile = editingContext.AutoSaveLocalFile;
if (_autoSaveLocalFile != null)
forceDirty = true;
ServerSupportingFileDirectory = editingContext.ServerSupportingFileDirectory;
SupportingFileStorage = editingContext.SupportingFileStorage;
ImageDataList = editingContext.ImageDataList;
ExtensionDataList = editingContext.ExtensionDataList;
SupportingFileService = editingContext.SupportingFileService;
// can now fire events
_initialized = true;
// Fix bug 574769: Post ID for a weblog sometimes gets carried over to another weblog so post-publishing fails.
if (resetPostId)
BlogPost.ResetPostForNewBlog(Blog.ClientOptions);
// only fire events after we are fully initialized (event handlers call back into
// this object and expect everything to be initialized)
OnBlogChanged();
OnBlogPostChanged();
OnEditingStatusChanged();
// force dirty if requested
if (forceDirty)
ForceDirty();
}
/// <summary>
/// Clear the currnet post (does not prompt to save changes)
/// </summary>
public void ClearPost()
{
EditPost(new BlogPostEditingContext(BlogId, new BlogPost()));
}
public bool SaveDraft()
{
try
{
return SaveToDrafts();
}
finally
{
// always note that the user tried to save
if (UserSavedPost != null)
UserSavedPost(this, EventArgs.Empty);
}
}
public bool ShouldAutoSave
{
get
{
// screen out invalid states (shouldn't need to do this but we
// are adding this feature late in the cycle and want to make
// sure there isn't anything we are missing)
if (BlogPost == null || LocalFile == null)
return false;
return PostEditorSettings.AutoSaveDrafts && PostIsDirty;
}
}
public bool AutoSaveIfRequired(bool forceSave)
{
if (ShouldAutoSave || forceSave)
{
AutoSave();
return true;
}
return false;
}
private DateTime AutoSaveStartTime
{
get
{
if (LocalFile.DateSaved == DateTime.MinValue)
return _editStartTime;
else
return LocalFile.DateSaved;
}
}
public void DeleteLocalPost(PostInfo postInfo)
{
// get the post file associated with this post
PostEditorFile postFile = PostEditorFile.GetExisting(new FileInfo(postInfo.Id));
// prompt the user to confirm deletion
string type = BlogPost.IsPage ? Res.Get(StringId.PageLower) : Res.Get(StringId.PostLower);
MessageId messageId = postFile.IsDraft ? MessageId.ConfirmDeleteDraft : MessageId.ConfirmDeletePost;
if (DisplayMessage.Show(messageId, _mainFrameWindow, type, postInfo.Title) == DialogResult.Yes)
{
// update main window to eliminate artifacts
_mainFrameWindow.Update();
// see if we are deleting the currently active file
bool deletingCurrentDraft = (postFile.Equals(LocalFile));
if (DeletePostFile(postFile))
{
// fire notification of the delete
if (UserDeletedPost != null)
UserDeletedPost(this, EventArgs.Empty);
// open a new untitled post if we just deleted the current draft
if (deletingCurrentDraft)
ClearPost();
}
}
}
public void DeleteCurrentDraft()
{
// check for valid/sane state
if (!PostIsDraft)
{
Trace.Fail("Attempted to delete a post that is not a draft!");
return;
}
// prompt the user to confirm deletion
string title = BlogPost.Title != String.Empty ? BlogPost.Title : BlogPost.IsPage ? PostInfo.UntitledPage : PostInfo.UntitledPost;
string type = BlogPost.IsPage ? Res.Get(StringId.PageLower) : Res.Get(StringId.PostLower);
if (DisplayMessage.Show(MessageId.ConfirmDeleteDraft, _mainFrameWindow, type, title) == DialogResult.Yes)
{
if (DeletePostFile(LocalFile))
{
// fire notification of the delete
if (UserDeletedPost != null)
UserDeletedPost(this, EventArgs.Empty);
// open a new untitled post
ClearPost();
}
}
}
public bool PublishAsDraft()
{
if (ValidatePublish())
return PostToWeblog(false);
else
return false;
}
public bool Publish()
{
if (ValidatePublish())
return PostToWeblog(true);
else
return false;
}
public void ViewPost()
{
if (BlogPost.IsPage && BlogPost.Permalink != String.Empty)
ShellHelper.LaunchUrl(BlogPost.Permalink);
else
ShellHelper.LaunchUrl(Blog.HomepageUrl);
}
public void EditPostOnline(bool clearPostWindow)
{
// calculate the url (no-op if there is no url)
string postEditingUrl = Blog.GetPostEditingUrl(BlogPost.Id);
if (!UrlHelper.IsUrl(postEditingUrl))
{
Trace.Fail("Invalid URL provided for online post editing: " + postEditingUrl);
return;
}
// clear the post editor if requested (ideally we would do this AFTER
// launching the browser but if we do then our window steals focus
// back from the browser)
if (clearPostWindow)
ClearPost();
// launch the editing url
ShellHelper.LaunchUrl(postEditingUrl);
}
#endregion
#region Public Interface: Events
public event EventHandler UserSavedPost;
public event EventHandler UserPublishedPost;
public event EventHandler UserDeletedPost;
#endregion
#region Private Helpers
private void DispatchEditPost(BlogPost blogPost)
{
DispatchEditPost(new BlogPostEditingContext(BlogId, blogPost), true);
}
/// <summary>
/// Dispatches an edit post request to either the current editor window
/// or to a new editor form depending upon the user's preferences and
/// the current editing state
/// </summary>
/// <param name="editingContext">editing conext</param>
private void DispatchEditPost(IBlogPostEditingContext editingContext, bool isNewPost)
{
// calcluate whether the user has a "blank" unsaved post
bool currentPostIsEmptyAndUnsaved =
((BlogPost != null) && BlogPost.IsNew && (BlogPost.Contents == null || BlogPost.Contents == String.Empty)) &&
!LocalFile.IsSaved && !PostIsDirty;
// edge case: current post is empty and unsaved and this is a new post,
// re-using the window in this case will just make the New button appear
// to not work at all, therefore we force a new window. We make an exception
// for creation of new pages, as firing up a new writer instance and then
// switching into "page authoring" mode is a natual thing to do (and shouldn't
// result in a new window for no apparent reason). In this case the user will
// get "feedback" by seeing the default title change to "Enter Page Title Here"
// as well as the contents of the property tray changing.
if (currentPostIsEmptyAndUnsaved && isNewPost && !editingContext.BlogPost.IsPage)
{
PostEditorForm.Launch(editingContext);
return;
}
// Notify all the editors that the post is about to close
// This will give them an chance to do any clean up, or in the
// case of video publish to hold up the close operation till videos
// have finished uploading.
CancelEventArgs e = new CancelEventArgs();
foreach (IBlogPostEditor editor in _postEditors)
{
editor.OnPostClosing(e);
if (e.Cancel)
break;
}
if (e.Cancel)
{
return;
}
switch (PostEditorSettings.PostWindowBehavior)
{
case PostWindowBehavior.UseSameWindow:
// allow the user a chance to save if necessary
if (PostIsDirty)
{
// cancel aborts the edit post operation
DialogResult saveChangesResult = PromptToSaveChanges();
if (saveChangesResult == DialogResult.Cancel)
{
return;
}
// special case -- we are actually re-editing the currently active post
// in this instance we need to "re-open" it to reflect the saved changes
else if (saveChangesResult == DialogResult.Yes && editingContext.LocalFile.Equals(LocalFile))
{
EditPostWithPostCloseEvent(LocalFile.Load());
break; ;
}
}
// edit the post using the existing window
EditPostWithPostCloseEvent(editingContext);
break;
case PostWindowBehavior.OpenNewWindow:
// special case: if the current frame contains an empty, unsaved
// post then replace it (covers the case of the user opening
// writer in order to edit an existing post -- in this case they
// should never have to deal with managing two windows
if (currentPostIsEmptyAndUnsaved)
{
EditPostWithPostCloseEvent(editingContext);
}
else
{
// otherwise open a new window
PostEditorForm.Launch(editingContext);
}
break;
case PostWindowBehavior.OpenNewWindowIfDirty:
if (PostIsDirty)
{
PostEditorForm.Launch(editingContext);
}
else
{
EditPostWithPostCloseEvent(editingContext);
}
break;
}
}
private void EditPostWithPostCloseEvent(IBlogPostEditingContext blogPostEditingContext)
{
// If the editor has already been initialized once, then we need to tell the editor it is getting its post closed.
if (_initialized)
{
foreach (IBlogPostEditor editor in _postEditors)
{
editor.OnPostClosed();
}
}
EditPost(blogPostEditingContext);
}
private DialogResult PromptToSaveChanges()
{
DialogResult result = DisplayMessage.Show(MessageId.QueryForUnsavedChanges, _mainFrameWindow);
if (result == DialogResult.Yes)
{
using (new WaitCursor())
SaveDraft();
}
return result;
}
private void AutoSave()
{
using (new QuickTimer("AutoSave"))
{
// save all pending edits to the post
BlogPostSaveOptions options = new BlogPostSaveOptions();
options.AutoSave = true;
SaveEditsToPost(true, options);
try
{
PostEditorFile fileToSave = AutoSaveLocalFile;
fileToSave.AutoSave(this, LocalFile);
}
catch (Exception ex)
{
Trace.Fail("AutoSave failed! " + ex.Message);
if (ApplicationDiagnostics.VerboseLogging)
{
Trace.WriteLine(ex.ToString());
}
}
}
}
private bool SaveToDrafts()
{
// save all pending edits to the post
SaveEditsToPost();
// save the post
try
{
// determine file to save (default to current one)
PostEditorFile fileToSave = LocalFile;
// if this is a Recent Post then don't actually save into Recent Posts since
// it has now changed and is a "Draft" pending re-publishing
if (fileToSave.IsRecentPost)
fileToSave = PostEditorFile.CreateNew(PostEditorFile.DraftsFolder);
// save the file and update the reference
fileToSave.SaveBlogPost((this as IBlogPostEditingContext));
LocalFile = fileToSave;
return true;
}
catch (Exception ex)
{
DisplayableExceptionDisplayForm.Show(_mainFrameWindow, ex);
ForceDirty();
return false;
}
}
private bool DeletePostFile(PostEditorFile postFile)
{
try
{
// screen files which have already been deleted through other means
if (!postFile.IsDeleted)
postFile.Delete();
return true;
}
catch (Exception ex)
{
DisplayableException displayableException = new DisplayableException(
StringId.ErrorOccurredDeletingDraft, StringId.ErrorOccurredDeletingDraftDetails, ex.Message);
DisplayableExceptionDisplayForm.Show(_mainFrameWindow, displayableException);
return false;
}
}
private void openPostForm_UserDeletedPost(PostInfo deletedPost)
{
// See if the file currently being edited was deleted. In this case
// clear out the post editor
if (LocalFile != null && LocalFile.IsDeleted)
ClearPost();
// Fire notification
if (UserDeletedPost != null)
UserDeletedPost(this, EventArgs.Empty);
}
private bool ValidatePublish()
{
if (this.Blog.IsSpacesBlog)
{
DisplayMessage.Show(MessageId.SpacesPublishingNotEnabled);
return false;
}
// check all of our post editors
foreach (IBlogPostEditor postEditor in _postEditors)
{
if (!postEditor.ValidatePublish())
return false;
}
// survived, ok to publish
return true;
}
public void Closing(CancelEventArgs e)
{
// Notify all the editors that the application is about to close
// This will give them an chance to do any clean up, or in the
// case of video publish to hold up the close operation till videos
// have finished uploading.
foreach (IBlogPostEditor postEditor in _postEditors)
{
postEditor.OnPostClosing(e);
if (e.Cancel)
return;
}
foreach (IBlogPostEditor postEditor in _postEditors)
{
postEditor.OnClosing(e);
if (e.Cancel)
return;
}
}
internal void OnClosed()
{
foreach (IBlogPostEditor postEditor in _postEditors)
{
postEditor.OnPostClosed();
postEditor.OnClosed();
}
}
private bool PostToWeblog(bool publish)
{
try
{
// save all pending edits
// we will preserve the dirty-ness of the post so in case if the publish
// failed or was cancelled, the post will remain dirty.
SaveEditsToPost(true, BlogPostSaveOptions.DefaultOptions);
// validate that we aren't attempting to post local files to a blog not configured to do so
if (!ValidateSupportingFileUsage())
return false;
// validate that we have the credentials required to publish
if (!VerifyBlogCredentials())
return false;
// try to update the weblog
bool isNewPost = BlogPost.IsNew;
if (UpdateWeblog(publish))
{
// save a copy to recent posts (note: we used to only save to recent
// posts only if a publish occurred, however we now do this always
// because we want the post to participate in syncing to online
// changes AND we don't want the post "trapped" in drafts if the
// user intends to edit and publish over the web.
// NOTE: if we want to make this behavior conditional then the logic is:
// if (published) SaveToRecentPosts(); else SaveToDrafts();
SaveToRecentPosts();
// notify editors that we successfully published
Debug.Assert(_lastPublishingResult.PostResult.PostId != String.Empty);
foreach (IBlogPostEditor postEditor in _postEditors)
postEditor.OnPublishSucceeded(BlogPost, _lastPublishingResult.PostResult);
// show file upload failed warning if necessary
DisplayAfterPublishFileUploadFailedWarningIfNecessary();
// success
return true;
}
else
{
return false;
}
}
finally
{
// always note that the user tried to publish
if (UserPublishedPost != null)
UserPublishedPost(this, EventArgs.Empty);
}
}
private void BeforePublish(object sender, UpdateWeblogProgressForm.PublishingEventArgs args)
{
UpdateWeblogProgressForm form = (UpdateWeblogProgressForm)sender;
bool noPluginsEnabled;
if (!HeaderAndFooterPrerequisitesMet(form, out noPluginsEnabled))
{
Debug.Assert(!noPluginsEnabled, "No plugins enabled yet header/footer prerequisites met!?");
args.RepublishOnSuccess = true;
return;
}
if (noPluginsEnabled)
return;
BlogPost.Contents = SmartContentInsertionHelper.StripDivsWithClass(BlogPost.Contents, ContentSourceManager.HEADERS_FOOTERS);
foreach (ContentSourceInfo csi in ContentSourceManager.GetActiveHeaderFooterPlugins(form, Blog.Id))
{
form.SetProgressMessage(string.Format(CultureInfo.InvariantCulture, Res.Get(StringId.PluginPublishProgress), csi.Name));
HeaderFooterSource plugin = (HeaderFooterSource)csi.Instance;
if (plugin.RequiresPermalink && string.IsNullOrEmpty(BlogPost.Permalink))
{
Trace.WriteLine("Skipping plugin " + csi.Name + " because the post has no permalink");
continue;
}
IExtensionData extData =
((IBlogPostEditingContext)this).ExtensionDataList.GetOrCreateExtensionData(csi.Id);
SmartContent smartContent = new SmartContent(extData);
HeaderFooterSource.Position position;
string html;
try
{
html = plugin.GeneratePublishHtml(form, smartContent, _publishingContext, args.Publish, out position);
}
catch (Exception e)
{
DisplayPluginException(form, csi, e);
continue;
}
if (string.IsNullOrEmpty(html))
continue;
if (SmartContentInsertionHelper.ContainsUnbalancedDivs(html))
{
Trace.Fail("Unbalanced divs detected in HTML generated by " + csi.Name + ": " + html);
DisplayMessage.Show(MessageId.MalformedHtmlIgnored, form, csi.Name);
continue;
}
// Don't use float alignment for footers--it causes them to float around
// stuff that isn't part of the post
bool noFloat = position == HeaderFooterSource.Position.Footer;
string generatedHtml = SmartContentInsertionHelper.GenerateBlock(ContentSourceManager.HEADERS_FOOTERS, null, smartContent, false, html, noFloat, null);
if (position == HeaderFooterSource.Position.Header)
BlogPost.Contents = generatedHtml + BlogPost.Contents;
else if (position == HeaderFooterSource.Position.Footer)
BlogPost.Contents = BlogPost.Contents + generatedHtml;
else
Debug.Fail("Unknown HeaderFooter position: " + position);
}
form.SetProgressMessage(null);
BlogPost.Contents = HtmlLinebreakStripper.RemoveLinebreaks(BlogPost.Contents);
}
private bool HeaderAndFooterPrerequisitesMet(IWin32Window owner, out bool noPluginsEnabled)
{
noPluginsEnabled = true;
foreach (ContentSourceInfo csi in ContentSourceManager.GetActiveHeaderFooterPlugins(owner, Blog.Id))
{
noPluginsEnabled = false;
// Short circuit because IsNew is the only requirement
if (!BlogPost.IsNew)
return true;
HeaderFooterSource plugin = (HeaderFooterSource)csi.Instance;
if (plugin.RequiresPermalink)
return false;
}
return true;
}
public class CancelPublishException : Exception
{
}
private class PublishOperationManager
{
private UpdateWeblogProgressForm _form;
private Blog _blog;
public PublishOperationManager(UpdateWeblogProgressForm form, Blog blog)
{
_form = form;
_blog = blog;
}
internal void DoPublishWork(IPublishingContext site, SmartContentSource source, ISmartContent sContent, ref string content)
{
if (source is IPublishTimeWorker)
{
try
{
// For each piece of IPublishTimeWorker smart content we find we need to ask if it has
// work to do while publishing. We pass null as the external context because that object
// is only for use when providing external code a chance to interact with the publish.
content = ((IPublishTimeWorker)source).DoPublishWork(_form, sContent, _blog.Id, site, null);
}
catch (WebException ex)
{
HttpRequestHelper.LogException(ex);
_exception = ex;
throw;
}
catch (Exception ex)
{
Trace.WriteLine("Content Source failed to do publish work: " + ex);
_exception = ex;
throw;
}
}
}
private Exception _exception;
public Exception Exception
{
get
{
return _exception;
}
}
}
private void PrePublishHooks(object sender, UpdateWeblogProgressForm.PublishEventArgs args)
{
Debug.Assert(!_mainFrameWindow.InvokeRequired, "PrePublishHooks invoked on non-UI thread");
UpdateWeblogProgressForm form = (UpdateWeblogProgressForm)sender;
bool publish = args.Publish;
// Let built in plugins do any extra processing they need to do during publish time
PublishOperationManager publishOperationManager = new PublishOperationManager(form, Blog);
string contents = SmartContentWorker.PerformOperation(_publishingContext.PostInfo.Contents, publishOperationManager.DoPublishWork, true, (IContentSourceSidebarContext)_publishingContext, false);
// One of the built in plugins threw an exception and we must cancel publish
if (publishOperationManager.Exception != null)
{
if (!(publishOperationManager.Exception is CancelPublishException))
{
UnhandledExceptionErrorMessage message = new UnhandledExceptionErrorMessage();
message.ShowMessage(_mainFrameWindow, publishOperationManager.Exception);
}
args.Cancel = true;
args.CancelReason = null;
return;
}
// We only save the new html if there was no exception while creating it.
BlogPost.Contents = contents;
LocalFile.SaveBlogPost(this as IBlogPostEditingContext);
foreach (ContentSourceInfo csi in ContentSourceManager.GetActivePublishNotificationPlugins(form, Blog.Id))
{
form.SetProgressMessage(string.Format(CultureInfo.InvariantCulture, Res.Get(StringId.PluginPublishProgress), csi.Name));
IProperties properties =
((IBlogPostEditingContext)this).ExtensionDataList.GetOrCreateExtensionData(csi.Id).Settings;
try
{
if (!((PublishNotificationHook)csi.Instance).OnPrePublish(form, properties, _publishingContext, publish))
{
args.Cancel = true;
args.CancelReason = csi.Name;
return;
}
}
catch (Exception e)
{
DisplayPluginException(form, csi, e);
continue;
}
}
form.SetProgressMessage(null);
}
private static void DisplayPluginException(IWin32Window owner, ContentSourceInfo csi, Exception e)
{
Trace.Fail(e.ToString());
DisplayableException ex = new DisplayableException(
Res.Get(StringId.UnexpectedErrorPluginTitle),
string.Format(CultureInfo.CurrentCulture, Res.Get(StringId.UnexpectedErrorPluginDescription), csi.Name, e.Message));
DisplayableExceptionDisplayForm.Show(owner, ex);
}
private void PostPublishHooks(object sender, UpdateWeblogProgressForm.PublishEventArgs args)
{
Debug.Assert(!_mainFrameWindow.InvokeRequired, "PostPublishHooks invoked on non-UI thread");
UpdateWeblogProgressForm form = (UpdateWeblogProgressForm)sender;
bool publish = args.Publish;
foreach (ContentSourceInfo csi in ContentSourceManager.GetActivePublishNotificationPlugins(form, Blog.Id))
{
form.SetProgressMessage(string.Format(CultureInfo.InvariantCulture, Res.Get(StringId.PluginPublishProgress), csi.Name));
IProperties properties =
((IBlogPostEditingContext)this).ExtensionDataList.GetOrCreateExtensionData(csi.Id).Settings;
try
{
((PublishNotificationHook)csi.Instance).OnPostPublish(form, properties, _publishingContext, publish);
}
catch (Exception ex)
{
DisplayPluginException(form, csi, ex);
continue;
}
}
form.SetProgressMessage(null);
}
/// <summary>
/// Saves info to the active blog post, but does not persist them
/// to disk. This will cause editors to become un-dirty.
/// </summary>
public void SaveEditsToPost()
{
SaveEditsToPost(false, BlogPostSaveOptions.DefaultOptions);
}
/// <summary>
/// Saves info to the active blog post, but does not persist them
/// to disk. Optionally preserve dirty state.
/// </summary>
public void SaveEditsToPost(bool preserveDirty, BlogPostSaveOptions options)
{
bool makeDirty = preserveDirty && PostIsDirty;
try
{
foreach (IBlogPostEditor postEditor in _postEditors)
postEditor.SaveChanges(BlogPost, options);
}
finally
{
if (makeDirty)
ForceDirty();
}
}
private bool UpdateWeblog(bool publish)
{
using (new WaitCursor())
{
// save all pending edits
if (!SaveToDrafts())
return false;
// upload to the weblog
using (UpdateWeblogProgressForm updateWeblogProgressForm =
new UpdateWeblogProgressForm(_mainFrameWindow, this, BlogPost.IsPage, BlogName, publish))
{
updateWeblogProgressForm.PrePublish += PrePublishHooks;
updateWeblogProgressForm.Publishing += BeforePublish;
updateWeblogProgressForm.PostPublish += PostPublishHooks;
// show the progress form
DialogResult result = updateWeblogProgressForm.ShowDialog(_mainFrameWindow);
// return success or failure
if (result == DialogResult.OK)
{
return true;
}
else if (result == DialogResult.Abort)
{
if (updateWeblogProgressForm.CancelReason != null)
DisplayMessage.Show(MessageId.PublishCanceledByPlugin, _mainFrameWindow, updateWeblogProgressForm.CancelReason);
return false;
}
else
{
if (updateWeblogProgressForm.Exception != null)
Trace.Fail(updateWeblogProgressForm.Exception.ToString());
// if this was a failure to upload images using the Metaweblog API newMediaObject
// then provide a special error message form that allows the user to reconfigure
// their file upload settings to another destination (e.g. FTP)
if (updateWeblogProgressForm.Exception is BlogClientFileUploadNotSupportedException)
{
result = FileUploadFailedForm.Show(_mainFrameWindow, GetUniqueImagesInPost());
if (result == DialogResult.Yes)
_editingSite.ConfigureWeblogFtpUpload(Blog.Id);
}
else if (updateWeblogProgressForm.Exception is BlogClientOperationCancelledException)
{
// show no UI for operation cancelled
Debug.WriteLine("BlogClient operation cancelled");
}
else
{
_blog.DisplayException(_mainFrameWindow, updateWeblogProgressForm.Exception);
}
// return failure
return false;
}
}
}
}
private void SaveToRecentPosts()
{
try
{
// note if this was saved in the drafts folder
PostEditorFile draftFile = null;
if (LocalFile.IsDraft)
draftFile = LocalFile;
// determine recent post file to save into (always try to find an existing recent post
// with this blog/post id -- if unable to find one then create new one)
PostEditorFile recentPostFile = PostEditorFile.FindPost(PostEditorFile.RecentPostsFolder, Blog.Id, BlogPost.Id);
if (recentPostFile == null)
recentPostFile = PostEditorFile.CreateNew(PostEditorFile.RecentPostsFolder);
// do the save and update the reference to the local file
recentPostFile.SaveBlogPost((this as IBlogPostEditingContext));
LocalFile = recentPostFile;
// delete copy from drafts if it was there
if (draftFile != null)
draftFile.Delete();
}
catch (Exception ex)
{
Trace.Fail("Unexpected exception saving recent post: " + ex.ToString());
}
}
private bool ValidateSupportingFileUsage()
{
if (Blog.SupportsImageUpload == SupportsFeature.No)
{
string[] images = GetUniqueImagesInPost();
if (images.Length > 0)
{
DialogResult result = FileUploadFailedForm.Show(_mainFrameWindow, images);
if (result == DialogResult.Yes)
_editingSite.ConfigureWeblogFtpUpload(Blog.Id);
return false;
}
}
// if we got this far then return true
return true;
}
private void DisplayAfterPublishFileUploadFailedWarningIfNecessary()
{
if (_lastPublishingResult != null && _lastPublishingResult.AfterPublishFileUploadException != null)
{
using (AfterPublishFileUploadFailedForm uploadFailedForm = new AfterPublishFileUploadFailedForm(_lastPublishingResult.AfterPublishFileUploadException, BlogPost.IsPage))
uploadFailedForm.ShowDialog(_mainFrameWindow);
}
}
private string[] GetUniqueImagesInPost()
{
ArrayList images = new ArrayList();
string[] postSupportingFiles = SupportingFileStorage.GetSupportingFilesInPost(BlogPost.Contents);
foreach (string supportingFile in postSupportingFiles)
{
if (PathHelper.IsPathImage(supportingFile) && IsNotExtraImage(supportingFile))
images.Add(Path.GetFileName(supportingFile));
}
return (string[])images.ToArray(typeof(string));
}
private bool IsNotExtraImage(string imagePath)
{
// : This is designed to filter out the extra images posted (e.g. "_thumb")
// so that the list displayed matches the number of images within the document
// we should make this filter 100% reliable then reintroduce it
return true;
/*
string fileName = Path.GetFileNameWithoutExtension();
return !fileName.EndsWith("_thumb") && !fileName.EndsWith("[1]");
*/
}
public void ForceDirty()
{
_forceDirtyPostEditor.ForceDirty();
}
#endregion
#region Private Event Handlers (Weblog Settings Edited, etc.
private void editingSite_GlobalWeblogSettingsEdited(string blogId, bool templateChanged)
{
// if the settings for our blog changed then notify the editors
if (blogId == Blog.Id)
{
// force our blog to update its client options
Blog.InvalidateClient();
foreach (IBlogPostEditor postEditor in _postEditors)
postEditor.OnBlogSettingsChanged(templateChanged);
// notify listeners that blog settings changed
if (BlogSettingsChanged != null)
BlogSettingsChanged(blogId, templateChanged);
// force a perform layout so the main frame can dynamically re-flow for
// any UI changes that were made as a result of the blog settings changing
_editingSite.FrameWindow.PerformLayout();
_editingSite.FrameWindow.Invalidate();
}
}
#endregion
#region Private Manipulation of Internal State (Current Blog, Current Post, LocalFile, etc.)
public Blog Blog
{
get { return _blog; }
}
private void OnBlogChanged()
{
if (_initialized)
{
// notify post editors
foreach (IBlogPostEditor postEditor in _postEditors)
postEditor.OnBlogChanged(Blog);
// fire the event
if (BlogChanged != null)
BlogChanged(this, EventArgs.Empty);
// force a perform layout so the main frame can dynamically re-flow for
// any UI changes that were made as a result of the blog changing
_editingSite.FrameWindow.PerformLayout();
}
}
private void SetCurrentBlog(string blogId)
{
DisposeCurrentBlog();
_blog = new Blog(blogId);
// update the default
BlogSettings.DefaultBlogId = blogId;
}
private void DisposeCurrentBlog()
{
if (_blog != null)
{
_blog.Dispose();
_blog = null;
}
}
private BlogPost BlogPost
{
get
{
return _blogPost;
}
set
{
_blogPost = value;
OnBlogPostChanged();
}
}
private void OnBlogPostChanged()
{
if (_initialized)
{
// notify post editors
foreach (IBlogPostEditor postEditor in _postEditors)
postEditor.Initialize(this, Blog.ClientOptions);
}
}
private BlogPostSupportingFileStorage SupportingFileStorage
{
get
{
return _supportingFileStorage;
}
set
{
_supportingFileStorage = value;
}
}
private string ServerSupportingFileDirectory
{
get
{
// create on demand based on the title of the post
if (_serverSupportingFileDirectory == String.Empty)
{
// convert title to usable directory name
string baseDirName = SupportingFileStorage.CleanPathForServer(BlogPost.Title);
// append seconds since midnight as an additional randomizer to make conflicts less likely
_serverSupportingFileDirectory = String.Format(CultureInfo.InvariantCulture, "{0}_{1}", baseDirName, (DateTime.Now.TimeOfDay.Ticks / TimeSpan.TicksPerSecond).ToString("X", CultureInfo.InvariantCulture));
}
return _serverSupportingFileDirectory;
}
set
{
if (value == null)
throw new ArgumentNullException("Cannot set ServerSupportingFileDirectory to null!!!");
_serverSupportingFileDirectory = value;
}
}
private BlogPostImageDataList ImageDataList
{
get { return _imageDataList; }
set { _imageDataList = value; }
}
private BlogPostExtensionDataList ExtensionDataList
{
get { return _extensionDataList; }
set { _extensionDataList = value; }
}
private ISupportingFileService SupportingFileService
{
get { return _fileService; }
set { _fileService = value; }
}
public PostEditorFile AutoSaveLocalFile
{
get
{
if (_autoSaveLocalFile == null)
{
_autoSaveLocalFile = PostEditorFile.CreateNew(new DirectoryInfo(PostEditorSettings.AutoSaveDirectory));
}
return _autoSaveLocalFile;
}
}
private void ResetAutoSave()
{
if (_autoSaveLocalFile != null)
{
PostEditorFile file = _autoSaveLocalFile;
_autoSaveLocalFile = null;
file.Delete();
}
}
private PostEditorFile LocalFile
{
get
{
return _localFile;
}
set
{
if (value == null)
throw new ArgumentException("Cannot set LocalFile to null!");
_localFile = value;
ResetAutoSave();
OnEditingStatusChanged();
}
}
private void OnEditingStatusChanged()
{
if (_initialized)
{
if (EditingStatusChanged != null)
EditingStatusChanged(this, EventArgs.Empty);
}
}
#endregion
#region Private Members
private bool _initialized = false;
private IMainFrameWindow _mainFrameWindow;
private IPublishingContext _publishingContext; // used for headers and footers
private IBlogPostEditingSite _editingSite;
private ArrayList _postEditors = new ArrayList();
private ForceDirtyPostEditor _forceDirtyPostEditor = new ForceDirtyPostEditor();
private Blog _blog;
private BlogPost _blogPost;
private BlogPostSupportingFileStorage _supportingFileStorage;
private string _serverSupportingFileDirectory = String.Empty;
private BlogPostImageDataList _imageDataList;
private BlogPostExtensionDataList _extensionDataList;
private ISupportingFileService _fileService;
private PostEditorFile _localFile;
private PostEditorFile _autoSaveLocalFile;
private DateTime _editStartTime;
#endregion
}
}
| |
using Aspose.Email;
using Aspose.Email.Mapi;
using Aspose.Email.Storage.Mbox;
using Aspose.Email.Storage.Pst;
using Aspose.Slides;
using System;
using System.IO;
namespace Aspose.Email.Live.Demos.UI.Services.Email
{
public partial class EmailService
{
public void ConvertMbox(Stream input, string shortResourceNameWithExtension, IOutputHandler handler, string outputType)
{
PrepareOutputType(ref outputType);
switch (outputType)
{
case "eml": ConvertMboxToEml(input, shortResourceNameWithExtension, handler); break;
case "msg": ConvertMboxToMsg(input, shortResourceNameWithExtension, handler); break;
case "mbox": ReturnSame(input, shortResourceNameWithExtension, handler); break;
case "pst": ConvertMboxToPst(input, shortResourceNameWithExtension, handler); break;
case "mht": ConvertMboxToMht(input, shortResourceNameWithExtension, handler); break;
case "html": ConvertMboxToHtml(input, shortResourceNameWithExtension, handler); break;
case "svg": ConvertMboxToSvg(input, shortResourceNameWithExtension, handler); break;
case "tiff": ConvertMboxToTiff(input, shortResourceNameWithExtension, handler); break;
case "jpg": ConvertMboxToJpg(input, shortResourceNameWithExtension, handler); break;
case "bmp": ConvertMboxToBmp(input, shortResourceNameWithExtension, handler); break;
case "png": ConvertMboxToPng(input, shortResourceNameWithExtension, handler); break;
case "pdf": ConvertMboxToPdf(input, shortResourceNameWithExtension, handler); break;
case "doc": ConvertMboxToDoc(input, shortResourceNameWithExtension, handler); break;
case "ppt": ConvertMboxToPpt(input, shortResourceNameWithExtension, handler); break;
case "rtf": ConvertMboxToRtf(input, shortResourceNameWithExtension, handler); break;
case "docx": ConvertMboxToDocx(input, shortResourceNameWithExtension, handler); break;
case "docm": ConvertMboxToDocm(input, shortResourceNameWithExtension, handler); break;
case "dotx": ConvertMboxToDotx(input, shortResourceNameWithExtension, handler); break;
case "dotm": ConvertMboxToDotm(input, shortResourceNameWithExtension, handler); break;
case "odt": ConvertMboxToOdt(input, shortResourceNameWithExtension, handler); break;
case "ott": ConvertMboxToOtt(input, shortResourceNameWithExtension, handler); break;
case "epub": ConvertMboxToEpub(input, shortResourceNameWithExtension, handler); break;
case "txt": ConvertMboxToTxt(input, shortResourceNameWithExtension, handler); break;
case "emf": ConvertMboxToEmf(input, shortResourceNameWithExtension, handler); break;
case "xps": ConvertMboxToXps(input, shortResourceNameWithExtension, handler); break;
case "pcl": ConvertMboxToPcl(input, shortResourceNameWithExtension, handler); break;
case "ps": ConvertMboxToPs(input, shortResourceNameWithExtension, handler); break;
case "mhtml": ConvertMboxToMhtml(input, shortResourceNameWithExtension, handler); break;
default:
throw new NotSupportedException($"Output type not supported {outputType.ToUpperInvariant()}");
}
}
public void ConvertMboxToTiff(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveMboxAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Tiff, ".tiff");
}
public void ConvertMboxToJpg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveMboxAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Jpeg, ".jpg");
}
public void ConvertMboxToBmp(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveMboxAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Bmp, ".bmp");
}
public void ConvertMboxToPng(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveMboxAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Png, ".png");
}
public void ConvertMboxToSvg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveMboxAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Svg, ".svg");
}
public void ConvertMboxToHtml(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveMboxAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Html, ".html");
}
public void ConvertMboxToMht(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
// Save as mht with header
var mhtSaveOptions = new MhtSaveOptions
{
//Specify formatting options required
//Here we are specifying to write header informations to output without writing extra print header
//and the output headers should display as the original headers in message
MhtFormatOptions = MhtFormatOptions.WriteHeader | MhtFormatOptions.HideExtraPrintHeader | MhtFormatOptions.DisplayAsOutlook,
// Check the body encoding for validity.
CheckBodyContentEncoding = true
};
using (var reader = new MboxrdStorageReader(input, false))
{
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
{
var message = reader.ReadNextMessage();
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_Message" + i + ".mht"))
message.Save(output, mhtSaveOptions);
}
}
}
///<Summary>
/// ConvertMboxToPst method to convert mbox to pst file
///</Summary>
public void ConvertMboxToPst(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var personalStorage = PersonalStorage.Create(handler.CreateOutputStream(Path.ChangeExtension(shortResourceNameWithExtension, ".pst")), FileFormatVersion.Unicode))
{
var inbox = personalStorage.RootFolder.AddSubFolder("Inbox");
using (MboxrdStorageReader reader = new MboxrdStorageReader(input, false))
{
MailMessage message;
while ((message = reader.ReadNextMessage()) != null)
{
using (var mapi = MapiMessage.FromMailMessage(message, MapiConversionOptions.UnicodeFormat))
inbox.AddMessage(mapi);
}
}
}
}
///<Summary>
/// ConvertMboxToEml method to convert mbox to eml file
///</Summary>
public void ConvertMboxToEml(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var reader = new MboxrdStorageReader(input, false))
{
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
{
using (var message = reader.ReadNextMessage())
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension+"_Message" + i + ".eml"))
message.Save(output, SaveOptions.DefaultEml);
}
}
}
}
///<Summary>
/// ConvertMboxToMsg method to convert mbox to msg file
///</Summary>
public void ConvertMboxToMsg(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var reader = new MboxrdStorageReader(input, false))
{
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
{
using (var message = reader.ReadNextMessage())
{
using (var output = handler.CreateOutputStream(shortResourceNameWithExtension + "_Message" + i + ".msg"))
message.Save(output, SaveOptions.DefaultMsgUnicode);
}
}
}
}
public void ConvertMboxToPdf(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Pdf);
}
public void ConvertMboxToDoc(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Doc);
}
public void ConvertMboxToPpt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
using (var reader = new MboxrdStorageReader(input, false))
{
using (var presentation = new Presentation())
{
var firstSlide = presentation.Slides[0];
var convertOptions = new MapiConversionOptions();
var renameCallback = new ImageSavingCallback(handler);
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
{
var message = reader.ReadNextMessage();
var newSlide = presentation.Slides.AddClone(firstSlide);
AddMessageInSlide(presentation, newSlide, MapiMessage.FromMailMessage(message, convertOptions), renameCallback);
}
presentation.Slides.Remove(firstSlide);
using (var output = handler.CreateOutputStream(Path.ChangeExtension(shortResourceNameWithExtension, ".ppt")))
presentation.Save(output, Aspose.Slides.Export.SaveFormat.Ppt);
}
}
}
public void ConvertMboxToRtf(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Rtf);
}
public void ConvertMboxToDocx(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Docx);
}
public void ConvertMboxToDocm(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Docm);
}
public void ConvertMboxToDotx(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Dotx);
}
public void ConvertMboxToDotm(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Dotm);
}
public void ConvertMboxToOdt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Odt);
}
public void ConvertMboxToOtt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Ott);
}
public void ConvertMboxToEpub(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Epub);
}
public void ConvertMboxToTxt(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Text);
}
public void ConvertMboxToEmf(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Emf);
}
public void ConvertMboxToXps(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Xps);
}
public void ConvertMboxToPcl(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Pcl);
}
public void ConvertMboxToPs(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Ps);
}
public void ConvertMboxToMhtml(Stream input, string shortResourceNameWithExtension, IOutputHandler handler)
{
SaveOstOrPstAsDocument(input, shortResourceNameWithExtension, handler, Words.SaveFormat.Mhtml);
}
void SaveMboxAsDocument(Stream input, string shortResourceNameWithExtension, IOutputHandler handler, Words.SaveFormat format, string saveExtension)
{
using (var reader = new MboxrdStorageReader(input, new MboxLoadOptions()
{
LeaveOpen = false
}))
{
var msgStream = new MemoryStream();
for (int i = 0; i < reader.GetTotalItemsCount(); i++)
{
var message = reader.ReadNextMessage();
message.Save(msgStream, SaveOptions.DefaultMhtml);
}
msgStream.Position = 0;
SaveDocumentStreamToFolder(msgStream, shortResourceNameWithExtension, handler, format);
}
}
}
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Reflection;
using Microsoft.Build.Framework;
using Microsoft.Build.Tasks;
using Microsoft.Build.Utilities;
using System.Text.RegularExpressions;
using System.Globalization;
using ResGen = Microsoft.Build.Tasks.GenerateResource.ResGen;
using Xunit;
namespace Microsoft.Build.UnitTests
{
public class ResGen_Tests
{
/// <summary>
/// Verify InputFiles:
/// - Defaults to null, in which case the task just returns true and continues
/// - If there are InputFiles, verify that they all show up on the command line
/// - Verify that OutputFiles defaults appropriately
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void InputFiles()
{
ResGen t = new ResGen();
ITaskItem[] singleTestFile = { new TaskItem("foo.resx") };
ITaskItem[] singleOutput = { new TaskItem("foo.resources") };
ITaskItem[] multipleTestFiles = { new TaskItem("hello.resx"), new TaskItem("world.resx"), new TaskItem("!.resx") };
ITaskItem[] multipleOutputs = { new TaskItem("hello.resources"), new TaskItem("world.resources"), new TaskItem("!.resources") };
// Default: InputFiles is null
Assert.Null(t.InputFiles); // "InputFiles is null by default"
Assert.Null(t.OutputFiles); // "OutputFiles is null by default"
ExecuteTaskAndVerifyLogContainsResource(t, true /* task passes */, "ResGen.NoInputFiles");
// One input file -- compile
t.InputFiles = singleTestFile;
t.StronglyTypedLanguage = null;
t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.Version45));
Assert.Equal(singleTestFile, t.InputFiles); // "New InputFiles value should be set"
Assert.Null(t.OutputFiles); // "OutputFiles is null until default name generation is triggered"
string commandLineParameter = String.Join(",", new string[] { singleTestFile[0].ItemSpec, singleOutput[0].ItemSpec });
CommandLine.ValidateHasParameter(t, commandLineParameter, true /* resgen 4.0 supports response files */);
CommandLine.ValidateHasParameter(t, @"/compile", true /* resgen 4.0 supports response files */);
// One input file -- STR
t.InputFiles = singleTestFile;
t.StronglyTypedLanguage = "c#";
CommandLine.ValidateHasParameter(t, singleTestFile[0].ItemSpec, false /* resgen 4.0 does not appear to support response files for STR */);
CommandLine.ValidateHasParameter(t, singleOutput[0].ItemSpec, false /* resgen 4.0 does not appear to support response files for STR */);
CommandLine.ValidateHasParameter(t, "/str:c#,,,", false /* resgen 4.0 does not appear to support response files for STR */);
// Multiple input files -- compile
t.InputFiles = multipleTestFiles;
t.OutputFiles = null; // want it to reset to default
t.StronglyTypedLanguage = null;
Assert.Equal(multipleTestFiles, t.InputFiles); // "New InputFiles value should be set"
CommandLine.ValidateHasParameter(t, @"/compile", true /* resgen 4.0 supports response files */);
for (int i = 0; i < multipleTestFiles.Length; i++)
{
commandLineParameter = String.Join(",", new string[] { multipleTestFiles[i].ItemSpec, multipleOutputs[i].ItemSpec });
CommandLine.ValidateHasParameter(t, commandLineParameter, true /* resgen 4.0 supports response files */);
}
// Multiple input files -- STR (should error)
t.InputFiles = multipleTestFiles;
t.StronglyTypedLanguage = "vb";
ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.STRLanguageButNotExactlyOneSourceFile");
}
/// <summary>
/// Verify OutputFiles:
/// - Default values were tested by InputFiles()
/// - Verify that if InputFiles and OutputFiles are different lengths (and both exist), an error is logged
/// - Verify that if OutputFiles are set explicitly, they map and show up on the command line as expected
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void OutputFiles()
{
ResGen t = new ResGen();
ITaskItem[] differentLengthInput = { new TaskItem("hello.resx") };
ITaskItem[] differentLengthOutput = { new TaskItem("world.resources"), new TaskItem("!.resources") };
ITaskItem[] differentLengthDefaultOutput = { new TaskItem("hello.resources") };
// Different length inputs -- should error
t.InputFiles = differentLengthInput;
t.OutputFiles = differentLengthOutput;
t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.Version45));
Assert.Equal(differentLengthInput, t.InputFiles); // "New InputFiles value should be set"
Assert.Equal(differentLengthOutput, t.OutputFiles); // "New OutputFiles value should be set"
ExecuteTaskAndVerifyLogContainsErrorFromResource
(
t,
"General.TwoVectorsMustHaveSameLength",
differentLengthInput.Length,
differentLengthOutput.Length,
"InputFiles",
"OutputFiles"
);
// If only OutputFiles is set, then the task should return -- as far as
// it's concerned, no work needs to be done.
t = new ResGen(); // zero out the log
t.InputFiles = null;
t.OutputFiles = differentLengthOutput;
t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.Version45));
Assert.Null(t.InputFiles); // "New InputFiles value should be set"
Assert.Equal(differentLengthOutput, t.OutputFiles); // "New OutputFiles value should be set"
ExecuteTaskAndVerifyLogContainsResource(t, true /* task passes */, "ResGen.NoInputFiles");
// However, if OutputFiles is set to null, it should revert back to default
t.InputFiles = differentLengthInput;
t.OutputFiles = null;
Assert.Equal(differentLengthInput, t.InputFiles); // "New InputFiles value should be set"
Assert.Null(t.OutputFiles); // "OutputFiles is null until default name generation is triggered"
string commandLineParameter = String.Join(",", new string[] { differentLengthInput[0].ItemSpec, differentLengthDefaultOutput[0].ItemSpec });
CommandLine.ValidateHasParameter(t, commandLineParameter, true /* resgen 4.0 supports response files */);
CommandLine.ValidateHasParameter(t, @"/compile", true /* resgen 4.0 supports response files */);
// Explicitly setting output
ITaskItem[] inputFiles = { new TaskItem("foo.resx") };
ITaskItem[] defaultOutput = { new TaskItem("foo.resources") };
ITaskItem[] explicitOutput = { new TaskItem("bar.txt") };
t.InputFiles = inputFiles;
t.OutputFiles = null;
Assert.Equal(inputFiles, t.InputFiles); // "New InputFiles value should be set"
Assert.Null(t.OutputFiles); // "OutputFiles is null until default name generation is triggered"
commandLineParameter = String.Join(",", new string[] { inputFiles[0].ItemSpec, defaultOutput[0].ItemSpec });
CommandLine.ValidateHasParameter(t, commandLineParameter, true /* resgen 4.0 supports response files */);
CommandLine.ValidateHasParameter(t, @"/compile", true /* resgen 4.0 supports response files */);
t.OutputFiles = explicitOutput;
Assert.Equal(inputFiles, t.InputFiles); // "New InputFiles value should be set"
Assert.Equal(explicitOutput, t.OutputFiles); // "New OutputFiles value should be set"
commandLineParameter = String.Join(",", new string[] { inputFiles[0].ItemSpec, explicitOutput[0].ItemSpec });
CommandLine.ValidateHasParameter(t, commandLineParameter, true /* resgen 4.0 supports response files */);
CommandLine.ValidateHasParameter(t, @"/compile", true /* resgen 4.0 supports response files */);
}
/// <summary>
/// Tests ResGen's /publicClass switch
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void PublicClass()
{
ResGen t = new ResGen();
ITaskItem[] throwawayInput = { new TaskItem("hello.resx") };
t.InputFiles = throwawayInput;
t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.VersionLatest));
Assert.False(t.PublicClass); // "PublicClass should be false by default"
CommandLine.ValidateNoParameterStartsWith(t, @"/publicClass", true /* resgen 4.0 supports response files */);
t.PublicClass = true;
Assert.True(t.PublicClass); // "PublicClass should be true"
CommandLine.ValidateHasParameter(t, @"/publicClass", true /* resgen 4.0 supports response files */);
}
/// <summary>
/// Tests the /r: parameter (passing in reference assemblies)
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void References()
{
ResGen t = new ResGen();
ITaskItem[] throwawayInput = { new TaskItem("hello.resx") };
ITaskItem a = new TaskItem();
ITaskItem b = new TaskItem();
t.InputFiles = throwawayInput;
t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.VersionLatest));
a.ItemSpec = "foo.dll";
b.ItemSpec = "bar.dll";
ITaskItem[] singleReference = { a };
ITaskItem[] multipleReferences = { a, b };
Assert.Null(t.References); // "References should be null by default"
CommandLine.ValidateNoParameterStartsWith(t, "/r:", true /* resgen 4.0 supports response files */);
// Single reference
t.References = singleReference;
Assert.Equal(singleReference, t.References); // "New References value should be set"
CommandLine.ValidateHasParameter(t, "/r:" + singleReference[0].ItemSpec, true /* resgen 4.0 supports response files */);
// MultipleReferences
t.References = multipleReferences;
Assert.Equal(multipleReferences, t.References); // "New References value should be set"
foreach (ITaskItem reference in multipleReferences)
{
CommandLine.ValidateHasParameter(t, "/r:" + reference.ItemSpec, true /* resgen 4.0 supports response files */);
}
// test cases where command line length is equal to the maximum allowed length and just above the maximum allowed length
// we do some calculation here to do ensure that the resulting command lines match these cases (see Case 1 and 2 below)
// reference switch adds space + "/r:", (4 characters)
int referenceSwitchDelta = 4;
//subtract one because leading space is added to command line arguments
int maxCommandLineLength = 28000 - 1;
int referencePathLength = 200;
//min reference argument is " /r:a.dll"
int minReferenceArgumentLength = referenceSwitchDelta + "a.dll".Length;
// reference name is of the form aaa...aaa###.dll (repeated a characters followed by 3
// digit identifier for uniqueness followed by the .dll file extension
StringBuilder referencePathBuilder = new StringBuilder();
referencePathBuilder.Append('a', referencePathLength - (3 /* 3 digit identifier */ + 4 /* file extension */));
string longReferenceNameBase = referencePathBuilder.ToString();
// reference switch length plus the length of the reference path
int referenceArgumentLength = referencePathLength + referenceSwitchDelta;
t = CreateCommandLineResGen();
// compute command line with only one reference switch so remaining added reference
// arguments will have the same length, since the first reference argument added may not have a
// leading space
List<ITaskItem> references = new List<ITaskItem>();
references.Add(new TaskItem() { ItemSpec = "a.dll" });
t.References = references.ToArray();
int baseCommandLineLength = CommandLine.GetCommandLine(t, false).Length;
Assert.True(baseCommandLineLength < maxCommandLineLength); // "Cannot create command line less than the maximum allowed command line"
// calculate how many reference arguments will need to be added and what the length of the last argument
// should be so that the command line length is equal to the maximum allowed length
int remainder;
int quotient = Math.DivRem(maxCommandLineLength - baseCommandLineLength, referenceArgumentLength, out remainder);
if (remainder < minReferenceArgumentLength)
{
remainder += referenceArgumentLength;
quotient--;
}
// compute the length of the last reference argument
int lastReferencePathLength = remainder - (4 /* switch length */ + 4 /* file extension */);
for (int i = 0; i < quotient; i++)
{
string refIndex = i.ToString().PadLeft(3, '0');
references.Add(new TaskItem() { ItemSpec = (longReferenceNameBase + refIndex + ".dll") });
}
//
// Case 1: Command line length is equal to the maximum allowed value
//
// create last reference argument
referencePathBuilder.Clear();
referencePathBuilder.Append('b', lastReferencePathLength).Append(".dll");
ITaskItem lastReference = new TaskItem() { ItemSpec = referencePathBuilder.ToString() };
references.Add(lastReference);
// set references
t.References = references.ToArray();
int commandLineLength = CommandLine.GetCommandLine(t, false).Length;
Assert.Equal(commandLineLength, maxCommandLineLength);
ExecuteTaskAndVerifyLogDoesNotContainResource
(
t,
false,
"ResGen.CommandTooLong",
CommandLine.GetCommandLine(t, false).Length
);
VerifyLogDoesNotContainResource((MockEngine)t.BuildEngine, GetPrivateLog(t), "ToolTask.CommandTooLong", typeof(ResGen).Name);
//
// Case 2: Command line length is one more than the maximum allowed value
//
// make last reference name longer by one character so that command line should become too long
referencePathBuilder.Insert(0, 'b');
lastReference.ItemSpec = referencePathBuilder.ToString();
// reset ResGen task, since execution can change the command line
t = CreateCommandLineResGen();
t.References = references.ToArray();
commandLineLength = CommandLine.GetCommandLine(t, false).Length;
Assert.Equal(commandLineLength, (maxCommandLineLength + 1));
ExecuteTaskAndVerifyLogContainsErrorFromResource
(
t,
"ResGen.CommandTooLong",
CommandLine.GetCommandLine(t, false).Length
);
VerifyLogDoesNotContainResource((MockEngine)t.BuildEngine, GetPrivateLog(t), "ToolTask.CommandTooLong", typeof(ResGen).Name);
}
private ResGen CreateCommandLineResGen()
{
ResGen t = new ResGen();
ITaskItem[] throwawayInput = { new TaskItem("hello.resx") };
// setting these values should ensure that no response file is used
t.UseCommandProcessor = false;
t.StronglyTypedLanguage = "CSharp";
t.InputFiles = throwawayInput;
t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.VersionLatest));
return t;
}
/// <summary>
/// Tests the SdkToolsPath property: Should log an error if it's null or a bad path.
/// </summary>
[Fact]
public void SdkToolsPath()
{
ResGen t = new ResGen();
string badParameterValue = @"C:\Program Files\Microsoft Visual Studio 10.0\My Fake SDK Path";
string goodParameterValue = Path.GetTempPath();
ITaskItem[] throwawayInput = { new TaskItem("hello.resx") };
// Without any inputs, the task just passes
t.InputFiles = throwawayInput;
Assert.Null(t.SdkToolsPath); // "SdkToolsPath should be null by default"
ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.SdkOrToolPathNotSpecifiedOrInvalid", t.SdkToolsPath, t.ToolPath);
t.SdkToolsPath = badParameterValue;
Assert.Equal(badParameterValue, t.SdkToolsPath); // "New SdkToolsPath value should be set"
ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.SdkOrToolPathNotSpecifiedOrInvalid", t.SdkToolsPath, t.ToolPath);
MockEngine e = new MockEngine();
t.BuildEngine = e;
t.SdkToolsPath = goodParameterValue;
Assert.Equal(goodParameterValue, t.SdkToolsPath); // "New SdkToolsPath value should be set"
bool taskPassed = t.Execute();
Assert.False(taskPassed); // "Task should still fail -- there are other things wrong with it."
// but that particular error shouldn't be there anymore.
string sdkToolsPathMessage = t.Log.FormatResourceString("ResGen.SdkOrToolPathNotSpecifiedOrInvalid", t.SdkToolsPath, t.ToolPath);
string messageWithNoCode;
string sdkToolsPathCode = t.Log.ExtractMessageCode(sdkToolsPathMessage, out messageWithNoCode);
e.AssertLogDoesntContain(sdkToolsPathCode);
}
/// <summary>
/// Verifies the parameters that for resgen.exe's /str: switch
/// </summary>
[Fact]
public void StronglyTypedParameters()
{
ResGen t = new ResGen();
ITaskItem[] throwawayInput = { new TaskItem("hello.resx") };
string strLanguage = "c#";
string strNamespace = "Microsoft.Build.Foo";
string strClass = "MyFoo";
string strFile = "MyFoo.cs";
// Without any inputs, the task just passes
t.InputFiles = throwawayInput;
t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.VersionLatest));
// Language is null by default
Assert.Null(t.StronglyTypedLanguage); // "StronglyTypedLanguage should be null by default"
CommandLine.ValidateNoParameterStartsWith(t, "/str:", false /* resgen 4.0 does not appear to support response files for STR */);
// If other STR parameters are passed, we error, suggesting they might want a language as well.
t.StronglyTypedNamespace = strNamespace;
CommandLine.ValidateNoParameterStartsWith(t, "/str:", false /* resgen 4.0 does not appear to support response files for STR */);
ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.STRClassNamespaceOrFilenameWithoutLanguage");
t.StronglyTypedNamespace = "";
t.StronglyTypedClassName = strClass;
CommandLine.ValidateNoParameterStartsWith(t, "/str:", false /* resgen 4.0 does not appear to support response files for STR */);
ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.STRClassNamespaceOrFilenameWithoutLanguage");
t.StronglyTypedClassName = "";
t.StronglyTypedFileName = strFile;
CommandLine.ValidateNoParameterStartsWith(t, "/str:", false /* resgen 4.0 does not appear to support response files for STR */);
ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.STRClassNamespaceOrFilenameWithoutLanguage");
// However, if it is passed, the /str: switch gets added
t.StronglyTypedLanguage = strLanguage;
t.StronglyTypedNamespace = "";
t.StronglyTypedClassName = "";
t.StronglyTypedFileName = "";
CommandLine.ValidateHasParameter(t, "/str:" + strLanguage + ",,,", false /* resgen 4.0 does not appear to support response files for STR */);
t.StronglyTypedNamespace = strNamespace;
CommandLine.ValidateHasParameter(t, "/str:" + strLanguage + "," + strNamespace + ",,", false /* resgen 4.0 does not appear to support response files for STR */);
t.StronglyTypedClassName = strClass;
CommandLine.ValidateHasParameter(t, "/str:" + strLanguage + "," + strNamespace + "," + strClass + ",", false /* resgen 4.0 does not appear to support response files for STR */);
t.StronglyTypedFileName = strFile;
CommandLine.ValidateHasParameter(t, "/str:" + strLanguage + "," + strNamespace + "," + strClass + "," + strFile, false /* resgen 4.0 does not appear to support response files for STR */);
}
/// <summary>
/// Tests the ToolPath property: Should log an error if it's null or a bad path.
/// </summary>
[Fact]
public void ToolPath()
{
ResGen t = new ResGen();
string badParameterValue = @"C:\Program Files\Microsoft Visual Studio 10.0\My Fake SDK Path";
string goodParameterValue = Path.GetTempPath();
ITaskItem[] throwawayInput = { new TaskItem("hello.resx") };
// Without any inputs, the task just passes
t.InputFiles = throwawayInput;
Assert.Null(t.ToolPath); // "ToolPath should be null by default"
ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.SdkOrToolPathNotSpecifiedOrInvalid", t.SdkToolsPath, t.ToolPath);
t.ToolPath = badParameterValue;
Assert.Equal(badParameterValue, t.ToolPath); // "New ToolPath value should be set"
ExecuteTaskAndVerifyLogContainsErrorFromResource(t, "ResGen.SdkOrToolPathNotSpecifiedOrInvalid", t.SdkToolsPath, t.ToolPath);
MockEngine e = new MockEngine();
t.BuildEngine = e;
t.ToolPath = goodParameterValue;
Assert.Equal(goodParameterValue, t.ToolPath); // "New ToolPath value should be set"
bool taskPassed = t.Execute();
Assert.False(taskPassed); // "Task should still fail -- there are other things wrong with it."
// but that particular error shouldn't be there anymore.
string toolPathMessage = t.Log.FormatResourceString("ResGen.SdkOrToolPathNotSpecifiedOrInvalid", t.SdkToolsPath, t.ToolPath);
string messageWithNoCode;
string toolPathCode = t.Log.ExtractMessageCode(toolPathMessage, out messageWithNoCode);
e.AssertLogDoesntContain(toolPathCode);
}
/// <summary>
/// Tests ResGen's /useSourcePath switch
/// </summary>
[Fact]
[Trait("Category", "mono-osx-failing")]
public void UseSourcePath()
{
ResGen t = new ResGen();
ITaskItem[] throwawayInput = { new TaskItem("hello.resx") };
t.InputFiles = throwawayInput;
t.ToolPath = Path.GetDirectoryName(ToolLocationHelper.GetPathToDotNetFrameworkSdkFile("resgen.exe", TargetDotNetFrameworkVersion.VersionLatest));
Assert.False(t.UseSourcePath); // "UseSourcePath should be false by default"
CommandLine.ValidateNoParameterStartsWith(t, @"/useSourcePath", true /* resgen 4.0 supports response files */);
t.UseSourcePath = true;
Assert.True(t.UseSourcePath); // "UseSourcePath should be true"
CommandLine.ValidateHasParameter(t, @"/useSourcePath", true /* resgen 4.0 supports response files */);
}
#region Helper Functions
/// <summary>
/// Given an instance of a ResGen task, executes that task (assuming all necessary parameters
/// have been set ahead of time) and verifies that the execution log contains the error
/// corresponding to the resource name passed in.
/// </summary>
/// <param name="t">The task to execute and check</param>
/// <param name="errorResource">The name of the resource string to check the log for</param>
/// <param name="args">Arguments needed to format the resource string properly</param>
private void ExecuteTaskAndVerifyLogContainsErrorFromResource(ResGen t, string errorResource, params object[] args)
{
ExecuteTaskAndVerifyLogContainsResource(t, false, errorResource, args);
}
/// <summary>
/// Given an instance of a ResGen task, executes that task (assuming all necessary parameters
/// have been set ahead of time), verifies that the task had the expected result, and checks
/// the log for the string corresponding to the resource name passed in
/// </summary>
/// <param name="t">The task to execute and check</param>
/// <param name="expectedResult">true if the task is expected to pass, false otherwise</param>
/// <param name="resourceString">The name of the resource string to check the log for</param>
/// <param name="args">Arguments needed to format the resource string properly</param>
private void ExecuteTaskAndVerifyLogContainsResource(ResGen t, bool expectedResult, string resourceString, params object[] args)
{
MockEngine e = new MockEngine();
t.BuildEngine = e;
bool taskPassed = t.Execute();
Assert.Equal(taskPassed, expectedResult); // "Unexpected task result"
VerifyLogContainsResource(e, t.Log, resourceString, args);
}
/// <summary>
/// Given a log and a resource string, acquires the text of that resource string and
/// compares it to the log. Asserts if the log does not contain the desired string.
/// </summary>
/// <param name="e">The MockEngine that contains the log we're checking</param>
/// <param name="log">The TaskLoggingHelper that we use to load the string resource</param>
/// <param name="errorResource">The name of the resource string to check the log for</param>
/// <param name="args">Arguments needed to format the resource string properly</param>
private void VerifyLogContainsResource(MockEngine e, TaskLoggingHelper log, string messageResource, params object[] args)
{
string message = log.FormatResourceString(messageResource, args);
e.AssertLogContains(message);
}
/// <summary>
/// Given an instance of a ResGen task, executes that task (assuming all necessary parameters
/// have been set ahead of time), verifies that the task had the expected result, and ensures
/// the log does not contain the string corresponding to the resource name passed in
/// </summary>
/// <param name="t">The task to execute and check</param>
/// <param name="expectedResult">true if the task is expected to pass, false otherwise</param>
/// <param name="resourceString">The name of the resource string to check the log for</param>
/// <param name="args">Arguments needed to format the resource string properly</param>
private void ExecuteTaskAndVerifyLogDoesNotContainResource(ResGen t, bool expectedResult, string resourceString, params object[] args)
{
MockEngine e = new MockEngine();
t.BuildEngine = e;
bool taskPassed = t.Execute();
Assert.Equal(taskPassed, expectedResult); // "Unexpected task result"
VerifyLogDoesNotContainResource(e, t.Log, resourceString, args);
}
/// <summary>
/// Given a log and a resource string, acquires the text of that resource string and
/// compares it to the log. Assert fails if the log contain the desired string.
/// </summary>
/// <param name="e">The MockEngine that contains the log we're checking</param>
/// <param name="log">The TaskLoggingHelper that we use to load the string resource</param>
/// <param name="errorResource">The name of the resource string to check the log for</param>
/// <param name="args">Arguments needed to format the resource string properly</param>
private void VerifyLogDoesNotContainResource(MockEngine e, TaskLoggingHelper log, string messageResource, params object[] args)
{
string message = log.FormatResourceString(messageResource, args);
e.AssertLogDoesntContain(message);
}
/// <summary>
/// Gets the LogPrivate on the given ToolTask instance. We need to use reflection since
/// LogPrivate is a private property.
/// </summary>
/// <returns></returns>
static private TaskLoggingHelper GetPrivateLog(ToolTask task)
{
PropertyInfo logPrivateProperty = typeof(ToolTask).GetProperty("LogPrivate", BindingFlags.Instance | BindingFlags.NonPublic);
return (TaskLoggingHelper)logPrivateProperty.GetValue(task, null);
}
#endregion // Helper Functions
}
}
| |
#region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
//
// DO NOT EDIT THIS FILE!
//
// This file was generated automatically by astgen.boo.
//
namespace Boo.Lang.Compiler.Ast
{
using System.Collections;
using System.Runtime.Serialization;
[System.Serializable]
public partial class CallableDefinition : TypeMember, INodeWithParameters, INodeWithGenericParameters
{
protected ParameterDeclarationCollection _parameters;
protected GenericParameterDeclarationCollection _genericParameters;
protected TypeReference _returnType;
protected AttributeCollection _returnTypeAttributes;
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public CallableDefinition CloneNode()
{
return (CallableDefinition)Clone();
}
/// <summary>
/// <see cref="Node.CleanClone"/>
/// </summary>
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
new public CallableDefinition CleanClone()
{
return (CallableDefinition)base.CleanClone();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public NodeType NodeType
{
get { return NodeType.CallableDefinition; }
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public void Accept(IAstVisitor visitor)
{
visitor.OnCallableDefinition(this);
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Matches(Node node)
{
if (node == null) return false;
if (NodeType != node.NodeType) return false;
var other = ( CallableDefinition)node;
if (_modifiers != other._modifiers) return NoMatch("CallableDefinition._modifiers");
if (_name != other._name) return NoMatch("CallableDefinition._name");
if (!Node.AllMatch(_attributes, other._attributes)) return NoMatch("CallableDefinition._attributes");
if (!Node.AllMatch(_parameters, other._parameters)) return NoMatch("CallableDefinition._parameters");
if (!Node.AllMatch(_genericParameters, other._genericParameters)) return NoMatch("CallableDefinition._genericParameters");
if (!Node.Matches(_returnType, other._returnType)) return NoMatch("CallableDefinition._returnType");
if (!Node.AllMatch(_returnTypeAttributes, other._returnTypeAttributes)) return NoMatch("CallableDefinition._returnTypeAttributes");
return true;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public bool Replace(Node existing, Node newNode)
{
if (base.Replace(existing, newNode))
{
return true;
}
if (_attributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_attributes.Replace(item, newItem))
{
return true;
}
}
}
if (_parameters != null)
{
ParameterDeclaration item = existing as ParameterDeclaration;
if (null != item)
{
ParameterDeclaration newItem = (ParameterDeclaration)newNode;
if (_parameters.Replace(item, newItem))
{
return true;
}
}
}
if (_genericParameters != null)
{
GenericParameterDeclaration item = existing as GenericParameterDeclaration;
if (null != item)
{
GenericParameterDeclaration newItem = (GenericParameterDeclaration)newNode;
if (_genericParameters.Replace(item, newItem))
{
return true;
}
}
}
if (_returnType == existing)
{
this.ReturnType = (TypeReference)newNode;
return true;
}
if (_returnTypeAttributes != null)
{
Attribute item = existing as Attribute;
if (null != item)
{
Attribute newItem = (Attribute)newNode;
if (_returnTypeAttributes.Replace(item, newItem))
{
return true;
}
}
}
return false;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override public object Clone()
{
CallableDefinition clone = (CallableDefinition)FormatterServices.GetUninitializedObject(typeof(CallableDefinition));
clone._lexicalInfo = _lexicalInfo;
clone._endSourceLocation = _endSourceLocation;
clone._documentation = _documentation;
clone._isSynthetic = _isSynthetic;
clone._entity = _entity;
if (_annotations != null) clone._annotations = (Hashtable)_annotations.Clone();
clone._modifiers = _modifiers;
clone._name = _name;
if (null != _attributes)
{
clone._attributes = _attributes.Clone() as AttributeCollection;
clone._attributes.InitializeParent(clone);
}
if (null != _parameters)
{
clone._parameters = _parameters.Clone() as ParameterDeclarationCollection;
clone._parameters.InitializeParent(clone);
}
if (null != _genericParameters)
{
clone._genericParameters = _genericParameters.Clone() as GenericParameterDeclarationCollection;
clone._genericParameters.InitializeParent(clone);
}
if (null != _returnType)
{
clone._returnType = _returnType.Clone() as TypeReference;
clone._returnType.InitializeParent(clone);
}
if (null != _returnTypeAttributes)
{
clone._returnTypeAttributes = _returnTypeAttributes.Clone() as AttributeCollection;
clone._returnTypeAttributes.InitializeParent(clone);
}
return clone;
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
override internal void ClearTypeSystemBindings()
{
_annotations = null;
_entity = null;
if (null != _attributes)
{
_attributes.ClearTypeSystemBindings();
}
if (null != _parameters)
{
_parameters.ClearTypeSystemBindings();
}
if (null != _genericParameters)
{
_genericParameters.ClearTypeSystemBindings();
}
if (null != _returnType)
{
_returnType.ClearTypeSystemBindings();
}
if (null != _returnTypeAttributes)
{
_returnTypeAttributes.ClearTypeSystemBindings();
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(ParameterDeclaration))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public ParameterDeclarationCollection Parameters
{
get { return _parameters ?? (_parameters = new ParameterDeclarationCollection(this)); }
set
{
if (_parameters != value)
{
_parameters = value;
if (null != _parameters)
{
_parameters.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(GenericParameterDeclaration))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public GenericParameterDeclarationCollection GenericParameters
{
get { return _genericParameters ?? (_genericParameters = new GenericParameterDeclarationCollection(this)); }
set
{
if (_genericParameters != value)
{
_genericParameters = value;
if (null != _genericParameters)
{
_genericParameters.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlElement]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public TypeReference ReturnType
{
get { return _returnType; }
set
{
if (_returnType != value)
{
_returnType = value;
if (null != _returnType)
{
_returnType.InitializeParent(this);
}
}
}
}
[System.Xml.Serialization.XmlArray]
[System.Xml.Serialization.XmlArrayItem(typeof(Attribute))]
[System.CodeDom.Compiler.GeneratedCodeAttribute("astgen.boo", "1")]
public AttributeCollection ReturnTypeAttributes
{
get { return _returnTypeAttributes ?? (_returnTypeAttributes = new AttributeCollection(this)); }
set
{
if (_returnTypeAttributes != value)
{
_returnTypeAttributes = value;
if (null != _returnTypeAttributes)
{
_returnTypeAttributes.InitializeParent(this);
}
}
}
}
}
}
| |
// ----------------------------------------------------------------------------
// <copyright file="PhotonEditor.cs" company="Exit Games GmbH">
// PhotonNetwork Framework for Unity - Copyright (C) 2011 Exit Games GmbH
// </copyright>
// <summary>
// MenuItems and in-Editor scripts for PhotonNetwork.
// </summary>
// <author>developer@exitgames.com</author>
// ----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using ExitGames.Client.Photon;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
public class PunWizardText
{
public string WindowTitle = "PUN Wizard";
public string SetupWizardWarningTitle = "Warning";
public string SetupWizardWarningMessage = "You have not yet run the Photon setup wizard! Your game won't be able to connect. See Windows -> Photon Unity Networking.";
public string MainMenuButton = "Main Menu";
public string SetupWizardTitle = "PUN Setup";
public string SetupWizardInfo = "Thanks for importing Photon Unity Networking.\nThis window should set you up.\n\n<b>-</b> To use an existing Photon Cloud App, enter your AppId.\n<b>-</b> To register an account or access an existing one, enter the account's mail address.\n<b>-</b> To use Photon OnPremise, skip this step.";
public string EmailOrAppIdLabel = "AppId or Email";
public string AlreadyRegisteredInfo = "The email is registered so we can't fetch your AppId (without password).\n\nPlease login online to get your AppId and paste it above.";
public string SkipRegistrationInfo = "Skipping? No problem:\nEdit your server settings in the PhotonServerSettings file.";
public string RegisteredNewAccountInfo = "We created a (free) account and fetched you an AppId.\nWelcome. Your PUN project is setup.";
public string AppliedToSettingsInfo = "Your AppId is now applied to this project.";
public string SetupCompleteInfo = "<b>Done!</b>\nAll connection settings can be edited in the <b>PhotonServerSettings</b> now.\nHave a look.";
public string CloseWindowButton = "Close";
public string SkipButton = "Skip";
public string SetupButton = "Setup Project";
public string MobileExportNoteLabel = "Build for mobiles impossible. Get PUN+ or Unity Pro for mobile or use Unity 5.";
public string MobilePunPlusExportNoteLabel = "PUN+ available. Using native sockets for iOS/Android.";
public string CancelButton = "Cancel";
public string PUNWizardLabel = "PUN Wizard";
public string SettingsButton = "Settings";
public string SetupServerCloudLabel = "Setup wizard for setting up your own server or the cloud.";
public string WarningPhotonDisconnect = "";
public string StartButton = "Start";
public string LocateSettingsButton = "Locate PhotonServerSettings";
public string SettingsHighlightLabel = "Highlights the used photon settings file in the project.";
public string DocumentationLabel = "Documentation";
public string OpenPDFText = "Reference PDF";
public string OpenPDFTooltip = "Opens the local documentation pdf.";
public string OpenDevNetText = "DevNet / Manual";
public string OpenDevNetTooltip = "Online documentation for Photon.";
public string OpenCloudDashboardText = "Cloud Dashboard Login";
public string OpenCloudDashboardTooltip = "Review Cloud App information and statistics.";
public string OpenForumText = "Open Forum";
public string OpenForumTooltip = "Online support for Photon.";
public string OkButton = "Ok";
public string OwnHostCloudCompareLabel = "I am not quite sure how 'my own host' compares to 'cloud'.";
public string ComparisonPageButton = "Cloud versus OnPremise";
public string ConnectionTitle = "Connecting";
public string ConnectionInfo = "Connecting to the account service...";
public string ErrorTextTitle = "Error";
public string IncorrectRPCListTitle = "Warning: RPC-list becoming incompatible!";
public string IncorrectRPCListLabel = "Your project's RPC-list is full, so we can't add some RPCs just compiled.\n\nBy removing outdated RPCs, the list will be long enough but incompatible with older client builds!\n\nMake sure you change the game version where you use PhotonNetwork.ConnectUsingSettings().";
public string RemoveOutdatedRPCsLabel = "Remove outdated RPCs";
public string FullRPCListTitle = "Warning: RPC-list is full!";
public string FullRPCListLabel = "Your project's RPC-list is too long for PUN.\n\nYou can change PUN's source to use short-typed RPC index. Look for comments 'LIMITS RPC COUNT'\n\nAlternatively, remove some RPC methods (use more parameters per RPC maybe).\n\nAfter a RPC-list refresh, make sure you change the game version where you use PhotonNetwork.ConnectUsingSettings().";
public string SkipRPCListUpdateLabel = "Skip RPC-list update";
public string PUNNameReplaceTitle = "Warning: RPC-list Compatibility";
public string PUNNameReplaceLabel = "PUN replaces RPC names with numbers by using the RPC-list. All clients must use the same list for that.\n\nClearing it most likely makes your client incompatible with previous versions! Change your game version or make sure the RPC-list matches other clients.";
public string RPCListCleared = "Clear RPC-list";
public string ServerSettingsCleanedWarning = "Cleared the PhotonServerSettings.RpcList! This makes new builds incompatible with older ones. Better change game version in PhotonNetwork.ConnectUsingSettings().";
public string RpcFoundMessage = "Some code uses the obsolete RPC attribute. PUN now requires the PunRPC attribute to mark remote-callable methods.\nThe Editor can search and replace that code which will modify your source.";
public string RpcFoundDialogTitle = "RPC Attribute Outdated";
public string RpcReplaceButton = "Replace. I got a backup.";
public string RpcSkipReplace = "Not now.";
public string WizardMainWindowInfo = "This window should help you find important settings for PUN, as well as documentation.";
}
[InitializeOnLoad]
public class PhotonEditor : EditorWindow
{
protected static Type WindowType = typeof (PhotonEditor);
protected Vector2 scrollPos = Vector2.zero;
private readonly Vector2 preferredSize = new Vector2(350, 400);
private static Texture2D BackgroundImage;
public static PunWizardText CurrentLang = new PunWizardText();
protected static AccountService.Origin RegisterOrigin = AccountService.Origin.Pun;
protected static string DocumentationLocation = "Assets/Photon Unity Networking/PhotonNetwork-Documentation.pdf";
protected static string UrlFreeLicense = "https://www.photonengine.com/dashboard/OnPremise";
protected static string UrlDevNet = "http://doc.photonengine.com/en/pun/current";
protected static string UrlForum = "http://forum.exitgames.com";
protected static string UrlCompare = "http://doc.photonengine.com/en/realtime/current/getting-started/onpremise-or-saas";
protected static string UrlHowToSetup = "http://doc.photonengine.com/en/onpremise/current/getting-started/photon-server-in-5min";
protected static string UrlAppIDExplained = "http://doc.photonengine.com/en/realtime/current/getting-started/obtain-your-app-id";
protected static string UrlAccountPage = "https://www.photonengine.com/Account/SignIn?email="; // opened in browser
protected static string UrlCloudDashboard = "https://www.photonengine.com/dashboard?email=";
private enum PhotonSetupStates
{
MainUi,
RegisterForPhotonCloud,
EmailAlreadyRegistered,
GoEditPhotonServerSettings
}
private bool isSetupWizard = false;
private PhotonSetupStates photonSetupState = PhotonSetupStates.RegisterForPhotonCloud;
private bool minimumInput = false;
private bool useMail = false;
private bool useAppId = false;
private bool useSkip = false;
private bool highlightedSettings = false;
private bool close = false;
private string mailOrAppId = string.Empty;
private static double lastWarning = 0;
private static bool postCompileActionsDone;
private static bool isPunPlus;
private static bool androidLibExists;
private static bool iphoneLibExists;
// setup once on load
static PhotonEditor()
{
EditorApplication.projectWindowChanged += EditorUpdate;
EditorApplication.hierarchyWindowChanged += EditorUpdate;
EditorApplication.playmodeStateChanged += PlaymodeStateChanged;
EditorApplication.update += OnUpdate;
// detect optional packages
PhotonEditor.CheckPunPlus();
}
// setup per window
public PhotonEditor()
{
minSize = this.preferredSize;
}
[MenuItem("Window/Photon Unity Networking/PUN Wizard &p", false, 0)]
protected static void MenuItemOpenWizard()
{
PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor;
win.photonSetupState = PhotonSetupStates.MainUi;
win.isSetupWizard = false;
}
[MenuItem("Window/Photon Unity Networking/Highlight Server Settings %#&p", false, 1)]
protected static void MenuItemHighlightSettings()
{
HighlightSettings();
}
/// <summary>Creates an Editor window, showing the cloud-registration wizard for Photon (entry point to setup PUN).</summary>
protected static void ShowRegistrationWizard()
{
PhotonEditor win = GetWindow(WindowType, false, CurrentLang.WindowTitle, true) as PhotonEditor;
win.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud;
win.isSetupWizard = true;
}
// called 100 times / sec
private static void OnUpdate()
{
// after a compile, check RPCs to create a cache-list
if (!postCompileActionsDone && !EditorApplication.isCompiling && !EditorApplication.isPlayingOrWillChangePlaymode && PhotonNetwork.PhotonServerSettings != null)
{
#if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_5_0
if (EditorApplication.isUpdating)
{
return;
}
#endif
PhotonEditor.UpdateRpcList();
postCompileActionsDone = true; // on compile, this falls back to false (without actively doing anything)
#if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_5_0
PhotonEditor.ImportWin8Support();
#endif
}
}
// called in editor, opens wizard for initial setup, keeps scene PhotonViews up to date and closes connections when compiling (to avoid issues)
private static void EditorUpdate()
{
if (PhotonNetwork.PhotonServerSettings == null)
{
PhotonNetwork.CreateSettings();
}
if (PhotonNetwork.PhotonServerSettings == null)
{
return;
}
// serverSetting is null when the file gets deleted. otherwise, the wizard should only run once and only if hosting option is not (yet) set
if (!PhotonNetwork.PhotonServerSettings.DisableAutoOpenWizard && PhotonNetwork.PhotonServerSettings.HostType == ServerSettings.HostingOption.NotSet)
{
ShowRegistrationWizard();
PhotonNetwork.PhotonServerSettings.DisableAutoOpenWizard = true;
PhotonEditor.SaveSettings();
}
// Workaround for TCP crash. Plus this surpresses any other recompile errors.
if (EditorApplication.isCompiling)
{
if (PhotonNetwork.connected)
{
if (lastWarning > EditorApplication.timeSinceStartup - 3)
{
// Prevent error spam
Debug.LogWarning(CurrentLang.WarningPhotonDisconnect);
lastWarning = EditorApplication.timeSinceStartup;
}
PhotonNetwork.Disconnect();
}
}
}
// called in editor on change of play-mode (used to show a message popup that connection settings are incomplete)
private static void PlaymodeStateChanged()
{
if (EditorApplication.isPlaying || !EditorApplication.isPlayingOrWillChangePlaymode)
{
return;
}
if (PhotonNetwork.PhotonServerSettings.HostType == ServerSettings.HostingOption.NotSet)
{
EditorUtility.DisplayDialog(CurrentLang.SetupWizardWarningTitle, CurrentLang.SetupWizardWarningMessage, CurrentLang.OkButton);
}
}
#region GUI and Wizard
// Window Update() callback. On-demand, when Window is open
protected void Update()
{
if (this.close)
{
Close();
}
}
protected virtual void OnGUI()
{
if (BackgroundImage == null)
{
BackgroundImage = AssetDatabase.LoadAssetAtPath("Assets/Photon Unity Networking/Editor/PhotonNetwork/background.jpg", typeof(Texture2D)) as Texture2D;
}
PhotonSetupStates oldGuiState = this.photonSetupState; // used to fix an annoying Editor input field issue: wont refresh until focus is changed.
GUI.SetNextControlName("");
this.scrollPos = GUILayout.BeginScrollView(this.scrollPos);
if (this.photonSetupState == PhotonSetupStates.MainUi)
{
UiMainWizard();
}
else
{
UiSetupApp();
}
GUILayout.EndScrollView();
if (oldGuiState != this.photonSetupState)
{
GUI.FocusControl("");
}
}
protected virtual void UiSetupApp()
{
GUI.skin.label.wordWrap = true;
if (!this.isSetupWizard)
{
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(CurrentLang.MainMenuButton, GUILayout.ExpandWidth(false)))
{
this.photonSetupState = PhotonSetupStates.MainUi;
}
GUILayout.EndHorizontal();
}
// setup header
UiTitleBox(CurrentLang.SetupWizardTitle, BackgroundImage);
// setup info text
GUI.skin.label.richText = true;
GUILayout.Label(CurrentLang.SetupWizardInfo);
// input of appid or mail
EditorGUILayout.Separator();
GUILayout.Label(CurrentLang.EmailOrAppIdLabel);
this.mailOrAppId = EditorGUILayout.TextField(this.mailOrAppId).Trim(); // note: we trim all input
if (this.mailOrAppId.Contains("@"))
{
// this should be a mail address
this.minimumInput = (this.mailOrAppId.Length >= 5 && this.mailOrAppId.Contains("."));
this.useMail = this.minimumInput;
this.useAppId = false;
}
else
{
// this should be an appId
this.minimumInput = ServerSettings.IsAppId(this.mailOrAppId);
this.useMail = false;
this.useAppId = this.minimumInput;
}
// button to skip setup
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(CurrentLang.SkipButton, GUILayout.Width(100)))
{
this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings;
this.useSkip = true;
this.useMail = false;
this.useAppId = false;
}
// SETUP button
EditorGUI.BeginDisabledGroup(!this.minimumInput);
if (GUILayout.Button(CurrentLang.SetupButton, GUILayout.Width(100)))
{
this.useSkip = false;
GUIUtility.keyboardControl = 0;
if (this.useMail)
{
RegisterWithEmail(this.mailOrAppId); // sets state
}
if (this.useAppId)
{
this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings;
Undo.RecordObject(PhotonNetwork.PhotonServerSettings, "Update PhotonServerSettings for PUN");
PhotonNetwork.PhotonServerSettings.UseCloud(this.mailOrAppId);
PhotonEditor.SaveSettings();
}
}
EditorGUI.EndDisabledGroup();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
// existing account needs to fetch AppId online
if (this.photonSetupState == PhotonSetupStates.EmailAlreadyRegistered)
{
// button to open dashboard and get the AppId
GUILayout.Space(15);
GUILayout.Label(CurrentLang.AlreadyRegisteredInfo);
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip), GUILayout.Width(205)))
{
Application.OpenURL(UrlCloudDashboard + Uri.EscapeUriString(this.mailOrAppId));
this.mailOrAppId = "";
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
if (this.photonSetupState == PhotonSetupStates.GoEditPhotonServerSettings)
{
if (!this.highlightedSettings)
{
this.highlightedSettings = true;
HighlightSettings();
}
GUILayout.Space(15);
if (this.useSkip)
{
GUILayout.Label(CurrentLang.SkipRegistrationInfo);
}
else if (this.useMail)
{
GUILayout.Label(CurrentLang.RegisteredNewAccountInfo);
}
else if (this.useAppId)
{
GUILayout.Label(CurrentLang.AppliedToSettingsInfo);
}
// setup-complete info
GUILayout.Space(15);
GUILayout.Label(CurrentLang.SetupCompleteInfo);
// close window (done)
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
if (GUILayout.Button(CurrentLang.CloseWindowButton, GUILayout.Width(205)))
{
this.close = true;
}
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
}
GUI.skin.label.richText = false;
}
private void UiTitleBox(string title, Texture2D bgIcon)
{
GUIStyle bgStyle = new GUIStyle(GUI.skin.GetStyle("Label"));
bgStyle.normal.background = bgIcon;
bgStyle.fontSize = 22;
bgStyle.fontStyle = FontStyle.Bold;
EditorGUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
EditorGUILayout.EndHorizontal();
Rect scale = GUILayoutUtility.GetLastRect();
scale.height = 30;
GUI.Label(scale, title, bgStyle);
GUILayout.Space(scale.height+5);
}
protected virtual void UiMainWizard()
{
GUILayout.Space(15);
// title
UiTitleBox(CurrentLang.PUNWizardLabel, BackgroundImage);
// wizard info text
GUILayout.Label(CurrentLang.WizardMainWindowInfo);
GUILayout.Space(15);
// pun+ info
if (isPunPlus)
{
GUILayout.Label(CurrentLang.MobilePunPlusExportNoteLabel);
GUILayout.Space(15);
}
#if !(UNITY_5_0 || UNITY_5)
else if (!InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.Android) || !InternalEditorUtility.HasAdvancedLicenseOnBuildTarget(BuildTarget.iOS))
{
GUILayout.Label(CurrentLang.MobileExportNoteLabel);
GUILayout.Space(15);
}
#endif
// settings button
GUILayout.BeginHorizontal();
GUILayout.Label(CurrentLang.SettingsButton, EditorStyles.boldLabel, GUILayout.Width(100));
GUILayout.BeginVertical();
if (GUILayout.Button(new GUIContent(CurrentLang.LocateSettingsButton, CurrentLang.SettingsHighlightLabel)))
{
HighlightSettings();
}
if (GUILayout.Button(new GUIContent(CurrentLang.OpenCloudDashboardText, CurrentLang.OpenCloudDashboardTooltip)))
{
Application.OpenURL(UrlCloudDashboard + Uri.EscapeUriString(this.mailOrAppId));
}
if (GUILayout.Button(new GUIContent(CurrentLang.SetupButton, CurrentLang.SetupServerCloudLabel)))
{
this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud;
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
GUILayout.Space(15);
EditorGUILayout.Separator();
// documentation
GUILayout.BeginHorizontal();
GUILayout.Label(CurrentLang.DocumentationLabel, EditorStyles.boldLabel, GUILayout.Width(100));
GUILayout.BeginVertical();
if (GUILayout.Button(new GUIContent(CurrentLang.OpenPDFText, CurrentLang.OpenPDFTooltip)))
{
EditorUtility.OpenWithDefaultApp(DocumentationLocation);
}
if (GUILayout.Button(new GUIContent(CurrentLang.OpenDevNetText, CurrentLang.OpenDevNetTooltip)))
{
Application.OpenURL(UrlDevNet);
}
GUI.skin.label.wordWrap = true;
GUILayout.Label(CurrentLang.OwnHostCloudCompareLabel);
if (GUILayout.Button(CurrentLang.ComparisonPageButton))
{
Application.OpenURL(UrlCompare);
}
if (GUILayout.Button(new GUIContent(CurrentLang.OpenForumText, CurrentLang.OpenForumTooltip)))
{
Application.OpenURL(UrlForum);
}
GUILayout.EndVertical();
GUILayout.EndHorizontal();
}
#endregion
protected virtual void RegisterWithEmail(string email)
{
EditorUtility.DisplayProgressBar(CurrentLang.ConnectionTitle, CurrentLang.ConnectionInfo, 0.5f);
string accountServiceType = string.Empty;
if (PhotonEditorUtils.HasVoice)
{
accountServiceType = "voice";
}
AccountService client = new AccountService();
client.RegisterByEmail(email, RegisterOrigin, accountServiceType); // this is the synchronous variant using the static RegisterOrigin. "result" is in the client
EditorUtility.ClearProgressBar();
if (client.ReturnCode == 0)
{
this.mailOrAppId = client.AppId;
PhotonNetwork.PhotonServerSettings.UseCloud(this.mailOrAppId, 0);
if (PhotonEditorUtils.HasVoice)
{
PhotonNetwork.PhotonServerSettings.VoiceAppID = client.AppId2;
}
PhotonEditor.SaveSettings();
this.photonSetupState = PhotonSetupStates.GoEditPhotonServerSettings;
}
else
{
PhotonNetwork.PhotonServerSettings.HostType = ServerSettings.HostingOption.PhotonCloud;
PhotonEditor.SaveSettings();
Debug.LogWarning(client.Message + " ReturnCode: " + client.ReturnCode);
if (client.Message.Contains("registered"))
{
this.photonSetupState = PhotonSetupStates.EmailAlreadyRegistered;
}
else
{
EditorUtility.DisplayDialog(CurrentLang.ErrorTextTitle, client.Message, CurrentLang.OkButton);
this.photonSetupState = PhotonSetupStates.RegisterForPhotonCloud;
}
}
}
protected internal static bool CheckPunPlus()
{
androidLibExists = File.Exists("Assets/Plugins/Android/armeabi-v7a/libPhotonSocketPlugin.so") &&
File.Exists("Assets/Plugins/Android/x86/libPhotonSocketPlugin.so");
iphoneLibExists = File.Exists("Assets/Plugins/IOS/libPhotonSocketPlugin.a");
isPunPlus = androidLibExists || iphoneLibExists;
return isPunPlus;
}
private static void ImportWin8Support()
{
if (EditorApplication.isCompiling || EditorApplication.isPlayingOrWillChangePlaymode)
{
return; // don't import while compiling
}
#if UNITY_4_2 || UNITY_4_3 || UNITY_4_4 || UNITY_4_5 || UNITY_4_6 || UNITY_4_7 || UNITY_5 || UNITY_5_0
const string win8Package = "Assets/Plugins/Photon3Unity3D-Win8.unitypackage";
bool win8LibsExist = File.Exists("Assets/Plugins/WP8/Photon3Unity3D.dll") && File.Exists("Assets/Plugins/Metro/Photon3Unity3D.dll");
if (!win8LibsExist && File.Exists(win8Package))
{
AssetDatabase.ImportPackage(win8Package, false);
}
#endif
}
// Pings PhotonServerSettings and makes it selected (show in Inspector)
private static void HighlightSettings()
{
Selection.objects = new UnityEngine.Object[] { PhotonNetwork.PhotonServerSettings };
EditorGUIUtility.PingObject(PhotonNetwork.PhotonServerSettings);
}
// Marks settings object as dirty, so it gets saved.
// unity 5.3 changes the usecase for SetDirty(). but here we don't modify a scene object! so it's ok to use
private static void SaveSettings()
{
EditorUtility.SetDirty(PhotonNetwork.PhotonServerSettings);
}
#region RPC List Handling
public static void UpdateRpcList()
{
List<string> additionalRpcs = new List<string>();
HashSet<string> currentRpcs = new HashSet<string>();
var types = GetAllSubTypesInScripts(typeof(MonoBehaviour));
int countOldRpcs = 0;
foreach (var mono in types)
{
MethodInfo[] methods = mono.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
foreach (MethodInfo method in methods)
{
bool isOldRpc = false;
#pragma warning disable 618
// we let the Editor check for outdated RPC attributes in code. that should not cause a compile warning
//if (method.IsDefined(typeof (RPC), false))
//{
// countOldRpcs++;
// isOldRpc = true;
//}
#pragma warning restore 618
if (isOldRpc || method.IsDefined(typeof(PunRPC), false))
{
currentRpcs.Add(method.Name);
if (!additionalRpcs.Contains(method.Name) && !PhotonNetwork.PhotonServerSettings.RpcList.Contains(method.Name))
{
additionalRpcs.Add(method.Name);
}
}
}
}
if (additionalRpcs.Count > 0)
{
// LIMITS RPC COUNT
if (additionalRpcs.Count + PhotonNetwork.PhotonServerSettings.RpcList.Count >= byte.MaxValue)
{
if (currentRpcs.Count <= byte.MaxValue)
{
bool clearList = EditorUtility.DisplayDialog(CurrentLang.IncorrectRPCListTitle, CurrentLang.IncorrectRPCListLabel, CurrentLang.RemoveOutdatedRPCsLabel, CurrentLang.CancelButton);
if (clearList)
{
PhotonNetwork.PhotonServerSettings.RpcList.Clear();
PhotonNetwork.PhotonServerSettings.RpcList.AddRange(currentRpcs);
}
else
{
return;
}
}
else
{
EditorUtility.DisplayDialog(CurrentLang.FullRPCListTitle, CurrentLang.FullRPCListLabel, CurrentLang.SkipRPCListUpdateLabel);
return;
}
}
additionalRpcs.Sort();
Undo.RecordObject(PhotonNetwork.PhotonServerSettings, "Update PUN RPC-list");
PhotonNetwork.PhotonServerSettings.RpcList.AddRange(additionalRpcs);
PhotonEditor.SaveSettings();
}
if (countOldRpcs > 0)
{
bool convertRPCs = EditorUtility.DisplayDialog(CurrentLang.RpcFoundDialogTitle, CurrentLang.RpcFoundMessage, CurrentLang.RpcReplaceButton, CurrentLang.RpcSkipReplace);
if (convertRPCs)
{
PhotonConverter.ConvertRpcAttribute("");
}
}
}
public static void ClearRpcList()
{
bool clearList = EditorUtility.DisplayDialog(CurrentLang.PUNNameReplaceTitle, CurrentLang.PUNNameReplaceLabel, CurrentLang.RPCListCleared, CurrentLang.CancelButton);
if (clearList)
{
PhotonNetwork.PhotonServerSettings.RpcList.Clear();
Debug.LogWarning(CurrentLang.ServerSettingsCleanedWarning);
}
}
public static System.Type[] GetAllSubTypesInScripts(System.Type aBaseClass)
{
var result = new System.Collections.Generic.List<System.Type>();
System.Reflection.Assembly[] AS = System.AppDomain.CurrentDomain.GetAssemblies();
foreach (var A in AS)
{
// this skips all but the Unity-scripted assemblies for RPC-list creation. You could remove this to search all assemblies in project
if (!A.FullName.StartsWith("Assembly-"))
{
// Debug.Log("Skipping Assembly: " + A);
continue;
}
//Debug.Log("Assembly: " + A.FullName);
System.Type[] types = A.GetTypes();
foreach (var T in types)
{
if (T.IsSubclassOf(aBaseClass))
{
result.Add(T);
}
}
}
return result.ToArray();
}
#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.
/******************************************************************************
* This file is auto-generated from a template file by the GenerateTests.csx *
* script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make *
* changes, please update the corresponding template and run according to the *
* directions listed in the file. *
******************************************************************************/
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace JIT.HardwareIntrinsics.X86
{
public static partial class Program
{
private static void ShiftRightLogicalUInt3232()
{
var test = new SimpleUnaryOpTest__ShiftRightLogicalUInt3232();
if (test.IsSupported)
{
// Validates basic functionality works, using Unsafe.Read
test.RunBasicScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates basic functionality works, using Load
test.RunBasicScenario_Load();
// Validates basic functionality works, using LoadAligned
test.RunBasicScenario_LoadAligned();
}
// Validates calling via reflection works, using Unsafe.Read
test.RunReflectionScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates calling via reflection works, using Load
test.RunReflectionScenario_Load();
// Validates calling via reflection works, using LoadAligned
test.RunReflectionScenario_LoadAligned();
}
// Validates passing a static member works
test.RunClsVarScenario();
// Validates passing a local works, using Unsafe.Read
test.RunLclVarScenario_UnsafeRead();
if (Avx.IsSupported)
{
// Validates passing a local works, using Load
test.RunLclVarScenario_Load();
// Validates passing a local works, using LoadAligned
test.RunLclVarScenario_LoadAligned();
}
// Validates passing the field of a local works
test.RunLclFldScenario();
// Validates passing an instance member works
test.RunFldScenario();
}
else
{
// Validates we throw on unsupported hardware
test.RunUnsupportedScenario();
}
if (!test.Succeeded)
{
throw new Exception("One or more scenarios did not complete as expected.");
}
}
}
public sealed unsafe class SimpleUnaryOpTest__ShiftRightLogicalUInt3232
{
private const int VectorSize = 32;
private const int Op1ElementCount = VectorSize / sizeof(UInt32);
private const int RetElementCount = VectorSize / sizeof(UInt32);
private static UInt32[] _data = new UInt32[Op1ElementCount];
private static Vector256<UInt32> _clsVar;
private Vector256<UInt32> _fld;
private SimpleUnaryOpTest__DataTable<UInt32, UInt32> _dataTable;
static SimpleUnaryOpTest__ShiftRightLogicalUInt3232()
{
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _clsVar), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize);
}
public SimpleUnaryOpTest__ShiftRightLogicalUInt3232()
{
Succeeded = true;
var random = new Random();
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<UInt32>, byte>(ref _fld), ref Unsafe.As<UInt32, byte>(ref _data[0]), VectorSize);
for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (uint)(random.Next(0, int.MaxValue)); }
_dataTable = new SimpleUnaryOpTest__DataTable<UInt32, UInt32>(_data, new UInt32[RetElementCount], VectorSize);
}
public bool IsSupported => Avx2.IsSupported;
public bool Succeeded { get; set; }
public void RunBasicScenario_UnsafeRead()
{
var result = Avx2.ShiftRightLogical(
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_Load()
{
var result = Avx2.ShiftRightLogical(
Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunBasicScenario_LoadAligned()
{
var result = Avx2.ShiftRightLogical(
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)),
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_UnsafeRead()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_Load()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunReflectionScenario_LoadAligned()
{
var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftRightLogical), new Type[] { typeof(Vector256<UInt32>), typeof(byte) })
.Invoke(null, new object[] {
Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr)),
(byte)32
});
Unsafe.Write(_dataTable.outArrayPtr, (Vector256<UInt32>)(result));
ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr);
}
public void RunClsVarScenario()
{
var result = Avx2.ShiftRightLogical(
_clsVar,
32
);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_clsVar, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_UnsafeRead()
{
var firstOp = Unsafe.Read<Vector256<UInt32>>(_dataTable.inArrayPtr);
var result = Avx2.ShiftRightLogical(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_Load()
{
var firstOp = Avx.LoadVector256((UInt32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclVarScenario_LoadAligned()
{
var firstOp = Avx.LoadAlignedVector256((UInt32*)(_dataTable.inArrayPtr));
var result = Avx2.ShiftRightLogical(firstOp, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(firstOp, _dataTable.outArrayPtr);
}
public void RunLclFldScenario()
{
var test = new SimpleUnaryOpTest__ShiftRightLogicalUInt3232();
var result = Avx2.ShiftRightLogical(test._fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(test._fld, _dataTable.outArrayPtr);
}
public void RunFldScenario()
{
var result = Avx2.ShiftRightLogical(_fld, 32);
Unsafe.Write(_dataTable.outArrayPtr, result);
ValidateResult(_fld, _dataTable.outArrayPtr);
}
public void RunUnsupportedScenario()
{
Succeeded = false;
try
{
RunBasicScenario_UnsafeRead();
}
catch (PlatformNotSupportedException)
{
Succeeded = true;
}
}
private void ValidateResult(Vector256<UInt32> firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "")
{
UInt32[] inArray = new UInt32[Op1ElementCount];
UInt32[] outArray = new UInt32[RetElementCount];
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize);
Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize);
ValidateResult(inArray, outArray, method);
}
private void ValidateResult(UInt32[] firstOp, UInt32[] result, [CallerMemberName] string method = "")
{
if (0 != result[0])
{
Succeeded = false;
}
else
{
for (var i = 1; i < RetElementCount; i++)
{
if (0!= result[i])
{
Succeeded = false;
break;
}
}
}
if (!Succeeded)
{
Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.ShiftRightLogical)}<UInt32>(Vector256<UInt32><9>): {method} failed:");
Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})");
Console.WriteLine($" result: ({string.Join(", ", result)})");
Console.WriteLine();
}
}
}
}
| |
/*
* 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 ec2-2014-10-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.EC2.Model
{
/// <summary>
///
/// </summary>
public partial class ImportInstanceLaunchSpecification
{
private string _additionalInfo;
private ArchitectureValues _architecture;
private List<string> _groupIds = new List<string>();
private List<string> _groupNames = new List<string>();
private ShutdownBehavior _instanceInitiatedShutdownBehavior;
private InstanceType _instanceType;
private bool? _monitoring;
private Placement _placement;
private string _privateIpAddress;
private string _subnetId;
private UserData _userData;
/// <summary>
/// Gets and sets the property AdditionalInfo.
/// </summary>
public string AdditionalInfo
{
get { return this._additionalInfo; }
set { this._additionalInfo = value; }
}
// Check to see if AdditionalInfo property is set
internal bool IsSetAdditionalInfo()
{
return this._additionalInfo != null;
}
/// <summary>
/// Gets and sets the property Architecture.
/// <para>
/// The architecture of the instance.
/// </para>
/// </summary>
public ArchitectureValues Architecture
{
get { return this._architecture; }
set { this._architecture = value; }
}
// Check to see if Architecture property is set
internal bool IsSetArchitecture()
{
return this._architecture != null;
}
/// <summary>
/// Gets and sets the property GroupIds.
/// <para>
/// One or more security group IDs.
/// </para>
/// </summary>
public List<string> GroupIds
{
get { return this._groupIds; }
set { this._groupIds = value; }
}
// Check to see if GroupIds property is set
internal bool IsSetGroupIds()
{
return this._groupIds != null && this._groupIds.Count > 0;
}
/// <summary>
/// Gets and sets the property GroupNames.
/// <para>
/// One or more security group names.
/// </para>
/// </summary>
public List<string> GroupNames
{
get { return this._groupNames; }
set { this._groupNames = value; }
}
// Check to see if GroupNames property is set
internal bool IsSetGroupNames()
{
return this._groupNames != null && this._groupNames.Count > 0;
}
/// <summary>
/// Gets and sets the property InstanceInitiatedShutdownBehavior.
/// <para>
/// Indicates whether an instance stops or terminates when you initiate shutdown from
/// the instance (using the operating system command for system shutdown).
/// </para>
/// </summary>
public ShutdownBehavior InstanceInitiatedShutdownBehavior
{
get { return this._instanceInitiatedShutdownBehavior; }
set { this._instanceInitiatedShutdownBehavior = value; }
}
// Check to see if InstanceInitiatedShutdownBehavior property is set
internal bool IsSetInstanceInitiatedShutdownBehavior()
{
return this._instanceInitiatedShutdownBehavior != null;
}
/// <summary>
/// Gets and sets the property InstanceType.
/// <para>
/// The instance type. This is not supported for VMs imported into a VPC, which are assigned
/// the default security group. After a VM is imported into a VPC, you can specify another
/// security group using the AWS Management Console. For more information, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instance-types.html">Instance
/// Types</a> in the <i>Amazon Elastic Compute Cloud User Guide for Linux</i>. For more
/// information about the Linux instance types you can import, see <a href="http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/VMImportPrerequisites.html">Before
/// You Get Started</a> in the Amazon Elastic Compute Cloud User Guide for Linux.
/// </para>
/// </summary>
public InstanceType InstanceType
{
get { return this._instanceType; }
set { this._instanceType = value; }
}
// Check to see if InstanceType property is set
internal bool IsSetInstanceType()
{
return this._instanceType != null;
}
/// <summary>
/// Gets and sets the property Monitoring.
/// </summary>
public bool Monitoring
{
get { return this._monitoring.GetValueOrDefault(); }
set { this._monitoring = value; }
}
// Check to see if Monitoring property is set
internal bool IsSetMonitoring()
{
return this._monitoring.HasValue;
}
/// <summary>
/// Gets and sets the property Placement.
/// </summary>
public Placement Placement
{
get { return this._placement; }
set { this._placement = value; }
}
// Check to see if Placement property is set
internal bool IsSetPlacement()
{
return this._placement != null;
}
/// <summary>
/// Gets and sets the property PrivateIpAddress.
/// <para>
/// [EC2-VPC] Optionally, you can use this parameter to assign the instance a specific
/// available IP address from the IP address range of the subnet.
/// </para>
/// </summary>
public string PrivateIpAddress
{
get { return this._privateIpAddress; }
set { this._privateIpAddress = value; }
}
// Check to see if PrivateIpAddress property is set
internal bool IsSetPrivateIpAddress()
{
return this._privateIpAddress != null;
}
/// <summary>
/// Gets and sets the property SubnetId.
/// <para>
/// [EC2-VPC] The ID of the subnet to launch the instance into.
/// </para>
/// </summary>
public string SubnetId
{
get { return this._subnetId; }
set { this._subnetId = value; }
}
// Check to see if SubnetId property is set
internal bool IsSetSubnetId()
{
return this._subnetId != null;
}
/// <summary>
/// Gets and sets the property UserData.
/// <para>
/// User data to be made available to the instance.
/// </para>
/// </summary>
public UserData UserData
{
get { return this._userData; }
set { this._userData = value; }
}
// Check to see if UserData property is set
internal bool IsSetUserData()
{
return this._userData != null;
}
}
}
| |
// 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.Diagnostics;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Text;
namespace System.IO
{
// Class for creating FileStream objects, and some basic file management
// routines such as Delete, etc.
[ComVisible(true)]
public sealed class FileInfo : FileSystemInfo
{
private String _name;
[System.Security.SecurityCritical]
private FileInfo() { }
[System.Security.SecuritySafeCritical]
public FileInfo(String fileName)
{
if (fileName == null)
throw new ArgumentNullException("fileName");
Contract.EndContractBlock();
Init(fileName);
}
[System.Security.SecurityCritical]
private void Init(String fileName)
{
OriginalPath = fileName;
// Must fully qualify the path for the security check
String fullPath = PathHelpers.GetFullPathInternal(fileName);
_name = Path.GetFileName(fileName);
FullPath = fullPath;
DisplayPath = GetDisplayPath(fileName);
}
private String GetDisplayPath(String originalPath)
{
return originalPath;
}
[System.Security.SecuritySafeCritical]
internal FileInfo(String fullPath, IFileSystemObject fileSystemObject) : base(fileSystemObject)
{
Debug.Assert(Path.IsPathRooted(fullPath), "fullPath must be fully qualified!");
_name = Path.GetFileName(fullPath);
OriginalPath = _name;
FullPath = fullPath;
DisplayPath = _name;
}
public override String Name
{
get { return _name; }
}
public long Length
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
if ((FileSystemObject.Attributes & FileAttributes.Directory) == FileAttributes.Directory)
{
throw new FileNotFoundException(SR.Format(SR.IO_FileNotFound_FileName, DisplayPath), DisplayPath);
}
return FileSystemObject.Length;
}
}
/* Returns the name of the directory that the file is in */
public String DirectoryName
{
[System.Security.SecuritySafeCritical]
get
{
return Path.GetDirectoryName(FullPath);
}
}
/* Creates an instance of the the parent directory */
public DirectoryInfo Directory
{
get
{
String dirName = DirectoryName;
if (dirName == null)
return null;
return new DirectoryInfo(dirName);
}
}
public bool IsReadOnly
{
get
{
return (Attributes & FileAttributes.ReadOnly) != 0;
}
set
{
if (value)
Attributes |= FileAttributes.ReadOnly;
else
Attributes &= ~FileAttributes.ReadOnly;
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public StreamReader OpenText()
{
Stream stream = FileStream.InternalOpen(FullPath);
return new StreamReader(stream, Encoding.UTF8, true);
}
public StreamWriter CreateText()
{
Stream stream = FileStream.InternalCreate(FullPath);
return new StreamWriter(stream);
}
public StreamWriter AppendText()
{
Stream stream = FileStream.InternalAppend(FullPath);
return new StreamWriter(stream);
}
// Copies an existing file to a new file. An exception is raised if the
// destination file already exists. Use the
// Copy(String, String, boolean) method to allow
// overwriting an existing file.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName
// and Write permissions to destFileName.
//
public FileInfo CopyTo(String destFileName)
{
if (destFileName == null)
throw new ArgumentNullException("destFileName", SR.ArgumentNull_FileName);
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "destFileName");
Contract.EndContractBlock();
destFileName = File.InternalCopy(FullPath, destFileName, false);
return new FileInfo(destFileName, null);
}
// Copies an existing file to a new file. If overwrite is
// false, then an IOException is thrown if the destination file
// already exists. If overwrite is true, the file is
// overwritten.
//
// The caller must have certain FileIOPermissions. The caller must have
// Read permission to sourceFileName and Create
// and Write permissions to destFileName.
//
public FileInfo CopyTo(String destFileName, bool overwrite)
{
if (destFileName == null)
throw new ArgumentNullException("destFileName", SR.ArgumentNull_FileName);
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "destFileName");
Contract.EndContractBlock();
destFileName = File.InternalCopy(FullPath, destFileName, overwrite);
return new FileInfo(destFileName, null);
}
public FileStream Create()
{
return File.Create(FullPath);
}
// Deletes a file. The file specified by the designated path is deleted.
// If the file does not exist, Delete succeeds without throwing
// an exception.
//
// On NT, Delete will fail for a file that is open for normal I/O
// or a file that is memory mapped. On Win95, the file will be
// deleted irregardless of whether the file is being used.
//
// Your application must have Delete permission to the target file.
//
[System.Security.SecuritySafeCritical]
public override void Delete()
{
FileSystem.Current.DeleteFile(FullPath);
}
// Tests if the given file exists. The result is true if the file
// given by the specified path exists; otherwise, the result is
// false.
//
// Your application must have Read permission for the target directory.
public override bool Exists
{
[System.Security.SecuritySafeCritical] // auto-generated
get
{
try
{
return FileSystemObject.Exists;
}
catch
{
return false;
}
}
}
// User must explicitly specify opening a new file or appending to one.
public FileStream Open(FileMode mode)
{
return Open(mode, FileAccess.ReadWrite, FileShare.None);
}
public FileStream Open(FileMode mode, FileAccess access)
{
return Open(mode, access, FileShare.None);
}
public FileStream Open(FileMode mode, FileAccess access, FileShare share)
{
return new FileStream(FullPath, mode, access, share);
}
[System.Security.SecuritySafeCritical] // auto-generated
public FileStream OpenRead()
{
return new FileStream(FullPath, FileMode.Open, FileAccess.Read,
FileShare.Read, 4096, false);
}
public FileStream OpenWrite()
{
return new FileStream(FullPath, FileMode.OpenOrCreate,
FileAccess.Write, FileShare.None);
}
// Moves a given file to a new location and potentially a new file name.
// This method does work across volumes.
//
// The caller must have certain FileIOPermissions. The caller must
// have Read and Write permission to
// sourceFileName and Write
// permissions to destFileName.
//
[System.Security.SecuritySafeCritical]
public void MoveTo(String destFileName)
{
if (destFileName == null)
throw new ArgumentNullException("destFileName");
if (destFileName.Length == 0)
throw new ArgumentException(SR.Argument_EmptyFileName, "destFileName");
Contract.EndContractBlock();
String fullDestFileName = PathHelpers.GetFullPathInternal(destFileName);
FileSystem.Current.MoveFile(FullPath, fullDestFileName);
FullPath = fullDestFileName;
OriginalPath = destFileName;
_name = Path.GetFileName(fullDestFileName);
DisplayPath = GetDisplayPath(destFileName);
// Flush any cached information about the file.
Invalidate();
}
// Returns the display path
public override String ToString()
{
return DisplayPath;
}
}
}
| |
/*
* Exchange Web Services Managed API
*
* 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.
*/
namespace Microsoft.Exchange.WebServices.Data
{
using System;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// Represents a generic item. Properties available on items are defined in the ItemSchema class.
/// </summary>
[Attachable]
[ServiceObjectDefinition(XmlElementNames.Item)]
public class Item : ServiceObject
{
private ItemAttachment parentAttachment;
/// <summary>
/// Initializes an unsaved local instance of <see cref="Item"/>. To bind to an existing item, use Item.Bind() instead.
/// </summary>
/// <param name="service">The ExchangeService object to which the item will be bound.</param>
internal Item(ExchangeService service)
: base(service)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="Item"/> class.
/// </summary>
/// <param name="parentAttachment">The parent attachment.</param>
internal Item(ItemAttachment parentAttachment)
: this(parentAttachment.Service)
{
EwsUtilities.Assert(
parentAttachment != null,
"Item.ctor",
"parentAttachment is null");
this.parentAttachment = parentAttachment;
}
/// <summary>
/// Binds to an existing item, whatever its actual type is, and loads the specified set of properties.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="service">The service to use to bind to the item.</param>
/// <param name="id">The Id of the item to bind to.</param>
/// <param name="propertySet">The set of properties to load.</param>
/// <returns>An Item instance representing the item corresponding to the specified Id.</returns>
public static Item Bind(
ExchangeService service,
ItemId id,
PropertySet propertySet)
{
return service.BindToItem<Item>(id, propertySet);
}
/// <summary>
/// Binds to an existing item, whatever its actual type is, and loads its first class properties.
/// Calling this method results in a call to EWS.
/// </summary>
/// <param name="service">The service to use to bind to the item.</param>
/// <param name="id">The Id of the item to bind to.</param>
/// <returns>An Item instance representing the item corresponding to the specified Id.</returns>
public static Item Bind(ExchangeService service, ItemId id)
{
return Item.Bind(
service,
id,
PropertySet.FirstClassProperties);
}
/// <summary>
/// Internal method to return the schema associated with this type of object.
/// </summary>
/// <returns>The schema associated with this type of object.</returns>
internal override ServiceObjectSchema GetSchema()
{
return ItemSchema.Instance;
}
/// <summary>
/// Gets the minimum required server version.
/// </summary>
/// <returns>Earliest Exchange version in which this service object type is supported.</returns>
internal override ExchangeVersion GetMinimumRequiredServerVersion()
{
return ExchangeVersion.Exchange2007_SP1;
}
/// <summary>
/// Throws exception if this is attachment.
/// </summary>
internal void ThrowIfThisIsAttachment()
{
if (this.IsAttachment)
{
throw new InvalidOperationException(Strings.OperationDoesNotSupportAttachments);
}
}
/// <summary>
/// The property definition for the Id of this object.
/// </summary>
/// <returns>A PropertyDefinition instance.</returns>
internal override PropertyDefinition GetIdPropertyDefinition()
{
return ItemSchema.Id;
}
/// <summary>
/// Loads the specified set of properties on the object.
/// </summary>
/// <param name="propertySet">The properties to load.</param>
internal override void InternalLoad(PropertySet propertySet)
{
this.ThrowIfThisIsNew();
this.ThrowIfThisIsAttachment();
this.Service.InternalLoadPropertiesForItems(
new Item[] { this },
propertySet,
ServiceErrorHandling.ThrowOnError);
}
/// <summary>
/// Deletes the object.
/// </summary>
/// <param name="deleteMode">The deletion mode.</param>
/// <param name="sendCancellationsMode">Indicates whether meeting cancellation messages should be sent.</param>
/// <param name="affectedTaskOccurrences">Indicate which occurrence of a recurring task should be deleted.</param>
internal override void InternalDelete(
DeleteMode deleteMode,
SendCancellationsMode? sendCancellationsMode,
AffectedTaskOccurrence? affectedTaskOccurrences)
{
this.InternalDelete(deleteMode, sendCancellationsMode, affectedTaskOccurrences, false);
}
/// <summary>
/// Deletes the object.
/// </summary>
/// <param name="deleteMode">The deletion mode.</param>
/// <param name="sendCancellationsMode">Indicates whether meeting cancellation messages should be sent.</param>
/// <param name="affectedTaskOccurrences">Indicate which occurrence of a recurring task should be deleted.</param>
/// <param name="suppressReadReceipts">Whether to suppress read receipts</param>
internal void InternalDelete(
DeleteMode deleteMode,
SendCancellationsMode? sendCancellationsMode,
AffectedTaskOccurrence? affectedTaskOccurrences,
bool suppressReadReceipts)
{
this.ThrowIfThisIsNew();
this.ThrowIfThisIsAttachment();
// If sendCancellationsMode is null, use the default value that's appropriate for item type.
if (!sendCancellationsMode.HasValue)
{
sendCancellationsMode = this.DefaultSendCancellationsMode;
}
// If affectedTaskOccurrences is null, use the default value that's appropriate for item type.
if (!affectedTaskOccurrences.HasValue)
{
affectedTaskOccurrences = this.DefaultAffectedTaskOccurrences;
}
this.Service.DeleteItem(
this.Id,
deleteMode,
sendCancellationsMode,
affectedTaskOccurrences,
suppressReadReceipts);
}
/// <summary>
/// Create item.
/// </summary>
/// <param name="parentFolderId">The parent folder id.</param>
/// <param name="messageDisposition">The message disposition.</param>
/// <param name="sendInvitationsMode">The send invitations mode.</param>
internal void InternalCreate(
FolderId parentFolderId,
MessageDisposition? messageDisposition,
SendInvitationsMode? sendInvitationsMode)
{
this.ThrowIfThisIsNotNew();
this.ThrowIfThisIsAttachment();
if (this.IsNew || this.IsDirty)
{
this.Service.CreateItem(
this,
parentFolderId,
messageDisposition,
sendInvitationsMode.HasValue ? sendInvitationsMode : this.DefaultSendInvitationsMode);
this.Attachments.Save();
}
}
/// <summary>
/// Update item.
/// </summary>
/// <param name="parentFolderId">The parent folder id.</param>
/// <param name="conflictResolutionMode">The conflict resolution mode.</param>
/// <param name="messageDisposition">The message disposition.</param>
/// <param name="sendInvitationsOrCancellationsMode">The send invitations or cancellations mode.</param>
/// <returns>Updated item.</returns>
internal Item InternalUpdate(
FolderId parentFolderId,
ConflictResolutionMode conflictResolutionMode,
MessageDisposition? messageDisposition,
SendInvitationsOrCancellationsMode? sendInvitationsOrCancellationsMode)
{
return this.InternalUpdate(parentFolderId, conflictResolutionMode, messageDisposition, sendInvitationsOrCancellationsMode, false);
}
/// <summary>
/// Update item.
/// </summary>
/// <param name="parentFolderId">The parent folder id.</param>
/// <param name="conflictResolutionMode">The conflict resolution mode.</param>
/// <param name="messageDisposition">The message disposition.</param>
/// <param name="sendInvitationsOrCancellationsMode">The send invitations or cancellations mode.</param>
/// <param name="suppressReadReceipts">Whether to suppress read receipts</param>
/// <returns>Updated item.</returns>
internal Item InternalUpdate(
FolderId parentFolderId,
ConflictResolutionMode conflictResolutionMode,
MessageDisposition? messageDisposition,
SendInvitationsOrCancellationsMode? sendInvitationsOrCancellationsMode,
bool suppressReadReceipts)
{
this.ThrowIfThisIsNew();
this.ThrowIfThisIsAttachment();
Item returnedItem = null;
if (this.IsDirty && this.PropertyBag.GetIsUpdateCallNecessary())
{
returnedItem = this.Service.UpdateItem(
this,
parentFolderId,
conflictResolutionMode,
messageDisposition,
sendInvitationsOrCancellationsMode.HasValue ? sendInvitationsOrCancellationsMode : this.DefaultSendInvitationsOrCancellationsMode,
suppressReadReceipts);
}
// Regardless of whether item is dirty or not, if it has unprocessed
// attachment changes, validate them and process now.
if (this.HasUnprocessedAttachmentChanges())
{
this.Attachments.Validate();
this.Attachments.Save();
}
return returnedItem;
}
/// <summary>
/// Gets a value indicating whether this instance has unprocessed attachment collection changes.
/// </summary>
internal bool HasUnprocessedAttachmentChanges()
{
return this.Attachments.HasUnprocessedChanges();
}
/// <summary>
/// Gets the parent attachment of this item.
/// </summary>
internal ItemAttachment ParentAttachment
{
get { return this.parentAttachment; }
}
/// <summary>
/// Gets Id of the root item for this item.
/// </summary>
internal ItemId RootItemId
{
get
{
if (this.IsAttachment && this.ParentAttachment.Owner != null)
{
return this.ParentAttachment.Owner.RootItemId;
}
else
{
return this.Id;
}
}
}
/// <summary>
/// Deletes the item. Calling this method results in a call to EWS.
/// </summary>
/// <param name="deleteMode">The deletion mode.</param>
public void Delete(DeleteMode deleteMode)
{
this.Delete(deleteMode, false);
}
/// <summary>
/// Deletes the item. Calling this method results in a call to EWS.
/// </summary>
/// <param name="deleteMode">The deletion mode.</param>
/// <param name="suppressReadReceipts">Whether to suppress read receipts</param>
public void Delete(DeleteMode deleteMode, bool suppressReadReceipts)
{
this.InternalDelete(deleteMode, null, null, suppressReadReceipts);
}
/// <summary>
/// Saves this item in a specific folder. Calling this method results in at least one call to EWS.
/// Mutliple calls to EWS might be made if attachments have been added.
/// </summary>
/// <param name="parentFolderId">The Id of the folder in which to save this item.</param>
public void Save(FolderId parentFolderId)
{
EwsUtilities.ValidateParam(parentFolderId, "parentFolderId");
this.InternalCreate(
parentFolderId,
MessageDisposition.SaveOnly,
null);
}
/// <summary>
/// Saves this item in a specific folder. Calling this method results in at least one call to EWS.
/// Mutliple calls to EWS might be made if attachments have been added.
/// </summary>
/// <param name="parentFolderName">The name of the folder in which to save this item.</param>
public void Save(WellKnownFolderName parentFolderName)
{
this.InternalCreate(
new FolderId(parentFolderName),
MessageDisposition.SaveOnly,
null);
}
/// <summary>
/// Saves this item in the default folder based on the item's type (for example, an e-mail message is saved to the Drafts folder).
/// Calling this method results in at least one call to EWS. Mutliple calls to EWS might be made if attachments have been added.
/// </summary>
public void Save()
{
this.InternalCreate(
null,
MessageDisposition.SaveOnly,
null);
}
/// <summary>
/// Applies the local changes that have been made to this item. Calling this method results in at least one call to EWS.
/// Mutliple calls to EWS might be made if attachments have been added or removed.
/// </summary>
/// <param name="conflictResolutionMode">The conflict resolution mode.</param>
public void Update(ConflictResolutionMode conflictResolutionMode)
{
this.Update(conflictResolutionMode, false);
}
/// <summary>
/// Applies the local changes that have been made to this item. Calling this method results in at least one call to EWS.
/// Mutliple calls to EWS might be made if attachments have been added or removed.
/// </summary>
/// <param name="conflictResolutionMode">The conflict resolution mode.</param>
/// <param name="suppressReadReceipts">Whether to suppress read receipts</param>
public void Update(ConflictResolutionMode conflictResolutionMode, bool suppressReadReceipts)
{
this.InternalUpdate(
null /* parentFolder */,
conflictResolutionMode,
MessageDisposition.SaveOnly,
null,
suppressReadReceipts);
}
/// <summary>
/// Creates a copy of this item in the specified folder. Calling this method results in a call to EWS.
/// <para>
/// Copy returns null if the copy operation is across two mailboxes or between a mailbox and a
/// public folder.
/// </para>
/// </summary>
/// <param name="destinationFolderId">The Id of the folder in which to create a copy of this item.</param>
/// <returns>The copy of this item.</returns>
public Item Copy(FolderId destinationFolderId)
{
this.ThrowIfThisIsNew();
this.ThrowIfThisIsAttachment();
EwsUtilities.ValidateParam(destinationFolderId, "destinationFolderId");
return this.Service.CopyItem(this.Id, destinationFolderId);
}
/// <summary>
/// Creates a copy of this item in the specified folder. Calling this method results in a call to EWS.
/// <para>
/// Copy returns null if the copy operation is across two mailboxes or between a mailbox and a
/// public folder.
/// </para>
/// </summary>
/// <param name="destinationFolderName">The name of the folder in which to create a copy of this item.</param>
/// <returns>The copy of this item.</returns>
public Item Copy(WellKnownFolderName destinationFolderName)
{
return this.Copy(new FolderId(destinationFolderName));
}
/// <summary>
/// Moves this item to a the specified folder. Calling this method results in a call to EWS.
/// <para>
/// Move returns null if the move operation is across two mailboxes or between a mailbox and a
/// public folder.
/// </para>
/// </summary>
/// <param name="destinationFolderId">The Id of the folder to which to move this item.</param>
/// <returns>The moved copy of this item.</returns>
public Item Move(FolderId destinationFolderId)
{
this.ThrowIfThisIsNew();
this.ThrowIfThisIsAttachment();
EwsUtilities.ValidateParam(destinationFolderId, "destinationFolderId");
return this.Service.MoveItem(this.Id, destinationFolderId);
}
/// <summary>
/// Moves this item to a the specified folder. Calling this method results in a call to EWS.
/// <para>
/// Move returns null if the move operation is across two mailboxes or between a mailbox and a
/// public folder.
/// </para>
/// </summary>
/// <param name="destinationFolderName">The name of the folder to which to move this item.</param>
/// <returns>The moved copy of this item.</returns>
public Item Move(WellKnownFolderName destinationFolderName)
{
return this.Move(new FolderId(destinationFolderName));
}
/// <summary>
/// Sets the extended property.
/// </summary>
/// <param name="extendedPropertyDefinition">The extended property definition.</param>
/// <param name="value">The value.</param>
public void SetExtendedProperty(ExtendedPropertyDefinition extendedPropertyDefinition, object value)
{
this.ExtendedProperties.SetExtendedProperty(extendedPropertyDefinition, value);
}
/// <summary>
/// Removes an extended property.
/// </summary>
/// <param name="extendedPropertyDefinition">The extended property definition.</param>
/// <returns>True if property was removed.</returns>
public bool RemoveExtendedProperty(ExtendedPropertyDefinition extendedPropertyDefinition)
{
return this.ExtendedProperties.RemoveExtendedProperty(extendedPropertyDefinition);
}
/// <summary>
/// Gets a list of extended properties defined on this object.
/// </summary>
/// <returns>Extended properties collection.</returns>
internal override ExtendedPropertyCollection GetExtendedProperties()
{
return this.ExtendedProperties;
}
/// <summary>
/// Validates this instance.
/// </summary>
internal override void Validate()
{
base.Validate();
this.Attachments.Validate();
// Flag parameter is only valid for Exchange2013 or higher
//
Flag flag;
if (this.TryGetProperty<Flag>(ItemSchema.Flag, out flag) && flag != null)
{
if (this.Service.RequestedServerVersion < ExchangeVersion.Exchange2013)
{
throw new ServiceVersionException(
string.Format(
Strings.ParameterIncompatibleWithRequestVersion,
"Flag",
ExchangeVersion.Exchange2013));
}
flag.Validate();
}
}
/// <summary>
/// Gets a value indicating whether a time zone SOAP header should be emitted in a CreateItem
/// or UpdateItem request so this item can be property saved or updated.
/// </summary>
/// <param name="isUpdateOperation">Indicates whether the operation being petrformed is an update operation.</param>
/// <returns>
/// <c>true</c> if a time zone SOAP header should be emitted; otherwise, <c>false</c>.
/// </returns>
internal override bool GetIsTimeZoneHeaderRequired(bool isUpdateOperation)
{
// Starting E14SP2, attachment will be sent along with CreateItem requests.
// if the attachment used to require the Timezone header, CreateItem request should do so too.
//
if (!isUpdateOperation &&
(this.Service.RequestedServerVersion >= ExchangeVersion.Exchange2010_SP2))
{
foreach (ItemAttachment itemAttachment in this.Attachments.OfType<ItemAttachment>())
{
if ((itemAttachment.Item != null) && itemAttachment.Item.GetIsTimeZoneHeaderRequired(false /* isUpdateOperation */))
{
return true;
}
}
}
return base.GetIsTimeZoneHeaderRequired(isUpdateOperation);
}
#region Properties
/// <summary>
/// Gets a value indicating whether the item is an attachment.
/// </summary>
public bool IsAttachment
{
get { return this.parentAttachment != null; }
}
/// <summary>
/// Gets a value indicating whether this object is a real store item, or if it's a local object
/// that has yet to be saved.
/// </summary>
public override bool IsNew
{
get
{
// Item attachments don't have an Id, need to check whether the
// parentAttachment is new or not.
if (this.IsAttachment)
{
return this.ParentAttachment.IsNew;
}
else
{
return base.IsNew;
}
}
}
/// <summary>
/// Gets the Id of this item.
/// </summary>
public ItemId Id
{
get { return (ItemId)this.PropertyBag[this.GetIdPropertyDefinition()]; }
}
/// <summary>
/// Get or sets the MIME content of this item.
/// </summary>
public MimeContent MimeContent
{
get { return (MimeContent)this.PropertyBag[ItemSchema.MimeContent]; }
set { this.PropertyBag[ItemSchema.MimeContent] = value; }
}
/// <summary>
/// Get or sets the MimeContentUTF8 of this item.
/// </summary>
public MimeContentUTF8 MimeContentUTF8
{
get { return (MimeContentUTF8)this.PropertyBag[ItemSchema.MimeContentUTF8]; }
set { this.PropertyBag[ItemSchema.MimeContentUTF8] = value; }
}
/// <summary>
/// Gets the Id of the parent folder of this item.
/// </summary>
public FolderId ParentFolderId
{
get { return (FolderId)this.PropertyBag[ItemSchema.ParentFolderId]; }
}
/// <summary>
/// Gets or sets the sensitivity of this item.
/// </summary>
public Sensitivity Sensitivity
{
get { return (Sensitivity)this.PropertyBag[ItemSchema.Sensitivity]; }
set { this.PropertyBag[ItemSchema.Sensitivity] = value; }
}
/// <summary>
/// Gets a list of the attachments to this item.
/// </summary>
public AttachmentCollection Attachments
{
get { return (AttachmentCollection)this.PropertyBag[ItemSchema.Attachments]; }
}
/// <summary>
/// Gets the time when this item was received.
/// </summary>
public DateTime DateTimeReceived
{
get { return (DateTime)this.PropertyBag[ItemSchema.DateTimeReceived]; }
}
/// <summary>
/// Gets the size of this item.
/// </summary>
public int Size
{
get { return (int)this.PropertyBag[ItemSchema.Size]; }
}
/// <summary>
/// Gets or sets the list of categories associated with this item.
/// </summary>
public StringList Categories
{
get { return (StringList)this.PropertyBag[ItemSchema.Categories]; }
set { this.PropertyBag[ItemSchema.Categories] = value; }
}
/// <summary>
/// Gets or sets the culture associated with this item.
/// </summary>
public string Culture
{
get { return (string)this.PropertyBag[ItemSchema.Culture]; }
set { this.PropertyBag[ItemSchema.Culture] = value; }
}
/// <summary>
/// Gets or sets the importance of this item.
/// </summary>
public Importance Importance
{
get { return (Importance)this.PropertyBag[ItemSchema.Importance]; }
set { this.PropertyBag[ItemSchema.Importance] = value; }
}
/// <summary>
/// Gets or sets the In-Reply-To reference of this item.
/// </summary>
public string InReplyTo
{
get { return (string)this.PropertyBag[ItemSchema.InReplyTo]; }
set { this.PropertyBag[ItemSchema.InReplyTo] = value; }
}
/// <summary>
/// Gets a value indicating whether the message has been submitted to be sent.
/// </summary>
public bool IsSubmitted
{
get { return (bool)this.PropertyBag[ItemSchema.IsSubmitted]; }
}
/// <summary>
/// Gets a value indicating whether this is an associated item.
/// </summary>
public bool IsAssociated
{
get { return (bool)this.PropertyBag[ItemSchema.IsAssociated]; }
}
/// <summary>
/// Gets a value indicating whether the item is is a draft. An item is a draft when it has not yet been sent.
/// </summary>
public bool IsDraft
{
get { return (bool)this.PropertyBag[ItemSchema.IsDraft]; }
}
/// <summary>
/// Gets a value indicating whether the item has been sent by the current authenticated user.
/// </summary>
public bool IsFromMe
{
get { return (bool)this.PropertyBag[ItemSchema.IsFromMe]; }
}
/// <summary>
/// Gets a value indicating whether the item is a resend of another item.
/// </summary>
public bool IsResend
{
get { return (bool)this.PropertyBag[ItemSchema.IsResend]; }
}
/// <summary>
/// Gets a value indicating whether the item has been modified since it was created.
/// </summary>
public bool IsUnmodified
{
get { return (bool)this.PropertyBag[ItemSchema.IsUnmodified]; }
}
/// <summary>
/// Gets a list of Internet headers for this item.
/// </summary>
public InternetMessageHeaderCollection InternetMessageHeaders
{
get { return (InternetMessageHeaderCollection)this.PropertyBag[ItemSchema.InternetMessageHeaders]; }
}
/// <summary>
/// Gets the date and time this item was sent.
/// </summary>
public DateTime DateTimeSent
{
get { return (DateTime)this.PropertyBag[ItemSchema.DateTimeSent]; }
}
/// <summary>
/// Gets the date and time this item was created.
/// </summary>
public DateTime DateTimeCreated
{
get { return (DateTime)this.PropertyBag[ItemSchema.DateTimeCreated]; }
}
/// <summary>
/// Gets a value indicating which response actions are allowed on this item. Examples of response actions are Reply and Forward.
/// </summary>
public ResponseActions AllowedResponseActions
{
get { return (ResponseActions)this.PropertyBag[ItemSchema.AllowedResponseActions]; }
}
/// <summary>
/// Gets or sets the date and time when the reminder is due for this item.
/// </summary>
public DateTime ReminderDueBy
{
get { return (DateTime)this.PropertyBag[ItemSchema.ReminderDueBy]; }
set { this.PropertyBag[ItemSchema.ReminderDueBy] = value; }
}
/// <summary>
/// Gets or sets a value indicating whether a reminder is set for this item.
/// </summary>
public bool IsReminderSet
{
get { return (bool)this.PropertyBag[ItemSchema.IsReminderSet]; }
set { this.PropertyBag[ItemSchema.IsReminderSet] = value; }
}
/// <summary>
/// Gets or sets the number of minutes before the start of this item when the reminder should be triggered.
/// </summary>
public int ReminderMinutesBeforeStart
{
get { return (int)this.PropertyBag[ItemSchema.ReminderMinutesBeforeStart]; }
set { this.PropertyBag[ItemSchema.ReminderMinutesBeforeStart] = value; }
}
/// <summary>
/// Gets a text summarizing the Cc receipients of this item.
/// </summary>
public string DisplayCc
{
get { return (string)this.PropertyBag[ItemSchema.DisplayCc]; }
}
/// <summary>
/// Gets a text summarizing the To recipients of this item.
/// </summary>
public string DisplayTo
{
get { return (string)this.PropertyBag[ItemSchema.DisplayTo]; }
}
/// <summary>
/// Gets a value indicating whether the item has attachments.
/// </summary>
public bool HasAttachments
{
get { return (bool)this.PropertyBag[ItemSchema.HasAttachments]; }
}
/// <summary>
/// Gets or sets the body of this item.
/// </summary>
public MessageBody Body
{
get { return (MessageBody)this.PropertyBag[ItemSchema.Body]; }
set { this.PropertyBag[ItemSchema.Body] = value; }
}
/// <summary>
/// Gets or sets the custom class name of this item.
/// </summary>
public string ItemClass
{
get { return (string)this.PropertyBag[ItemSchema.ItemClass]; }
set { this.PropertyBag[ItemSchema.ItemClass] = value; }
}
/// <summary>
/// Gets or sets the subject of this item.
/// </summary>
public string Subject
{
get { return (string)this.PropertyBag[ItemSchema.Subject]; }
set { this.SetSubject(value); }
}
/// <summary>
/// Gets the query string that should be appended to the Exchange Web client URL to open this item using the appropriate read form in a web browser.
/// </summary>
public string WebClientReadFormQueryString
{
get { return (string)this.PropertyBag[ItemSchema.WebClientReadFormQueryString]; }
}
/// <summary>
/// Gets the query string that should be appended to the Exchange Web client URL to open this item using the appropriate edit form in a web browser.
/// </summary>
public string WebClientEditFormQueryString
{
get { return (string)this.PropertyBag[ItemSchema.WebClientEditFormQueryString]; }
}
/// <summary>
/// Gets a list of extended properties defined on this item.
/// </summary>
public ExtendedPropertyCollection ExtendedProperties
{
get { return (ExtendedPropertyCollection)this.PropertyBag[ServiceObjectSchema.ExtendedProperties]; }
}
/// <summary>
/// Gets a value indicating the effective rights the current authenticated user has on this item.
/// </summary>
public EffectiveRights EffectiveRights
{
get { return (EffectiveRights)this.PropertyBag[ItemSchema.EffectiveRights]; }
}
/// <summary>
/// Gets the name of the user who last modified this item.
/// </summary>
public string LastModifiedName
{
get { return (string)this.PropertyBag[ItemSchema.LastModifiedName]; }
}
/// <summary>
/// Gets the date and time this item was last modified.
/// </summary>
public DateTime LastModifiedTime
{
get { return (DateTime)this.PropertyBag[ItemSchema.LastModifiedTime]; }
}
/// <summary>
/// Gets the Id of the conversation this item is part of.
/// </summary>
public ConversationId ConversationId
{
get { return (ConversationId)this.PropertyBag[ItemSchema.ConversationId]; }
}
/// <summary>
/// Gets the body part that is unique to the conversation this item is part of.
/// </summary>
public UniqueBody UniqueBody
{
get { return (UniqueBody)this.PropertyBag[ItemSchema.UniqueBody]; }
}
/// <summary>
/// Gets the store entry id.
/// </summary>
public byte[] StoreEntryId
{
get { return (byte[])this.PropertyBag[ItemSchema.StoreEntryId]; }
}
/// <summary>
/// Gets the item instance key.
/// </summary>
public byte[] InstanceKey
{
get { return (byte[])this.PropertyBag[ItemSchema.InstanceKey]; }
}
/// <summary>
/// Get or set the Flag value for this item.
/// </summary>
public Flag Flag
{
get { return (Flag)this.PropertyBag[ItemSchema.Flag]; }
set { this.PropertyBag[ItemSchema.Flag] = value; }
}
/// <summary>
/// Gets the normalized body of the item.
/// </summary>
public NormalizedBody NormalizedBody
{
get { return (NormalizedBody)this.PropertyBag[ItemSchema.NormalizedBody]; }
}
/// <summary>
/// Gets the EntityExtractionResult of the item.
/// </summary>
public EntityExtractionResult EntityExtractionResult
{
get { return (EntityExtractionResult)this.PropertyBag[ItemSchema.EntityExtractionResult]; }
}
/// <summary>
/// Gets or sets the policy tag.
/// </summary>
public PolicyTag PolicyTag
{
get { return (PolicyTag)this.PropertyBag[ItemSchema.PolicyTag]; }
set { this.PropertyBag[ItemSchema.PolicyTag] = value; }
}
/// <summary>
/// Gets or sets the archive tag.
/// </summary>
public ArchiveTag ArchiveTag
{
get { return (ArchiveTag)this.PropertyBag[ItemSchema.ArchiveTag]; }
set { this.PropertyBag[ItemSchema.ArchiveTag] = value; }
}
/// <summary>
/// Gets the retention date.
/// </summary>
public DateTime? RetentionDate
{
get { return (DateTime?)this.PropertyBag[ItemSchema.RetentionDate]; }
}
/// <summary>
/// Gets the item Preview.
/// </summary>
public string Preview
{
get { return (string)this.PropertyBag[ItemSchema.Preview]; }
}
/// <summary>
/// Gets the text body of the item.
/// </summary>
public TextBody TextBody
{
get { return (TextBody)this.PropertyBag[ItemSchema.TextBody]; }
}
/// <summary>
/// Gets the icon index.
/// </summary>
public IconIndex IconIndex
{
get { return (IconIndex)this.PropertyBag[ItemSchema.IconIndex]; }
}
/// <summary>
/// Gets or sets the list of hashtags associated with this item.
/// </summary>
public StringList Hashtags
{
get { return (StringList)this.PropertyBag[ItemSchema.Hashtags]; }
set { this.PropertyBag[ItemSchema.Hashtags] = value; }
}
/// <summary>
/// Gets the Mentions associated with the message.
/// </summary>
public EmailAddressCollection Mentions
{
get { return (EmailAddressCollection)this.PropertyBag[ItemSchema.Mentions]; }
set { this.PropertyBag[ItemSchema.Mentions] = value; }
}
/// <summary>
/// Gets a value indicating whether the item mentions me.
/// </summary>
public bool? MentionedMe
{
get { return (bool?)this.PropertyBag[ItemSchema.MentionedMe]; }
}
/// <summary>
/// Gets the default setting for how to treat affected task occurrences on Delete.
/// Subclasses will override this for different default behavior.
/// </summary>
internal virtual AffectedTaskOccurrence? DefaultAffectedTaskOccurrences
{
get { return null; }
}
/// <summary>
/// Gets the default setting for sending cancellations on Delete.
/// Subclasses will override this for different default behavior.
/// </summary>
internal virtual SendCancellationsMode? DefaultSendCancellationsMode
{
get { return null; }
}
/// <summary>
/// Gets the default settings for sending invitations on Save.
/// Subclasses will override this for different default behavior.
/// </summary>
internal virtual SendInvitationsMode? DefaultSendInvitationsMode
{
get { return null; }
}
/// <summary>
/// Gets the default settings for sending invitations or cancellations on Update.
/// Subclasses will override this for different default behavior.
/// </summary>
internal virtual SendInvitationsOrCancellationsMode? DefaultSendInvitationsOrCancellationsMode
{
get { return null; }
}
/// <summary>
/// Sets the subject.
/// </summary>
/// <param name="subject">The subject.</param>
internal virtual void SetSubject(string subject)
{
this.PropertyBag[ItemSchema.Subject] = subject;
}
#endregion
}
}
| |
using System;
using System.Runtime.InteropServices;
namespace LibuvSharp
{
unsafe public abstract class Handle : IHandle, IDisposable
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void callback(IntPtr req, int status);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void alloc_callback_unix(IntPtr data, int size, out UnixBufferStruct buf);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void alloc_callback_win(IntPtr data, int size, out WindowsBufferStruct buf);
public Loop Loop { get; protected set; }
public IntPtr NativeHandle { get; protected set; }
internal GCHandle GCHandle { get; set; }
uv_handle_t *handle {
get {
CheckDisposed();
return (uv_handle_t *)NativeHandle;
}
}
internal IntPtr DataPointer {
get {
return handle->data;
}
set {
handle->data = value;
}
}
internal static T FromIntPtr<T>(IntPtr ptr)
{
return (T)GCHandle.FromIntPtr(((uv_handle_t*)ptr)->data).Target;
}
public HandleType HandleType {
get {
return handle->type;
}
}
internal Handle(Loop loop, IntPtr handle)
{
Ensure.ArgumentNotNull(loop, "loop");
NativeHandle = handle;
GCHandle = GCHandle.Alloc(this);
Loop = loop;
Loop.handles[NativeHandle] = this;
close_cb = CloseCallback;
DataPointer = GCHandle.ToIntPtr(GCHandle);
}
internal Handle(Loop loop, int size)
: this(loop, UV.Alloc(size))
{
}
internal Handle(Loop loop, HandleType handleType)
: this(loop, Handle.Size(handleType))
{
}
internal Handle(Loop loop, HandleType handleType, Func<IntPtr, IntPtr, int> constructor)
: this(loop, handleType)
{
Construct(constructor);
}
internal Handle(Loop loop, HandleType handleType, Func<IntPtr, IntPtr, int, int> constructor, int arg1)
: this(loop, handleType)
{
Construct(constructor, arg1);
}
internal void Construct(Func<IntPtr, IntPtr, int> constructor)
{
int r = constructor(Loop.NativeHandle, NativeHandle);
Ensure.Success(r);
}
internal void Construct(Func<IntPtr, IntPtr, int, int> constructor, int arg1)
{
int r = constructor(Loop.NativeHandle, NativeHandle, arg1);
Ensure.Success(r);
}
internal void Construct(Func<IntPtr, IntPtr, int, int, int> constructor, int arg1, int arg2)
{
int r = constructor(Loop.NativeHandle, NativeHandle, arg1, arg2);
Ensure.Success(r);
}
public event Action Closed;
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
static extern void uv_close(IntPtr handle, close_callback cb);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate void close_callback(IntPtr handle);
Action closeCallback;
static close_callback close_cb = CloseCallback;
static void CloseCallback(IntPtr handlePointer)
{
var handle = Handle.FromIntPtr<Handle>(handlePointer);
handle.Cleanup(handlePointer, handle.closeCallback);
}
public void Cleanup(IntPtr nativeHandle, Action callback)
{
// Remove handle
if (NativeHandle != IntPtr.Zero) {
Loop.handles.Remove(nativeHandle);
UV.Free(nativeHandle);
NativeHandle = IntPtr.Zero;
if (Closed != null) {
Closed();
}
if (callback != null) {
callback();
}
if (GCHandle.IsAllocated) {
GCHandle.Free();
}
}
}
public void Close(Action callback)
{
if (!IsClosing && !IsClosed ) {
closeCallback = callback;
uv_close(NativeHandle, close_cb);
}
}
public void Close()
{
Close(null);
}
public bool IsClosed {
get {
return NativeHandle == IntPtr.Zero;
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
Close();
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
internal static extern int uv_is_active(IntPtr handle);
public bool IsActive {
get {
if (IsClosed) {
return false;
}
return uv_is_active(NativeHandle) != 0;
}
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
internal static extern int uv_is_closing(IntPtr handle);
public bool IsClosing {
get {
if (IsClosed) {
return false;
}
return uv_is_closing(NativeHandle) != 0;
}
}
/// <summary>
/// Is the underlying still alive? Returns true if handle
/// is not closing or closed.
/// </summary>
/// <value><c>true</c> if this instance is not closing or closed; otherwise, <c>false</c>.</value>
public bool IsAlive {
get {
return !IsClosed && !IsClosing;
}
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
static extern void uv_ref(IntPtr handle);
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
static extern void uv_unref(IntPtr handle);
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
static extern int uv_has_ref(IntPtr handle);
public void Ref()
{
if (IsClosed) {
return;
}
uv_ref(NativeHandle);
}
public void Unref()
{
if (IsClosed) {
return;
}
uv_unref(NativeHandle);
}
public bool HasRef {
get {
if (IsClosed) {
return false;
}
return uv_has_ref(NativeHandle) != 0;
}
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
internal static extern int uv_handle_size(HandleType type);
public static int Size(HandleType type)
{
return uv_handle_size(type);
}
[DllImport("uv", CallingConvention = CallingConvention.Cdecl)]
static extern HandleType uv_guess_handle(int fd);
public static HandleType Guess(int fd)
{
return uv_guess_handle(fd);
}
protected void CheckDisposed()
{
if (NativeHandle == IntPtr.Zero) {
throw new ObjectDisposedException(GetType().ToString(), "handle was closed");
}
}
protected void Invoke(Func<IntPtr, int> function)
{
CheckDisposed();
int r = function(NativeHandle);
Ensure.Success(r);
}
protected void Invoke<T1>(Func<IntPtr, T1, int> function, T1 arg1)
{
CheckDisposed();
int r = function(NativeHandle, arg1);
Ensure.Success(r);
}
protected void Invoke<T1, T2>(Func<IntPtr, T1, T2, int> function, T1 arg1, T2 arg2)
{
CheckDisposed();
int r = function(NativeHandle, arg1, arg2);
Ensure.Success(r);
}
protected void Invoke<T1, T2, T3>(Func<IntPtr, T1, T2, T3, int> function, T1 arg1, T2 arg2, T3 arg3)
{
CheckDisposed();
int r = function(NativeHandle, arg1, arg2, arg3);
Ensure.Success(r);
}
}
}
| |
// F#: * We never generate a real field, so all the tests are modified to check for the right property
// * Fixed missing codetypereference in access to static fields
// * Also accessing protected static fields without "CodeTypeReference" is not correct in F#
// * Reorganized class order
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.Reflection;
using Microsoft.Samples.CodeDomTestSuite;
using Microsoft.VisualBasic;
using Microsoft.JScript;
public class DeclareField : CodeDomTestTree {
public override string Comment
{
get { return "public static fields not allowed in F#"; }
}
public override TestTypes TestType {
get {
return TestTypes.Everett;
}
}
public override bool ShouldCompile {
get {
return true;
}
}
public override bool ShouldVerify {
get {
return true;
}
}
public override string Name {
get {
return "DeclareField";
}
}
public override string Description {
get {
return "Tests declarations of fields.";
}
}
public override void BuildTree (CodeDomProvider provider, CodeCompileUnit cu) {
CodeNamespace nspace = new CodeNamespace("NSPC");
nspace.Imports.Add(new CodeNamespaceImport("System"));
cu.Namespaces.Add(nspace);
CodeTypeDeclaration cd = new CodeTypeDeclaration("TestFields");
cd.IsClass = true;
nspace.Types.Add(cd);
// GENERATES (C#):
// public static int UseStaticPublicField(int i) {
// ClassWithFields.StaticPublicField = i;
// return ClassWithFields.StaticPublicField;
//
CodeMemberMethod cmm;
if (Supports(provider, GeneratorSupport.PublicStaticMembers))
{
AddScenario("CheckUseStaticPublicField");
cmm = new CodeMemberMethod();
cmm.Name = "UseStaticPublicField";
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
cmm.ReturnType = new CodeTypeReference(typeof(int));
cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(
new CodeTypeReferenceExpression("ClassWithFields"), "StaticPublicField"),
new CodeArgumentReferenceExpression("i")));
cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
CodeTypeReferenceExpression("ClassWithFields"), "StaticPublicField")));
cd.Members.Add(cmm);
}
// GENERATES (C#):
// public static int UseNonStaticPublicField(int i) {
// ClassWithFields variable = new ClassWithFields();
// variable.NonStaticPublicField = i;
// return variable.NonStaticPublicField;
// }
AddScenario("CheckUseNonStaticPublicField");
cmm = new CodeMemberMethod();
cmm.Name = "UseNonStaticPublicField";
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
cmm.ReturnType = new CodeTypeReference(typeof(int));
cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
cmm.Statements.Add(new CodeVariableDeclarationStatement("ClassWithFields", "variable", new CodeObjectCreateExpression("ClassWithFields")));
cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(
new CodeVariableReferenceExpression("variable"), "NonStaticPublicField"),
new CodeArgumentReferenceExpression("i")));
cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
CodeVariableReferenceExpression("variable"), "NonStaticPublicField")));
cd.Members.Add(cmm);
// GENERATES (C#):
// public static int UseNonStaticInternalField(int i) {
// ClassWithFields variable = new ClassWithFields();
// variable.NonStaticInternalField = i;
// return variable.NonStaticInternalField;
// }
if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider))
{
cmm = new CodeMemberMethod();
AddScenario("CheckUseNonStaticInternalField");
cmm.Name = "UseNonStaticInternalField";
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
cmm.ReturnType = new CodeTypeReference(typeof(int));
cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
cmm.Statements.Add(new CodeVariableDeclarationStatement("ClassWithFields", "variable", new CodeObjectCreateExpression("ClassWithFields")));
cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(
new CodeVariableReferenceExpression("variable"), "NonStaticInternalField"),
new CodeArgumentReferenceExpression("i")));
cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
CodeVariableReferenceExpression("variable"), "NonStaticInternalField")));
cd.Members.Add(cmm);
}
// GENERATES (C#):
// public static int UseInternalField(int i) {
// ClassWithFields.InternalField = i;
// return ClassWithFields.InternalField;
// }
if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider))
{
AddScenario("CheckUseInternalField");
cmm = new CodeMemberMethod();
cmm.Name = "UseInternalField";
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
cmm.ReturnType = new CodeTypeReference(typeof(int));
cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
cmm.Statements.Add(new CodeAssignStatement(new CodeFieldReferenceExpression(new
CodeTypeReferenceExpression("ClassWithFields"), "InternalField"),
new CodeArgumentReferenceExpression("i")));
cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
CodeTypeReferenceExpression("ClassWithFields"), "InternalField")));
cd.Members.Add(cmm);
}
// GENERATES (C#):
// public static int UseConstantField(int i) {
// return ClassWithFields.ConstantField;
// }
AddScenario("CheckUseConstantField");
cmm = new CodeMemberMethod();
cmm.Name = "UseConstantField";
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
cmm.ReturnType = new CodeTypeReference(typeof(int));
cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
cmm.Statements.Add(new CodeMethodReturnStatement(new CodeFieldReferenceExpression(new
CodeTypeReferenceExpression("ClassWithFields"), "ConstantField")));
cd.Members.Add(cmm);
// code a new class to test that the protected field can be accessed by classes that inherit it
// GENERATES (C#):
// public class TestProtectedField : ClassWithFields {
// public static int UseProtectedField(int i) {
// ProtectedField = i;
// return ProtectedField;
// }
// }
cd = new CodeTypeDeclaration("TestProtectedField");
cd.BaseTypes.Add(new CodeTypeReference("ClassWithFields"));
cd.IsClass = true;
nspace.Types.Add(cd);
cmm = new CodeMemberMethod();
AddScenario("CheckUseProtectedField");
cmm.Name = "UseProtectedField";
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
cmm.ReturnType = new CodeTypeReference(typeof(int));
cmm.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(int)), "i"));
CodeFieldReferenceExpression reference = new CodeFieldReferenceExpression();
reference.FieldName = "ProtectedField";
reference.TargetObject = new CodeTypeReferenceExpression("ClassWithFields");
cmm.Statements.Add(new CodeAssignStatement(reference,
new CodeArgumentReferenceExpression("i")));
cmm.Statements.Add(new CodeMethodReturnStatement(reference));
cd.Members.Add(cmm);
// declare class with fields
// GENERATES (C#):
// public class ClassWithFields {
// public static int StaticPublicField = 5;
// /*FamANDAssem*/ internal static int InternalField = 0;
// public const int ConstantField = 0;
// protected static int ProtectedField = 0;
// private static int PrivateField = 5;
// public int NonStaticPublicField = 5;
// /*FamANDAssem*/ internal int NonStaticInternalField = 0;
// public static int UsePrivateField(int i) {
// PrivateField = i;
// return PrivateField;
// }
// }
cd = new CodeTypeDeclaration ("ClassWithFields");
cd.IsClass = true;
nspace.Types.Add (cd);
CodeMemberField field;
if (Supports (provider, GeneratorSupport.PublicStaticMembers)) {
field = new CodeMemberField ();
field.Name = "StaticPublicField";
field.Attributes = MemberAttributes.Public | MemberAttributes.Static;
field.Type = new CodeTypeReference (typeof (int));
field.InitExpression = new CodePrimitiveExpression (5);
cd.Members.Add (field);
}
if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) {
field = new CodeMemberField ();
field.Name = "InternalField";
field.Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Static;
field.Type = new CodeTypeReference (typeof (int));
field.InitExpression = new CodePrimitiveExpression (0);
cd.Members.Add (field);
}
field = new CodeMemberField ();
field.Name = "ConstantField";
field.Attributes = MemberAttributes.Public | MemberAttributes.Const;
field.Type = new CodeTypeReference (typeof (int));
field.InitExpression = new CodePrimitiveExpression (0);
cd.Members.Add (field);
field = new CodeMemberField ();
field.Name = "ProtectedField";
field.Attributes = MemberAttributes.Family | MemberAttributes.Static;
field.Type = new CodeTypeReference (typeof (int));
field.InitExpression = new CodePrimitiveExpression (0);
cd.Members.Add (field);
field = new CodeMemberField ();
field.Name = "PrivateField";
field.Attributes = MemberAttributes.Private | MemberAttributes.Static;
field.Type = new CodeTypeReference (typeof (int));
field.InitExpression = new CodePrimitiveExpression (5);
cd.Members.Add (field);
field = new CodeMemberField ();
field.Name = "NonStaticPublicField";
field.Attributes = MemberAttributes.Public | MemberAttributes.Final;
field.Type = new CodeTypeReference (typeof (int));
field.InitExpression = new CodePrimitiveExpression (5);
cd.Members.Add (field);
if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) {
field = new CodeMemberField ();
field.Name = "NonStaticInternalField";
field.Attributes = MemberAttributes.FamilyOrAssembly | MemberAttributes.Final;
field.Type = new CodeTypeReference (typeof (int));
field.InitExpression = new CodePrimitiveExpression (0);
cd.Members.Add (field);
}
// create a method to test access to private field
AddScenario ("CheckUsePrivateField");
cmm = new CodeMemberMethod ();
cmm.Name = "UsePrivateField";
cmm.Attributes = MemberAttributes.Public | MemberAttributes.Static;
cmm.ReturnType = new CodeTypeReference (typeof (int));
cmm.Parameters.Add (new CodeParameterDeclarationExpression (new CodeTypeReference (typeof (int)), "i"));
CodeFieldReferenceExpression fieldref = new CodeFieldReferenceExpression ();
fieldref.TargetObject = new CodeTypeReferenceExpression("ClassWithFields");
fieldref.FieldName = "PrivateField";
cmm.Statements.Add (new CodeAssignStatement (fieldref, new CodeArgumentReferenceExpression ("i")));
cmm.Statements.Add (new CodeMethodReturnStatement (fieldref));
cd.Members.Add (cmm);
}
public override void VerifyAssembly (CodeDomProvider provider, Assembly asm) {
object genObject;
Type genType;
AddScenario ("InstantiateTestFields", "Find and instantiate TestFields.");
if (!FindAndInstantiate ("NSPC.TestFields", asm, out genObject, out genType))
return;
VerifyScenario ("InstantiateTestFields");
if (VerifyMethod (genType, genObject, "UsePrivateField", new object[] {6}, 6)) {
VerifyScenario ("CheckUsePrivateField");
}
if (VerifyMethod (genType, genObject, "UseConstantField", new object[] {6}, 0)) {
VerifyScenario ("CheckUseConstantField");
}
if (VerifyMethod (genType, genObject, "UseNonStaticPublicField", new object[] {6}, 6)) {
VerifyScenario ("CheckUseNonStaticPublicField");
}
if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) {
if (VerifyMethod (genType, genObject, "UseNonStaticInternalField", new object[] { 6 }, 6)) {
VerifyScenario ("CheckUseNonStaticInternalField");
}
}
if (!(provider is JScriptCodeProvider) && !(provider is VBCodeProvider)) {
if (VerifyMethod (genType, genObject, "UseInternalField", new object[] { 6 }, 6)) {
VerifyScenario ("CheckUseInternalField");
}
}
if (Supports (provider, GeneratorSupport.PublicStaticMembers) && VerifyMethod (genType, genObject, "UseStaticPublicField",
new object [] { 6 }, 6)) {
VerifyScenario ("CheckUseStaticPublicField");
}
AddScenario ("InstantiateTestProtectedField", "Find and instantiate TestProtectedFields.");
if (!FindAndInstantiate ("NSPC.TestProtectedField", asm, out genObject, out genType))
return;
VerifyScenario ("InstantiateTestProtectedField");
if (VerifyMethod (genType, genObject, "UseProtectedField", new object[] {6}, 6)) {
VerifyScenario ("CheckUseProtectedField");
}
AddScenario ("InstantiateClassWithFields", "Find and instantiate ClassWithFields.");
if (!FindAndInstantiate ("NSPC.ClassWithFields", asm, out genObject, out genType))
return;
VerifyScenario ("InstantiateClassWithFields");
if (VerifyMethod (genType, genObject, "UsePrivateField", new object[] {6}, 6)) {
VerifyScenario ("CheckUsePrivateField");
}
}
}
| |
/*
* 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 OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace OpenSim.Region.ClientStack.LindenUDP
{
/// <summary>
/// This class handles UDP texture requests.
/// </summary>
public class LLImageManager
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IAssetService m_assetCache;
private IJ2KDecoder m_j2kDecodeModule;
private AssetBase m_missingImage;
/// <summary>
/// Priority queue for determining which image to send first.
/// </summary>
private C5.IntervalHeap<J2KImage> m_priorityQueue = new C5.IntervalHeap<J2KImage>(10, new J2KImageComparer());
private bool m_shuttingdown;
/// <summary>
/// Used to control thread access to the priority queue.
/// </summary>
private object m_syncRoot = new object();
public LLImageManager(IClientAPI client, IAssetService pAssetCache, IJ2KDecoder pJ2kDecodeModule)
{
Client = client;
m_assetCache = pAssetCache;
if (pAssetCache != null)
m_missingImage = pAssetCache.Get("5748decc-f629-461c-9a36-a35a221fe21f");
if (m_missingImage == null)
m_log.Error("[ClientView] - Couldn't set missing image asset, falling back to missing image packet. This is known to crash the client");
m_j2kDecodeModule = pJ2kDecodeModule;
}
/// <summary>
/// Client served by this image manager
/// </summary>
public IClientAPI Client { get; private set; }
public AssetBase MissingImage { get { return m_missingImage; } }
/// <summary>
/// Clear the image queue.
/// </summary>
/// <returns>The number of requests cleared.</returns>
public int ClearImageQueue()
{
int requestsDeleted;
lock (m_priorityQueue)
{
requestsDeleted = m_priorityQueue.Count;
// Surprisingly, there doesn't seem to be a clear method at this time.
while (!m_priorityQueue.IsEmpty)
m_priorityQueue.DeleteMax();
}
return requestsDeleted;
}
/// <summary>
/// Faux destructor
/// </summary>
public void Close()
{
m_shuttingdown = true;
}
/// <summary>
/// Handles an incoming texture request or update to an existing texture request
/// </summary>
/// <param name="newRequest"></param>
public void EnqueueReq(TextureRequestArgs newRequest)
{
if (!m_shuttingdown)
{
J2KImage imgrequest;
// Do a linear search for this texture download
lock (m_syncRoot)
m_priorityQueue.Find(delegate(J2KImage img) { return img.TextureID == newRequest.RequestedAssetID; }, out imgrequest);
if (imgrequest != null)
{
if (newRequest.DiscardLevel == -1 && newRequest.Priority == 0f)
{
//m_log.Debug("[TEX]: (CAN) ID=" + newRequest.RequestedAssetID);
try
{
lock (m_syncRoot)
m_priorityQueue.Delete(imgrequest.PriorityQueueHandle);
}
catch (Exception) { }
}
else
{
// m_log.DebugFormat(
// "[LL IMAGE MANAGER]: Received duplicate of existing request for {0}, start packet {1} from {2}",
// newRequest.RequestedAssetID, newRequest.PacketNumber, m_client.Name);
// m_log.DebugFormat("[TEX]: (UPD) ID={0}: D={1}, S={2}, P={3}",
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
//Check the packet sequence to make sure this isn't older than
//one we've already received
if (newRequest.requestSequence > imgrequest.LastSequence)
{
//Update the sequence number of the last RequestImage packet
imgrequest.LastSequence = newRequest.requestSequence;
//Update the requested discard level
imgrequest.DiscardLevel = newRequest.DiscardLevel;
//Update the requested packet number
imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
//Update the requested priority
imgrequest.Priority = newRequest.Priority;
UpdateImageInQueue(imgrequest);
imgrequest.RunUpdate();
// J2KImage imgrequest2 = new J2KImage(this);
// imgrequest2.J2KDecoder = m_j2kDecodeModule;
// imgrequest2.AssetService = m_assetCache;
// imgrequest2.AgentID = m_client.AgentId;
// imgrequest2.InventoryAccessModule = m_client.Scene.RequestModuleInterface<IInventoryAccessModule>();
// imgrequest2.DiscardLevel = newRequest.DiscardLevel;
// imgrequest2.StartPacket = Math.Max(1, newRequest.PacketNumber);
// imgrequest2.Priority = newRequest.Priority;
// imgrequest2.TextureID = newRequest.RequestedAssetID;
// imgrequest2.Priority = newRequest.Priority;
//
// //Add this download to the priority queue
// AddImageToQueue(imgrequest2);
//
// imgrequest2.RunUpdate();
}
// else
// {
// m_log.DebugFormat(
// "[LL IMAGE MANAGER]: Ignoring duplicate of existing request for {0} (sequence {1}) from {2} as its request sequence {3} is not greater",
// newRequest.RequestedAssetID, imgrequest.LastSequence, m_client.Name, newRequest.requestSequence);
// }
}
}
else
{
if (newRequest.DiscardLevel == -1 && newRequest.Priority == 0f)
{
//m_log.DebugFormat("[TEX]: (IGN) ID={0}: D={1}, S={2}, P={3}",
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
}
else
{
// m_log.DebugFormat(
// "[LL IMAGE MANAGER]: Received request for {0}, start packet {1} from {2}",
// newRequest.RequestedAssetID, newRequest.PacketNumber, m_client.Name);
//m_log.DebugFormat("[TEX]: (NEW) ID={0}: D={1}, S={2}, P={3}",
// newRequest.RequestedAssetID, newRequest.DiscardLevel, newRequest.PacketNumber, newRequest.Priority);
imgrequest = new J2KImage(this);
imgrequest.J2KDecoder = m_j2kDecodeModule;
imgrequest.AssetService = m_assetCache;
imgrequest.AgentID = Client.AgentId;
imgrequest.InventoryAccessModule = Client.Scene.RequestModuleInterface<IInventoryAccessModule>();
imgrequest.DiscardLevel = newRequest.DiscardLevel;
imgrequest.StartPacket = Math.Max(1, newRequest.PacketNumber);
imgrequest.Priority = newRequest.Priority;
imgrequest.TextureID = newRequest.RequestedAssetID;
imgrequest.Priority = newRequest.Priority;
//Add this download to the priority queue
AddImageToQueue(imgrequest);
imgrequest.RunUpdate();
}
}
}
}
/// <summary>
/// Returns an array containing all the images in the queue.
/// </summary>
/// <returns></returns>
public J2KImage[] GetImages()
{
lock (m_priorityQueue)
return m_priorityQueue.ToArray();
}
public bool HasUpdates()
{
J2KImage image = GetHighestPriorityImage();
return image != null && image.IsDecoded;
}
public bool ProcessImageQueue(int packetsToSend)
{
int packetsSent = 0;
while (packetsSent < packetsToSend)
{
J2KImage image = GetHighestPriorityImage();
// If null was returned, the texture priority queue is currently empty
if (image == null)
break;
if (image.IsDecoded)
{
int sent;
bool imageDone = image.SendPackets(Client, packetsToSend - packetsSent, out sent);
packetsSent += sent;
// If the send is complete, destroy any knowledge of this transfer
if (imageDone)
RemoveImageFromQueue(image);
}
else
{
// TODO: This is a limitation of how LLImageManager is currently
// written. Undecoded textures should not be going into the priority
// queue, because a high priority undecoded texture will clog up the
// pipeline for a client
// m_log.DebugFormat(
// "[LL IMAGE MANAGER]: Exiting image queue processing early on encountering undecoded image {0}",
// image.TextureID);
break;
}
}
// if (packetsSent != 0)
// m_log.DebugFormat("[LL IMAGE MANAGER]: Processed {0} packets from image queue", packetsSent);
return m_priorityQueue.Count > 0;
}
private sealed class J2KImageComparer : IComparer<J2KImage>
{
public int Compare(J2KImage x, J2KImage y)
{
return x.Priority.CompareTo(y.Priority);
}
}
#region Priority Queue Helpers
private void AddImageToQueue(J2KImage image)
{
image.PriorityQueueHandle = null;
lock (m_syncRoot)
{
try
{
m_priorityQueue.Add(ref image.PriorityQueueHandle, image);
}
catch (Exception) { }
}
}
private J2KImage GetHighestPriorityImage()
{
J2KImage image = null;
lock (m_syncRoot)
{
if (m_priorityQueue.Count > 0)
{
try
{
image = m_priorityQueue.FindMax();
}
catch (Exception) { }
}
}
return image;
}
private void RemoveImageFromQueue(J2KImage image)
{
lock (m_syncRoot)
{
try
{
m_priorityQueue.Delete(image.PriorityQueueHandle);
}
catch (Exception) { }
}
}
private void UpdateImageInQueue(J2KImage image)
{
lock (m_syncRoot)
{
try
{
m_priorityQueue.Replace(image.PriorityQueueHandle, image);
}
catch (Exception)
{
image.PriorityQueueHandle = null;
m_priorityQueue.Add(ref image.PriorityQueueHandle, image);
}
}
}
#endregion Priority Queue Helpers
}
}
| |
using System;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using Sce.PlayStation.Core;
using Sce.PlayStation.Core.Graphics;
using Sce.PlayStation.Core.Imaging;
using Sce.PlayStation.Core.Environment;
using Sce.PlayStation.Core.Input;
namespace API
{
public static class Text
{
private static GraphicsContext graphics;
private static ShaderProgram textureShaderProgram;
private static ShaderProgram colorShaderProgram;
private static Matrix4 projectionMatrix;
private static Matrix4 viewMatrix;
private static VertexBuffer rectVertices;
private static VertexBuffer circleVertices;
private static Dictionary<string, TextSprite> spriteDict;
private static int spriteNamelessCount;
private static Font defaultFont;
private static Font currentFont;
public static bool Init(GraphicsContext graphicsContext, Stopwatch swInit = null)
{
graphics = graphicsContext;
textureShaderProgram = createSimpleTextureShader();
colorShaderProgram = createSimpleColorShader();
projectionMatrix = Matrix4.Ortho(0, Width,
0, Height,
0.0f, 32768.0f);
viewMatrix = Matrix4.LookAt(new Vector3(0, Height, 0),
new Vector3(0, Height, 1),
new Vector3(0, -1, 0));
rectVertices = new VertexBuffer(4, VertexFormat.Float3);
rectVertices.SetVertices(0, new float[]{0, 0, 0,
1, 0, 0,
1, 1, 0,
0, 1, 0});
circleVertices = new VertexBuffer(36, VertexFormat.Float3);
float[] circleVertex = new float[3 * 36];
for (int i = 0; i < 36; i++) {
float radian = ((i * 10) / 180.0f * FMath.PI);
circleVertex[3 * i + 0] = FMath.Cos(radian);
circleVertex[3 * i + 1] = FMath.Sin(radian);
circleVertex[3 * i + 2] = 0.0f;
}
circleVertices.SetVertices(0, circleVertex);
defaultFont = new Font(FontAlias.System, 24, FontStyle.Regular);
SetDefaultFont();
spriteDict = new Dictionary<string, TextSprite>();
spriteNamelessCount = 0;
return true;
}
/// Terminate
public static void Term()
{
ClearSprite();
defaultFont.Dispose();
circleVertices.Dispose();
rectVertices.Dispose();
colorShaderProgram.Dispose();
textureShaderProgram.Dispose();
graphics = null;
}
public static int Width
{
get {return graphics.GetFrameBuffer().Width;}
}
public static int Height
{
get {return graphics.GetFrameBuffer().Height;}
}
/// Touch coordinates -> screen coordinates conversion : X
public static int TouchPixelX(TouchData touchData)
{
return (int)((touchData.X + 0.5f) * Width);
}
/// Touch coordinates -> screen coordinates conversion : Y
public static int TouchPixelY(TouchData touchData)
{
return (int)((touchData.Y + 0.5f) * Height);
}
public static void AddSprite(TextSprite sprite)
{
AddSprite("[nameless]:" + spriteNamelessCount, sprite);
spriteNamelessCount++;
}
public static void AddSprite(string key, TextSprite sprite)
{
if (spriteDict.ContainsKey(key) == false) {
spriteDict.Add(key, sprite);
}
}
/// Register a sprite that draws text
public static void AddSprite(string key, string text, uint argb, Font font, int positionX, int positionY)
{
if (spriteDict.ContainsKey(text) == false) {
AddSprite(key, new TextSprite(text, argb, font, positionX, positionY));
}
}
/// Register a sprite that draws text
public static void AddSprite(string text, uint argb, int positionX, int positionY)
{
AddSprite(text, text, argb, currentFont, positionX, positionY);
}
public static void RemoveSprite(string key)
{
if (spriteDict.ContainsKey(key)) {
spriteDict[key].Dispose();
spriteDict.Remove(key);
}
}
public static void ClearSprite()
{
foreach (string key in spriteDict.Keys) {
spriteDict[key].Dispose();
}
spriteDict.Clear();
spriteNamelessCount = 0;
}
// if use Text's method, please call this method.
public static void Update()
{
int keyNo = 0;
string[] removeKey = new string[spriteDict.Count];
foreach (var key in spriteDict.Keys) {
if(false == spriteDict[key].CheckLifeTimer())
{
removeKey[keyNo] = key;
keyNo++;
}
}
for(int i = 0; i < keyNo; i++)
{
if(removeKey[i] != null)
{
RemoveSprite(removeKey[i]);
}
}
}
public static void DrawSprite(string key)
{
if (spriteDict.ContainsKey(key)) {
DrawSprite(spriteDict[key]);
}
}
public static void DrawSprite(TextSprite sprite)
{
var modelMatrix = sprite.CreateModelMatrix();
var worldViewProj = projectionMatrix * viewMatrix * modelMatrix;
textureShaderProgram.SetUniformValue(0, ref worldViewProj);
graphics.SetShaderProgram(textureShaderProgram);
graphics.SetVertexBuffer(0, sprite.Vertices);
graphics.SetTexture(0, sprite.Texture);
graphics.Enable(EnableMode.Blend);
graphics.SetBlendFunc(BlendFuncMode.Add, BlendFuncFactor.SrcAlpha, BlendFuncFactor.OneMinusSrcAlpha);
graphics.DrawArrays(DrawMode.TriangleFan, 0, 4);
sprite.SetLifeTimer();
}
public static Font CurrentFont
{
get {return currentFont;}
}
public static Font SetDefaultFont()
{
return SetFont(defaultFont);
}
public static Font SetFont(Font font)
{
Font previousFont = currentFont;
currentFont = font;
return previousFont;
}
public static void DrawText(string text, uint argb, Font font, int positionX, int positionY)
{
AddSprite(text, text, argb, font, positionX, positionY);
DrawSprite(text);
}
public static void DrawText(string text, uint argb, int positionX, int positionY)
{
AddSprite(text, text, argb, currentFont, positionX, positionY);
DrawSprite(text);
}
public static void FillVertices(VertexBuffer vertices, uint argb, float positionX, float positionY, float scaleX, float scaleY)
{
var transMatrix = Matrix4.Translation(new Vector3(positionX, positionY, 0.0f));
var scaleMatrix = Matrix4.Scale(new Vector3(scaleX, scaleY, 1.0f));
var modelMatrix = transMatrix * scaleMatrix;
var worldViewProj = projectionMatrix * viewMatrix * modelMatrix;
colorShaderProgram.SetUniformValue(0, ref worldViewProj);
Vector4 color = new Vector4((float)((argb >> 16) & 0xff) / 0xff,
(float)((argb >> 8) & 0xff) / 0xff,
(float)((argb >> 0) & 0xff) / 0xff,
(float)((argb >> 24) & 0xff) / 0xff);
colorShaderProgram.SetUniformValue(colorShaderProgram.FindUniform("MaterialColor"), ref color);
graphics.SetShaderProgram(colorShaderProgram);
graphics.SetVertexBuffer(0, vertices);
graphics.DrawArrays(DrawMode.TriangleFan, 0, vertices.VertexCount);
}
public static Texture2D createTexture(string text, Font font, uint argb)
{
int width = font.GetTextWidth(text, 0, text.Length);
int height = font.Metrics.Height;
var image = new Image(ImageMode.Rgba,
new ImageSize(width, height),
new ImageColor(0, 0, 0, 0));
image.DrawText(text,
new ImageColor((int)((argb >> 16) & 0xff),
(int)((argb >> 8) & 0xff),
(int)((argb >> 0) & 0xff),
(int)((argb >> 24) & 0xff)),
font, new ImagePosition(0, 0));
var texture = new Texture2D(width, height, false, PixelFormat.Rgba);
texture.SetPixels(0, image.ToBuffer());
image.Dispose();
return texture;
}
private static ShaderProgram createSimpleTextureShader()
{
string ResourceName = "API.shaders.Texture.cgx";
Assembly resourceAssembly = Assembly.GetExecutingAssembly();
if (resourceAssembly.GetManifestResourceInfo(ResourceName) == null)
{
throw new FileNotFoundException("File not found.", ResourceName);
}
Stream fileStreamVertex = resourceAssembly.GetManifestResourceStream(ResourceName);
Byte[] dataBufferVertex = new Byte[fileStreamVertex.Length];
fileStreamVertex.Read(dataBufferVertex, 0, dataBufferVertex.Length);
var shaderProgram = new ShaderProgram(dataBufferVertex);
// var shaderProgram = new ShaderProgram("/Application/shaders/Texture.cgx");
shaderProgram.SetAttributeBinding(0, "a_Position");
shaderProgram.SetAttributeBinding(1, "a_TexCoord");
shaderProgram.SetUniformBinding(0, "WorldViewProj");
return shaderProgram;
}
private static ShaderProgram createSimpleColorShader()
{
string ResourceName = "API.shaders.Simple.cgx";
Assembly resourceAssembly = Assembly.GetExecutingAssembly();
if (resourceAssembly.GetManifestResourceInfo(ResourceName) == null)
{
throw new FileNotFoundException("File not found.", ResourceName);
}
Stream fileStreamVertex = resourceAssembly.GetManifestResourceStream(ResourceName);
Byte[] dataBufferVertex = new Byte[fileStreamVertex.Length];
fileStreamVertex.Read(dataBufferVertex, 0, dataBufferVertex.Length);
var shaderProgram = new ShaderProgram(dataBufferVertex);
// var shaderProgram = new ShaderProgram("/Application/shaders/Simple.cgx");
shaderProgram.SetAttributeBinding(0, "a_Position");
//shaderProgram.SetAttributeBinding(1, "a_Color0");
shaderProgram.SetUniformBinding(0, "WorldViewProj");
return shaderProgram;
}
}
}
| |
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Localization;
using Newtonsoft.Json.Linq;
using OrchardCore.ContentManagement;
using OrchardCore.ContentManagement.Display;
using OrchardCore.ContentManagement.Metadata;
using OrchardCore.ContentManagement.Metadata.Settings;
using OrchardCore.DisplayManagement.ModelBinding;
using OrchardCore.DisplayManagement.Notify;
using OrchardCore.Menu.Models;
using YesSql;
namespace OrchardCore.Menu.Controllers
{
public class AdminController : Controller
{
private readonly IContentManager _contentManager;
private readonly IAuthorizationService _authorizationService;
private readonly IContentItemDisplayManager _contentItemDisplayManager;
private readonly IContentDefinitionManager _contentDefinitionManager;
private readonly ISession _session;
private readonly INotifier _notifier;
private readonly IHtmlLocalizer H;
private readonly IUpdateModelAccessor _updateModelAccessor;
public AdminController(
ISession session,
IContentManager contentManager,
IAuthorizationService authorizationService,
IContentItemDisplayManager contentItemDisplayManager,
IContentDefinitionManager contentDefinitionManager,
INotifier notifier,
IHtmlLocalizer<AdminController> localizer,
IUpdateModelAccessor updateModelAccessor)
{
_contentManager = contentManager;
_authorizationService = authorizationService;
_contentItemDisplayManager = contentItemDisplayManager;
_contentDefinitionManager = contentDefinitionManager;
_session = session;
_notifier = notifier;
_updateModelAccessor = updateModelAccessor;
H = localizer;
}
public async Task<IActionResult> Create(string id, string menuContentItemId, string menuItemId)
{
if (String.IsNullOrWhiteSpace(id))
{
return NotFound();
}
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu))
{
return Forbid();
}
var contentItem = await _contentManager.NewAsync(id);
dynamic model = await _contentItemDisplayManager.BuildEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, true);
model.MenuContentItemId = menuContentItemId;
model.MenuItemId = menuItemId;
return View(model);
}
[HttpPost]
[ActionName("Create")]
public async Task<IActionResult> CreatePost(string id, string menuContentItemId, string menuItemId)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu))
{
return Forbid();
}
ContentItem menu;
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Menu");
if (!contentTypeDefinition.GetSettings<ContentTypeSettings>().Draftable)
{
menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.Latest);
}
else
{
menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.DraftRequired);
}
if (menu == null)
{
return NotFound();
}
var contentItem = await _contentManager.NewAsync(id);
dynamic model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, true);
if (!ModelState.IsValid)
{
model.MenuContentItemId = menuContentItemId;
model.MenuItemId = menuItemId;
return View(model);
}
if (menuItemId == null)
{
// Use the menu as the parent if no target is specified
menu.Alter<MenuItemsListPart>(part => part.MenuItems.Add(contentItem));
}
else
{
// Look for the target menu item in the hierarchy
var parentMenuItem = FindMenuItem(menu.Content, menuItemId);
// Couldn't find targeted menu item
if (parentMenuItem == null)
{
return NotFound();
}
var menuItems = parentMenuItem?.MenuItemsListPart?.MenuItems as JArray;
if (menuItems == null)
{
parentMenuItem["MenuItemsListPart"] = new JObject(
new JProperty("MenuItems", menuItems = new JArray())
);
}
menuItems.Add(JObject.FromObject(contentItem));
}
await _contentManager.SaveDraftAsync(menu);
return RedirectToAction("Edit", "Admin", new { area = "OrchardCore.Contents", contentItemId = menuContentItemId });
}
public async Task<IActionResult> Edit(string menuContentItemId, string menuItemId)
{
var menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.Latest);
if (menu == null)
{
return NotFound();
}
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu, menu))
{
return Forbid();
}
// Look for the target menu item in the hierarchy
JObject menuItem = FindMenuItem(menu.Content, menuItemId);
// Couldn't find targeted menu item
if (menuItem == null)
{
return NotFound();
}
var contentItem = menuItem.ToObject<ContentItem>();
dynamic model = await _contentItemDisplayManager.BuildEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, false);
model.MenuContentItemId = menuContentItemId;
model.MenuItemId = menuItemId;
return View(model);
}
[HttpPost]
[ActionName("Edit")]
public async Task<IActionResult> EditPost(string menuContentItemId, string menuItemId)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu))
{
return Forbid();
}
ContentItem menu;
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Menu");
if (!contentTypeDefinition.GetSettings<ContentTypeSettings>().Draftable)
{
menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.Latest);
}
else
{
menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.DraftRequired);
}
if (menu == null)
{
return NotFound();
}
// Look for the target menu item in the hierarchy
JObject menuItem = FindMenuItem(menu.Content, menuItemId);
// Couldn't find targeted menu item
if (menuItem == null)
{
return NotFound();
}
var contentItem = menuItem.ToObject<ContentItem>();
dynamic model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, false);
if (!ModelState.IsValid)
{
model.MenuContentItemId = menuContentItemId;
model.MenuItemId = menuItemId;
return View(model);
}
menuItem.Merge(contentItem.Content, new JsonMergeSettings
{
MergeArrayHandling = MergeArrayHandling.Replace,
MergeNullValueHandling = MergeNullValueHandling.Merge
});
await _contentManager.SaveDraftAsync(menu);
return RedirectToAction("Edit", "Admin", new { area = "OrchardCore.Contents", contentItemId = menuContentItemId });
}
[HttpPost]
public async Task<IActionResult> Delete(string menuContentItemId, string menuItemId)
{
if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageMenu))
{
return Forbid();
}
ContentItem menu;
var contentTypeDefinition = _contentDefinitionManager.GetTypeDefinition("Menu");
if (!contentTypeDefinition.GetSettings<ContentTypeSettings>().Draftable)
{
menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.Latest);
}
else
{
menu = await _contentManager.GetAsync(menuContentItemId, VersionOptions.DraftRequired);
}
if (menu == null)
{
return NotFound();
}
// Look for the target menu item in the hierarchy
var menuItem = FindMenuItem(menu.Content, menuItemId);
// Couldn't find targeted menu item
if (menuItem == null)
{
return NotFound();
}
menuItem.Remove();
await _contentManager.SaveDraftAsync(menu);
_notifier.Success(H["Menu item deleted successfully"]);
return RedirectToAction("Edit", "Admin", new { area = "OrchardCore.Contents", contentItemId = menuContentItemId });
}
private JObject FindMenuItem(JObject contentItem, string menuItemId)
{
if (contentItem["ContentItemId"]?.Value<string>() == menuItemId)
{
return contentItem;
}
if (contentItem.GetValue("MenuItemsListPart") == null)
{
return null;
}
var menuItems = (JArray)contentItem["MenuItemsListPart"]["MenuItems"];
JObject result;
foreach (JObject menuItem in menuItems)
{
// Search in inner menu items
result = FindMenuItem(menuItem, menuItemId);
if (result != null)
{
return result;
}
}
return null;
}
}
}
| |
using Microsoft.Data.Entity.Migrations;
namespace AllReady.Migrations
{
public partial class UpdatingModelForUserEmailChange : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity");
migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill");
migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill");
migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.CreateTable(
name: "ClosestLocation",
columns: table => new
{
PostalCode = table.Column<string>(nullable: false),
City = table.Column<string>(nullable: true),
Distance = table.Column<double>(nullable: false),
State = table.Column<string>(nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_ClosestLocation", x => x.PostalCode);
});
migrationBuilder.CreateTable(
name: "PostalCodeGeoCoordinate",
columns: table => new
{
Latitude = table.Column<double>(nullable: false),
Longitude = table.Column<double>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_PostalCodeGeoCoordinate", x => new { x.Latitude, x.Longitude });
});
migrationBuilder.AddColumn<string>(
name: "PendingNewEmail",
table: "AspNetUsers",
nullable: true);
migrationBuilder.AddForeignKey(
name: "FK_Activity_Campaign_CampaignId",
table: "Activity",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ActivitySkill_Activity_ActivityId",
table: "ActivitySkill",
column: "ActivityId",
principalTable: "Activity",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_ActivitySkill_Skill_SkillId",
table: "ActivitySkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_Campaign_Organization_ManagingOrganizationId",
table: "Campaign",
column: "ManagingOrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Campaign_CampaignId",
table: "CampaignContact",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Contact_ContactId",
table: "CampaignContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Contact_ContactId",
table: "OrganizationContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Organization_OrganizationId",
table: "OrganizationContact",
column: "OrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_Skill_SkillId",
table: "TaskSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_AllReadyTask_TaskId",
table: "TaskSkill",
column: "TaskId",
principalTable: "AllReadyTask",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_Skill_SkillId",
table: "UserSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_ApplicationUser_UserId",
table: "UserSkill",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(name: "FK_Activity_Campaign_CampaignId", table: "Activity");
migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Activity_ActivityId", table: "ActivitySkill");
migrationBuilder.DropForeignKey(name: "FK_ActivitySkill_Skill_SkillId", table: "ActivitySkill");
migrationBuilder.DropForeignKey(name: "FK_Campaign_Organization_ManagingOrganizationId", table: "Campaign");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Campaign_CampaignId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_CampaignContact_Contact_ContactId", table: "CampaignContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Contact_ContactId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_OrganizationContact_Organization_OrganizationId", table: "OrganizationContact");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_Skill_SkillId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_TaskSkill_AllReadyTask_TaskId", table: "TaskSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_Skill_SkillId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_UserSkill_ApplicationUser_UserId", table: "UserSkill");
migrationBuilder.DropForeignKey(name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId", table: "AspNetRoleClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId", table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId", table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_IdentityRole_RoleId", table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(name: "FK_IdentityUserRole<string>_ApplicationUser_UserId", table: "AspNetUserRoles");
migrationBuilder.DropColumn(name: "PendingNewEmail", table: "AspNetUsers");
migrationBuilder.DropTable("ClosestLocation");
migrationBuilder.DropTable("PostalCodeGeoCoordinate");
migrationBuilder.AddForeignKey(
name: "FK_Activity_Campaign_CampaignId",
table: "Activity",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ActivitySkill_Activity_ActivityId",
table: "ActivitySkill",
column: "ActivityId",
principalTable: "Activity",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_ActivitySkill_Skill_SkillId",
table: "ActivitySkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_Campaign_Organization_ManagingOrganizationId",
table: "Campaign",
column: "ManagingOrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Campaign_CampaignId",
table: "CampaignContact",
column: "CampaignId",
principalTable: "Campaign",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_CampaignContact_Contact_ContactId",
table: "CampaignContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Contact_ContactId",
table: "OrganizationContact",
column: "ContactId",
principalTable: "Contact",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_OrganizationContact_Organization_OrganizationId",
table: "OrganizationContact",
column: "OrganizationId",
principalTable: "Organization",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_Skill_SkillId",
table: "TaskSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_TaskSkill_AllReadyTask_TaskId",
table: "TaskSkill",
column: "TaskId",
principalTable: "AllReadyTask",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_Skill_SkillId",
table: "UserSkill",
column: "SkillId",
principalTable: "Skill",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_UserSkill_ApplicationUser_UserId",
table: "UserSkill",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityRoleClaim<string>_IdentityRole_RoleId",
table: "AspNetRoleClaims",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserClaim<string>_ApplicationUser_UserId",
table: "AspNetUserClaims",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserLogin<string>_ApplicationUser_UserId",
table: "AspNetUserLogins",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_IdentityRole_RoleId",
table: "AspNetUserRoles",
column: "RoleId",
principalTable: "AspNetRoles",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_IdentityUserRole<string>_ApplicationUser_UserId",
table: "AspNetUserRoles",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
| |
namespace Microsoft.Protocols.TestSuites.MS_ASCNTC
{
using System;
using System.Collections.Generic;
using System.Xml;
using Microsoft.Protocols.TestSuites.Common;
using DataStructures = Microsoft.Protocols.TestSuites.Common.DataStructures;
using Request = Microsoft.Protocols.TestSuites.Common.Request;
/// <summary>
/// A static class contains all helper methods used in test cases.
/// </summary>
internal static class TestSuiteHelper
{
/// <summary>
/// Create MIME for SendMail command.
/// </summary>
/// <param name="from">The email address of sender.</param>
/// <param name="to">The email address of recipient.</param>
/// <param name="subject">The email subject.</param>
/// <param name="body">The email body content.</param>
/// <returns>A MIME for SendMail command.</returns>
internal static string CreateMIME(string from, string to, string subject, string body)
{
// Create a plain text MIME
string mime =
@"From: {0}
To: {1}
Subject: {2}
Content-Type: text/plain; charset=""us-ascii""
MIME-Version: 1.0
{3}
";
return Common.FormatString(mime, from, to, subject, body);
}
/// <summary>
/// Create an initial Sync request by using the specified collection Id.
/// </summary>
/// <param name="collectionId">Identify the folder as the collection being synchronized.</param>
/// <param name="supportedElements">The elements in Supported element.</param>
/// <returns>The SyncRequest instance.</returns>
internal static SyncRequest CreateInitialSyncRequest(string collectionId, Request.Supported supportedElements)
{
Request.SyncCollection syncCollection = new Request.SyncCollection
{
CollectionId = collectionId,
SyncKey = "0",
Supported = supportedElements
};
return Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection });
}
/// <summary>
/// Create a Sync Add request.
/// </summary>
/// <param name="syncKey">Specify the sync key obtained from the last Sync response</param>
/// <param name="collectionId">Specify the serverId of the folder to be synchronized.</param>
/// <param name="applicationData">The data used to specify the Add element for Sync command.</param>
/// <returns>The SyncRequest instance.</returns>
internal static SyncRequest CreateSyncAddRequest(string syncKey, string collectionId, Request.SyncCollectionAddApplicationData applicationData)
{
SyncRequest syncAddRequest = TestSuiteHelper.CreateSyncRequest(syncKey, collectionId, null);
Request.SyncCollectionAdd add = new Request.SyncCollectionAdd
{
ClientId = Guid.NewGuid().ToString("N"),
ApplicationData = applicationData
};
List<object> commandList = new List<object> { add };
syncAddRequest.RequestData.Collections[0].Commands = commandList.ToArray();
return syncAddRequest;
}
/// <summary>
/// Create a Sync Change request by using the specified sync key, folder collectionId and change application data.
/// </summary>
/// <param name="syncKey">Specify the sync key obtained from the last Sync response.</param>
/// <param name="collectionId">Specify the serverId of the folder to be synchronized.</param>
/// <param name="changeData">The data used to specify the Change element for Sync command.</param>
/// <returns>The SyncRequest instance.</returns>
internal static SyncRequest CreateSyncChangeRequest(string syncKey, string collectionId, Request.SyncCollectionChange changeData)
{
Request.SyncCollection syncCollection = CreateSyncCollection(syncKey, collectionId);
syncCollection.Commands = new object[] { changeData };
return Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection });
}
/// <summary>
/// Create a generic Sync request without command references by using the specified sync key, folder collectionId and body preference option.
/// </summary>
/// <param name="syncKey">Specify the sync key obtained from the last Sync response.</param>
/// <param name="collectionId">Specify the serverId of the folder to be synchronized.</param>
/// <param name="bodyPreference">Sets preference information related to the type and size of information for body.</param>
/// <returns>The SyncRequest instance.</returns>
internal static SyncRequest CreateSyncRequest(string syncKey, string collectionId, Request.BodyPreference bodyPreference)
{
Request.SyncCollection syncCollection = CreateSyncCollection(syncKey, collectionId);
Request.Options syncOptions = new Request.Options();
List<object> syncOptionItems = new List<object>();
List<Request.ItemsChoiceType1> syncOptionItemsName = new List<Request.ItemsChoiceType1>();
if (null != bodyPreference)
{
syncOptionItemsName.Add(Request.ItemsChoiceType1.BodyPreference);
syncOptionItems.Add(bodyPreference);
// when body format is mime (Refer to [MS-ASAIRS] 2.2.2.22 Type)
if (bodyPreference.Type == 0x4)
{
syncOptionItemsName.Add(Request.ItemsChoiceType1.MIMESupport);
// '2' indicates server sends MIME data for all messages but not S/MIME messages only.
syncOptionItems.Add((byte)0x2);
}
}
syncOptions.Items = syncOptionItems.ToArray();
syncOptions.ItemsElementName = syncOptionItemsName.ToArray();
syncCollection.Options = new Request.Options[] { syncOptions };
return Common.CreateSyncRequest(new Request.SyncCollection[] { syncCollection });
}
/// <summary>
/// Create an instance of SyncCollection
/// </summary>
/// <param name="syncKey">Specify the synchronization key obtained from the last Sync command response.</param>
/// <param name="collectionId">Specify the serverId of the folder to be synchronized.</param>
/// <returns>An instance of SyncCollection.</returns>
internal static Request.SyncCollection CreateSyncCollection(string syncKey, string collectionId)
{
Request.SyncCollection syncCollection = new Request.SyncCollection
{
SyncKey = syncKey,
GetChanges = true,
GetChangesSpecified = true,
CollectionId = collectionId,
WindowSize = "100"
};
return syncCollection;
}
/// <summary>
/// Create a Search request.
/// </summary>
/// <param name="query">The query string.</param>
/// <param name="collectionId">The collection id of searched folder.</param>
/// <param name="bodyPreference">The bodyPreference in the options element.</param>
/// <returns>A Search command request.</returns>
internal static SearchRequest CreateSearchRequest(string query, string collectionId, Request.BodyPreference bodyPreference)
{
SearchRequest request = new SearchRequest
{
RequestData =
{
Items = new Request.SearchStore[]
{
new Request.SearchStore()
{
Name = SearchName.Mailbox.ToString(),
Query = new Request.queryType()
{
Items = new object[]
{
new Request.queryType()
{
Items = new object[]
{
collectionId,
query
},
ItemsElementName = new Request.ItemsChoiceType2[]
{
Request.ItemsChoiceType2.CollectionId,
Request.ItemsChoiceType2.FreeText
}
}
},
ItemsElementName = new Request.ItemsChoiceType2[]
{
Request.ItemsChoiceType2.And
}
}
}
}
}
};
List<object> items = new List<object>();
List<Request.ItemsChoiceType6> itemsElementName = new List<Request.ItemsChoiceType6>();
if (bodyPreference != null)
{
items.Add(bodyPreference);
itemsElementName.Add(Request.ItemsChoiceType6.BodyPreference);
// Include the MIMESupport element in request to retrieve the MIME body
if (bodyPreference.Type == 4)
{
items.Add((byte)2);
itemsElementName.Add(Request.ItemsChoiceType6.MIMESupport);
}
}
items.Add(string.Empty);
itemsElementName.Add(Request.ItemsChoiceType6.RebuildResults);
items.Add("0-9");
itemsElementName.Add(Request.ItemsChoiceType6.Range);
items.Add(string.Empty);
itemsElementName.Add(Request.ItemsChoiceType6.DeepTraversal);
request.RequestData.Items[0].Options = new Request.Options1()
{
ItemsElementName = itemsElementName.ToArray(),
Items = items.ToArray()
};
return request;
}
/// <summary>
/// Create an ItemOperations command request.
/// </summary>
/// <param name="collectionId">The collection id.</param>
/// <param name="serverId">The serverId of the item.</param>
/// <param name="bodyPreference">The bodyPreference in the options element.</param>
/// <param name="schema">Sets the schema information.</param>
/// <returns>An ItemOperations command request.</returns>
internal static ItemOperationsRequest CreateItemOperationsRequest(string collectionId, string serverId, Request.BodyPreference bodyPreference, Request.Schema schema)
{
ItemOperationsRequest request = new ItemOperationsRequest { RequestData = new Request.ItemOperations() };
Request.ItemOperationsFetch fetch = new Request.ItemOperationsFetch
{
Store = SearchName.Mailbox.ToString(),
CollectionId = collectionId,
ServerId = serverId
};
List<object> items = new List<object>();
List<Request.ItemsChoiceType5> itemsElementName = new List<Request.ItemsChoiceType5>();
if (null != schema)
{
itemsElementName.Add(Request.ItemsChoiceType5.Schema);
items.Add(schema);
}
if (null != bodyPreference)
{
itemsElementName.Add(Request.ItemsChoiceType5.BodyPreference);
items.Add(bodyPreference);
if (bodyPreference.Type == 0x4)
{
itemsElementName.Add(Request.ItemsChoiceType5.MIMESupport);
// '2' indicates server sends MIME data for all messages but not S/MIME messages only
items.Add((byte)0x2);
}
}
if (items.Count > 0)
{
fetch.Options = new Request.ItemOperationsFetchOptions()
{
ItemsElementName = itemsElementName.ToArray(),
Items = items.ToArray()
};
}
request.RequestData.Items = new object[] { fetch };
return request;
}
/// <summary>
/// Get the specified email item from the Sync Add response by using the subject/FileAs.
/// </summary>
/// <param name="syncStore">The Sync result.</param>
/// <param name="fileAs">The contact FileAs.</param>
/// <returns>Return the specified email item.</returns>
internal static DataStructures.Sync GetSyncAddItem(DataStructures.SyncStore syncStore, string fileAs)
{
DataStructures.Sync item = null;
if (syncStore.AddElements.Count != 0)
{
foreach (DataStructures.Sync syncItem in syncStore.AddElements)
{
if (syncItem.Contact.FileAs == fileAs)
{
item = syncItem;
break;
}
if (syncItem.Email.Subject == fileAs)
{
item = syncItem;
break;
}
}
}
return item;
}
/// <summary>
/// Get the specified email item from the Sync Change response by using the subject.
/// </summary>
/// <param name="syncStore">The Sync result.</param>
/// <param name="fileAs">The contact FileAs.</param>
/// <returns>Return the specified email item.</returns>
internal static DataStructures.Sync GetSyncChangeItem(DataStructures.SyncStore syncStore, string fileAs)
{
DataStructures.Sync item = null;
if (syncStore.ChangeElements.Count != 0)
{
foreach (DataStructures.Sync syncItem in syncStore.ChangeElements)
{
if (syncItem.Contact.FileAs == fileAs)
{
item = syncItem;
break;
}
}
}
return item;
}
/// <summary>
/// Get the email item from the Search response by using the subject as the search criteria.
/// </summary>
/// <param name="searchStore">The Search command result.</param>
/// <param name="fileAs">The FileAs of the contact.</param>
/// <returns>The email item corresponds to the specified subject.</returns>
internal static DataStructures.Search GetSearchItem(DataStructures.SearchStore searchStore, string fileAs)
{
DataStructures.Search searchItem = null;
if (searchStore.Results.Count > 0)
{
foreach (DataStructures.Search item in searchStore.Results)
{
if (item.Contact.FileAs == fileAs)
{
searchItem = item;
break;
}
}
}
return searchItem;
}
/// <summary>
/// Check if the response message only contains the specified element in the specified xml tag.
/// </summary>
/// <param name="rawResponseXml">The raw xml of the response returned by SUT</param>
/// <param name="tagName">The name of the specified xml tag.</param>
/// <param name="elementName">The element name that the raw xml should contain.</param>
/// <returns>If the response only contains the specified element, return true; otherwise, false.</returns>
internal static bool IsOnlySpecifiedElementExist(XmlElement rawResponseXml, string tagName, string elementName)
{
bool isOnlySpecifiedElement = false;
if (rawResponseXml != null)
{
XmlNodeList nodes = rawResponseXml.GetElementsByTagName(tagName);
foreach (XmlNode node in nodes)
{
if (node.HasChildNodes)
{
XmlNodeList children = node.ChildNodes;
if (children.Count > 0)
{
foreach (XmlNode child in children)
{
if (string.Equals(child.Name, elementName))
{
isOnlySpecifiedElement = true;
}
else
{
isOnlySpecifiedElement = false;
break;
}
}
}
else
{
isOnlySpecifiedElement = false;
}
}
else
{
isOnlySpecifiedElement = false;
}
}
}
return isOnlySpecifiedElement;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
// This class is used to compress a Path to BAML.
//
// At compile-time this api is called into to "flatten" graphics calls to a BinaryWriter
// At run-time this api is called into to rehydrate the flattened graphics calls
// via invoking methods on a supplied StreamGeometryContext.
//
// Via this compression - we reduce the time spent parsing at startup, we create smaller baml,
// and we reduce creation of temporary strings.
//
using MS.Internal;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Security;
using System.IO;
using MS.Utility;
#if PBTCOMPILER
using MS.Internal.Markup;
namespace MS.Internal.Markup
#else
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Media3D;
using MS.Internal.PresentationCore;
namespace MS.Internal.Media
#endif
{
/// <summary>
/// ParserStreamGeometryContext
/// </summary>
internal class ParserStreamGeometryContext : StreamGeometryContext
{
enum ParserGeometryContextOpCodes : byte
{
BeginFigure = 0,
LineTo = 1,
QuadraticBezierTo = 2,
BezierTo = 3,
PolyLineTo = 4,
PolyQuadraticBezierTo = 5,
PolyBezierTo = 6,
ArcTo = 7,
Closed = 8,
FillRule = 9,
}
private const byte HighNibble = 0xF0;
private const byte LowNibble = 0x0F;
private const byte SetBool1 = 0x10; // 00010000
private const byte SetBool2 = 0x20; // 00100000
private const byte SetBool3 = 0x40; // 01000000
private const byte SetBool4 = 0x80; // 10000000
#region Constructors
/// <summary>
/// This constructor exists to prevent external derivation
/// </summary>
internal ParserStreamGeometryContext(BinaryWriter bw)
{
_bw = bw;
}
#endregion Constructors
#region internal Methods
#if PRESENTATION_CORE
internal void SetFillRule(FillRule fillRule)
#else
internal void SetFillRule(bool boolFillRule)
#endif
{
#if PRESENTATION_CORE
bool boolFillRule = FillRuleToBool(fillRule);
#endif
byte packedByte = PackByte(ParserGeometryContextOpCodes.FillRule, boolFillRule, false);
_bw.Write(packedByte);
}
/// <summary>
/// BeginFigure - Start a new figure.
/// </summary>
/// <remarks>
/// Stored as [PointAndTwoBools] (see SerializepointAndTwoBools method).
/// </remarks>
public override void BeginFigure(Point startPoint, bool isFilled, bool isClosed)
{
//
// We need to update the BeginFigure block of the last figure (if
// there was one).
//
FinishFigure();
_startPoint = startPoint;
_isFilled = isFilled;
_isClosed = isClosed;
_figureStreamPosition = CurrentStreamPosition;
//
// This will be overwritten later when we start the next figure (i.e. when we're sure isClosed isn't
// going to change). We write it out now to ensure that we reserve exactly the right amount of space.
// Note that the number of bytes written is dependant on the particular value of startPoint, since
// we can compress doubles when they are in fact integral.
//
SerializePointAndTwoBools(ParserGeometryContextOpCodes.BeginFigure, startPoint, isFilled, isClosed);
}
/// <summary>
/// LineTo - append a LineTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [PointAndTwoBools] (see SerializepointAndTwoBools method).
/// </remarks>
public override void LineTo(Point point, bool isStroked, bool isSmoothJoin)
{
SerializePointAndTwoBools(ParserGeometryContextOpCodes.LineTo, point, isStroked, isSmoothJoin);
}
/// <summary>
/// QuadraticBezierTo - append a QuadraticBezierTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [PointAndTwoBools] [Number] [Number]
/// </remarks>
public override void QuadraticBezierTo(Point point1, Point point2, bool isStroked, bool isSmoothJoin)
{
SerializePointAndTwoBools(ParserGeometryContextOpCodes.QuadraticBezierTo, point1, isStroked, isSmoothJoin);
XamlSerializationHelper.WriteDouble(_bw, point2.X);
XamlSerializationHelper.WriteDouble(_bw, point2.Y);
}
/// <summary>
/// BezierTo - apply a BezierTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [PointAndTwoBools] [Number] [Number] [Number] [Number]
/// </remarks>
public override void BezierTo(Point point1, Point point2, Point point3, bool isStroked, bool isSmoothJoin)
{
SerializePointAndTwoBools(ParserGeometryContextOpCodes.BezierTo, point1, isStroked, isSmoothJoin);
XamlSerializationHelper.WriteDouble(_bw, point2.X);
XamlSerializationHelper.WriteDouble(_bw, point2.Y);
XamlSerializationHelper.WriteDouble(_bw, point3.X);
XamlSerializationHelper.WriteDouble(_bw, point3.Y);
}
/// <summary>
/// PolyLineTo - append a PolyLineTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [ListOfPointAndTwoBools] (see SerializeListOfPointsAndTwoBools method).
/// </remarks>
public override void PolyLineTo(IList<Point> points, bool isStroked, bool isSmoothJoin)
{
SerializeListOfPointsAndTwoBools(ParserGeometryContextOpCodes.PolyLineTo, points, isStroked, isSmoothJoin);
}
/// <summary>
/// PolyQuadraticBezierTo - append a PolyQuadraticBezierTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [ListOfPointAndTwoBools] (see SerializeListOfPointsAndTwoBools method).
/// </remarks>
public override void PolyQuadraticBezierTo(IList<Point> points, bool isStroked, bool isSmoothJoin)
{
SerializeListOfPointsAndTwoBools(ParserGeometryContextOpCodes.PolyQuadraticBezierTo, points, isStroked, isSmoothJoin);
}
/// <summary>
/// PolyBezierTo - append a PolyBezierTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [ListOfPointAndTwoBools] (see SerializeListOfPointsAndTwoBools method).
/// </remarks>
public override void PolyBezierTo(IList<Point> points, bool isStroked, bool isSmoothJoin)
{
SerializeListOfPointsAndTwoBools(ParserGeometryContextOpCodes.PolyBezierTo, points, isStroked, isSmoothJoin);
}
/// <summary>
/// ArcTo - append an ArcTo to the current figure.
/// </summary>
/// <remarks>
/// Stored as [PointAndTwoBools] [Packed byte for isLargeArc and sweepDirection] [Pair of Numbers for Size] [Pair of Numbers for rotation Angle]
///
/// Also note that we've special cased this method signature to avoid moving the enum for SweepDirection into PBT (will require codegen changes).
/// </remarks>
#if PBTCOMPILER
public override void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, bool sweepDirection, bool isStroked, bool isSmoothJoin)
#else
public override void ArcTo(Point point, Size size, double rotationAngle, bool isLargeArc, SweepDirection sweepDirection, bool isStroked, bool isSmoothJoin)
#endif
{
SerializePointAndTwoBools(ParserGeometryContextOpCodes.ArcTo, point, isStroked, isSmoothJoin);
//
// Pack isLargeArc & sweepDirection into a single byte.
//
byte packMe = 0;
if (isLargeArc)
{
packMe = LowNibble;
}
#if PBTCOMPILER
if (sweepDirection)
#else
if (SweepToBool(sweepDirection))
#endif
{
packMe |= HighNibble;
}
_bw.Write(packMe);
//
// Write out Size & Rotation Angle.
//
XamlSerializationHelper.WriteDouble(_bw, size.Width);
XamlSerializationHelper.WriteDouble(_bw, size.Height);
XamlSerializationHelper.WriteDouble(_bw, rotationAngle);
}
internal bool FigurePending
{
get
{
return (_figureStreamPosition > -1);
}
}
internal int CurrentStreamPosition
{
get
{
return checked((int)_bw.Seek(0, SeekOrigin.Current));
}
}
internal void FinishFigure()
{
if (FigurePending)
{
int currentOffset = CurrentStreamPosition;
//
// Go back and overwrite our existing begin figure block. See comment in BeginFigure.
//
_bw.Seek(_figureStreamPosition, SeekOrigin.Begin);
SerializePointAndTwoBools(ParserGeometryContextOpCodes.BeginFigure, _startPoint, _isFilled, _isClosed);
_bw.Seek(currentOffset, SeekOrigin.Begin);
}
}
/// <summary>
/// This is the same as the Close call:
/// Closes the Context and flushes the content.
/// Afterwards the Context can not be used anymore.
/// This call does not require all Push calls to have been Popped.
/// </summary>
internal override void DisposeCore()
{
}
/// <summary>
/// SetClosedState - Sets the current closed state of the figure.
/// </summary>
internal override void SetClosedState(bool closed)
{
_isClosed = closed;
}
/// <summary>
/// Mark that the stream is Done.
/// </summary>
internal void MarkEOF()
{
//
// We need to update the BeginFigure block of the last figure (if
// there was one).
//
FinishFigure();
_bw.Write((byte) ParserGeometryContextOpCodes.Closed);
}
#if PRESENTATION_CORE
internal static void Deserialize(BinaryReader br, StreamGeometryContext sc, StreamGeometry geometry)
{
bool closed = false;
Byte currentByte;
while (!closed)
{
currentByte = br.ReadByte();
ParserGeometryContextOpCodes opCode = UnPackOpCode(currentByte);
switch(opCode)
{
case ParserGeometryContextOpCodes.FillRule :
DeserializeFillRule(br, currentByte, geometry);
break;
case ParserGeometryContextOpCodes.BeginFigure :
DeserializeBeginFigure(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.LineTo :
DeserializeLineTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.QuadraticBezierTo :
DeserializeQuadraticBezierTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.BezierTo :
DeserializeBezierTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.PolyLineTo :
DeserializePolyLineTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.PolyQuadraticBezierTo :
DeserializePolyQuadraticBezierTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.PolyBezierTo :
DeserializePolyBezierTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.ArcTo :
DeserializeArcTo(br, currentByte, sc);
break;
case ParserGeometryContextOpCodes.Closed :
closed = true;
break;
}
}
}
#endif
#endregion internal Methods
#region private Methods
//
// Deserialization Methods.
//
// These are only required at "runtime" - therefore only in PRESENTATION_CORE
//
#if PRESENTATION_CORE
private static void DeserializeFillRule(BinaryReader br, Byte firstByte, StreamGeometry geometry)
{
bool boolFillRule;
bool unused;
FillRule fillRule;
UnPackBools(firstByte, out boolFillRule, out unused);
fillRule = BoolToFillRule(boolFillRule);
geometry.FillRule = fillRule;
}
private static void DeserializeBeginFigure(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
{
Point point;
bool isFilled;
bool isClosed;
DeserializePointAndTwoBools(br, firstByte, out point, out isFilled, out isClosed);
sc.BeginFigure(point, isFilled, isClosed);
}
private static void DeserializeLineTo(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
{
Point point;
bool isStroked;
bool isSmoothJoin;
DeserializePointAndTwoBools(br, firstByte, out point, out isStroked, out isSmoothJoin);
sc.LineTo(point, isStroked, isSmoothJoin);
}
private static void DeserializeQuadraticBezierTo(BinaryReader br, byte firstByte, StreamGeometryContext sc)
{
Point point1;
Point point2 = new Point();
bool isStroked;
bool isSmoothJoin;
DeserializePointAndTwoBools(br, firstByte, out point1, out isStroked, out isSmoothJoin);
point2.X = XamlSerializationHelper.ReadDouble(br);
point2.Y = XamlSerializationHelper.ReadDouble(br);
sc.QuadraticBezierTo(point1, point2, isStroked, isSmoothJoin);
}
private static void DeserializeBezierTo(BinaryReader br, byte firstByte, StreamGeometryContext sc)
{
Point point1;
Point point2 = new Point();
Point point3 = new Point();
bool isStroked;
bool isSmoothJoin;
DeserializePointAndTwoBools(br, firstByte, out point1, out isStroked, out isSmoothJoin);
point2.X = XamlSerializationHelper.ReadDouble(br);
point2.Y = XamlSerializationHelper.ReadDouble(br);
point3.X = XamlSerializationHelper.ReadDouble(br);
point3.Y = XamlSerializationHelper.ReadDouble(br);
sc.BezierTo(point1, point2, point3, isStroked, isSmoothJoin);
}
private static void DeserializePolyLineTo(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
{
bool isStroked;
bool isSmoothJoin;
IList<Point> points;
points = DeserializeListOfPointsAndTwoBools(br, firstByte, out isStroked, out isSmoothJoin);
sc.PolyLineTo(points, isStroked, isSmoothJoin);
}
private static void DeserializePolyQuadraticBezierTo(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
{
bool isStroked;
bool isSmoothJoin;
IList<Point> points;
points = DeserializeListOfPointsAndTwoBools(br, firstByte, out isStroked, out isSmoothJoin);
sc.PolyQuadraticBezierTo(points, isStroked, isSmoothJoin);
}
private static void DeserializePolyBezierTo(BinaryReader br, Byte firstByte, StreamGeometryContext sc)
{
bool isStroked;
bool isSmoothJoin;
IList<Point> points;
points = DeserializeListOfPointsAndTwoBools(br, firstByte, out isStroked, out isSmoothJoin);
sc.PolyBezierTo(points, isStroked, isSmoothJoin);
}
private static void DeserializeArcTo(BinaryReader br, byte firstByte, StreamGeometryContext sc)
{
Point point;
Size size = new Size();
double rotationAngle;
bool isStroked;
bool isSmoothJoin;
bool isLargeArc;
SweepDirection sweepDirection;
DeserializePointAndTwoBools(br, firstByte, out point, out isStroked, out isSmoothJoin);
// Read the packed byte for isLargeArd & sweepDirection.
//
// Pack isLargeArc & sweepDirection into a signle byte.
//
byte packedByte = br.ReadByte();
isLargeArc = ((packedByte & LowNibble) != 0);
sweepDirection = BoolToSweep(((packedByte & HighNibble) != 0));
size.Width = XamlSerializationHelper.ReadDouble(br);
size.Height = XamlSerializationHelper.ReadDouble(br);
rotationAngle = XamlSerializationHelper.ReadDouble(br);
sc.ArcTo(point, size, rotationAngle, isLargeArc, sweepDirection, isStroked, isSmoothJoin);
}
//
// Private Deserialization helpers.
//
private static void UnPackBools(byte packedByte, out bool bool1, out bool bool2)
{
bool1 = (packedByte & SetBool1) != 0;
bool2 = (packedByte & SetBool2) != 0;
}
private static void UnPackBools(byte packedByte, out bool bool1, out bool bool2, out bool bool3, out bool bool4)
{
bool1 = (packedByte & SetBool1) != 0;
bool2 = (packedByte & SetBool2) != 0;
bool3 = (packedByte & SetBool3) != 0;
bool4 = (packedByte & SetBool4) != 0;
}
private static ParserGeometryContextOpCodes UnPackOpCode(byte packedByte)
{
return ((ParserGeometryContextOpCodes) (packedByte & 0x0F));
}
private static IList<Point> DeserializeListOfPointsAndTwoBools(BinaryReader br, Byte firstByte, out bool bool1, out bool bool2)
{
int count;
IList<Point> points;
Point point;
// Pack the two bools into one byte
UnPackBools(firstByte, out bool1, out bool2);
count = br.ReadInt32();
points = new List<Point>(count);
for(int i = 0; i < count; i++)
{
point = new Point(XamlSerializationHelper.ReadDouble(br),
XamlSerializationHelper.ReadDouble(br));
points.Add(point);
}
return points;
}
private static void DeserializePointAndTwoBools(BinaryReader br, Byte firstByte, out Point point, out bool bool1, out bool bool2)
{
bool isScaledIntegerX = false;
bool isScaledIntegerY = false;
UnPackBools(firstByte, out bool1, out bool2, out isScaledIntegerX, out isScaledIntegerY);
point = new Point(DeserializeDouble(br, isScaledIntegerX),
DeserializeDouble(br, isScaledIntegerY));
}
private static Double DeserializeDouble(BinaryReader br, bool isScaledInt)
{
if (isScaledInt)
{
return XamlSerializationHelper.ReadScaledInteger(br);
}
else
{
return XamlSerializationHelper.ReadDouble(br);
}
}
//
// Private serialization helpers
//
private static SweepDirection BoolToSweep(bool value)
{
if(!value)
return SweepDirection.Counterclockwise;
else
return SweepDirection.Clockwise;
}
private static bool SweepToBool(SweepDirection sweep)
{
if (sweep == SweepDirection.Counterclockwise)
return false;
else
return true;
}
private static FillRule BoolToFillRule(bool value)
{
if(!value)
return FillRule.EvenOdd;
else
return FillRule.Nonzero;
}
private static bool FillRuleToBool(FillRule fill)
{
if (fill == FillRule.EvenOdd)
return false;
else
return true;
}
#endif
//
// SerializePointAndTwoBools
//
// Binary format is :
//
// <Byte+OpCode> <Number1> <Number2>
//
// Where :
// <Byte+OpCode> := OpCode + bool1 + bool2 + isScaledIntegerX + isScaledIntegerY
// <NumberN> := <ScaledInteger> | <SerializationFloatTypeForSpecialNumbers> | <SerializationFloatType.Double+Double>
// <SerializationFloatTypeForSpecialNumbers> := <SerializationFloatType.Zero> | <SerializationFloatType.One> | <SerializationFloatType.MinusOne>
// <SerializationFloatType.Double+Double> := <SerializationFloatType.Double> <Double>
//
// By packing the flags for isScaledInteger into the first byte - we save 2 extra bytes per number for the common case.
//
// As a result - most LineTo's (and other operations) will be stored in 9 bytes.
// Some LineTo's will be 6 (or even sometimes 3)
// Max LineTo will be 19 (two doubles).
private void SerializePointAndTwoBools(ParserGeometryContextOpCodes opCode,
Point point,
bool bool1,
bool bool2)
{
int intValueX = 0;
int intValueY = 0;
bool isScaledIntegerX, isScaledIntegerY;
isScaledIntegerX = XamlSerializationHelper.CanConvertToInteger(point.X, ref intValueX);
isScaledIntegerY = XamlSerializationHelper.CanConvertToInteger(point.Y, ref intValueY);
_bw.Write(PackByte(opCode, bool1, bool2, isScaledIntegerX, isScaledIntegerY));
SerializeDouble(point.X, isScaledIntegerX, intValueX);
SerializeDouble(point.Y, isScaledIntegerY, intValueY);
}
// SerializeListOfPointsAndTwoBools
//
// Binary format is :
//
// <Byte+OpCode> <Count> <Number1> ... <NumberN>
//
// <Byte+OpCode> := OpCode + bool1 + bool2
// <Count> := int32
// <NumberN> := <SerializationFloatType.ScaledInteger+Integer> | <SerializationFloatTypeForSpecialNumbers> | <SerializationFloatType.Double+Double>
private void SerializeListOfPointsAndTwoBools(ParserGeometryContextOpCodes opCode, IList<Point> points, bool bool1, bool bool2)
{
// Pack the two bools into one byte
Byte packedByte = PackByte(opCode, bool1, bool2);
_bw.Write(packedByte);
// Write the count.
_bw.Write(points.Count);
// Write out all the Points
for(int i = 0; i < points.Count; i++)
{
XamlSerializationHelper.WriteDouble(_bw, points[i].X);
XamlSerializationHelper.WriteDouble(_bw, points[i].Y);
}
}
private void SerializeDouble(double value, bool isScaledInt, int scaledIntValue)
{
if (isScaledInt)
{
_bw.Write(scaledIntValue);
}
else
{
XamlSerializationHelper.WriteDouble(_bw, value);
}
}
private static byte PackByte(ParserGeometryContextOpCodes opCode, bool bool1, bool bool2)
{
return PackByte(opCode, bool1, bool2, false, false);
}
// PackByte
// Packs an op-code, and up to 4 booleans into a single byte.
//
// Binary format is :
// First 4 bits map directly to the op-code.
// Next 4 bits map to booleans 1 - 4.
//
// Like this:
//
// 7| 6 | 5 | 4 | 3 | 2 | 1 | 0 |
// <B4>|<B3>|<B2>|<B1><- Op Code ->
//
private static byte PackByte(ParserGeometryContextOpCodes opCode, bool bool1, bool bool2, bool bool3, bool bool4)
{
byte packedByte = (byte) opCode;
if (packedByte >= 16)
{
throw new ArgumentException(SR.Get(SRID.UnknownPathOperationType));
}
if (bool1)
{
packedByte |= SetBool1;
}
if (bool2)
{
packedByte |= SetBool2;
}
if (bool3)
{
packedByte |= SetBool3;
}
if (bool4)
{
packedByte |= SetBool4;
}
return packedByte;
}
#endregion private Methods
private BinaryWriter _bw;
Point _startPoint;
bool _isClosed;
bool _isFilled;
int _figureStreamPosition = -1;
}
}
| |
/*
Copyright (c) 2004-2009 Krzysztof Ostrowski. All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED "AS IS" BY THE ABOVE COPYRIGHT HOLDER(S)
AND ALL OTHER CONTRIBUTORS 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 ABOVE COPYRIGHT HOLDER(S) OR ANY OTHER
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.Text;
using System.Xml.Serialization;
namespace QS.Fx.Base
{
[QS.Fx.Reflection.ValueClass(QS.Fx.Reflection.ValueClasses.UINT32)]
[QS.Fx.Printing.Printable(QS.Fx.Printing.PrintingStyle.Native)]
[QS.Fx.Serialization.ClassID(QS.ClassID.Fx_Base_Unsigned_32)]
[XmlType(TypeName = "UINT32")]
public sealed class UINT32 : QS.Fx.Serialization.ISerializable, IComparable<UINT32>, IComparable, IEquatable<UINT32>, QS.Fx.Serialization.IStringSerializable
{
#region Constructor
public UINT32(uint number)
{
this.number = number;
}
public UINT32(string number)
{
this.String = number;
}
public UINT32()
{
}
#endregion
#region Fields
private uint number;
#endregion
#region Accessors
[XmlIgnore]
public uint Number
{
get { return this.number; }
set { this.number = value; }
}
[XmlAttribute("value")]
public string String
{
get { return this.number.ToString(); }
set { this.number = Convert.ToUInt32(value); }
}
#endregion
#region Casting
public static explicit operator uint(UINT32 u)
{
return u.number;
}
public static explicit operator UINT32(uint number)
{
return new UINT32(number);
}
public static explicit operator UINT32(string number)
{
return new UINT32(number);
}
public static explicit operator string(UINT32 number)
{
return number.String;
}
#endregion
#region Overridden from System.Object
public override string ToString()
{
return this.number.ToString("x");
}
public override bool Equals(object obj)
{
return (obj is UINT32) && (((UINT32)obj).number == this.number);
}
public override int GetHashCode()
{
return this.number.GetHashCode();
}
#endregion
#region IComparable<Incarnation> Members
public int CompareTo(UINT32 other)
{
return this.number.CompareTo(other.number);
}
#endregion
#region ISerializable Members
public unsafe QS.Fx.Serialization.SerializableInfo SerializableInfo
{
get { return new QS.Fx.Serialization.SerializableInfo((ushort) QS.ClassID.Fx_Base_Unsigned_32, sizeof(uint), sizeof(uint), 0); }
}
public unsafe void SerializeTo(ref QS.Fx.Base.ConsumableBlock header, ref IList<QS.Fx.Base.Block> data)
{
fixed (byte* bufferptr = header.Array)
{
*((uint*)(bufferptr + header.Offset)) = this.number;
}
header.consume(sizeof(uint));
}
public unsafe void DeserializeFrom(ref QS.Fx.Base.ConsumableBlock header, ref QS.Fx.Base.ConsumableBlock data)
{
fixed (byte* bufferptr = header.Array)
{
this.number = *((uint*)(bufferptr + header.Offset));
}
header.consume(sizeof(uint));
}
#endregion
#region IComparable Members
int IComparable.CompareTo(object other)
{
if (other is UINT32)
return this.number.CompareTo(((UINT32)other).number);
else
throw new Exception("Cannot compare with an object that is not an Unsigned_32.");
}
#endregion
#region IEquatable<Incarnation> Members
bool IEquatable<UINT32>.Equals(UINT32 other)
{
return other.number == this.number;
}
#endregion
#region IStringSerializable Members
ushort QS.Fx.Serialization.IStringSerializable.ClassID
{
get { return (ushort) QS.ClassID.Fx_Base_Unsigned_32; }
}
string QS.Fx.Serialization.IStringSerializable.AsString
{
get { return this.String; }
set { this.String = value; }
}
#endregion
}
}
| |
// $Id: ClientGmsImpl.java,v 1.12 2004/09/08 09:17:17 belaban Exp $
using System;
using System.Collections;
using Alachisoft.NCache.Common.Threading;
using Alachisoft.NCache.Common.Net;
using Alachisoft.NCache.Common.Enum;
namespace Alachisoft.NGroups.Protocols.pbcast
{
/// <summary> Client part of GMS. Whenever a new member wants to join a group, it starts in the CLIENT role.
/// No multicasts to the group will be received and processed until the member has been joined and
/// turned into a SERVER (either coordinator or participant, mostly just participant). This class
/// only implements <code>Join</code> (called by clients who want to join a certain group, and
/// <code>ViewChange</code> which is called by the coordinator that was contacted by this client, to
/// tell the client what its initial membership is.
/// </summary>
/// <author> Bela Ban
/// </author>
/// <version> $Revision: 1.12 $
/// </version>
internal class ClientGmsImpl:GmsImpl
{
internal ArrayList initial_mbrs = ArrayList.Synchronized(new ArrayList(11));
internal bool initial_mbrs_received = false;
internal object view_installation_mutex = new object();
internal Promise join_promise = new Promise();
public ClientGmsImpl(GMS g)
{
gms = g;
}
/// <summary> Joins this process to a group. Determines the coordinator and sends a unicast
/// handleJoin() message to it. The coordinator returns a JoinRsp and then broadcasts the new view, which
/// contains a message digest and the current membership (including the joiner). The joiner is then
/// supposed to install the new view and the digest and starts accepting mcast messages. Previous
/// mcast messages were discarded (this is done in PBCAST).<p>
/// If successful, impl is changed to an instance of ParticipantGmsImpl.
/// Otherwise, we continue trying to send join() messages to the coordinator,
/// until we succeed (or there is no member in the group. In this case, we create our own singleton group).
/// <p>When GMS.disable_initial_coord is set to true, then we won't become coordinator on receiving an initial
/// membership of 0, but instead will retry (forever) until we get an initial membership of > 0.
/// </summary>
/// <param name="mbr">Our own address (assigned through SET_LOCAL_ADDRESS)
/// </param>
public override void join(Address mbr, bool isStartedAsMirror)
{
Address coord = null;
Address last_tried_coord = null;
JoinRsp rsp = null;
Digest tmp_digest = null;
leaving = false;
int join_retries = 1;
join_promise.Reset();
while (!leaving)
{
findInitialMembers();
gms.Stack.NCacheLog.Debug("pb.ClientGmsImpl.join()", "initial_mbrs are " + Global.CollectionToString(initial_mbrs));
if (initial_mbrs.Count == 0)
{
if (gms.disable_initial_coord)
{
gms.Stack.NCacheLog.Debug("pb.ClientGmsImpl.join()", "received an initial membership of 0, but cannot become coordinator (disable_initial_coord=" + gms.disable_initial_coord + "), will retry fetching the initial membership");
continue;
}
gms.Stack.NCacheLog.CriticalInfo("ClientGmsImpl.Join", "no initial members discovered: creating group as first member.");
becomeSingletonMember(mbr);
return ;
}
coord = determineCoord(initial_mbrs);
if (coord == null)
{
gms.Stack.NCacheLog.Error("pb.ClientGmsImpl.join()", "could not determine coordinator from responses " + Global.CollectionToString(initial_mbrs));
continue;
}
if (coord.CompareTo(gms.local_addr) == 0)
{
gms.Stack.NCacheLog.Error("pb.ClientGmsImpl.join()", "coordinator anomaly. More members exist yet i am the coordinator " + Global.CollectionToString(initial_mbrs));
ArrayList members = new ArrayList();
for (int i = 0; i < initial_mbrs.Count; i++)
{
PingRsp ping_rsp = (PingRsp)initial_mbrs[i];
if (ping_rsp.OwnAddress != null && gms.local_addr != null && !ping_rsp.OwnAddress.Equals(gms.local_addr))
{
members.Add(ping_rsp.OwnAddress);
}
}
gms.InformOthersAboutCoordinatorDeath(members, coord);
if (last_tried_coord == null)
last_tried_coord = coord;
else
{
if (last_tried_coord.Equals(coord))
join_retries++;
else
{
last_tried_coord = coord;
join_retries = 1;
}
}
Util.Util.sleep(gms.join_timeout);
continue;
}
try
{
gms.Stack.NCacheLog.Debug("pb.ClientGmsImpl.join()", "sending handleJoin(" + mbr + ") to " + coord);
if (last_tried_coord == null)
last_tried_coord = coord;
else
{
if (last_tried_coord.Equals(coord))
join_retries++;
else
{
last_tried_coord = coord;
join_retries = 1;
}
}
sendJoinMessage(coord, mbr, gms.subGroup_addr, isStartedAsMirror);
rsp = (JoinRsp) join_promise.WaitResult(gms.join_timeout);
if (rsp == null)
{
if (join_retries >= gms.join_retry_count)
{
gms.Stack.NCacheLog.Error("ClientGmsImpl.Join", "received no joining response after " + join_retries + " tries, so becoming a singlton member");
becomeSingletonMember(mbr);
return;
}
else
{
//I did not receive join response, so there is a chance that coordinator is down
//Lets verifiy it.
if (gms.VerifySuspect(coord,false))
{
if(gms.Stack.NCacheLog.IsErrorEnabled) gms.Stack.NCacheLog.CriticalInfo("ClientGmsImpl.Join()", "selected coordinator " + coord + " seems down; Lets inform others");
//Coordinator is not alive;Lets inform the others
ArrayList members = new ArrayList();
for (int i = 0; i < initial_mbrs.Count; i++)
{
PingRsp ping_rsp = (PingRsp)initial_mbrs[i];
if (ping_rsp.OwnAddress != null && gms.local_addr != null && !ping_rsp.OwnAddress.Equals(gms.local_addr))
{
members.Add(ping_rsp.OwnAddress);
}
}
gms.InformOthersAboutCoordinatorDeath(members, coord);
}
}
gms.Stack.NCacheLog.Error("ClientGmsImpl.Join()", "handleJoin(" + mbr + ") failed, retrying; coordinator:" + coord + " ;No of retries : " + (join_retries + 1));
}
else
{
if (rsp.JoinResult == JoinResult.Rejected)
{
gms.Stack.NCacheLog.Error("ClientGmsImpl.Join", "joining request rejected by coordinator");
becomeSingletonMember(mbr);
return;
}
if (rsp.JoinResult == JoinResult.MembershipChangeAlreadyInProgress)
{
gms.Stack.NCacheLog.CriticalInfo("Coord.CheckOwnClusterHealth", "Reply: JoinResult.MembershipChangeAlreadyInProgress");
Util.Util.sleep(gms.join_timeout);
continue;
}
gms.Stack.NCacheLog.Debug("pb.ClientGmsImpl.join()", "Join successfull");
// 1. Install digest
tmp_digest = rsp.Digest;
if (tmp_digest != null)
{
tmp_digest.incrementHighSeqno(coord); // see DESIGN for an explanantion
gms.Stack.NCacheLog.Debug("pb.ClientGmsImpl.join()", "digest is " + tmp_digest);
gms.Digest = tmp_digest;
}
else
gms.Stack.NCacheLog.Error("pb.ClientGmsImpl.join()", "digest of JOIN response is null");
// 2. Install view
gms.Stack.NCacheLog.Debug("pb.ClientGmsImpl.join()", "[" + gms.local_addr + "]: JoinRsp=" + rsp.View + " [size=" + rsp.View.size() + "]\n\n");
if (rsp.View != null)
{
if (!installView(rsp.View))
{
gms.Stack.NCacheLog.Error("pb.ClientGmsImpl.join()", "view installation failed, retrying to join group");
continue;
}
gms.Stack.IsOperational = true;
return ;
}
else
gms.Stack.NCacheLog.Error("pb.ClientGmsImpl.join()", "view of JOIN response is null");
}
}
catch (System.Exception e)
{
gms.Stack.NCacheLog.Error("ClientGmsImpl.join()", "Message: "+e.Message+" StackTrace: "+e.StackTrace + ", retrying");
}
Util.Util.sleep(gms.join_retry_timeout);
}
}
public override void leave(Address mbr)
{
leaving = true;
wrongMethod("leave");
}
public override void handleJoinResponse(JoinRsp join_rsp)
{
join_promise.SetResult(join_rsp); // will wake up join() method
}
public override void handleLeaveResponse()
{
}
public override void suspect(Address mbr)
{
wrongMethod("suspect");
}
public override void unsuspect(Address mbr)
{
wrongMethod("unsuspect");
}
public override JoinRsp handleJoin(Address mbr, string subGroup_name, bool isStartedAsMirror, string gmsId)
{
wrongMethod("handleJoin");
return null;
}
/// <summary>Returns false. Clients don't handle leave() requests </summary>
public override void handleLeave(Address mbr, bool suspected)
{
wrongMethod("handleLeave");
}
/// <summary> Does nothing. Discards all views while still client.</summary>
public override void handleViewChange(View new_view, Digest digest)
{
lock (this)
{
gms.Stack.NCacheLog.Debug("pb.ClientGmsImpl.handleViewChange()", "view " + Global.CollectionToString(new_view.Members) + " is discarded as we are not a participant");
}
gms.passDown(new Event(Event.VIEW_CHANGE_OK, new object(),Priority.High));
}
/// <summary> Called by join(). Installs the view returned by calling Coord.handleJoin() and
/// becomes coordinator.
/// </summary>
private bool installView(View new_view)
{
ArrayList mems = new_view.Members;
gms.Stack.NCacheLog.Debug("pb.ClientGmsImpl.installView()", "new_view=" + new_view);
if (gms.local_addr == null || mems == null || !mems.Contains(gms.local_addr))
{
gms.Stack.NCacheLog.Error("pb.ClientGmsImpl.installView()", "I (" + gms.local_addr + ") am not member of " + Global.CollectionToString(mems) + ", will not install view");
return false;
}
gms.installView(new_view);
gms.becomeParticipant();
gms.Stack.IsOperational = true;
return true;
}
/// <summary>Returns immediately. Clients don't handle suspect() requests </summary>
public override void handleSuspect(Address mbr)
{
wrongMethod("handleSuspect");
return ;
}
/// <summary>
/// Informs the coodinator about the nodes to which this node can not establish connection
/// on receiving the first view. Only the node who has most recently joined the cluster
/// should inform the coodinator other nodes will neglect this event.
/// </summary>
/// <param name="nodes"></param>
public override void handleConnectionFailure(System.Collections.ArrayList nodes)
{
if (nodes != null && nodes.Count > 0)
{
if (gms.Stack.NCacheLog.IsInfoEnabled) gms.Stack.NCacheLog.Info("ClientGmsImp.handleConnectionFailure", "informing coordinator about connection failure with [" + Global.CollectionToString(nodes) + "]");
GMS.HDR header = new GMS.HDR(GMS.HDR.CAN_NOT_CONNECT_TO);
header.nodeList = nodes;
Message msg = new Message(gms.determineCoordinator(), null, new byte[0]);
msg.putHeader(HeaderType.GMS, header);
gms.passDown(new Event(Event.MSG, msg, Priority.High));
}
}
public override bool handleUpEvent(Event evt)
{
ArrayList tmp;
switch (evt.Type)
{
case Event.FIND_INITIAL_MBRS_OK:
tmp = (ArrayList) evt.Arg;
lock (initial_mbrs.SyncRoot)
{
if (tmp != null && tmp.Count > 0)
for (int i = 0; i < tmp.Count; i++)
initial_mbrs.Add(tmp[i]);
initial_mbrs_received = true;
System.Threading.Monitor.Pulse(initial_mbrs.SyncRoot);
}
return false; // don't pass up the stack
}
return true;
}
/* --------------------------- Private Methods ------------------------------------ */
internal virtual void sendJoinMessage(Address coord, Address mbr, string subGroup_name, bool isStartedAsMirror)
{
Message msg;
GMS.HDR hdr;
msg = new Message(coord, null, null);
hdr = new GMS.HDR(GMS.HDR.JOIN_REQ, mbr, subGroup_name, isStartedAsMirror);
hdr.GMSId = gms.unique_id;
msg.putHeader(HeaderType.GMS, hdr);
gms.passDown(new Event(Event.MSG_URGENT, msg,Priority.High));
}
internal virtual void sendSpeicalJoinMessage(Address mbr, ArrayList dests)
{
Message msg;
GMS.HDR hdr;
msg = new Message(null, null, new byte[0]);
msg.Dests = dests;
hdr = new GMS.HDR(GMS.HDR.SPECIAL_JOIN_REQUEST, mbr);
hdr.GMSId = gms.unique_id;
msg.putHeader(HeaderType.GMS, hdr);
gms.passDown(new Event(Event.MSG_URGENT, msg, Priority.High));
}
/// <summary> Pings initial members. Removes self before returning vector of initial members.
/// Uses IP multicast or gossiping, depending on parameters.
/// </summary>
internal virtual void findInitialMembers()
{
PingRsp ping_rsp;
lock (initial_mbrs.SyncRoot)
{
initial_mbrs.Clear();
initial_mbrs_received = false;
gms.passDown(new Event(Event.FIND_INITIAL_MBRS));
// the initial_mbrs_received flag is needed when passDown() is executed on the same thread, so when
// it returns, a response might actually have been received (even though the initial_mbrs might still be empty)
if (initial_mbrs_received == false)
{
try
{
System.Threading.Monitor.Wait(initial_mbrs.SyncRoot);
}
catch (System.Exception ex)
{
gms.Stack.NCacheLog.Error("ClientGmsImpl.findInitialMembers", ex.Message);
}
}
for (int i = 0; i < initial_mbrs.Count; i++)
{
ping_rsp = (PingRsp) initial_mbrs[i];
if (ping_rsp.OwnAddress != null && gms.local_addr != null && ping_rsp.OwnAddress.Equals(gms.local_addr))
{
//initial_mbrs.RemoveAt(i);
break;
}
if (!ping_rsp.IsStarted) initial_mbrs.RemoveAt(i);
}
}
}
/// <summary>The coordinator is determined by a majority vote.
/// If there are an equal number of votes for more than 1 candidate, we determine the winner randomly.
///
/// This is bad!. I've changed the election process altogether. I guess i'm the new pervez musharaf here
/// Let everyone cast a vote and unlike the non-deterministic coordinator selection process of jgroups. Ours
/// is a deterministic one. First we find members with most vote counts. If there is a tie member with lowest
/// IP addres wins, if there is tie again member with low port value wins.
///
/// This algortihm is determistic and ensures same results on every node icluding the coordinator. (shoaib)
/// </summary>
internal virtual Address determineCoord(ArrayList mbrs)
{
if (mbrs == null || mbrs.Count < 1)
return null;
Address winner = null;
int max_votecast = 0;
Hashtable votes = Hashtable.Synchronized(new Hashtable(11));
for (int i = 0; i < mbrs.Count; i++)
{
PingRsp mbr = (PingRsp) mbrs[i];
if (mbr.CoordAddress != null)
{
if (!votes.ContainsKey(mbr.CoordAddress))
votes[mbr.CoordAddress] = mbr.HasJoined ? 1000:1;
else
{
int count = ((int) votes[mbr.CoordAddress]);
votes[mbr.CoordAddress] = (int) (count + 1);
}
/// Find the maximum vote cast value. This will be used to resolve a
/// tie later on. (shoaib)
if(((int) votes[mbr.CoordAddress]) > max_votecast)
max_votecast = ((int) votes[mbr.CoordAddress]);
gms.Stack.NCacheLog.CriticalInfo("pb.ClientGmsImpl.determineCoord()", "Owner " + mbr.OwnAddress + " -- CoordAddress " + mbr.CoordAddress + " -- Vote " + (int)votes[mbr.CoordAddress]);
if ((mbr.OwnAddress.IpAddress.Equals(gms.local_addr.IpAddress)) && (mbr.OwnAddress.Port < gms.local_addr.Port))
{
gms.Stack.NCacheLog.Debug("pb.ClientGmsImpl.determineCoord()", "WINNER SET TO ACTIVE NODE's Coord = " + Convert.ToString(mbr.CoordAddress));
winner = mbr.CoordAddress;
}
}
}
/// Collect all the candidates with the highest but similar vote count.
/// Ideally there should only be one. (shoaib)
ArrayList candidates = new ArrayList(votes.Count);
for (IDictionaryEnumerator e = votes.GetEnumerator(); e.MoveNext(); )
{
if (((int)e.Value) == max_votecast)
{
candidates.Add(e.Key);
}
}
candidates.Sort();
if (winner == null)
{
winner = (Address)candidates[0];
}
if (candidates.Count > 1)
gms.Stack.NCacheLog.Warn("pb.ClientGmsImpl.determineCoord()", "there was more than 1 candidate for coordinator: " + Global.CollectionToString(candidates));
gms.Stack.NCacheLog.CriticalInfo("pb.ClientGmsImpl.determineCoord()", "election winner: " + winner + " with votes " + max_votecast);
return winner;
}
internal virtual void becomeSingletonMember(Address mbr)
{
Digest initial_digest;
ViewId view_id = null;
ArrayList mbrs = ArrayList.Synchronized(new ArrayList(1));
// set the initial digest (since I'm the first member)
initial_digest = new Digest(1); // 1 member (it's only me)
initial_digest.add(gms.local_addr, 0, 0); // initial seqno mcast by me will be 1 (highest seen +1)
gms.Digest = initial_digest;
view_id = new ViewId(mbr); // create singleton view with mbr as only member
mbrs.Add(mbr);
View v = new View(view_id, mbrs);
v.CoordinatorGmsId = gms.unique_id;
ArrayList subgroupMbrs = new ArrayList();
subgroupMbrs.Add(mbr);
gms._subGroupMbrsMap[gms.subGroup_addr] = subgroupMbrs;
gms._mbrSubGroupMap[mbr] = gms.subGroup_addr;
v.SequencerTbl = gms._subGroupMbrsMap.Clone() as Hashtable;
v.MbrsSubgroupMap = gms._mbrSubGroupMap.Clone() as Hashtable;
v.AddGmsId(mbr, gms.unique_id);
gms.installView(v);
gms.becomeCoordinator(); // not really necessary - installView() should do it
gms.Stack.IsOperational = true;
gms.Stack.NCacheLog.Debug("pb.ClientGmsImpl.becomeSingletonMember()", "created group (first member). My view is " + gms.view_id + ", impl is " + gms.Impl.GetType().FullName);
}
/// <summary>
/// In case of PartitionOfReplica this will verify that all the initial memebrs are completely up and running, It will also verify that
/// the replica of a POR and its phycsical Active counterpart has the same coordinator.
/// </summary>
/// <returns>True if ClusterHealth 'seems' ok otherwise false, True also in cas of everyother TOPOLOGY other than POR </returns>
private bool VerifyInitialembers()
{
if (initial_mbrs != null && initial_mbrs.Count > 1)
{
for (int i = 0; i < initial_mbrs.Count; i++)
{
PingRsp mbr = (PingRsp)initial_mbrs[i];
for (int j = i + 1; j <= initial_mbrs.Count - (i + 1); j++)
{
PingRsp ReplicaMbr = (PingRsp)initial_mbrs[j];
if (mbr.OwnAddress.IpAddress.Equals(ReplicaMbr.OwnAddress.IpAddress) && !mbr.CoordAddress.Equals(ReplicaMbr.CoordAddress))
return false;
}
}
}
return true;
}
public override bool isInStateTransfer
{
get
{
return false;
}
}
}
}
| |
#region LGPL License
/*
Axiom Game Engine Library
Copyright (C) 2003 Axiom Project Team
The overall design, and a majority of the core engine and rendering code
contained within this library is a derivative of the open source Object Oriented
Graphics Engine OGRE, which can be found at http://ogre.sourceforge.net.
Many thanks to the OGRE team for maintaining such a high quality project.
The math library included in this project, in addition to being a derivative of
the works of Ogre, also include derivative work of the free portion of the
Wild Magic mathematics source code that is distributed with the excellent
book Game Engine Design.
http://www.wild-magic.com/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#endregion
using System;
using System.Diagnostics;
namespace Axiom.MathLib {
/// <summary>
/// Summary description for Quaternion.
/// </summary>
public struct Quaternion {
#region Private member variables and constants
const float EPSILON = 1e-03f;
public float w, x, y, z;
private static readonly Quaternion identityQuat = new Quaternion(1.0f, 0.0f, 0.0f, 0.0f);
private static readonly Quaternion zeroQuat = new Quaternion(0.0f, 0.0f, 0.0f, 0.0f);
private static readonly int[] next = new int[3]{ 1, 2, 0 };
#endregion
#region Constructors
// public Quaternion()
// {
// this.w = 1.0f;
// }
/// <summary>
/// Creates a new Quaternion.
/// </summary>
public Quaternion(float w, float x, float y, float z) {
this.w = w;
this.x = x;
this.y = y;
this.z = z;
}
private Quaternion(string parsableText)
{
if(parsableText == null)
throw new ArgumentException("Text cannot be null.");
try
{
if ( parsableText[0] == '[' ) //[pitch,yaw,roll], Rotation in euler angles in degrees
{
string[] vals = parsableText.TrimStart('[').TrimEnd(']').Split(',');
Quaternion q = Quaternion.FromEulerAnglesInDegrees(float.Parse(vals[0]), float.Parse(vals[1]), float.Parse(vals[2]));
w = q.w;
x = q.x;
y = q.y;
z = q.z;
}
else
{
string[] vals = parsableText.TrimStart('(').TrimEnd(')').Split(',');
x = float.Parse(vals[0]);
y = float.Parse(vals[1]);
z = float.Parse(vals[2]);
w = float.Parse(vals[3]);
}
}
catch(Exception)
{
throw new FormatException(string.Format("Could not parse Quaternion from '{0}'.",parsableText));
}
}
#endregion
/// <summary>
///
/// </summary>
/// <param name="result"></param>
/// <param name="source"></param>
/// <returns></returns>
public static void AssignRef(ref Quaternion result, ref Quaternion source) {
result.w = source.w;
result.x = source.x;
result.y = source.y;
result.z = source.z;
}
/// <summary>
///
/// </summary>
/// <param name="result"></param>
/// <param name="quat"></param>
/// <param name="vector"></param>
/// <returns></returns>
public static void MultiplyRef(ref Quaternion result, ref Quaternion left, ref Quaternion right) {
result.w = left.w * right.w - left.x * right.x - left.y * right.y - left.z * right.z;
result.x = left.w * right.x + left.x * right.w + left.y * right.z - left.z * right.y;
result.y = left.w * right.y + left.y * right.w + left.z * right.x - left.x * right.z;
result.z = left.w * right.z + left.z * right.w + left.x * right.y - left.y * right.x;
}
/// <summary>
///
/// </summary>
/// <param name="result"></param>
/// <param name="quat"></param>
/// <param name="vector"></param>
/// <returns></returns>
public static void MultiplyRef (ref Vector3 result, ref Quaternion quat, ref Vector3 vector) {
// nVidia SDK implementation
Vector3 uuv = Vector3.Zero;
Vector3 qvec = new Vector3(quat.x, quat.y, quat.z);
result.x = (qvec.y * vector.z) - (qvec.z * vector.y);
result.y = (qvec.z * vector.x) - (qvec.x * vector.z);
result.z = (qvec.x * vector.y) - (qvec.y * vector.x);
uuv.x = (qvec.y * result.z) - (qvec.z * result.y);
uuv.y = (qvec.z * result.x) - (qvec.x * result.z);
uuv.z = (qvec.x * result.y) - (qvec.y * result.x);
float f = 2.0f * quat.w;
result.x = result.x * f + vector.x + uuv.x * 2.0f;
result.y = result.y * f + vector.y + uuv.y * 2.0f;
result.z = result.z * f + vector.z + uuv.z * 2.0f;
}
/// <summary>
/// Used when a float value is multiplied by a Quaternion.
/// </summary>
/// <param name="result"></param>
/// <param name="quat"></param>
/// <param name="scalar"></param>
/// <returns></returns>
public static void MultiplyRef (ref Quaternion result, ref Quaternion quat, float scalar) {
result.w = scalar * quat.w;
result.x = scalar * quat.x;
result.y = scalar * quat.y;
result.z = scalar * quat.z;
}
/// <summary>
/// Used when a Quaternion is added to another Quaternion.
/// </summary>
/// <param name="result"></param>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static void AddRef (ref Quaternion result, ref Quaternion left, ref Quaternion right) {
result.w = left.w + right.w;
result.x = left.x + right.x;
result.y = left.y + right.y;
result.z = left.z + right.z;
}
/// <summary>
/// Negates a Quaternion, which simply returns a new Quaternion
/// with all components negated.
/// </summary>
/// <param name="result"></param>
/// <param name="quat"></param>
/// <returns></returns>
public static void NegateRef(ref Quaternion result, ref Quaternion quat) {
result.w = -quat.w;
result.x = -quat.x;
result.y = -quat.y;
result.z = -quat.z;
}
public static bool EqualsRef(ref Quaternion left, ref Quaternion right) {
return (left.w == right.w && left.x == right.x && left.y == right.y && left.z == right.z);
}
#region Operator Overloads + CLS compliant method equivalents
/// <summary>
/// Used to multiply 2 Quaternions together.
/// </summary>
/// <remarks>
/// Quaternion multiplication is not communative in most cases.
/// i.e. p*q != q*p
/// </remarks>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static Quaternion Multiply (Quaternion left, Quaternion right) {
return left * right;
}
/// <summary>
/// Used to multiply 2 Quaternions together.
/// </summary>
/// <remarks>
/// Quaternion multiplication is not communative in most cases.
/// i.e. p*q != q*p
/// </remarks>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static Quaternion operator * (Quaternion left, Quaternion right) {
Quaternion q = new Quaternion();
q.w = left.w * right.w - left.x * right.x - left.y * right.y - left.z * right.z;
q.x = left.w * right.x + left.x * right.w + left.y * right.z - left.z * right.y;
q.y = left.w * right.y + left.y * right.w + left.z * right.x - left.x * right.z;
q.z = left.w * right.z + left.z * right.w + left.x * right.y - left.y * right.x;
/*
return new Quaternion
(
left.w * right.w - left.x * right.x - left.y * right.y - left.z * right.z,
left.w * right.x + left.x * right.w + left.y * right.z - left.z * right.y,
left.w * right.y + left.y * right.w + left.z * right.x - left.x * right.z,
left.w * right.z + left.z * right.w + left.x * right.y - left.y * right.x
); */
return q;
}
/// <summary>
///
/// </summary>
/// <param name="quat"></param>
/// <param name="vector"></param>
/// <returns></returns>
public static Vector3 Multiply (Quaternion quat, Vector3 vector) {
return quat * vector;
}
/// <summary>
///
/// </summary>
/// <param name="quat"></param>
/// <param name="vector"></param>
/// <returns></returns>
public static Vector3 operator*(Quaternion quat, Vector3 vector) {
// nVidia SDK implementation
Vector3 uv = Vector3.Zero;
Vector3 uuv = Vector3.Zero;
Vector3 qvec = new Vector3(quat.x, quat.y, quat.z);
uv.x = (qvec.y * vector.z) - (qvec.z * vector.y);
uv.y = (qvec.z * vector.x) - (qvec.x * vector.z);
uv.z = (qvec.x * vector.y) - (qvec.y * vector.x);
uuv.x = (qvec.y * uv.z) - (qvec.z * uv.y);
uuv.y = (qvec.z * uv.x) - (qvec.x * uv.z);
uuv.z = (qvec.x * uv.y) - (qvec.y * uv.x);
float f = 2.0f * quat.w;
uv.x = uv.x * f + vector.x + uuv.x * 2.0f;
uv.y = uv.y * f + vector.y + uuv.y * 2.0f;
uv.z = uv.z * f + vector.z + uuv.z * 2.0f;
return uv;
// get the rotation matrix of the Quaternion and multiply it times the vector
//return quat.ToRotationMatrix() * vector;
}
/// <summary>
/// Used when a float value is multiplied by a Quaternion.
/// </summary>
/// <param name="scalar"></param>
/// <param name="right"></param>
/// <returns></returns>
public static Quaternion Multiply (float scalar, Quaternion right) {
return scalar * right;
}
/// <summary>
/// Used when a float value is multiplied by a Quaternion.
/// </summary>
/// <param name="scalar"></param>
/// <param name="right"></param>
/// <returns></returns>
public static Quaternion operator*(float scalar, Quaternion right) {
return new Quaternion(scalar * right.w, scalar * right.x, scalar * right.y, scalar * right.z);
}
/// <summary>
/// Used when a Quaternion is multiplied by a float value.
/// </summary>
/// <param name="left"></param>
/// <param name="scalar"></param>
/// <returns></returns>
public static Quaternion Multiply (Quaternion left, float scalar) {
return left * scalar;
}
/// <summary>
/// Used when a Quaternion is multiplied by a float value.
/// </summary>
/// <param name="left"></param>
/// <param name="scalar"></param>
/// <returns></returns>
public static Quaternion operator*(Quaternion left, float scalar) {
return new Quaternion(scalar * left.w, scalar * left.x, scalar * left.y, scalar * left.z);
}
/// <summary>
/// Used when a Quaternion is added to another Quaternion.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static Quaternion Add (Quaternion left, Quaternion right) {
return left + right;
}
/// <summary>
/// Used when a Quaternion is added to another Quaternion.
/// </summary>
/// <param name="left"></param>
/// <param name="right"></param>
/// <returns></returns>
public static Quaternion operator+(Quaternion left, Quaternion right) {
return new Quaternion(left.w + right.w, left.x + right.x, left.y + right.y, left.z + right.z);
}
/// <summary>
/// Negates a Quaternion, which simply returns a new Quaternion
/// with all components negated.
/// </summary>
/// <param name="right"></param>
/// <returns></returns>
public static Quaternion operator - (Quaternion right) {
return new Quaternion(-right.w, -right.x, -right.y, -right.z);
}
public static bool operator == (Quaternion left, Quaternion right) {
return (left.w == right.w && left.x == right.x && left.y == right.y && left.z == right.z);
}
public static bool operator != (Quaternion left, Quaternion right)
{
return (left.w != right.w || left.x != right.x || left.y != right.y || left.z != right.z);
}
#endregion
#region Properties
/// <summary>
/// An Identity Quaternion.
/// </summary>
public static Quaternion Identity {
get {
return identityQuat;
}
}
/// <summary>
/// A Quaternion with all elements set to 0.0f;
/// </summary>
public static Quaternion Zero {
get {
return zeroQuat;
}
}
/// <summary>
/// Squared 'length' of this quaternion.
/// </summary>
public float Norm {
get {
return x * x + y * y + z * z + w * w;
}
}
/// <summary>
/// Local X-axis portion of this rotation.
/// </summary>
public Vector3 XAxis {
get {
float fTx = 2.0f * x;
float fTy = 2.0f * y;
float fTz = 2.0f * z;
float fTwy = fTy * w;
float fTwz = fTz * w;
float fTxy = fTy * x;
float fTxz = fTz * x;
float fTyy = fTy * y;
float fTzz = fTz * z;
return new Vector3(1.0f - (fTyy + fTzz), fTxy + fTwz, fTxz - fTwy);
}
}
/// <summary>
/// Local Y-axis portion of this rotation.
/// </summary>
public Vector3 YAxis {
get {
float fTx = 2.0f * x;
float fTy = 2.0f * y;
float fTz = 2.0f * z;
float fTwx = fTx * w;
float fTwz = fTz * w;
float fTxx = fTx * x;
float fTxy = fTy * x;
float fTyz = fTz * y;
float fTzz = fTz * z;
return new Vector3(fTxy - fTwz, 1.0f - (fTxx + fTzz), fTyz + fTwx);
}
}
/// <summary>
/// Local Z-axis portion of this rotation.
/// </summary>
public Vector3 ZAxis {
get {
float fTx = 2.0f * x;
float fTy = 2.0f * y;
float fTz = 2.0f * z;
float fTwx = fTx * w;
float fTwy = fTy * w;
float fTxx = fTx * x;
float fTxz = fTz * x;
float fTyy = fTy * y;
float fTyz = fTz * y;
return new Vector3(fTxz + fTwy, fTyz - fTwx, 1.0f - (fTxx+fTyy));
}
}
public float PitchInDegrees { get { return MathUtil.RadiansToDegrees(Pitch); } set { Pitch = MathUtil.DegreesToRadians(value); } }
public float YawInDegrees { get { return MathUtil.RadiansToDegrees(Yaw); } set { Yaw = MathUtil.DegreesToRadians(value); } }
public float RollInDegrees { get { return MathUtil.RadiansToDegrees(Roll); } set { Roll = MathUtil.DegreesToRadians(value); } }
public float Pitch {
set{
float pitch, yaw, roll;
ToEulerAngles(out pitch,out yaw,out roll);
FromEulerAngles(value, yaw, roll);
}
get{
float test = x*y + z*w;
if (Math.Abs(test) > 0.499f) // singularity at north and south pole
return 0f;
return (float)Math.Atan2(2*x*w-2*y*z , 1 - 2*x*x - 2*z*z);
}
}
public float Yaw {
set{
float pitch, yaw, roll;
ToEulerAngles(out pitch,out yaw,out roll);
FromEulerAngles(pitch, value, roll);
}
get{
float test = x*y + z*w;
if (Math.Abs(test) > 0.499f) // singularity at north and south pole
return Math.Sign(test) * 2 * (float)Math.Atan2(x,w);
return (float)Math.Atan2(2*y*w-2*x*z , 1 - 2*y*y - 2*z*z);
}
}
public float Roll {
set{
float pitch, yaw, roll;
ToEulerAngles(out pitch,out yaw,out roll);
FromEulerAngles(pitch, yaw, value);
}
get{
float test = x*y + z*w;
if (Math.Abs(test) > 0.499f) // singularity at north and south pole
return Math.Sign(test) * MathUtil.PI / 2;
return (float)Math.Asin(2*test);
}
}
public string EulerString {
get {
float pitch, yaw, roll;
this.ToEulerAnglesInDegrees(out pitch, out yaw, out roll);
return string.Format("[{0}, {1}, {2}]", pitch, yaw, roll);
}
}
#endregion
#region Static methods
public static Quaternion Parse(string text)
{
return new Quaternion(text);
}
public static Quaternion Slerp(float time, Quaternion quatA, Quaternion quatB) {
return Slerp(time, quatA, quatB, false);
}
/// <summary>
///
/// </summary>
/// <param name="time"></param>
/// <param name="quatA"></param>
/// <param name="quatB"></param>
/// <param name="useShortestPath"></param>
/// <returns></returns>
public static Quaternion Slerp(float time, Quaternion quatA, Quaternion quatB, bool useShortestPath) {
float cos = quatA.Dot(quatB);
float angle = MathUtil.ACos(cos);
if(MathUtil.Abs(angle) < EPSILON) {
return quatA;
}
float sin = MathUtil.Sin(angle);
float inverseSin = 1.0f / sin;
float coeff0 = MathUtil.Sin((1.0f - time) * angle) * inverseSin;
float coeff1 = MathUtil.Sin(time * angle) * inverseSin;
Quaternion result;
if(cos < 0.0f && useShortestPath) {
coeff0 = -coeff0;
// taking the complement requires renormalisation
Quaternion t = coeff0 * quatA + coeff1 * quatB;
t.Normalize();
result = t;
}
else {
result = (coeff0 * quatA + coeff1 * quatB);
}
return result;
}
public static void SlerpRef(ref Quaternion result, float time, ref Quaternion quatA, ref Quaternion quatB, bool useShortestPath) {
float cos = quatA.w * quatB.w + quatA.x * quatB.x + quatA.y * quatB.y + quatA.z * quatB.z;
float angle = MathUtil.ACos(cos);
if(MathUtil.Abs(angle) < EPSILON) {
result = quatA;
return;
}
float sin = MathUtil.Sin(angle);
float inverseSin = 1.0f / sin;
float coeff0 = MathUtil.Sin((1.0f - time) * angle) * inverseSin;
float coeff1 = MathUtil.Sin(time * angle) * inverseSin;
if(cos < 0.0f && useShortestPath) {
coeff0 = -coeff0;
// taking the complement requires renormalisation
result.w = coeff0 * quatA.w + coeff1 * quatB.w;
result.x = coeff0 * quatA.x + coeff1 * quatB.x;
result.y = coeff0 * quatA.y + coeff1 * quatB.y;
result.z = coeff0 * quatA.z + coeff1 * quatB.z;
float factor = 1.0f / MathUtil.Sqrt(result.Norm);
result.w *= factor;
result.x *= factor;
result.y *= factor;
result.z *= factor;
}
else {
result.w = coeff0 * quatA.w + coeff1 * quatB.w;
result.x = coeff0 * quatA.x + coeff1 * quatB.x;
result.y = coeff0 * quatA.y + coeff1 * quatB.y;
result.z = coeff0 * quatA.z + coeff1 * quatB.z;
}
}
/// <summary>
///
/// </summary>
/// <param name="result"></param>
/// <param name="time"></param>
/// <param name="quatA"></param>
/// <param name="quatB"></param>
/// <param name="useShortestPath"></param>
/// <returns></returns>
public static void NlerpRef(ref Quaternion result, float time, ref Quaternion quatA, ref Quaternion quatB, bool shortestPath) {
float cos = quatA.w * quatB.w + quatA.x * quatB.x + quatA.y * quatB.y + quatA.z * quatB.z;
if (cos < 0.0f && shortestPath) {
result.w = quatA.w + time * (- quatB.w - quatA.w);
result.x = quatA.x + time * (- quatB.x - quatA.x);
result.y = quatA.y + time * (- quatB.y - quatA.y);
result.z = quatA.z + time * (- quatB.z - quatA.z);
}
else {
result.w = quatA.w + time * (quatB.w - quatA.w);
result.x = quatA.x + time * (quatB.x - quatA.x);
result.y = quatA.y + time * (quatB.y - quatA.y);
result.z = quatA.z + time * (quatB.z - quatA.z);
}
float factor = 1.0f / MathUtil.Sqrt(result.x * result.x + result.y * result.y + result.z * result.z + result.w * result.w);
result.w = result.w * factor;
result.x = result.x * factor;
result.y = result.y * factor;
result.z = result.z * factor;
}
/// <summary>
///
/// </summary>
/// <param name="time"></param>
/// <param name="quatA"></param>
/// <param name="quatB"></param>
/// <param name="useShortestPath"></param>
/// <returns></returns>
public static Quaternion Nlerp(float time, Quaternion quatA, Quaternion quatB, bool shortestPath) {
Quaternion result;
float cos = quatA.Dot(quatB);
if (cos < 0.0f && shortestPath) {
result = quatA + time * ((-1 * quatB) + (-1 * quatA));
}
else {
result = quatA + time * (quatB + (-1 * quatA));
}
result.Normalize();
return result;
}
/// <summary>
/// Creates a Quaternion from a supplied angle and axis.
/// </summary>
/// <param name="angle">Value of an angle in radians.</param>
/// <param name="axis">Arbitrary axis vector.</param>
/// <returns></returns>
public static Quaternion FromAngleAxis(float angle, Vector3 axis) {
Quaternion quat = new Quaternion();
float halfAngle = 0.5f * angle;
float sin = MathUtil.Sin(halfAngle);
quat.w = MathUtil.Cos(halfAngle);
quat.x = sin * axis.x;
quat.y = sin * axis.y;
quat.z = sin * axis.z;
return quat;
}
public static Quaternion Squad(float t, Quaternion p, Quaternion a, Quaternion b, Quaternion q) {
return Squad(t, p, a, b, q, false);
}
/// <summary>
/// Performs spherical quadratic interpolation.
/// </summary>
/// <param name="t"></param>
/// <param name="p"></param>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="q"></param>
/// <returns></returns>
public static Quaternion Squad(float t, Quaternion p, Quaternion a, Quaternion b, Quaternion q, bool useShortestPath) {
float slerpT = 2.0f * t * (1.0f - t);
// use spherical linear interpolation
Quaternion slerpP = Slerp(t, p, q, useShortestPath);
Quaternion slerpQ = Slerp(t, a, b);
// run another Slerp on the results of the first 2, and return the results
return Slerp(slerpT, slerpP, slerpQ);
}
#endregion
#region Public methods
#region Euler Angles
public Vector3 ToEulerAnglesInDegrees() {
float pitch, yaw, roll;
ToEulerAngles(out pitch, out yaw, out roll);
return new Vector3(MathUtil.RadiansToDegrees(pitch), MathUtil.RadiansToDegrees(yaw), MathUtil.RadiansToDegrees(roll));
}
public Vector3 ToEulerAngles() {
float pitch, yaw, roll;
ToEulerAngles(out pitch, out yaw, out roll);
return new Vector3(pitch, yaw, roll);
}
public void ToEulerAnglesInDegrees(out float pitch, out float yaw, out float roll) {
ToEulerAngles(out pitch,out yaw,out roll);
pitch = MathUtil.RadiansToDegrees(pitch);
yaw = MathUtil.RadiansToDegrees(yaw);
roll = MathUtil.RadiansToDegrees(roll);
}
public void ToEulerAngles(out float pitch, out float yaw, out float roll) {
float halfPi = (float)Math.PI / 2;
float test = x*y + z*w;
if (test > 0.499f) { // singularity at north pole
yaw = 2 * (float)Math.Atan2(x,w);
roll = halfPi;
pitch = 0;
} else if (test < -0.499f) { // singularity at south pole
yaw = -2 * (float)Math.Atan2(x,w);
roll = -halfPi;
pitch = 0;
} else {
float sqx = x*x;
float sqy = y*y;
float sqz = z*z;
yaw = (float)Math.Atan2(2*y*w-2*x*z , 1 - 2*sqy - 2*sqz);
roll = (float)Math.Asin(2*test);
pitch = (float)Math.Atan2(2*x*w-2*y*z , 1 - 2*sqx - 2*sqz);
}
if(Math.Abs(pitch) <= float.Epsilon)
pitch = 0f;
if(Math.Abs(yaw) <= float.Epsilon)
yaw = 0f;
if(Math.Abs(roll) <= float.Epsilon)
roll = 0f;
}
public static Quaternion FromEulerAnglesInDegrees(float pitch, float yaw, float roll) {
return FromEulerAngles( MathUtil.DegreesToRadians(pitch), MathUtil.DegreesToRadians(yaw), MathUtil.DegreesToRadians(roll) );
}
/// <summary>
/// Combines the euler angles in the order roll, pitch, yaw to create a rotation quaternion.
/// This means that if you wrote this in standard math form, it would be Qy * Qp * Qr.
/// </summary>
/// <param name="pitch"></param>
/// <param name="yaw"></param>
/// <param name="roll"></param>
/// <returns></returns>
public static Quaternion FromEulerAngles(float pitch, float yaw, float roll) {
return Quaternion.FromAngleAxis(yaw, Vector3.UnitY)
* Quaternion.FromAngleAxis(pitch, Vector3.UnitX)
* Quaternion.FromAngleAxis(roll, Vector3.UnitZ);
/*TODO: Debug
//Equation from http://www.euclideanspace.com/maths/geometry/rotations/conversions/eulerToQuaternion/index.htm
//heading
float c1 = (float)Math.Cos(yaw/2);
float s1 = (float)Math.Sin(yaw/2);
//attitude
float c2 = (float)Math.Cos(roll/2);
float s2 = (float)Math.Sin(roll/2);
//bank
float c3 = (float)Math.Cos(pitch/2);
float s3 = (float)Math.Sin(pitch/2);
float c1c2 = c1*c2;
float s1s2 = s1*s2;
float w =c1c2*c3 - s1s2*s3;
float x =c1c2*s3 + s1s2*c3;
float y =s1*c2*c3 + c1*s2*s3;
float z =c1*s2*c3 - s1*c2*s3;
return new Quaternion(w,x,y,z);*/
}
#endregion
/// <summary>
/// Performs a Dot Product operation on 2 Quaternions.
/// </summary>
/// <param name="quat"></param>
/// <returns></returns>
public float Dot(Quaternion quat) {
return this.w * quat.w + this.x * quat.x + this.y * quat.y + this.z * quat.z;
}
/// <summary>
/// Normalizes elements of this quaterion to the range [0,1].
/// </summary>
public void Normalize() {
float factor = 1.0f / MathUtil.Sqrt(this.Norm);
w = w * factor;
x = x * factor;
y = y * factor;
z = z * factor;
}
/// <summary>
///
/// </summary>
/// <param name="angle"></param>
/// <param name="axis"></param>
/// <returns></returns>
public void ToAngleAxis(ref float angle, ref Vector3 axis) {
// The quaternion representing the rotation is
// q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k)
float sqrLength = x * x + y * y + z * z;
if(sqrLength > EPSILON * EPSILON) {
angle = 2.0f * MathUtil.ACos(w);
float invLength = MathUtil.InvSqrt(sqrLength);
axis.x = x * invLength;
axis.y = y * invLength;
axis.z = z * invLength;
}
else {
angle = 0.0f;
axis.x = 1.0f;
axis.y = 0.0f;
axis.z = 0.0f;
}
}
/// <summary>
/// Find the rotation from the orientation; scales it and
/// assigns it to the result; and assigns the translation
/// to the result.
/// </summary>
/// <param name="result"></param>
/// <param name="orientation"></param>
/// <param name="scale"></param>
/// <param name="translation"></param>
/// <returns></returns>
public static void ToRotationMatrixPlusTranslationRef(ref Matrix4 result, ref Quaternion orientation, ref Vector3 scale, ref Vector3 translation) {
float tx = 2.0f * orientation.x;
float ty = 2.0f * orientation.y;
float tz = 2.0f * orientation.z;
float twx = tx * orientation.w;
float twy = ty * orientation.w;
float twz = tz * orientation.w;
float txx = tx * orientation.x;
float txy = ty * orientation.x;
float txz = tz * orientation.x;
float tyy = ty * orientation.y;
float tyz = tz * orientation.y;
float tzz = tz * orientation.z;
result.m00 = (1.0f-(tyy+tzz)) * scale.x;
result.m01 = (txy-twz) * scale.y;
result.m02 = (txz+twy) * scale.z;
result.m10 = (txy+twz) * scale.x;
result.m11 = (1.0f-(txx+tzz)) * scale.y;
result.m12 = (tyz-twx) * scale.z;
result.m20 = (txz-twy) * scale.x;
result.m21 = (tyz+twx) * scale.y;
result.m22 = (1.0f-(txx+tyy)) * scale.z;
result.m03 = translation.x;
result.m13 = translation.y;
result.m23 = translation.z;
result.m33 = 1.0f;
}
/// <summary>
/// Gets a 3x3 rotation matrix from this Quaternion.
/// </summary>
/// <returns></returns>
public Matrix3 ToRotationMatrix() {
Matrix3 rotation = new Matrix3();
float tx = 2.0f * this.x;
float ty = 2.0f * this.y;
float tz = 2.0f * this.z;
float twx = tx * this.w;
float twy = ty * this.w;
float twz = tz * this.w;
float txx = tx * this.x;
float txy = ty * this.x;
float txz = tz * this.x;
float tyy = ty * this.y;
float tyz = tz * this.y;
float tzz = tz * this.z;
rotation.m00 = 1.0f-(tyy+tzz);
rotation.m01 = txy-twz;
rotation.m02 = txz+twy;
rotation.m10 = txy+twz;
rotation.m11 = 1.0f-(txx+tzz);
rotation.m12 = tyz-twx;
rotation.m20 = txz-twy;
rotation.m21 = tyz+twx;
rotation.m22 = 1.0f-(txx+tyy);
return rotation;
}
public void ToRotationMatrixRef(out Matrix3 rotation)
{
float tx = 2.0f * this.x;
float ty = 2.0f * this.y;
float tz = 2.0f * this.z;
float twx = tx * this.w;
float twy = ty * this.w;
float twz = tz * this.w;
float txx = tx * this.x;
float txy = ty * this.x;
float txz = tz * this.x;
float tyy = ty * this.y;
float tyz = tz * this.y;
float tzz = tz * this.z;
rotation.m00 = 1.0f - (tyy + tzz);
rotation.m01 = txy - twz;
rotation.m02 = txz + twy;
rotation.m10 = txy + twz;
rotation.m11 = 1.0f - (txx + tzz);
rotation.m12 = tyz - twx;
rotation.m20 = txz - twy;
rotation.m21 = tyz + twx;
rotation.m22 = 1.0f - (txx + tyy);
}
/// <summary>
/// Computes the inverse of a Quaternion.
/// </summary>
/// <returns></returns>
public Quaternion Inverse() {
float norm = this.w * this.w + this.x * this.x + this.y * this.y + this.z * this.z;
if ( norm > 0.0f ) {
float inverseNorm = 1.0f / norm;
return new Quaternion(this.w * inverseNorm, -this.x * inverseNorm, -this.y * inverseNorm, -this.z * inverseNorm);
}
else {
// return an invalid result to flag the error
return Quaternion.Zero;
}
}
public static void InverseRef(ref Quaternion quat, ref Quaternion result) {
float norm = quat.w * quat.w + quat.x * quat.x + quat.y * quat.y + quat.z * quat.z;
if ( norm > 0.0f ) {
float inverseNorm = 1.0f / norm;
result.w = quat.w * inverseNorm;
result.x = -quat.x * inverseNorm;
result.y = -quat.y * inverseNorm;
result.z = -quat.z * inverseNorm;
}
else {
result.w = 0;
result.x = 0;
result.y = 0;
result.z = 0;
}
}
/// <summary>
/// Variant of Inverse() that is only valid for unit quaternions.
/// </summary>
/// <returns></returns>
public Quaternion UnitInverse() {
return new Quaternion(w, -x, -y, -z);
}
/// <summary>
///
/// </summary>
/// <param name="xAxis"></param>
/// <param name="yAxis"></param>
/// <param name="zAxis"></param>
public void ToAxes (out Vector3 xAxis, out Vector3 yAxis, out Vector3 zAxis) {
xAxis = new Vector3();
yAxis = new Vector3();
zAxis = new Vector3();
Matrix3 rotation = this.ToRotationMatrix();
xAxis.x = rotation.m00;
xAxis.y = rotation.m10;
xAxis.z = rotation.m20;
yAxis.x = rotation.m01;
yAxis.y = rotation.m11;
yAxis.z = rotation.m21;
zAxis.x = rotation.m02;
zAxis.y = rotation.m12;
zAxis.z = rotation.m22;
}
/// <summary>
///
/// </summary>
/// <param name="xAxis"></param>
/// <param name="yAxis"></param>
/// <param name="zAxis"></param>
public void FromAxes(Vector3 xAxis, Vector3 yAxis, Vector3 zAxis) {
Matrix3 rotation = new Matrix3();
rotation.m00 = xAxis.x;
rotation.m10= xAxis.y;
rotation.m20 = xAxis.z;
rotation.m01 = yAxis.x;
rotation.m11 = yAxis.y;
rotation.m21 = yAxis.z;
rotation.m02 = zAxis.x;
rotation.m12 = zAxis.y;
rotation.m22 = zAxis.z;
// set this quaternions values from the rotation matrix built
FromRotationMatrix(rotation);
}
/// <summary>
///
/// </summary>
/// <param name="matrix"></param>
public void FromRotationMatrix(Matrix3 matrix) {
// Algorithm in Ken Shoemake's article in 1987 SIGGRAPH course notes
// article "Quaternion Calculus and Fast Animation".
float trace = matrix.m00 + matrix.m11 + matrix.m22;
float root = 0.0f;
if ( trace > 0.0f ) {
// |this.w| > 1/2, may as well choose this.w > 1/2
root = MathUtil.Sqrt(trace + 1.0f); // 2w
this.w = 0.5f * root;
root = 0.5f / root; // 1/(4w)
this.x = (matrix.m21 - matrix.m12) * root;
this.y = (matrix.m02 - matrix.m20) * root;
this.z = (matrix.m10 - matrix.m01) * root;
}
else {
// |this.w| <= 1/2
int i = 0;
if ( matrix.m11 > matrix.m00 )
i = 1;
if ( matrix.m22 > matrix[i,i] )
i = 2;
int j = next[i];
int k = next[j];
root = MathUtil.Sqrt(matrix[i,i] - matrix[j,j] - matrix[k,k] + 1.0f);
unsafe {
fixed(float* apkQuat = &this.x) {
apkQuat[i] = 0.5f * root;
root = 0.5f / root;
this.w = (matrix[k,j] - matrix[j,k]) * root;
apkQuat[j] = (matrix[j,i] + matrix[i,j]) * root;
apkQuat[k] = (matrix[k,i] + matrix[i,k]) * root;
}
}
}
}
/// <summary>
/// Calculates the logarithm of a Quaternion.
/// </summary>
/// <returns></returns>
public Quaternion Log() {
// BLACKBOX: Learn this
// If q = cos(A)+sin(A)*(x*i+y*j+z*k) where (x,y,z) is unit length, then
// log(q) = A*(x*i+y*j+z*k). If sin(A) is near zero, use log(q) =
// sin(A)*(x*i+y*j+z*k) since sin(A)/A has limit 1.
// start off with a zero quat
Quaternion result = Quaternion.Zero;
if(MathUtil.Abs(w) < 1.0f) {
float angle = MathUtil.ACos(w);
float sin = MathUtil.Sin(angle);
if(MathUtil.Abs(sin) >= EPSILON) {
float coeff = angle / sin;
result.x = coeff * x;
result.y = coeff * y;
result.z = coeff * z;
}
else {
result.x = x;
result.y = y;
result.z = z;
}
}
return result;
}
/// <summary>
/// Calculates the Exponent of a Quaternion.
/// </summary>
/// <returns></returns>
public Quaternion Exp() {
// If q = A*(x*i+y*j+z*k) where (x,y,z) is unit length, then
// exp(q) = cos(A)+sin(A)*(x*i+y*j+z*k). If sin(A) is near zero,
// use exp(q) = cos(A)+A*(x*i+y*j+z*k) since A/sin(A) has limit 1.
float angle = MathUtil.Sqrt(x * x + y * y + z * z);
float sin = MathUtil.Sin(angle);
// start off with a zero quat
Quaternion result = Quaternion.Zero;
result.w = MathUtil.Cos(angle);
if ( MathUtil.Abs(sin) >= EPSILON ) {
float coeff = sin / angle;
result.x = coeff * x;
result.y = coeff * y;
result.z = coeff * z;
}
else {
result.x = x;
result.y = y;
result.z = z;
}
return result;
}
#endregion
#region Object overloads
/// <summary>
/// Overrides the Object.ToString() method to provide a text representation of
/// a Vector3.
/// </summary>
/// <returns>A string representation of a vector3.</returns>
public override string ToString()
{
return string.Format("({0}, {1}, {2}, {3})", this.x, this.y, this.z, this.w);
}
public string ToParsableText()
{
return ToString();
}
/// <summary>
/// Overrides the Object.ToString() method to provide a text representation of
/// a Vector3.
/// </summary>
/// <returns>A string representation of a vector3.</returns>
public string ToIntegerString()
{
return string.Format("({0}, {1}, {2}, {3})", (int)this.x, (int)this.y, (int)this.z, (int)this.w);
}
/// <summary>
/// Overrides the Object.ToString() method to provide a text representation of
/// a Vector3.
/// </summary>
/// <returns>A string representation of a vector3.</returns>
public string ToString(bool shortenDecmialPlaces)
{
if(shortenDecmialPlaces)
return string.Format("({0:0.##}, {1:0.##} ,{2:0.##}, {3:0.##})", this.x, this.y, this.z, this.w);
return ToString();
}
public override int GetHashCode() {
return x.GetHashCode() ^ y.GetHashCode() ^ z.GetHashCode() ^ w.GetHashCode();
}
public override bool Equals(object obj) {
return obj is Quaternion && this == (Quaternion)obj;
}
public bool Equals(Quaternion obj, float tolerance) {
return (Math.Abs(x - obj.x) < tolerance && Math.Abs(y - obj.y) < tolerance &&
Math.Abs(z - obj.z) < tolerance && Math.Abs(w - obj.w) < tolerance);
}
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace CocosSharp
{
public class CCTileMapLayer : CCNode, IDisposable
{
const int NumOfVerticesPerQuad = 6;
const int NumOfCornersPerQuad = 4;
const int NumOfPrimitivesPerQuad = 2;
// Index buffer value types are unsigned shorts => (2^16) / 4 = 16384 max tiles
const int MaxTilesPerDrawBuffer = (ushort.MaxValue + 1) / 4;
bool visibleTileRangeDirty;
bool tileAnimationsDirty;
bool useAutomaticVertexZ;
float defaultTileVertexZ;
float minVertexZ;
bool antialiased;
bool halfTexelOffset;
bool tileQuadsDirty;
CCColor4B tileColor;
CCAffineTransform tileCoordsToNodeTransform;
CCAffineTransform nodeToTileCoordsTransform;
// Used by hexagonal and staggered isometric
CCAffineTransform tileCoordsToNodeTransformOdd;
CCAffineTransform nodeToTileCoordsTransformOdd;
List<CCTileMapDrawBufferManager> drawBufferManagers;
CCCustomCommand tileRenderCommand;
Dictionary<short, short> currentTileGidAnimations;
List<CCActionState> activeTileAnimationActionStates;
CCTileMapInfo mapInfo;
#region Properties
// Static properties
public static float DefaultTexelToContentSizeRatio
{
set { DefaultTexelToContentSizeRatios = new CCSize(value, value); }
}
public static CCSize DefaultTexelToContentSizeRatios { get; set; }
// Instance properties
internal CCTileGidAndFlags[] TileGIDAndFlagsArray { get; private set; }
public string LayerName { get; set; }
public CCTileMapType MapType { get { return mapInfo.MapType; } }
public CCTileMapCoordinates LayerSize { get; private set; }
public CCTileMapCoordinates TileCoordOffset { get; private set; }
public CCSize TileTexelSize { get { return mapInfo.TileTexelSize; } }
public Dictionary<string, string> LayerProperties { get; set; }
public Dictionary<short, CCRepeatForever> TileAnimations { get; private set; }
public bool Antialiased
{
get { return antialiased; }
set
{
antialiased = value;
foreach (var drawBufferManager in drawBufferManagers)
{
drawBufferManager.TileSetInfo.Texture.IsAntialiased = antialiased;
}
}
}
public bool HalfTexelOffset
{
get { return halfTexelOffset; }
set
{
if (halfTexelOffset != value)
{
halfTexelOffset = value;
tileQuadsDirty = true;
}
}
}
public override byte Opacity
{
get { return base.Opacity; }
set
{
base.Opacity = value;
tileColor = CCColor4B.White;
tileColor.A = Opacity;
}
}
public CCSize TileContentSize
{
get { return TileTexelSize * CCTileMapLayer.DefaultTexelToContentSizeRatios; }
}
uint NumberOfTiles
{
get { return (uint)(LayerSize.Row * LayerSize.Column); }
}
#endregion Properties
#region Constructors
static CCTileMapLayer()
{
DefaultTexelToContentSizeRatios = CCSize.One;
}
public CCTileMapLayer(CCTileSetInfo[] tileSetInfos, CCTileLayerInfo layerInfo, CCTileMapInfo mapInfo)
: this(tileSetInfos, layerInfo, mapInfo, layerInfo.LayerDimensions)
{
}
// Private constructor chaining
CCTileMapLayer(CCTileSetInfo[] tileSetInfos, CCTileLayerInfo layerInfo, CCTileMapInfo mapInfo, CCTileMapCoordinates layerSize)
: this(tileSetInfos, layerInfo, mapInfo, layerSize, (int)(layerSize.Row * layerSize.Column))
{
}
CCTileMapLayer(CCTileSetInfo[] tileSetInfos, CCTileLayerInfo layerInfo, CCTileMapInfo mapInfo, CCTileMapCoordinates layerSize, int totalNumberOfTiles)
: this(tileSetInfos, layerInfo, mapInfo, layerSize, totalNumberOfTiles, (int)(totalNumberOfTiles * 0.35f + 1))
{
}
CCTileMapLayer(CCTileSetInfo[] tileSetInfos, CCTileLayerInfo layerInfo, CCTileMapInfo mapInfo, CCTileMapCoordinates layerSize,
int totalNumberOfTiles, int tileCapacity)
{
tileRenderCommand = new CCCustomCommand(RenderTileMapLayer);
this.mapInfo = mapInfo;
LayerName = layerInfo.Name;
LayerSize = layerSize;
Opacity = layerInfo.Opacity;
LayerProperties = new Dictionary<string, string>(layerInfo.Properties);
TileCoordOffset = new CCTileMapCoordinates(layerInfo.TileCoordOffset);
ContentSize = LayerSize.Size * TileTexelSize * CCTileMapLayer.DefaultTexelToContentSizeRatios;
HalfTexelOffset = CCTileMap.DefaultHalfTexelOffset;
TileGIDAndFlagsArray = layerInfo.TileGIDAndFlags;
UpdateTileCoordsToNodeTransform();
ParseInternalProperties();
InitialiseTileAnimations();
InitialiseDrawBuffers(tileSetInfos);
GenerateMinVertexZ();
}
void ParseInternalProperties()
{
string vertexZStr = PropertyNamed("cc_vertexz");
if (!String.IsNullOrEmpty(vertexZStr))
{
if (vertexZStr == "automatic")
{
useAutomaticVertexZ = true;
}
else
{
defaultTileVertexZ = CCUtils.CCParseInt(vertexZStr);
}
}
}
void InitialiseDrawBuffers(CCTileSetInfo[] tileSetInfos)
{
drawBufferManagers = new List<CCTileMapDrawBufferManager>();
if (tileSetInfos != null)
{
foreach (var tileSetInfo in tileSetInfos)
{
// Initialize the QuadsVertexBuffers
if (tileSetInfo.TilesheetSize != CCSize.Zero)
{
drawBufferManagers.Add(InitialiseDrawBuffer(tileSetInfo));
}
}
}
tileQuadsDirty = false;
}
CCTileMapDrawBufferManager InitialiseDrawBuffer(CCTileSetInfo tileSetInfo)
{
CCTileMapDrawBufferManager drawBufferManager = new CCTileMapDrawBufferManager(LayerSize.Row, LayerSize.Column, this, tileSetInfo);
for (int y = 0; y < LayerSize.Row; y++)
{
for (int x = 0; x < LayerSize.Column; x++)
{
UpdateQuadAt(drawBufferManager, x, y, false);
}
}
drawBufferManager.UpdateQuadBuffers();
return drawBufferManager;
}
void InitialiseTileAnimations()
{
currentTileGidAnimations = new Dictionary<short, short>();
activeTileAnimationActionStates = new List<CCActionState>();
var tileAnimDict = mapInfo.TileAnimations;
TileAnimations = new Dictionary<short, CCRepeatForever>();
foreach (short gid in tileAnimDict.Keys)
{
var repeatAction = new CCRepeatForever(new CCTileAnimation(gid, tileAnimDict[gid]));
TileAnimations.Add(gid, repeatAction);
}
}
void GenerateMinVertexZ()
{
if (useAutomaticVertexZ)
{
switch (MapType)
{
case CCTileMapType.Iso:
minVertexZ = -(LayerSize.Column + LayerSize.Row - 2);
break;
case CCTileMapType.Ortho:
minVertexZ = -(LayerSize.Row - 1);
break;
case CCTileMapType.Staggered:
minVertexZ = -(LayerSize.Row - 1);
break;
default:
break;
}
}
else
minVertexZ = defaultTileVertexZ;
}
#endregion Constructors
protected override void AddedToScene()
{
base.AddedToScene();
visibleTileRangeDirty = true;
StartTileAnimations();
}
protected override void VisibleBoundsChanged()
{
base.VisibleBoundsChanged();
visibleTileRangeDirty = true;
}
protected override void ParentUpdatedTransform()
{
base.ParentUpdatedTransform();
visibleTileRangeDirty = true;
}
protected override void Dispose(bool disposing)
{
if (disposing)
foreach (var drawBufferManager in drawBufferManagers)
drawBufferManager.Dispose();
base.Dispose(disposing);
}
#region Drawing
void UpdateAllTileQuads()
{
foreach (CCTileMapDrawBufferManager drawBufferManager in drawBufferManagers)
{
for (int y = 0; y < LayerSize.Row; y++)
{
for (int x = 0; x < LayerSize.Column; x++)
{
UpdateQuadAt(drawBufferManager, x, y, false);
}
}
drawBufferManager.UpdateQuadBuffers();
}
tileQuadsDirty = false;
}
void UpdateTileCoordsToNodeTransform()
{
CCSize texToContentScaling = CCTileMapLayer.DefaultTexelToContentSizeRatios;
float width = TileTexelSize.Width * texToContentScaling.Width;
float height = TileTexelSize.Height * texToContentScaling.Height;
float yOffset = (LayerSize.Row - 1) * height;
tileCoordsToNodeTransformOdd = CCAffineTransform.Identity;
switch (MapType)
{
case CCTileMapType.Ortho:
// Note: For an orthographic map, top-left represents the origin (0,0)
// Moving right increases the column
// Moving left increases the row
tileCoordsToNodeTransform = new CCAffineTransform(new Matrix
(
width, 0.0f, 0.0f, 0.0f,
0.0f, -height, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, yOffset, 0.0f, 1.0f
));
break;
case CCTileMapType.Iso:
// Note: For an isometric map, top-right tile represents the origin (0,0)
// Moving left increases the column
// Moving right increases the row
float xOffset = (LayerSize.Column - 1) * (width / 2);
tileCoordsToNodeTransform = new CCAffineTransform(new Matrix
(
width / 2, -height / 2, 0.0f, 0.0f,
-width / 2, -height / 2, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
xOffset, yOffset, 0.0f, 1.0f
));
break;
case CCTileMapType.Hex:
tileCoordsToNodeTransform = new CCAffineTransform(new Matrix
(
height * (float)Math.Sqrt(0.75), 0.0f, 0.0f, 0.0f,
0.0f, -height, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, yOffset, 0.0f, 1.0f
));
tileCoordsToNodeTransformOdd = new CCAffineTransform(new Matrix
(
height * (float)Math.Sqrt(0.75), 0.0f, 0.0f, 0.0f,
0.0f , -height, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, yOffset - height/2, 0.0f, 1.0f
));
break;
case CCTileMapType.Staggered:
tileCoordsToNodeTransform = new CCAffineTransform(new Matrix
(
width, 0.0f, 0.0f, 0.0f,
0.0f, -height / 2, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, yOffset / 2, 0.0f, 1.0f
));
tileCoordsToNodeTransformOdd = new CCAffineTransform(new Matrix
(
width, 0.0f, 0.0f, 0.0f,
0.0f, -height / 2, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
width / 2, yOffset / 2, 0.0f, 1.0f
));
break;
default:
tileCoordsToNodeTransform = CCAffineTransform.Identity;
break;
}
// Adding global tile offsets that are specified by the layer info
CCPoint tileOffset = LayerOffset(TileCoordOffset);
tileCoordsToNodeTransform.Tx += tileOffset.X;
tileCoordsToNodeTransform.Ty += tileOffset.Y;
tileCoordsToNodeTransformOdd.Tx += tileOffset.X;
tileCoordsToNodeTransformOdd.Ty += tileOffset.Y;
nodeToTileCoordsTransform = tileCoordsToNodeTransform.Inverse;
nodeToTileCoordsTransformOdd = tileCoordsToNodeTransformOdd.Inverse;
}
protected override void VisitRenderer(ref CCAffineTransform worldTransform)
{
if (tileQuadsDirty)
UpdateAllTileQuads();
tileRenderCommand.GlobalDepth = worldTransform.Tz + minVertexZ;
tileRenderCommand.WorldTransform = worldTransform;
DrawManager.Renderer.AddCommand(tileRenderCommand);
}
void RenderTileMapLayer()
{
if (visibleTileRangeDirty)
UpdateVisibleTileRange();
if (tileAnimationsDirty)
UpdateTileAnimations();
CCDrawManager drawManager = DrawManager;
var alphaTest = drawManager.AlphaTestEffect;
alphaTest.AlphaFunction = CompareFunction.Greater;
alphaTest.ReferenceAlpha = 0;
drawManager.PushEffect(alphaTest);
foreach (var drawBufferManager in drawBufferManagers)
{
drawManager.BindTexture(drawBufferManager.TileSetInfo.Texture);
foreach (var buffer in drawBufferManager.Buffers)
{
if (buffer.ShouldDrawBuffer == false || buffer.NumberOfVisibleVertices == 0)
continue;
drawManager.DrawBuffer(buffer.QuadsVertexBuffer, buffer.IndexBuffer, 0,
buffer.NumberOfVisiblePrimitives);
}
}
drawManager.PopEffect();
}
#endregion Drawing
#region Convenience methods
bool AreValidTileCoordinates(int xCoord, int yCoord)
{
bool isValid = xCoord < LayerSize.Column && yCoord < LayerSize.Row && xCoord >= 0 && yCoord >= 0;
Debug.Assert(isValid, String.Format("CCTileMapLayer: Invalid tile coordinates x: {0} y: {1}", xCoord, yCoord));
return isValid;
}
bool AreValidTileCoordinates(CCTileMapCoordinates tileCoords)
{
return AreValidTileCoordinates(tileCoords.Column, tileCoords.Row);
}
int FlattenedTileIndex(int col, int row)
{
return (int)(col + (row * (LayerSize.Column)));
}
int FlattenedTileIndex(CCTileMapCoordinates tileCoords)
{
return FlattenedTileIndex(tileCoords.Column, tileCoords.Row);
}
CCTileMapCoordinates TileCoordForFlattenedIndex(int flattenedIndex)
{
int col, row;
row = flattenedIndex / LayerSize.Column;
col = flattenedIndex % LayerSize.Column;
return new CCTileMapCoordinates(col, row);
}
CCTileMapDrawBufferManager GetDrawBufferManagerByGid(short gid)
{
foreach (var drawBufferManager in drawBufferManagers)
{
if (drawBufferManager.TileSetInfo.FirstGid <= gid && drawBufferManager.TileSetInfo.LastGid >= gid)
{
return drawBufferManager;
}
}
return null;
}
#endregion Convenience methods
#region Fetching tile
public CCSprite ExtractTile(CCTileMapCoordinates tileCoords, bool addToTileMapLayer = true)
{
return ExtractTile(tileCoords.Column, tileCoords.Row, addToTileMapLayer);
}
public CCSprite ExtractTile(int column, int row, bool addToTileMapLayer = true)
{
if (!AreValidTileCoordinates(column, row))
return null;
CCTileGidAndFlags gidAndFlags = TileGIDAndFlags(column, row);
int flattendedIndex = FlattenedTileIndex(column, row);
var drawBufferManager = GetDrawBufferManagerByGid(gidAndFlags.Gid);
if (drawBufferManager == null)
{
CCLog.Log("Requestd Tile GID for col/row: {0}/{1} can not be extracted because it does not exist.", column, row);
return null;
}
CCTileSetInfo tileSetInfo = drawBufferManager.TileSetInfo;
CCRect texRect = tileSetInfo.TextureRectForGID(gidAndFlags.Gid);
CCSprite tileSprite = new CCSprite(tileSetInfo.Texture, texRect);
tileSprite.ContentSize = texRect.Size * CCTileMapLayer.DefaultTexelToContentSizeRatios;
tileSprite.Position = TilePosition(column, row);
tileSprite.VertexZ = TileVertexZ(column, row);
tileSprite.AnchorPoint = CCPoint.Zero;
tileSprite.Opacity = Opacity;
tileSprite.FlipX = false;
tileSprite.FlipY = false;
tileSprite.Rotation = 0.0f;
if ((gidAndFlags.Flags & CCTileFlags.TileDiagonal) != 0)
{
CCSize halfContentSize = tileSprite.ContentSize * 0.5f;
tileSprite.AnchorPoint = CCPoint.AnchorMiddle;
tileSprite.Position += new CCPoint(halfContentSize.Width, halfContentSize.Height);
CCTileFlags horAndVertFlag = gidAndFlags.Flags & (CCTileFlags.Horizontal | CCTileFlags.Vertical);
// Handle the 4 diagonally flipped states.
if (horAndVertFlag == CCTileFlags.Horizontal)
{
tileSprite.Rotation = 90.0f;
}
else if (horAndVertFlag == CCTileFlags.Vertical)
{
tileSprite.Rotation = 270.0f;
}
else if (horAndVertFlag == (CCTileFlags.Vertical | CCTileFlags.Horizontal))
{
tileSprite.Rotation = 90.0f;
tileSprite.FlipX = true;
}
else
{
tileSprite.Rotation = 270.0f;
tileSprite.FlipX = true;
}
}
else
{
if ((gidAndFlags.Flags & CCTileFlags.Horizontal) != 0)
{
tileSprite.FlipX = true;
}
if ((gidAndFlags.Flags & CCTileFlags.Vertical) != 0)
{
tileSprite.FlipY = true;
}
}
if (addToTileMapLayer)
{
AddChild(tileSprite, flattendedIndex, flattendedIndex);
}
RemoveTile(column, row);
return tileSprite;
}
#endregion Fetching tile
#region Fetching tile properties
public CCTileMapCoordinates ClosestTileCoordAtNodePosition(CCPoint nodePos)
{
// Tile positions are relative to bottom-left corner of quad
// However the tile hit test should be relative to tile center
// Therefore adjust node position
CCSize offsetSize = (TileContentSize) * 0.5f;
CCPoint offsetPt = new CCPoint(offsetSize.Width, offsetSize.Height);
CCPoint offsetDiff = nodePos - offsetPt;
CCPoint transformedPoint = nodeToTileCoordsTransform.Transform(offsetDiff).RoundToInteger();
if (MapType == CCTileMapType.Hex || MapType == CCTileMapType.Staggered)
{
CCPoint oddTransformedPoint = nodeToTileCoordsTransformOdd.Transform(offsetDiff).RoundToInteger();
if ((MapType == CCTileMapType.Hex && oddTransformedPoint.X % 2 == 1) ||
(MapType == CCTileMapType.Staggered && oddTransformedPoint.Y % 2 == 1))
transformedPoint = oddTransformedPoint;
}
return new CCTileMapCoordinates((int)transformedPoint.X, (int)transformedPoint.Y);
}
public CCTileGidAndFlags TileGIDAndFlags(CCTileMapCoordinates tileCoords)
{
return TileGIDAndFlags(tileCoords.Column, tileCoords.Row);
}
public CCTileGidAndFlags TileGIDAndFlags(int column, int row)
{
CCTileGidAndFlags tileGIDAndFlags = new CCTileGidAndFlags(0, 0);
if (AreValidTileCoordinates(column, row))
{
int flattenedIndex = FlattenedTileIndex(column, row);
tileGIDAndFlags = TileGIDAndFlagsArray[flattenedIndex];
}
return tileGIDAndFlags;
}
public CCPoint TilePosition(int column, int row)
{
return TilePosition(new CCTileMapCoordinates(column, row));
}
public CCPoint TilePosition(int flattenedIndex)
{
return TilePosition(TileCoordForFlattenedIndex(flattenedIndex));
}
public CCPoint TilePosition(CCTileMapCoordinates tileCoords)
{
if ((MapType == CCTileMapType.Hex && tileCoords.Column % 2 == 1) ||
(MapType == CCTileMapType.Staggered && tileCoords.Row % 2 == 1))
return tileCoordsToNodeTransformOdd.Transform(tileCoords.Point);
return tileCoordsToNodeTransform.Transform(tileCoords.Point);
}
public float TileVertexZ(int flattenedIndex)
{
return TileVertexZ(TileCoordForFlattenedIndex(flattenedIndex));
}
public float TileVertexZ(int column, int row)
{
float vertexZ = 0;
if (useAutomaticVertexZ)
{
switch (MapType)
{
case CCTileMapType.Iso:
float maxVal = LayerSize.Column + LayerSize.Row;
vertexZ = -(maxVal - (column + row));
break;
case CCTileMapType.Ortho:
vertexZ = -(LayerSize.Row - row);
break;
case CCTileMapType.Staggered:
vertexZ = -(LayerSize.Row - row);
break;
case CCTileMapType.Hex:
Debug.Assert(false, "CCTMXLayer:TileVertexZ: Automatic z-ordering for Hex tiles not supported");
break;
default:
Debug.Assert(false, "CCTMXLayer:TileVertexZ: Unsupported layer orientation");
break;
}
}
else
{
vertexZ = defaultTileVertexZ;
}
return vertexZ;
}
public float TileVertexZ(CCTileMapCoordinates tileCoords)
{
return TileVertexZ(tileCoords.Column, tileCoords.Row);
}
String PropertyNamed(string propertyName)
{
string property = String.Empty;
LayerProperties.TryGetValue(propertyName, out property);
return property;
}
CCPoint LayerOffset(CCTileMapCoordinates tileCoords)
{
CCPoint offsetInNodespace = CCPoint.Zero;
switch (MapType)
{
case CCTileMapType.Ortho:
offsetInNodespace = new CCPoint(tileCoords.Column * TileTexelSize.Width, -tileCoords.Row * TileTexelSize.Height);
break;
case CCTileMapType.Iso:
offsetInNodespace = new CCPoint((TileTexelSize.Width / 2) * (tileCoords.Column - tileCoords.Row),
(TileTexelSize.Height / 2) * (-tileCoords.Column - tileCoords.Row));
break;
case CCTileMapType.Staggered:
float diffX = 0;
if ((int)tileCoords.Row % 2 == 1)
diffX = TileTexelSize.Width / 2;
offsetInNodespace = new CCPoint(tileCoords.Column * TileTexelSize.Width + diffX,
-tileCoords.Row * TileTexelSize.Height / 2);
break;
case CCTileMapType.Hex:
break;
}
offsetInNodespace *= CCTileMapLayer.DefaultTexelToContentSizeRatios;
return offsetInNodespace;
}
#endregion Fetching tile properties
#region Removing tiles
public void RemoveTile(int column, int row)
{
if (AreValidTileCoordinates(column, row))
{
CCTileGidAndFlags gidAndFlags = TileGIDAndFlags(column, row);
if (gidAndFlags.Gid != 0)
{
// Remove tile from GID map
SetBatchRenderedTileGID(column, row, CCTileGidAndFlags.EmptyTile);
}
}
}
public void RemoveTile(CCTileMapCoordinates tileCoords)
{
RemoveTile(tileCoords.Column, tileCoords.Row);
}
#endregion Removing tiles
#region Updating tiles
public void SetTileGID(CCTileGidAndFlags gidAndFlags, CCTileMapCoordinates tileCoords)
{
if (gidAndFlags.Gid == 0)
{
RemoveTile(tileCoords);
return;
}
if (AreValidTileCoordinates(tileCoords) == false)
{
Debug.Assert(false, String.Format("CCTileMapLayer: Invalid tile coordinates row: {0} column: {1}",
tileCoords.Row, tileCoords.Column));
return;
}
CCTileGidAndFlags currentGID = TileGIDAndFlags(tileCoords);
if (currentGID == gidAndFlags)
return;
CCTileMapDrawBufferManager drawBufferManager = GetDrawBufferManagerByGid(gidAndFlags.Gid);
if (drawBufferManager == null)
{
foreach (CCTileSetInfo tileSetInfo in mapInfo.Tilesets)
{
if (tileSetInfo.FirstGid <= gidAndFlags.Gid && tileSetInfo.LastGid >= gidAndFlags.Gid)
{
drawBufferManager = InitialiseDrawBuffer(tileSetInfo);
break;
}
}
if (drawBufferManagers == null)
{
Debug.Assert(false, String.Format("CCTileMapLayer: Invalid tile grid id: {0}", gidAndFlags.Gid));
return;
}
drawBufferManagers.Add(drawBufferManager);
visibleTileRangeDirty = true;
}
SetBatchRenderedTileGID(tileCoords.Column, tileCoords.Row, gidAndFlags);
}
public void ReplaceTileGIDQuad(short originalGid, short gidOfQuadToUse)
{
currentTileGidAnimations[originalGid] = gidOfQuadToUse;
tileAnimationsDirty = true;
}
void SetBatchRenderedTileGID(int column, int row, CCTileGidAndFlags gidAndFlags)
{
int flattenedIndex = FlattenedTileIndex(column, row);
CCTileGidAndFlags prevGid = TileGIDAndFlagsArray[flattenedIndex];
if (gidAndFlags != prevGid)
{
TileGIDAndFlagsArray[flattenedIndex] = gidAndFlags;
if (prevGid.Gid == 0)
{
var drawBufferManager = GetDrawBufferManagerByGid(gidAndFlags.Gid);
CCTileMapVertAndIndexBuffer drawBuffer = drawBufferManager.GetDrawBufferAtIndex(flattenedIndex);
drawBuffer.UpdateQuad(flattenedIndex, ref gidAndFlags, true);
}
else if (gidAndFlags.Gid == 0)
{
var oldDrawBufferManager = GetDrawBufferManagerByGid(prevGid.Gid);
CCTileMapVertAndIndexBuffer drawBuffer = oldDrawBufferManager.GetDrawBufferAtIndex(flattenedIndex);
drawBuffer.UpdateQuad(flattenedIndex, ref gidAndFlags, true);
}
else
{
var emptyTile = CCTileGidAndFlags.EmptyTile;
var oldDrawBufferManager = GetDrawBufferManagerByGid(prevGid.Gid);
CCTileMapVertAndIndexBuffer oldDrawBuffer = oldDrawBufferManager.GetDrawBufferAtIndex(flattenedIndex);
oldDrawBuffer.UpdateQuad(flattenedIndex, ref emptyTile, true);
var drawBufferManager = GetDrawBufferManagerByGid(gidAndFlags.Gid);
CCTileMapVertAndIndexBuffer drawBuffer = drawBufferManager.GetDrawBufferAtIndex(flattenedIndex);
drawBuffer.UpdateQuad(flattenedIndex, ref gidAndFlags, true);
}
}
}
#endregion Updating tiles
#region Updating buffers
void UpdateQuadAt(CCTileMapDrawBufferManager drawBufferManager, CCTileMapCoordinates tileCoords, bool updateBuffer = true)
{
UpdateQuadAt(drawBufferManager, tileCoords.Column, tileCoords.Row, updateBuffer);
}
void UpdateQuadAt(CCTileMapDrawBufferManager drawBufferManager, int tileCoordX, int tileCoordY, bool updateBuffer = true)
{
int flattenedTileIndex = FlattenedTileIndex(tileCoordX, tileCoordY);
CCTileGidAndFlags tileGID = TileGIDAndFlagsArray[flattenedTileIndex];
if (drawBufferManager.TileSetInfo.FirstGid <= tileGID.Gid && drawBufferManager.TileSetInfo.LastGid >= tileGID.Gid || tileGID.Gid == 0)
{
CCTileMapVertAndIndexBuffer drawBuffer = drawBufferManager.GetDrawBufferAtIndex(flattenedTileIndex);
drawBuffer.UpdateQuad(flattenedTileIndex, ref tileGID, updateBuffer);
}
}
void UpdateVisibleTileRange()
{
var culledBounds = AffineWorldTransform.Inverse.Transform(VisibleBoundsWorldspace);
var contentRect = new CCRect(0.0f, 0.0f, ContentSize.Width, ContentSize.Height);
culledBounds = culledBounds.Intersection(ref contentRect);
foreach (var drawBufferManager in drawBufferManagers)
{
// The tileset dimensions may in fact be larger than the actual map tile size which will affect culling
CCSize tileSetTileSize = drawBufferManager.TileSetInfo.TileTexelSize * CCTileMapLayer.DefaultTexelToContentSizeRatios;
float tileSetTileSizeMax = Math.Max(tileSetTileSize.Width, tileSetTileSize.Height);
CCSize mapTileSize = TileTexelSize * CCTileMapLayer.DefaultTexelToContentSizeRatios;
CCRect visibleTiles = nodeToTileCoordsTransform.Transform(culledBounds);
visibleTiles = visibleTiles.IntegerRoundedUpRect();
visibleTiles.Origin.Y += 1;
visibleTiles.Origin.X -= 1;
int tilesOverX = 0;
int tilesOverY = 0;
CCRect overTileRect = new CCRect(0.0f, 0.0f,
Math.Max(tileSetTileSizeMax - mapTileSize.Width, 0),
Math.Max(tileSetTileSizeMax - mapTileSize.Height, 0));
overTileRect = nodeToTileCoordsTransform.Transform(overTileRect);
tilesOverX = (int)(Math.Ceiling(overTileRect.Origin.X + overTileRect.Size.Width) - Math.Floor(overTileRect.Origin.X));
tilesOverY = (int)(Math.Ceiling(overTileRect.Origin.Y + overTileRect.Size.Height) - Math.Floor(overTileRect.Origin.Y));
int yBegin = (int)Math.Max(0, visibleTiles.Origin.Y - tilesOverY);
int yEnd = (int)Math.Min(LayerSize.Row - 1, visibleTiles.Origin.Y + visibleTiles.Size.Height + tilesOverY);
int xBegin = (int)Math.Max(0, visibleTiles.Origin.X - tilesOverX);
int xEnd = (int)Math.Min(LayerSize.Column - 1, visibleTiles.Origin.X + visibleTiles.Size.Width + tilesOverX);
drawBufferManager.StartUpdateVisibleTiles(FlattenedTileIndex(new CCTileMapCoordinates(xBegin, yBegin)));
for (int y = yBegin; y <= yEnd; ++y)
{
CCTileMapCoordinates startCoord = new CCTileMapCoordinates(xBegin, y);
CCTileMapCoordinates endCoord = new CCTileMapCoordinates(xEnd, y);
drawBufferManager.AddVisibleTileRange(FlattenedTileIndex(startCoord), FlattenedTileIndex(endCoord));
}
drawBufferManager.EndUpdateVisibleTiles();
visibleTileRangeDirty = false;
}
}
void UpdateTileAnimations()
{
foreach (KeyValuePair<short, short> tileAnim in currentTileGidAnimations)
{
var drawBufferManager = GetDrawBufferManagerByGid(tileAnim.Key);
if (drawBufferManager != null) drawBufferManager.ReplaceTileGIDQuad(tileAnim.Key, tileAnim.Value);
}
tileAnimationsDirty = false;
}
#endregion Updating buffers
#region Tile Animation methods
public void StartTileAnimations()
{
foreach (KeyValuePair<short, CCRepeatForever> tileAnim in TileAnimations)
activeTileAnimationActionStates.Add(RunAction(tileAnim.Value));
}
public void StopTileAnimations()
{
foreach (CCActionState actionState in activeTileAnimationActionStates)
StopAction(actionState);
activeTileAnimationActionStates.Clear();
}
#endregion Tile Animation methods
#region Internal draw buffer management
class CCTileMapDrawBufferManager : IDisposable
{
public List<CCTileMapVertAndIndexBuffer> Buffers { get; private set; }
public CCTileSetInfo TileSetInfo { get; private set; }
CCTileMapLayer TileMapLayer { get; set; }
public CCTileMapDrawBufferManager(int mapCols, int mapRows, CCTileMapLayer tileMapLayer, CCTileSetInfo tileSetInfo)
{
Buffers = new List<CCTileMapVertAndIndexBuffer>();
TileSetInfo = tileSetInfo;
TileMapLayer = tileMapLayer;
// Create the appropriate number of buffers to hold the map.
int numOfTiles = mapCols * mapRows;
int tilesProcessed = 0;
while (tilesProcessed < numOfTiles)
{
int tilesLeft = numOfTiles - tilesProcessed;
int tilesInThisBuffer = Math.Min(tilesLeft, MaxTilesPerDrawBuffer);
CreateDrawBuffer(tilesInThisBuffer, tilesProcessed);
tilesProcessed += tilesInThisBuffer;
}
}
public CCTileMapVertAndIndexBuffer GetDrawBufferAtIndex(int tileIndex)
{
foreach (var buffer in Buffers)
{
if (tileIndex >= buffer.TileStartIndex && tileIndex <= buffer.TileEndIndex)
return buffer;
}
throw new Exception(String.Format("No DrawBuffer found for specified tile index: {0}", tileIndex));
}
public void StartUpdateVisibleTiles(int startTileIndex)
{
foreach (var buffer in Buffers)
buffer.StartUpdateIndexBuffer(startTileIndex);
}
public void AddVisibleTileRange(int startTileIndex, int endTileIndex)
{
foreach (var buffer in Buffers)
buffer.AddTileRange(startTileIndex, endTileIndex);
}
public void EndUpdateVisibleTiles()
{
foreach (var buffer in Buffers)
buffer.EndUpdateIndexBuffer();
}
~CCTileMapDrawBufferManager()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
while (Buffers.Count > 0)
{
CCTileMapVertAndIndexBuffer buffer = Buffers[0];
Buffers.RemoveAt(0);
buffer.QuadsVertexBuffer.Dispose();
buffer.IndexBuffer.Dispose();
buffer.QuadsVertexBuffer = null;
buffer.IndexBuffer = null;
}
}
}
void CreateDrawBuffer(int tileCount, int firstTileId)
{
int vertsInThisBuffer = tileCount * NumOfCornersPerQuad;
int indicesInThisBuffer = tileCount * NumOfVerticesPerQuad;
var buffer = new CCTileMapVertAndIndexBuffer
{
TileStartIndex = firstTileId,
TileEndIndex = firstTileId + tileCount - 1,
QuadsVertexBuffer = new CCVertexBuffer<CCV3F_C4B_T2F>(vertsInThisBuffer, CCBufferUsage.WriteOnly),
IndexBuffer = new CCIndexBuffer<ushort>(indicesInThisBuffer, BufferUsage.WriteOnly),
TileMapLayer = TileMapLayer,
TileSetInfo = TileSetInfo
};
Buffers.Add(buffer);
}
public void UpdateQuadBuffers()
{
foreach (var buffer in Buffers)
{
buffer.QuadsVertexBuffer.Count = buffer.NumberOfTiles * NumOfCornersPerQuad;
buffer.QuadsVertexBuffer.UpdateBuffer();
}
}
public void ReplaceTileGIDQuad(short originalGid, short gidOfQuadToUse)
{
foreach (var buffer in Buffers)
buffer.ReplaceTileGIDQuad(originalGid, gidOfQuadToUse);
}
}
class CCTileMapVertAndIndexBuffer
{
#region Properties
public int TileStartIndex { get; set; }
public int TileEndIndex { get; set; }
public CCVertexBuffer<CCV3F_C4B_T2F> QuadsVertexBuffer { get; set; }
public CCIndexBuffer<ushort> IndexBuffer { get; set; }
public CCTileMapLayer TileMapLayer { get; set; }
public CCTileSetInfo TileSetInfo { get; set; }
public bool ShouldDrawBuffer { get; private set; }
public int IndexBufferSize { get; private set; }
public int StartingVisibleTileIndex { get; private set; }
public int NumberOfVisibleVertices { get; private set; }
public int NumberOfVisiblePrimitives { get; private set; }
public int NumberOfTiles
{
get { return TileEndIndex - TileStartIndex + 1; }
}
#endregion Properties
public void StartUpdateIndexBuffer(int startTileIndex)
{
IndexBufferSize = 0;
NumberOfVisiblePrimitives = 0;
NumberOfVisibleVertices = 0;
StartingVisibleTileIndex = Math.Max(startTileIndex - TileStartIndex, 0);
ShouldDrawBuffer = false;
}
public void AddTileRange(int startTileIndex, int endTileIndex)
{
startTileIndex = Math.Max(startTileIndex, TileStartIndex);
endTileIndex = Math.Min(endTileIndex, TileEndIndex);
if (endTileIndex >= startTileIndex)
ShouldDrawBuffer = true;
else
return;
for (int tileIndex = startTileIndex; tileIndex <= endTileIndex; tileIndex++)
{
if (TileMapLayer.TileGIDAndFlagsArray[tileIndex].Gid == 0)
continue;
ushort quadVertIndex = (ushort)((tileIndex - TileStartIndex) * NumOfCornersPerQuad);
int indexBufferOffset = IndexBufferSize;
var indices = IndexBuffer.Data.Elements;
indices[(int)(indexBufferOffset + 0)] = (ushort)(quadVertIndex + 0);
indices[(int)(indexBufferOffset + 1)] = (ushort)(quadVertIndex + 1);
indices[(int)(indexBufferOffset + 2)] = (ushort)(quadVertIndex + 2);
indices[(int)(indexBufferOffset + 3)] = (ushort)(quadVertIndex + 3);
indices[(int)(indexBufferOffset + 4)] = (ushort)(quadVertIndex + 2);
indices[(int)(indexBufferOffset + 5)] = (ushort)(quadVertIndex + 1);
IndexBufferSize += NumOfVerticesPerQuad;
NumberOfVisiblePrimitives += NumOfPrimitivesPerQuad;
NumberOfVisibleVertices += NumOfCornersPerQuad;
}
}
public void EndUpdateIndexBuffer()
{
IndexBuffer.Count = IndexBufferSize;
IndexBuffer.UpdateBuffer();
}
public void ReplaceTileGIDQuad(short originalGid, short gidOfQuadToUse)
{
var indices = IndexBuffer.Data.Elements;
for (int i = 0, N = IndexBufferSize; i < N; i += 6)
{
int tileIndex = (indices[i] / NumOfCornersPerQuad) + TileStartIndex;
var gidAndFlag = TileMapLayer.TileGIDAndFlagsArray[tileIndex];
/*
So here we're updating the underlying quadvertexbuffer after each quad change
The alternative is to determine the min/max tile index and call QuadsVertexBuffer.UpdateBuffer() over that range.
The assumption is that replacing tile gid quads is primarily used for animating tiles that share a common original gid.
In particular, we would expect that animated tiles are small in number and/or sparsely spread out across the tile map
e.g. Water tiles/trees/character/light source etc.
So it's likely updating over a range would unnecessarily update a large number of unchanged quads
*/
if (gidAndFlag.Gid == originalGid)
{
var replacementQuadGid = new CCTileGidAndFlags(gidOfQuadToUse, gidAndFlag.Flags);
UpdateQuad(tileIndex, ref replacementQuadGid, true);
}
}
}
public void UpdateQuad(int flattenedTileIndex, ref CCTileGidAndFlags tileGID, bool updateBuffer = false)
{
int adjustedTileIndex = flattenedTileIndex - TileStartIndex;
int adjustedStartVertexIndex = adjustedTileIndex * NumOfCornersPerQuad;
if (tileGID.Gid == 0)
{
for (int i = 0; i < NumOfCornersPerQuad; i++)
QuadsVertexBuffer.Data[adjustedStartVertexIndex + i] = new CCV3F_C4B_T2F();
if (updateBuffer)
QuadsVertexBuffer.UpdateBuffer(adjustedStartVertexIndex, NumOfCornersPerQuad);
return;
}
else if (tileGID.Gid < TileSetInfo.FirstGid || tileGID.Gid > TileSetInfo.LastGid)
{
return;
}
float left, right, top, bottom, vertexZ;
vertexZ = TileMapLayer.TileVertexZ(flattenedTileIndex);
CCSize tileSize = TileSetInfo.TileTexelSize * CCTileMapLayer.DefaultTexelToContentSizeRatios;
CCSize texSize = TileSetInfo.TilesheetSize;
CCPoint tilePos = TileMapLayer.TilePosition(flattenedTileIndex);
var quadVertexData = QuadsVertexBuffer.Data;
var quad = new CCV3F_C4B_T2F_Quad();
// vertices
if ((tileGID.Flags & CCTileFlags.TileDiagonal) != 0)
{
left = tilePos.X;
right = tilePos.X + tileSize.Height;
bottom = tilePos.Y + tileSize.Width;
top = tilePos.Y;
}
else
{
left = tilePos.X;
right = tilePos.X + tileSize.Width;
bottom = tilePos.Y + tileSize.Height;
top = tilePos.Y;
}
float temp;
if ((tileGID.Flags & CCTileFlags.Vertical) != 0)
{
temp = top;
top = bottom;
bottom = temp;
}
if ((tileGID.Flags & CCTileFlags.Horizontal) != 0)
{
temp = left;
left = right;
right = temp;
}
if ((tileGID.Flags & CCTileFlags.TileDiagonal) != 0)
{
quad.BottomLeft.Vertices = new CCVertex3F(left, bottom, vertexZ);
quad.BottomRight.Vertices = new CCVertex3F(left, top, vertexZ);
quad.TopLeft.Vertices = new CCVertex3F(right, bottom, vertexZ);
quad.TopRight.Vertices = new CCVertex3F(right, top, vertexZ);
}
else
{
quad.BottomLeft.Vertices = new CCVertex3F(left, bottom, vertexZ);
quad.BottomRight.Vertices = new CCVertex3F(right, bottom, vertexZ);
quad.TopLeft.Vertices = new CCVertex3F(left, top, vertexZ);
quad.TopRight.Vertices = new CCVertex3F(right, top, vertexZ);
}
float offsetW = TileMapLayer.HalfTexelOffset ? 0.5f / texSize.Width : 0.0f;
float offsetH = TileMapLayer.HalfTexelOffset? 0.5f / texSize.Height : 0.0f;
// texcoords
CCRect tileTexture = TileSetInfo.TextureRectForGID(tileGID.Gid);
left = tileTexture.Origin.X / texSize.Width + offsetW;
right = (tileTexture.Origin.X + tileTexture.Size.Width) / texSize.Width - offsetW;
bottom = tileTexture.Origin.Y / texSize.Height + offsetH;
top = (tileTexture.Origin.Y + tileTexture.Size.Height) / texSize.Height - offsetH;
quad.BottomLeft.TexCoords = new CCTex2F(left, bottom);
quad.BottomRight.TexCoords = new CCTex2F(right, bottom);
quad.TopLeft.TexCoords = new CCTex2F(left, top);
quad.TopRight.TexCoords = new CCTex2F(right, top);
quad.BottomLeft.Colors = CCColor4B.White;
quad.BottomRight.Colors = CCColor4B.White;
quad.TopLeft.Colors = CCColor4B.White;
quad.TopRight.Colors = CCColor4B.White;
QuadsVertexBuffer.Data.Elements[adjustedStartVertexIndex] = quad.TopLeft;
QuadsVertexBuffer.Data.Elements[adjustedStartVertexIndex + 1] = quad.BottomLeft;
QuadsVertexBuffer.Data.Elements[adjustedStartVertexIndex + 2] = quad.TopRight;
QuadsVertexBuffer.Data.Elements[adjustedStartVertexIndex + 3] = quad.BottomRight;
if (updateBuffer)
QuadsVertexBuffer.UpdateBuffer(adjustedStartVertexIndex, NumOfCornersPerQuad);
}
}
#endregion Internal draw buffer management
}
}
| |
using System;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Data.Common;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Xml;
using System.Xml.Serialization;
using SubSonic;
using SubSonic.Utilities;
namespace DalSic
{
/// <summary>
/// Strongly-typed collection for the LabDetalleSolicitudScreening class.
/// </summary>
[Serializable]
public partial class LabDetalleSolicitudScreeningCollection : ActiveList<LabDetalleSolicitudScreening, LabDetalleSolicitudScreeningCollection>
{
public LabDetalleSolicitudScreeningCollection() {}
/// <summary>
/// Filters an existing collection based on the set criteria. This is an in-memory filter
/// Thanks to developingchris for this!
/// </summary>
/// <returns>LabDetalleSolicitudScreeningCollection</returns>
public LabDetalleSolicitudScreeningCollection Filter()
{
for (int i = this.Count - 1; i > -1; i--)
{
LabDetalleSolicitudScreening o = this[i];
foreach (SubSonic.Where w in this.wheres)
{
bool remove = false;
System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName);
if (pi.CanRead)
{
object val = pi.GetValue(o, null);
switch (w.Comparison)
{
case SubSonic.Comparison.Equals:
if (!val.Equals(w.ParameterValue))
{
remove = true;
}
break;
}
}
if (remove)
{
this.Remove(o);
break;
}
}
}
return this;
}
}
/// <summary>
/// This is an ActiveRecord class which wraps the LAB_DetalleSolicitudScreening table.
/// </summary>
[Serializable]
public partial class LabDetalleSolicitudScreening : ActiveRecord<LabDetalleSolicitudScreening>, IActiveRecord
{
#region .ctors and Default Settings
public LabDetalleSolicitudScreening()
{
SetSQLProps();
InitSetDefaults();
MarkNew();
}
private void InitSetDefaults() { SetDefaults(); }
public LabDetalleSolicitudScreening(bool useDatabaseDefaults)
{
SetSQLProps();
if(useDatabaseDefaults)
ForceDefaults();
MarkNew();
}
public LabDetalleSolicitudScreening(object keyID)
{
SetSQLProps();
InitSetDefaults();
LoadByKey(keyID);
}
public LabDetalleSolicitudScreening(string columnName, object columnValue)
{
SetSQLProps();
InitSetDefaults();
LoadByParam(columnName,columnValue);
}
protected static void SetSQLProps() { GetTableSchema(); }
#endregion
#region Schema and Query Accessor
public static Query CreateQuery() { return new Query(Schema); }
public static TableSchema.Table Schema
{
get
{
if (BaseSchema == null)
SetSQLProps();
return BaseSchema;
}
}
private static void GetTableSchema()
{
if(!IsSchemaInitialized)
{
//Schema declaration
TableSchema.Table schema = new TableSchema.Table("LAB_DetalleSolicitudScreening", TableType.Table, DataService.GetInstance("sicProvider"));
schema.Columns = new TableSchema.TableColumnCollection();
schema.SchemaName = @"dbo";
//columns
TableSchema.TableColumn colvarIdDetalleSolicitudScreening = new TableSchema.TableColumn(schema);
colvarIdDetalleSolicitudScreening.ColumnName = "idDetalleSolicitudScreening";
colvarIdDetalleSolicitudScreening.DataType = DbType.Int32;
colvarIdDetalleSolicitudScreening.MaxLength = 0;
colvarIdDetalleSolicitudScreening.AutoIncrement = true;
colvarIdDetalleSolicitudScreening.IsNullable = false;
colvarIdDetalleSolicitudScreening.IsPrimaryKey = true;
colvarIdDetalleSolicitudScreening.IsForeignKey = false;
colvarIdDetalleSolicitudScreening.IsReadOnly = false;
colvarIdDetalleSolicitudScreening.DefaultSetting = @"";
colvarIdDetalleSolicitudScreening.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdDetalleSolicitudScreening);
TableSchema.TableColumn colvarIdSolicitudScreening = new TableSchema.TableColumn(schema);
colvarIdSolicitudScreening.ColumnName = "idSolicitudScreening";
colvarIdSolicitudScreening.DataType = DbType.Int32;
colvarIdSolicitudScreening.MaxLength = 0;
colvarIdSolicitudScreening.AutoIncrement = false;
colvarIdSolicitudScreening.IsNullable = false;
colvarIdSolicitudScreening.IsPrimaryKey = false;
colvarIdSolicitudScreening.IsForeignKey = true;
colvarIdSolicitudScreening.IsReadOnly = false;
colvarIdSolicitudScreening.DefaultSetting = @"";
colvarIdSolicitudScreening.ForeignKeyTableName = "LAB_SolicitudScreening";
schema.Columns.Add(colvarIdSolicitudScreening);
TableSchema.TableColumn colvarIdItem = new TableSchema.TableColumn(schema);
colvarIdItem.ColumnName = "idItem";
colvarIdItem.DataType = DbType.Int32;
colvarIdItem.MaxLength = 0;
colvarIdItem.AutoIncrement = false;
colvarIdItem.IsNullable = false;
colvarIdItem.IsPrimaryKey = false;
colvarIdItem.IsForeignKey = true;
colvarIdItem.IsReadOnly = false;
colvarIdItem.DefaultSetting = @"";
colvarIdItem.ForeignKeyTableName = "LAB_ItemScreening";
schema.Columns.Add(colvarIdItem);
TableSchema.TableColumn colvarResultado = new TableSchema.TableColumn(schema);
colvarResultado.ColumnName = "resultado";
colvarResultado.DataType = DbType.String;
colvarResultado.MaxLength = 500;
colvarResultado.AutoIncrement = false;
colvarResultado.IsNullable = false;
colvarResultado.IsPrimaryKey = false;
colvarResultado.IsForeignKey = false;
colvarResultado.IsReadOnly = false;
colvarResultado.DefaultSetting = @"";
colvarResultado.ForeignKeyTableName = "";
schema.Columns.Add(colvarResultado);
TableSchema.TableColumn colvarMetodo = new TableSchema.TableColumn(schema);
colvarMetodo.ColumnName = "metodo";
colvarMetodo.DataType = DbType.String;
colvarMetodo.MaxLength = 500;
colvarMetodo.AutoIncrement = false;
colvarMetodo.IsNullable = false;
colvarMetodo.IsPrimaryKey = false;
colvarMetodo.IsForeignKey = false;
colvarMetodo.IsReadOnly = false;
colvarMetodo.DefaultSetting = @"";
colvarMetodo.ForeignKeyTableName = "";
schema.Columns.Add(colvarMetodo);
TableSchema.TableColumn colvarValorReferencia = new TableSchema.TableColumn(schema);
colvarValorReferencia.ColumnName = "valorReferencia";
colvarValorReferencia.DataType = DbType.String;
colvarValorReferencia.MaxLength = 500;
colvarValorReferencia.AutoIncrement = false;
colvarValorReferencia.IsNullable = false;
colvarValorReferencia.IsPrimaryKey = false;
colvarValorReferencia.IsForeignKey = false;
colvarValorReferencia.IsReadOnly = false;
colvarValorReferencia.DefaultSetting = @"";
colvarValorReferencia.ForeignKeyTableName = "";
schema.Columns.Add(colvarValorReferencia);
TableSchema.TableColumn colvarIdUsuarioResultado = new TableSchema.TableColumn(schema);
colvarIdUsuarioResultado.ColumnName = "idUsuarioResultado";
colvarIdUsuarioResultado.DataType = DbType.AnsiString;
colvarIdUsuarioResultado.MaxLength = 50;
colvarIdUsuarioResultado.AutoIncrement = false;
colvarIdUsuarioResultado.IsNullable = false;
colvarIdUsuarioResultado.IsPrimaryKey = false;
colvarIdUsuarioResultado.IsForeignKey = false;
colvarIdUsuarioResultado.IsReadOnly = false;
colvarIdUsuarioResultado.DefaultSetting = @"";
colvarIdUsuarioResultado.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdUsuarioResultado);
TableSchema.TableColumn colvarFechaResultado = new TableSchema.TableColumn(schema);
colvarFechaResultado.ColumnName = "fechaResultado";
colvarFechaResultado.DataType = DbType.DateTime;
colvarFechaResultado.MaxLength = 0;
colvarFechaResultado.AutoIncrement = false;
colvarFechaResultado.IsNullable = false;
colvarFechaResultado.IsPrimaryKey = false;
colvarFechaResultado.IsForeignKey = false;
colvarFechaResultado.IsReadOnly = false;
colvarFechaResultado.DefaultSetting = @"(((1)/(1))/(1900))";
colvarFechaResultado.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaResultado);
TableSchema.TableColumn colvarIdUsuarioValida = new TableSchema.TableColumn(schema);
colvarIdUsuarioValida.ColumnName = "idUsuarioValida";
colvarIdUsuarioValida.DataType = DbType.AnsiString;
colvarIdUsuarioValida.MaxLength = 50;
colvarIdUsuarioValida.AutoIncrement = false;
colvarIdUsuarioValida.IsNullable = false;
colvarIdUsuarioValida.IsPrimaryKey = false;
colvarIdUsuarioValida.IsForeignKey = false;
colvarIdUsuarioValida.IsReadOnly = false;
colvarIdUsuarioValida.DefaultSetting = @"";
colvarIdUsuarioValida.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdUsuarioValida);
TableSchema.TableColumn colvarFechaValida = new TableSchema.TableColumn(schema);
colvarFechaValida.ColumnName = "fechaValida";
colvarFechaValida.DataType = DbType.DateTime;
colvarFechaValida.MaxLength = 0;
colvarFechaValida.AutoIncrement = false;
colvarFechaValida.IsNullable = false;
colvarFechaValida.IsPrimaryKey = false;
colvarFechaValida.IsForeignKey = false;
colvarFechaValida.IsReadOnly = false;
colvarFechaValida.DefaultSetting = @"(((1)/(1))/(1900))";
colvarFechaValida.ForeignKeyTableName = "";
schema.Columns.Add(colvarFechaValida);
TableSchema.TableColumn colvarValorEncontrado = new TableSchema.TableColumn(schema);
colvarValorEncontrado.ColumnName = "valorEncontrado";
colvarValorEncontrado.DataType = DbType.AnsiString;
colvarValorEncontrado.MaxLength = 30;
colvarValorEncontrado.AutoIncrement = false;
colvarValorEncontrado.IsNullable = true;
colvarValorEncontrado.IsPrimaryKey = false;
colvarValorEncontrado.IsForeignKey = false;
colvarValorEncontrado.IsReadOnly = false;
colvarValorEncontrado.DefaultSetting = @"";
colvarValorEncontrado.ForeignKeyTableName = "";
schema.Columns.Add(colvarValorEncontrado);
TableSchema.TableColumn colvarIdResultado = new TableSchema.TableColumn(schema);
colvarIdResultado.ColumnName = "IdResultado";
colvarIdResultado.DataType = DbType.Int32;
colvarIdResultado.MaxLength = 0;
colvarIdResultado.AutoIncrement = false;
colvarIdResultado.IsNullable = true;
colvarIdResultado.IsPrimaryKey = false;
colvarIdResultado.IsForeignKey = false;
colvarIdResultado.IsReadOnly = false;
colvarIdResultado.DefaultSetting = @"";
colvarIdResultado.ForeignKeyTableName = "";
schema.Columns.Add(colvarIdResultado);
BaseSchema = schema;
//add this schema to the provider
//so we can query it later
DataService.Providers["sicProvider"].AddSchema("LAB_DetalleSolicitudScreening",schema);
}
}
#endregion
#region Props
[XmlAttribute("IdDetalleSolicitudScreening")]
[Bindable(true)]
public int IdDetalleSolicitudScreening
{
get { return GetColumnValue<int>(Columns.IdDetalleSolicitudScreening); }
set { SetColumnValue(Columns.IdDetalleSolicitudScreening, value); }
}
[XmlAttribute("IdSolicitudScreening")]
[Bindable(true)]
public int IdSolicitudScreening
{
get { return GetColumnValue<int>(Columns.IdSolicitudScreening); }
set { SetColumnValue(Columns.IdSolicitudScreening, value); }
}
[XmlAttribute("IdItem")]
[Bindable(true)]
public int IdItem
{
get { return GetColumnValue<int>(Columns.IdItem); }
set { SetColumnValue(Columns.IdItem, value); }
}
[XmlAttribute("Resultado")]
[Bindable(true)]
public string Resultado
{
get { return GetColumnValue<string>(Columns.Resultado); }
set { SetColumnValue(Columns.Resultado, value); }
}
[XmlAttribute("Metodo")]
[Bindable(true)]
public string Metodo
{
get { return GetColumnValue<string>(Columns.Metodo); }
set { SetColumnValue(Columns.Metodo, value); }
}
[XmlAttribute("ValorReferencia")]
[Bindable(true)]
public string ValorReferencia
{
get { return GetColumnValue<string>(Columns.ValorReferencia); }
set { SetColumnValue(Columns.ValorReferencia, value); }
}
[XmlAttribute("IdUsuarioResultado")]
[Bindable(true)]
public string IdUsuarioResultado
{
get { return GetColumnValue<string>(Columns.IdUsuarioResultado); }
set { SetColumnValue(Columns.IdUsuarioResultado, value); }
}
[XmlAttribute("FechaResultado")]
[Bindable(true)]
public DateTime FechaResultado
{
get { return GetColumnValue<DateTime>(Columns.FechaResultado); }
set { SetColumnValue(Columns.FechaResultado, value); }
}
[XmlAttribute("IdUsuarioValida")]
[Bindable(true)]
public string IdUsuarioValida
{
get { return GetColumnValue<string>(Columns.IdUsuarioValida); }
set { SetColumnValue(Columns.IdUsuarioValida, value); }
}
[XmlAttribute("FechaValida")]
[Bindable(true)]
public DateTime FechaValida
{
get { return GetColumnValue<DateTime>(Columns.FechaValida); }
set { SetColumnValue(Columns.FechaValida, value); }
}
[XmlAttribute("ValorEncontrado")]
[Bindable(true)]
public string ValorEncontrado
{
get { return GetColumnValue<string>(Columns.ValorEncontrado); }
set { SetColumnValue(Columns.ValorEncontrado, value); }
}
[XmlAttribute("IdResultado")]
[Bindable(true)]
public int? IdResultado
{
get { return GetColumnValue<int?>(Columns.IdResultado); }
set { SetColumnValue(Columns.IdResultado, value); }
}
#endregion
#region ForeignKey Properties
/// <summary>
/// Returns a LabSolicitudScreening ActiveRecord object related to this LabDetalleSolicitudScreening
///
/// </summary>
public DalSic.LabSolicitudScreening LabSolicitudScreening
{
get { return DalSic.LabSolicitudScreening.FetchByID(this.IdSolicitudScreening); }
set { SetColumnValue("idSolicitudScreening", value.IdSolicitudScreening); }
}
/// <summary>
/// Returns a LabItemScreening ActiveRecord object related to this LabDetalleSolicitudScreening
///
/// </summary>
public DalSic.LabItemScreening LabItemScreening
{
get { return DalSic.LabItemScreening.FetchByID(this.IdItem); }
set { SetColumnValue("idItem", value.IdItemScreening); }
}
#endregion
//no ManyToMany tables defined (0)
#region ObjectDataSource support
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
public static void Insert(int varIdSolicitudScreening,int varIdItem,string varResultado,string varMetodo,string varValorReferencia,string varIdUsuarioResultado,DateTime varFechaResultado,string varIdUsuarioValida,DateTime varFechaValida,string varValorEncontrado,int? varIdResultado)
{
LabDetalleSolicitudScreening item = new LabDetalleSolicitudScreening();
item.IdSolicitudScreening = varIdSolicitudScreening;
item.IdItem = varIdItem;
item.Resultado = varResultado;
item.Metodo = varMetodo;
item.ValorReferencia = varValorReferencia;
item.IdUsuarioResultado = varIdUsuarioResultado;
item.FechaResultado = varFechaResultado;
item.IdUsuarioValida = varIdUsuarioValida;
item.FechaValida = varFechaValida;
item.ValorEncontrado = varValorEncontrado;
item.IdResultado = varIdResultado;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
public static void Update(int varIdDetalleSolicitudScreening,int varIdSolicitudScreening,int varIdItem,string varResultado,string varMetodo,string varValorReferencia,string varIdUsuarioResultado,DateTime varFechaResultado,string varIdUsuarioValida,DateTime varFechaValida,string varValorEncontrado,int? varIdResultado)
{
LabDetalleSolicitudScreening item = new LabDetalleSolicitudScreening();
item.IdDetalleSolicitudScreening = varIdDetalleSolicitudScreening;
item.IdSolicitudScreening = varIdSolicitudScreening;
item.IdItem = varIdItem;
item.Resultado = varResultado;
item.Metodo = varMetodo;
item.ValorReferencia = varValorReferencia;
item.IdUsuarioResultado = varIdUsuarioResultado;
item.FechaResultado = varFechaResultado;
item.IdUsuarioValida = varIdUsuarioValida;
item.FechaValida = varFechaValida;
item.ValorEncontrado = varValorEncontrado;
item.IdResultado = varIdResultado;
item.IsNew = false;
if (System.Web.HttpContext.Current != null)
item.Save(System.Web.HttpContext.Current.User.Identity.Name);
else
item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name);
}
#endregion
#region Typed Columns
public static TableSchema.TableColumn IdDetalleSolicitudScreeningColumn
{
get { return Schema.Columns[0]; }
}
public static TableSchema.TableColumn IdSolicitudScreeningColumn
{
get { return Schema.Columns[1]; }
}
public static TableSchema.TableColumn IdItemColumn
{
get { return Schema.Columns[2]; }
}
public static TableSchema.TableColumn ResultadoColumn
{
get { return Schema.Columns[3]; }
}
public static TableSchema.TableColumn MetodoColumn
{
get { return Schema.Columns[4]; }
}
public static TableSchema.TableColumn ValorReferenciaColumn
{
get { return Schema.Columns[5]; }
}
public static TableSchema.TableColumn IdUsuarioResultadoColumn
{
get { return Schema.Columns[6]; }
}
public static TableSchema.TableColumn FechaResultadoColumn
{
get { return Schema.Columns[7]; }
}
public static TableSchema.TableColumn IdUsuarioValidaColumn
{
get { return Schema.Columns[8]; }
}
public static TableSchema.TableColumn FechaValidaColumn
{
get { return Schema.Columns[9]; }
}
public static TableSchema.TableColumn ValorEncontradoColumn
{
get { return Schema.Columns[10]; }
}
public static TableSchema.TableColumn IdResultadoColumn
{
get { return Schema.Columns[11]; }
}
#endregion
#region Columns Struct
public struct Columns
{
public static string IdDetalleSolicitudScreening = @"idDetalleSolicitudScreening";
public static string IdSolicitudScreening = @"idSolicitudScreening";
public static string IdItem = @"idItem";
public static string Resultado = @"resultado";
public static string Metodo = @"metodo";
public static string ValorReferencia = @"valorReferencia";
public static string IdUsuarioResultado = @"idUsuarioResultado";
public static string FechaResultado = @"fechaResultado";
public static string IdUsuarioValida = @"idUsuarioValida";
public static string FechaValida = @"fechaValida";
public static string ValorEncontrado = @"valorEncontrado";
public static string IdResultado = @"IdResultado";
}
#endregion
#region Update PK Collections
#endregion
#region Deep Save
#endregion
}
}
| |
using System;
using System.ComponentModel;
using System.Data;
using System.Xml;
using Epi.Data;
namespace Epi.Fields
{
/// <summary>
/// Date Time Field.
/// </summary>
public class DateTimeField : InputTextBoxField
{
#region Private Members
private XmlElement viewElement;
private XmlNode fieldNode;
private BackgroundWorker _updater;
private BackgroundWorker _inserter;
#endregion Private members
#region Constructors
/// <summary>
/// Constructor for the class
/// </summary>
/// <param name="page">The page this field belongs to</param>
public DateTimeField(Page page)
: base(page)
{
construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">View</param>
public DateTimeField(View view)
: base(view)
{
construct();
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="page">Page</param>
/// <param name="viewElement">Xml view element</param>
public DateTimeField(Page page, XmlElement viewElement)
: base(page)
{
construct();
this.viewElement = viewElement;
this.Page = page;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="view">View</param>
/// <param name="fieldNode">Xml field node</param>
public DateTimeField(View view, XmlNode fieldNode)
: base(view)
{
construct();
this.fieldNode = fieldNode;
this.view.Project.Metadata.GetFieldData(this, this.fieldNode);
}
private void construct()
{
genericDbColumnType = GenericDbColumnType.DateTime;
this.dbColumnType = DbType.DateTime;
}
/// <summary>
/// Load from row
/// </summary>
/// <param name="row">Row</param>
public override void LoadFromRow(DataRow row)
{
base.LoadFromRow(row);
}
public DateTimeField Clone()
{
DateTimeField clone = (DateTimeField)this.MemberwiseClone();
base.AssignMembers(clone);
return clone;
}
#endregion Constructors
#region Public Properties
public virtual string Watermark
{
get
{
System.Globalization.DateTimeFormatInfo formatInfo = System.Globalization.DateTimeFormatInfo.CurrentInfo;
return string.Format("{0} {1}", formatInfo.ShortDatePattern.ToUpper(), formatInfo.LongTimePattern.ToUpper());
}
set {; }
}
/// <summary>
/// Returns field type
/// </summary>
public override MetaFieldType FieldType
{
get
{
return MetaFieldType.DateTime;
}
}
/// <summary>
/// The view element of the field
/// </summary>
public XmlElement ViewElement
{
get
{
return viewElement;
}
set
{
viewElement = value;
}
}
/// <summary>
/// Returns a string representation of Current Record Value
/// </summary>
public override string CurrentRecordValueString
{
get
{
if (CurrentRecordValueObject == null || CurrentRecordValueObject.Equals(DBNull.Value))
{
return string.Empty;
}
else
{
string dateTime = string.Empty;
dateTime = ((DateTime)CurrentRecordValueObject).ToString();
return dateTime;
}
}
set
{
if (!string.IsNullOrEmpty(value))
{
bool result;
DateTime dateTimeEntered;
result = DateTime.TryParse(value, out dateTimeEntered);
if (result)
{
CurrentRecordValueObject = dateTimeEntered;
}
else
{
CurrentRecordValueObject = null;
}
}
else
{
CurrentRecordValueObject = null;
}
}
}
#endregion Public Properties
#region Public Methods
/// <summary>
/// Returns the string value that is reflected my a mirror field.
/// </summary>
/// <returns>reflected value string</returns>
public virtual string GetReflectedValue()
{
return this.CurrentRecordValueObject.ToString();
}
#endregion Public methods
#region Private Methods
/// <summary>
/// Inserts the field to the database
/// </summary>
protected override void InsertField()
{
this.Id = GetMetadata().CreateField(this);
base.OnFieldAdded();
}
/// <summary>
/// Update the field to the database
/// </summary>
protected override void UpdateField()
{
GetMetadata().UpdateField(this);
}
#endregion Protected Methods
#region Event Handlers
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading.Tasks;
namespace Microsoft.NodejsTools.Npm.SPI
{
internal class NpmCommander : AbstractNpmLogSource, INpmCommander
{
private class NmpCommandRunner : IDisposable
{
private NpmCommander commander;
private NpmCommand command;
public static async Task<bool> ExecuteAsync(NpmCommander commander, NpmCommand command)
{
using (var runner = new NmpCommandRunner(commander, command))
{
return await runner.command.ExecuteAsync();
}
}
private NmpCommandRunner(NpmCommander commander, NpmCommand command)
{
this.commander = commander;
this.command = command;
this.commander.executingCommand = command;
this.command.CommandStarted += this.commander.command_CommandStarted;
this.command.OutputLogged += this.commander.command_OutputLogged;
this.command.CommandCompleted += this.commander.command_CommandCompleted;
this.command.ErrorLogged += this.commander.command_ErrorLogged;
this.command.ExceptionLogged += this.commander.command_ExceptionLogged;
}
public void Dispose()
{
this.commander.executingCommand = null;
this.command.CommandStarted -= this.commander.command_CommandStarted;
this.command.OutputLogged -= this.commander.command_OutputLogged;
this.command.CommandCompleted -= this.commander.command_CommandCompleted;
this.command.ErrorLogged -= this.commander.command_ErrorLogged;
this.command.ExceptionLogged -= this.commander.command_ExceptionLogged;
}
}
private readonly NpmController npmController;
private NpmCommand executingCommand;
private bool disposed;
public NpmCommander(NpmController controller)
{
this.npmController = controller;
CommandStarted += this.npmController.LogCommandStarted;
OutputLogged += this.npmController.LogOutput;
ErrorLogged += this.npmController.LogError;
ExceptionLogged += this.npmController.LogException;
CommandCompleted += this.npmController.LogCommandCompleted;
}
public void Dispose()
{
if (!this.disposed)
{
this.disposed = true;
CommandStarted -= this.npmController.LogCommandStarted;
OutputLogged -= this.npmController.LogOutput;
ErrorLogged -= this.npmController.LogError;
ExceptionLogged -= this.npmController.LogException;
CommandCompleted -= this.npmController.LogCommandCompleted;
}
}
private void command_CommandStarted(object sender, EventArgs e)
{
OnCommandStarted();
}
private void command_ExceptionLogged(object sender, NpmExceptionEventArgs e)
{
OnExceptionLogged(e.Exception);
}
private void command_ErrorLogged(object sender, NpmLogEventArgs e)
{
OnErrorLogged(e.LogText);
}
private void command_OutputLogged(object sender, NpmLogEventArgs e)
{
OnOutputLogged(e.LogText);
}
private void command_CommandCompleted(object sender, NpmCommandCompletedEventArgs e)
{
OnCommandCompleted(e.Arguments, e.WithErrors, e.Cancelled);
}
private async Task<bool> DoCommandExecute(bool refreshNpmController, NpmCommand command)
{
Debug.Assert(this.executingCommand == null, "Attempting to execute multiple commands at the same time.");
try
{
var success = await NmpCommandRunner.ExecuteAsync(this, command);
if (refreshNpmController)
{
this.npmController.Refresh();
}
return success;
}
catch (Exception e)
{
OnOutputLogged(e.ToString());
}
return false;
}
public async Task<bool> Install()
{
return await DoCommandExecute(true,
new NpmInstallCommand(
this.npmController.FullPathToRootPackageDirectory,
this.npmController.PathToNpm));
}
private Task<bool> InstallPackageByVersionAsync(
string pathToRootDirectory,
string packageName,
string versionRange,
DependencyType type,
bool global,
bool saveToPackageJson)
{
return DoCommandExecute(true,
new NpmInstallCommand(
pathToRootDirectory,
packageName,
versionRange,
type,
global,
saveToPackageJson,
this.npmController.PathToNpm));
}
public Task<bool> InstallPackageByVersionAsync(
string packageName,
string versionRange,
DependencyType type,
bool saveToPackageJson)
{
return InstallPackageByVersionAsync(this.npmController.FullPathToRootPackageDirectory, packageName, versionRange, type, false, saveToPackageJson);
}
private DependencyType GetDependencyType(string packageName)
{
var type = DependencyType.Standard;
var root = this.npmController.RootPackage;
if (null != root)
{
var match = root.Modules[packageName];
if (null != match)
{
if (match.IsDevDependency)
{
type = DependencyType.Development;
}
else if (match.IsOptionalDependency)
{
type = DependencyType.Optional;
}
}
}
return type;
}
public async Task<bool> UninstallPackageAsync(string packageName)
{
return await DoCommandExecute(true,
new NpmUninstallCommand(
this.npmController.FullPathToRootPackageDirectory,
packageName,
GetDependencyType(packageName),
false,
this.npmController.PathToNpm));
}
public async Task<bool> UpdatePackagesAsync()
{
return await UpdatePackagesAsync(new List<IPackage>());
}
public async Task<bool> UpdatePackagesAsync(IEnumerable<IPackage> packages)
{
return await DoCommandExecute(true,
new NpmUpdateCommand(
this.npmController.FullPathToRootPackageDirectory,
packages,
false,
this.npmController.PathToNpm));
}
public async Task<bool> ExecuteNpmCommandAsync(string arguments)
{
return await DoCommandExecute(true,
new GenericNpmCommand(
this.npmController.FullPathToRootPackageDirectory,
arguments,
this.npmController.PathToNpm));
}
}
}
| |
namespace UnitTest
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Xml;
using RMarshal = System.Runtime.InteropServices.Marshal;
using NUnit.Framework;
using Bond;
using Bond.Protocols;
using Bond.IO.Unsafe;
using Marshal = Bond.Marshal;
public static class Util
{
private const int UnsafeBufferSize = 192 * 1024;
public static IEnumerable<MethodInfo> GetDeclaredMethods(this Type type, string name)
{
return type.GetMethods().Where(m => m.Name == name);
}
public static MethodInfo GetMethod(this Type type, string name, params Type[] paramTypes)
{
var methods = type.GetDeclaredMethods(name);
return (
from method in methods
let parameters = method.GetParameters()
where parameters != null
where parameters.Select(p => p.ParameterType).Where(t => !t.IsGenericParameter).SequenceEqual(paramTypes)
select method).FirstOrDefault();
}
public static void TranscodeCBCB(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new CompactBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new CompactBinaryWriter<OutputStream>(output);
Transcode.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeCBFB(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new CompactBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new FastBinaryWriter<OutputStream>(output);
Transcode.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeCBSP<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new CompactBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new SimpleBinaryWriter<OutputStream>(output);
Transcode<From>.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeCBXml<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new CompactBinaryReader<InputStream>(input);
var hasBase = Schema<From>.RuntimeSchema.HasBase;
var writer = new SimpleXmlWriter(to, new SimpleXmlWriter.Settings { UseNamespaces = hasBase });
Transcode<From>.FromTo(reader, writer);
writer.Flush();
}
public static void TranscodeCBJson<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new CompactBinaryReader<InputStream>(input);
var writer = new SimpleJsonWriter(to);
Transcode<From>.FromTo(reader, writer);
writer.Flush();
}
public static void TranscodeFBCB(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new FastBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new CompactBinaryWriter<OutputStream>(output);
Transcode.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeFBFB(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new FastBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new FastBinaryWriter<OutputStream>(output);
Transcode.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeFBSP<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new FastBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new SimpleBinaryWriter<OutputStream>(output);
Transcode<From>.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeFBXml<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new FastBinaryReader<InputStream>(input);
var hasBase = Schema<From>.RuntimeSchema.HasBase;
var writer = new SimpleXmlWriter(to, new SimpleXmlWriter.Settings { UseNamespaces = hasBase });
Transcode<From>.FromTo(reader, writer);
writer.Flush();
}
public static void TranscodeFBJson<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new FastBinaryReader<InputStream>(input);
var writer = new SimpleJsonWriter(to);
Transcode<From>.FromTo(reader, writer);
writer.Flush();
}
public static void TranscodeSPSP<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new SimpleBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new SimpleBinaryWriter<OutputStream>(output);
Transcode<From>.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeSPCB<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new SimpleBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new CompactBinaryWriter<OutputStream>(output);
Transcode<From>.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeSPFB<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new SimpleBinaryReader<InputStream>(input);
var output = new OutputStream(to, 19);
var writer = new FastBinaryWriter<OutputStream>(output);
Transcode<From>.FromTo(reader, writer);
output.Flush();
}
public static void TranscodeSPXml<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new SimpleBinaryReader<InputStream>(input);
var hasBase = Schema<From>.RuntimeSchema.HasBase;
var writer = new SimpleXmlWriter(to, new SimpleXmlWriter.Settings { UseNamespaces = hasBase });
Transcode<From>.FromTo(reader, writer);
writer.Flush();
}
public static void TranscodeSPJson<From>(Stream from, Stream to)
{
var input = new InputStream(from, 11);
var reader = new SimpleBinaryReader<InputStream>(input);
var writer = new SimpleJsonWriter(to);
Transcode<From>.FromTo(reader, writer);
writer.Flush();
}
public static void SerializeCB<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new CompactBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static void MarshalCB<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new CompactBinaryWriter<OutputStream>(output);
Marshal.To(writer, obj);
output.Flush();
}
public static void SerializerMarshalCB<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new CompactBinaryWriter<OutputStream>(output);
var serializer = new Serializer<CompactBinaryWriter<OutputStream>>(typeof(T));
serializer.Marshal(obj, writer);
output.Flush();
}
public static ArraySegment<byte> MarshalCB<T>(T obj)
{
var output = new OutputBuffer(new byte[11]);
var writer = new CompactBinaryWriter<OutputBuffer>(output);
Marshal.To(writer, obj);
return output.Data;
}
public static void SerializeCB<T>(IBonded<T> obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new CompactBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static void SerializeCB(IBonded obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new CompactBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static ArraySegment<byte> SerializeUnsafeCB<T>(T obj)
{
var output = new OutputBuffer();
var writer = new CompactBinaryWriter<OutputBuffer>(output);
Serialize.To(writer, obj);
return output.Data;
}
public static IntPtr SerializePointerCB<T>(T obj, IntPtr ptr, int length)
{
var output = new OutputPointer(ptr, length);
var writer = new CompactBinaryWriter<OutputPointer>(output);
Serialize.To(writer, obj);
return output.Data;
}
public static ArraySegment<byte> SerializeSafeCB<T>(T obj)
{
var output = new Bond.IO.Safe.OutputBuffer(new byte[11]);
var writer = new CompactBinaryWriter<Bond.IO.Safe.OutputBuffer>(output);
Serialize.To(writer, obj);
return output.Data;
}
public static ArraySegment<byte> SerializeSafeCBNoInlining<T>(T obj)
{
var output = new Bond.IO.Safe.OutputBuffer(new byte[11]);
var writer = new CompactBinaryWriter<Bond.IO.Safe.OutputBuffer>(output);
var serializer = new Serializer<CompactBinaryWriter<Bond.IO.Safe.OutputBuffer>>(typeof(T), false);
serializer.Serialize(obj, writer);
return output.Data;
}
public static T DeserializeCB<T>(Stream stream)
{
var input = new InputStream(stream);
var reader = new CompactBinaryReader<InputStream>(input);
return Deserialize<T>.From(reader);
}
public static T DeserializeSafeCB<T>(ArraySegment<byte> data)
{
var input = new Bond.IO.Safe.InputBuffer(data);
var reader = new CompactBinaryReader<Bond.IO.Safe.InputBuffer>(input);
return Deserialize<T>.From(reader);
}
public static T DeserializeUnsafeCB<T>(ArraySegment<byte> data)
{
var input = new InputBuffer(data);
var reader = new CompactBinaryReader<InputBuffer>(input);
return Deserialize<T>.From(reader);
}
public static T DeserializePointerCB<T>(IntPtr data, int length)
{
var input = new InputPointer(data, length);
var reader = new CompactBinaryReader<InputPointer>(input);
return Deserialize<T>.From(reader);
}
public static void SerializeFB<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new FastBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static void MarshalFB<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new FastBinaryWriter<OutputStream>(output);
Marshal.To(writer, obj);
output.Flush();
}
public static void SerializerMarshalFB<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new FastBinaryWriter<OutputStream>(output);
var serializer = new Serializer<FastBinaryWriter<OutputStream>>(typeof(T));
serializer.Marshal(obj, writer);
output.Flush();
}
public static ArraySegment<byte> MarshalFB<T>(T obj)
{
var output = new OutputBuffer();
var writer = new FastBinaryWriter<OutputBuffer>(output);
Marshal.To(writer, obj);
return output.Data;
}
public static void SerializeFB<T>(IBonded<T> obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new FastBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static void SerializeFB(IBonded obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new FastBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static ArraySegment<byte> SerializeFB<T>(T obj)
{
var output = new OutputBuffer();
var writer = new FastBinaryWriter<OutputBuffer>(output);
Serialize.To(writer, obj);
return output.Data;
}
public static T DeserializeFB<T>(Stream stream)
{
var input = new InputStream(stream);
var reader = new FastBinaryReader<InputStream>(input);
return Deserialize<T>.From(reader);
}
public static T DeserializeSafeFB<T>(ArraySegment<byte> data)
{
var input = new Bond.IO.Safe.InputBuffer(data);
var reader = new FastBinaryReader<Bond.IO.Safe.InputBuffer>(input);
return Deserialize<T>.From(reader);
}
public static T DeserializeUnsafeFB<T>(ArraySegment<byte> data)
{
var input = new InputBuffer(data);
var reader = new FastBinaryReader<InputBuffer>(input);
return Deserialize<T>.From(reader);
}
public static T DeserializePointerFB<T>(IntPtr data, int length)
{
var input = new InputPointer(data, length);
var reader = new FastBinaryReader<InputPointer>(input);
return Deserialize<T>.From(reader);
}
public static void SerializeSP<T>(T obj, Stream stream, ushort version)
{
var output = new OutputStream(stream, 11);
var writer = new SimpleBinaryWriter<OutputStream>(output, version);
Serialize.To(writer, obj);
output.Flush();
}
public static void SerializeSP<T>(T obj, Stream stream)
{
SerializeSP(obj, stream, 1);
}
public static void SerializeSP2<T>(T obj, Stream stream)
{
SerializeSP(obj, stream, 2);
}
public static void SerializeSP<T>(IBonded<T> obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new SimpleBinaryWriter<OutputStream>(output);
Serialize.To(writer, obj);
output.Flush();
}
public static ArraySegment<byte> SerializeSP<T>(T obj, ushort version)
{
var output = new OutputBuffer();
var writer = new SimpleBinaryWriter<OutputBuffer>(output, version);
Serialize.To(writer, obj);
return output.Data;
}
public static ArraySegment<byte> SerializeSP<T>(T obj)
{
return SerializeSP(obj, 1);
}
public static ArraySegment<byte> SerializeSP2<T>(T obj)
{
return SerializeSP(obj, 2);
}
public static void SerializeJson<T>(T obj, Stream stream)
{
var writer = new SimpleJsonWriter(stream);
Serialize.To(writer, obj);
writer.Flush();
}
public static void MarshalSP<T>(T obj, Stream stream)
{
var output = new OutputStream(stream, 11);
var writer = new SimpleBinaryWriter<OutputStream>(output);
Marshal.To(writer, obj);
output.Flush();
}
public static To DeserializeSP<From, To>(Stream stream, ushort version)
{
var input = new InputStream(stream);
var reader = new SimpleBinaryReader<InputStream>(input, version);
var deserializer = new Deserializer<SimpleBinaryReader<InputStream>>(typeof(To), Schema<From>.RuntimeSchema);
return deserializer.Deserialize<To>(reader);
}
public static To DeserializeSP<From, To>(Stream stream)
{
return DeserializeSP<From, To>(stream, 1);
}
public static To DeserializeSP2<From, To>(Stream stream)
{
return DeserializeSP<From, To>(stream, 2);
}
public static To DeserializeSafeSP<From, To>(ArraySegment<byte> data, ushort version)
{
var input = new Bond.IO.Safe.InputBuffer(data.Array, data.Offset, data.Count);
var reader = new SimpleBinaryReader<Bond.IO.Safe.InputBuffer>(input, version);
var deserializer = new Deserializer<SimpleBinaryReader<Bond.IO.Safe.InputBuffer>>(typeof(To), Schema<From>.RuntimeSchema);
return deserializer.Deserialize<To>(reader);
}
public static To DeserializeSafeSP<From, To>(ArraySegment<byte> data)
{
return DeserializeSafeSP<From, To>(data, 1);
}
public static To DeserializeSafeSP2<From, To>(ArraySegment<byte> data)
{
return DeserializeSafeSP<From, To>(data, 2);
}
public static To DeserializeUnsafeSP<From, To>(ArraySegment<byte> data, ushort version)
{
var input = new InputBuffer(data);
var reader = new SimpleBinaryReader<InputBuffer>(input, version);
var deserializer = new Deserializer<SimpleBinaryReader<InputBuffer>>(typeof(To), Schema<From>.RuntimeSchema);
return deserializer.Deserialize<To>(reader);
}
public static To DeserializeUnsafeSP<From, To>(ArraySegment<byte> data)
{
return DeserializeUnsafeSP<From, To>(data, 1);
}
public static To DeserializeUnsafeSP2<From, To>(ArraySegment<byte> data)
{
return DeserializeUnsafeSP<From, To>(data, 2);
}
public static To DeserializePointerSP<From, To>(IntPtr data, int length)
{
var input = new InputPointer(data, length);
var reader = new SimpleBinaryReader<InputPointer>(input);
var deserializer = new Deserializer<SimpleBinaryReader<InputPointer>>(typeof(To), Schema<From>.RuntimeSchema);
return deserializer.Deserialize<To>(reader);
}
public static void SerializeXml<T>(T obj, Stream stream)
{
var hasBase = Schema<T>.RuntimeSchema.HasBase;
var writer = new SimpleXmlWriter(stream, new SimpleXmlWriter.Settings { UseNamespaces = hasBase });
Serialize.To(writer, obj);
writer.Flush();
}
public static void SerializeXmlWithNamespaces<T>(T obj, Stream stream)
{
var writer = new SimpleXmlWriter(stream, new SimpleXmlWriter.Settings { UseNamespaces = true });
Serialize.To(writer, obj);
writer.Flush();
}
public static void SerializeXml<T>(IBonded<T> obj, Stream stream)
{
var writer = new SimpleXmlWriter(stream, new SimpleXmlWriter.Settings { UseNamespaces = true });
Serialize.To(writer, obj);
writer.Flush();
}
public static T DeserializeXml<T>(Stream stream)
{
var reader = new SimpleXmlReader(stream);
return Deserialize<T>.From(reader);
}
public static T DeserializeJson<T>(Stream stream)
{
var reader = new SimpleJsonReader(stream);
return Deserialize<T>.From(reader);
}
public static T DeserializeTagged<T>(IClonableTaggedProtocolReader reader)
{
return Deserialize<T>.From(reader);
}
public static To DeserializeUntagged<From, To>(IClonableUntaggedProtocolReader reader)
{
var deserializer = new Deserializer<IClonableUntaggedProtocolReader>(typeof(To), Schema<From>.RuntimeSchema);
return deserializer.Deserialize<To>(reader);
}
public static string SerializeXmlString<T>(T obj)
{
var builder = new StringBuilder();
var writer = new SimpleXmlWriter(XmlWriter.Create(builder, new XmlWriterSettings { OmitXmlDeclaration = true, Indent = true }));
Serialize.To(writer, obj);
writer.Flush();
return builder.ToString();
}
public static IBonded<T> MakeBondedCB<T>(T obj)
{
var stream = new MemoryStream();
SerializeCB(obj, stream);
stream.Position = 0;
// Create new MemoryStream at non-zero offset in a buffer
var buffer = new byte[stream.Length + 2];
stream.Read(buffer, 1, buffer.Length - 2);
var input = new InputStream(new MemoryStream(buffer, 1, buffer.Length - 2, false, true));
var reader = new CompactBinaryReader<InputStream>(input);
return new Bonded<T, CompactBinaryReader<InputStream>>(reader);
}
public static IBonded<T> MakeBondedSP<T>(T obj)
{
var stream = new MemoryStream();
SerializeSP(obj, stream);
stream.Position = 0;
// Create new MemoryStream at non-zero offset in a buffer
var buffer = new byte[stream.Length + 2];
stream.Read(buffer, 1, buffer.Length - 2);
var input = new InputStream(new MemoryStream(buffer, 1, buffer.Length - 2, false, true));
var reader = new SimpleBinaryReader<InputStream>(input);
return new Bonded<T, SimpleBinaryReader<InputStream>>(reader);
}
public delegate void RoundtripStream<From, To>(Action<From, Stream> serialize, Func<Stream, To> deserialize);
public delegate void MarshalStream<From>(Action<From, Stream> serialize);
public delegate void MarshalMemory<From>(Func<From, ArraySegment<byte>> serialize);
public delegate void TranscodeStream<From, To>(Action<From, Stream> serialize, Action<Stream, Stream> transcode, Func<Stream, To> deserialize);
public delegate void RoundtripMemory<From, To>(Func<From, ArraySegment<byte>> serialize, Func<ArraySegment<byte>, To> deserialize);
public delegate void RoundtripPointer<From, To>(Func<From, IntPtr, int, IntPtr> serialize, Func<IntPtr, int, To> deserialize);
public delegate void RoundtripMemoryPointer<From, To>(Func<From, ArraySegment<byte>> serialize, Func<IntPtr, int, To> deserialize);
public static void AllSerializeDeserialize<From, To>(From from, bool noTranscoding = false)
where From : class
where To : class
{
RoundtripMemory<From, To> memoryRoundtrip = (serialize, deserialize) =>
{
var data = serialize(from);
var to = deserialize(data);
Assert.IsTrue(from.IsEqual(to));
};
RoundtripPointer<From, To> pointerRoundtrip = (serialize, deserialize) =>
{
var ptr = RMarshal.AllocHGlobal(UnsafeBufferSize);
var data = serialize(from, ptr, UnsafeBufferSize);
var to = deserialize(data, UnsafeBufferSize);
Assert.IsTrue(from.IsEqual(to));
RMarshal.FreeHGlobal(data);
};
RoundtripMemoryPointer<From, To> memoryPointerRoundtrip = (serialize, deserialize) =>
{
var data = serialize(from);
var pinned = GCHandle.Alloc(data.Array, GCHandleType.Pinned);
var to = deserialize(RMarshal.UnsafeAddrOfPinnedArrayElement(data.Array, data.Offset), data.Count);
Assert.IsTrue(from.IsEqual(to));
pinned.Free();
};
RoundtripStream<From, To> streamRoundtrip = (serialize, deserialize) =>
{
var stream = new MemoryStream();
serialize(from, stream);
stream.Position = 0;
var to = deserialize(stream);
Assert.IsTrue(from.IsEqual(to));
};
MarshalStream<From> streamMarshal = serialize => streamRoundtrip(serialize, stream =>
{
stream.Position = 0;
return Unmarshal<To>.From(new InputStream(stream));
});
MarshalStream<From> streamMarshalSchema = serialize => streamRoundtrip(serialize, stream =>
{
stream.Position = 0;
return Unmarshal.From(new InputStream(stream), Schema<From>.RuntimeSchema).Deserialize<To>();
});
MarshalStream<From> streamMarshalNoSchema = serialize => streamRoundtrip(serialize, stream =>
{
stream.Position = 0;
return Unmarshal.From(new InputStream(stream)).Deserialize<To>();
});
MarshalMemory<From> memoryMarshal = serialize => memoryRoundtrip(serialize, Unmarshal<To>.From);
TranscodeStream<From, To> streamTranscode = (serialize, transcode, deserialize) =>
streamRoundtrip((obj, stream) =>
{
using (var tmp = new MemoryStream())
{
serialize(obj, tmp);
tmp.Position = 0;
transcode(tmp, stream);
}
}, deserialize);
if (noTranscoding)
streamTranscode = (serialize, transcode, deserialize) => { };
// Compact Binary
streamRoundtrip(SerializeCB, DeserializeCB<To>);
memoryRoundtrip(SerializeUnsafeCB, DeserializeSafeCB<To>);
memoryRoundtrip(SerializeUnsafeCB, DeserializeUnsafeCB<To>);
memoryPointerRoundtrip(SerializeUnsafeCB, DeserializePointerCB<To>);
pointerRoundtrip(SerializePointerCB, DeserializePointerCB<To>);
memoryRoundtrip(SerializeSafeCB, DeserializeSafeCB<To>);
memoryRoundtrip(SerializeSafeCB, DeserializeUnsafeCB<To>);
memoryPointerRoundtrip(SerializeSafeCB, DeserializePointerCB<To>);
memoryRoundtrip(SerializeSafeCBNoInlining, DeserializeSafeCB<To>);
streamMarshal(MarshalCB);
streamMarshal(SerializerMarshalCB);
streamMarshalSchema(MarshalCB);
streamMarshalNoSchema(MarshalCB);
memoryMarshal(MarshalCB);
streamTranscode(SerializeCB, TranscodeCBCB, DeserializeCB<To>);
streamTranscode(SerializeCB, TranscodeCBFB, DeserializeFB<To>);
streamRoundtrip(SerializeCB, stream =>
{
var input = new InputStream(stream);
var reader = new CompactBinaryReader<InputStream>(input);
return DeserializeTagged<To>(reader);
});
// Fast Binary
streamRoundtrip(SerializeFB, DeserializeFB<To>);
memoryRoundtrip(SerializeFB, DeserializeSafeFB<To>);
memoryRoundtrip(SerializeFB, DeserializeUnsafeFB<To>);
memoryPointerRoundtrip(SerializeFB, DeserializePointerFB<To>);
streamMarshal(MarshalFB);
streamMarshal(SerializerMarshalFB);
streamMarshalSchema(MarshalFB);
streamMarshalNoSchema(MarshalFB);
memoryMarshal(MarshalFB);
streamTranscode(SerializeFB, TranscodeFBFB, DeserializeFB<To>);
streamTranscode(SerializeFB, TranscodeFBCB, DeserializeCB<To>);
streamRoundtrip(SerializeFB, stream =>
{
var input = new InputStream(stream);
var reader = new FastBinaryReader<InputStream>(input);
return DeserializeTagged<To>(reader);
});
// Simple doesn't support omitting fields
if (typeof(From) != typeof(Nothing) && typeof(From) != typeof(GenericsWithNothing))
{
streamRoundtrip(SerializeSP, DeserializeSP<From, To>);
memoryRoundtrip(SerializeSP, DeserializeSafeSP<From, To>);
memoryRoundtrip(SerializeSP, DeserializeUnsafeSP<From, To>);
memoryPointerRoundtrip(SerializeSP, DeserializePointerSP<From, To>);
streamRoundtrip(SerializeSP2, DeserializeSP2<From, To>);
memoryRoundtrip(SerializeSP2, DeserializeSafeSP2<From, To>);
memoryRoundtrip(SerializeSP2, DeserializeUnsafeSP2<From, To>);
streamTranscode(SerializeCB, TranscodeCBSP<From>, DeserializeSP<From, To>);
streamTranscode(SerializeFB, TranscodeFBSP<From>, DeserializeSP<From, To>);
streamTranscode(SerializeSP, TranscodeSPSP<From>, DeserializeSP<From, To>);
streamTranscode(SerializeSP, TranscodeSPCB<From>, DeserializeCB<To>);
streamTranscode(SerializeSP, TranscodeSPFB<From>, DeserializeFB<To>);
// Pull parser doesn't supprot bonded<T>
if (AnyField<From>(Reflection.IsBonded))
{
streamTranscode(SerializeSP, TranscodeSPXml<From>, DeserializeXml<To>);
// NewtonSoft JSON doesn't support uint64
if (typeof (From) != typeof (MaxUInt64))
{
streamTranscode(SerializeSP, TranscodeSPJson<From>, DeserializeJson<To>);
}
}
streamRoundtrip(SerializeSP, stream =>
{
var input = new InputStream(stream);
var reader = new SimpleBinaryReader<InputStream>(input);
return DeserializeUntagged<From, To>(reader);
});
streamMarshalSchema(MarshalSP);
}
// Pull parser doesn't supprot bonded<T>
if (AnyField<From>(Reflection.IsBonded))
{
streamRoundtrip(SerializeXml, DeserializeXml<To>);
streamTranscode(SerializeCB, TranscodeCBXml<From>, DeserializeXml<To>);
streamTranscode(SerializeFB, TranscodeFBXml<From>, DeserializeXml<To>);
// NewtonSoft JSON doesn't support uint64
if (typeof (From) != typeof (MaxUInt64))
{
streamRoundtrip(SerializeJson, DeserializeJson<To>);
streamTranscode(SerializeCB, TranscodeCBJson<From>, DeserializeJson<To>);
streamTranscode(SerializeFB, TranscodeFBJson<From>, DeserializeJson<To>);
}
}
}
delegate bool TypePredicate(Type field);
static bool AnyField<T>(TypePredicate predicate)
{
var types = new HashSet<Type>();
return AnyField(types, typeof(T), predicate);
}
static bool AnyField(HashSet<Type> types, Type type, TypePredicate predicate)
{
types.Add(type);
return type.GetSchemaFields()
.Select(field => field.MemberType)
.Where(fieldType => !types.Contains(fieldType))
.Any(fieldType => predicate(fieldType) || fieldType.IsBondStruct() && AnyField(types, fieldType, predicate));
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.